@ecomweb/storefront-kit 0.14.1 → 0.15.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/README.md +25 -1
- package/bin/check-client-bundle-lib.d.mts +16 -0
- package/bin/check-client-bundle-lib.mjs +58 -0
- package/bin/check-client-bundle.d.mts +11 -0
- package/bin/check-client-bundle.mjs +8 -0
- package/dist/api/client.js +39 -0
- package/dist/api/client.js.map +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/proxy-guard.js +29 -0
- package/dist/api/proxy-guard.js.map +1 -0
- package/dist/api/proxy-routes.js +126 -0
- package/dist/api/proxy-routes.js.map +1 -0
- package/dist/api/proxy.js +17 -4
- package/dist/api/proxy.js.map +1 -1
- package/dist/api/server-sdk.js +41 -0
- package/dist/api/server-sdk.js.map +1 -0
- package/dist/api/store-preview-header.js.map +1 -1
- package/dist/auth/sdk.js +15 -5
- package/dist/auth/sdk.js.map +1 -1
- package/dist/auth/session-refresh.js +7 -4
- package/dist/auth/session-refresh.js.map +1 -1
- package/dist/cart/api.js.map +1 -1
- package/dist/checkout/get-payment-state.js +4 -8
- package/dist/checkout/get-payment-state.js.map +1 -1
- package/dist/checkout/initiate-gateway-payment.js +5 -7
- package/dist/checkout/initiate-gateway-payment.js.map +1 -1
- package/dist/checkout/order-handoff.js.map +1 -1
- package/dist/checkout/payment-redirect.js.map +1 -1
- package/dist/client-info.js +1 -1
- package/dist/config/public.js +2 -0
- package/dist/config/public.js.map +1 -1
- package/dist/config/schema.js +16 -4
- package/dist/config/schema.js.map +1 -1
- package/dist/config/secret-guard.js +20 -0
- package/dist/config/secret-guard.js.map +1 -0
- package/dist/config/server.js +15 -8
- package/dist/config/server.js.map +1 -1
- package/dist/config.d.ts +14 -4
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +25 -68
- package/dist/index.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +14 -3
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
- package/dist/orders/api-client.js +3 -3
- package/dist/orders/api-client.js.map +1 -1
- package/dist/orders/bank-transfer.js +1 -1
- package/dist/orders/bank-transfer.js.map +1 -1
- package/dist/orders/use-order-status.js +2 -2
- package/dist/orders/use-order-status.js.map +1 -1
- package/dist/promotions/use-promotion-validation.js +2 -2
- package/dist/promotions/use-promotion-validation.js.map +1 -1
- package/dist/request/served-store.js +5 -0
- package/dist/request/served-store.js.map +1 -0
- package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
- package/dist/sdk.js +3 -3
- package/dist/sdk.js.map +1 -1
- package/dist/server/routes.js +16 -9
- package/dist/server/routes.js.map +1 -1
- package/dist/server.d.ts +38 -5
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/shipping/use-shipping-calculation.js +2 -2
- package/dist/shipping/use-shipping-calculation.js.map +1 -1
- package/package.json +6 -2
- package/dist/api/server-client.js +0 -162
- package/dist/api/server-client.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z.string().min(1),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n
|
|
1
|
+
{"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** The message for a secret key found where the browser could read it. */\nexport const SECRET_IN_PUBLIC_MESSAGE =\n \"holds a secret key; secret keys go in server-only variables (ECOMWEB_SECRET_KEY, PLATFORM_SECRET_KEY)\";\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z\n .string()\n .min(1)\n .refine(v => !v.trim().startsWith(\"sk_\"), {\n message: SECRET_IN_PUBLIC_MESSAGE,\n }),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n /**\n * Signs every server-side call. Empty only while `next build` runs (builds\n * get no secret); read it through `storefrontSecretKey()`, which throws on\n * an empty one.\n */\n secretKey: z\n .string({ error: \"is required\" })\n .refine(v => !v.trim().startsWith(\"pk_\"), {\n message:\n \"is a publishable key; this variable takes the secret key (sk_...)\",\n }),\n clientIpForwarderSecret: z.string().min(1).optional(),\n appBaseUrl: z.string().min(1),\n appEnv: z.string().min(1),\n googleVerification: z.string().optional(),\n logLevel: z.enum(LOG_LEVELS).optional(),\n /**\n * The header carrying the shopper's IP that this server's edge sets and a\n * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it\n * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.\n */\n clientIpHeader: z.enum([\"x-forwarded-for\", \"cf-connecting-ip\"]),\n /**\n * Requests a minute to one store, on one server, above which the\n * multi-tenant middleware logs that store (log only, nothing is refused).\n * 0 turns it off.\n */\n storeTrafficLogPerMinute: z.number().int().min(0),\n});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\n\n/**\n * Thrown when the storefront's environment variables are missing or invalid.\n * The message names the variable behind every bad field.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>,\n notes: Record<string, string> = {}\n): T {\n const result = schema.safeParse(candidate);\n if (result.success) return result.data;\n const lines = result.error.issues.map(issue => {\n const field = String(issue.path[0] ?? \"\");\n const note = notes[field] ? ` ${notes[field]}` : \"\";\n return ` - ${envNameOf[field] ?? field}: ${issue.message}${note}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\n}\n\n/** A non-negative integer from `v`, else `fallback`. */\nexport function countOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\nexport function sampleRateOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1\n ? n\n : fallback;\n}\n"],"mappings":"AAAA,SAAS,SAAS;AAKlB,MAAM,aAAa,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAGvD,SAAS,SAAS,KAAgB,KAAiC;AACxE,QAAM,IAAI,IAAI,GAAG,GAAG,KAAK;AACzB,SAAO,IAAI,IAAI;AACjB;AAEO,SAAS,WAAW,GAA6C;AACtE,SAAQ,WAAiC,SAAS,KAAK,EAAE,IACpD,IACD;AACN;AAGO,MAAM,2BACX;AAGF,MAAM,UAAU,EAAE,IAAI,EAAE,UAAU,WAAW,CAAC;AAEvC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,MAAM,EAAE,KAAK,CAAC,SAAS,QAAQ,CAAC;AAAA,EAChC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACrC,QAAQ;AAAA,EACR,cAAc,EAAE,OAAO;AAAA,EACvB,QAAQ;AAAA,EACR,kBAAkB,EACf,OAAO,EACP,IAAI,CAAC,EACL,OAAO,OAAK,CAAC,EAAE,KAAK,EAAE,WAAW,KAAK,GAAG;AAAA,IACxC,SAAS;AAAA,EACX,CAAC;AAAA,EACH,sBAAsB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACjD,gBAAgB,EAAE,OAAO,EAAE,SAAS;AAAA,EACpC,0BAA0B,EAAE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,IAAI,MAAM,KAAK,CAAC,KAAK;AACjD,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO,GAAG,IAAI;AAAA,EAClE,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;AAGO,SAAS,QAAQ,GAAuB,UAA0B;AACvE,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,UAAU,CAAC,KAAK,KAAK,IAAI,IAAI;AAChE;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigError,
|
|
3
|
+
SECRET_IN_PUBLIC_MESSAGE
|
|
4
|
+
} from "./schema.js";
|
|
5
|
+
function isSecretKeyValue(value) {
|
|
6
|
+
return value?.trim().startsWith("sk_") ?? false;
|
|
7
|
+
}
|
|
8
|
+
function assertNoSecretInPublicEnv(env) {
|
|
9
|
+
const leaked = Object.keys(env).filter((key) => key.startsWith("NEXT_PUBLIC_") && isSecretKeyValue(env[key])).sort();
|
|
10
|
+
if (leaked.length === 0) return;
|
|
11
|
+
throw new ConfigError(
|
|
12
|
+
`Invalid storefront configuration:
|
|
13
|
+
${leaked.map((key) => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`).join("\n")}`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
export {
|
|
17
|
+
assertNoSecretInPublicEnv,
|
|
18
|
+
isSecretKeyValue
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=secret-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/config/secret-guard.ts"],"sourcesContent":["import {\n ConfigError,\n SECRET_IN_PUBLIC_MESSAGE,\n type EnvSource,\n} from \"./schema\";\n\n/** True when `value` is a secret key (`sk_` prefix, ignoring whitespace). */\nexport function isSecretKeyValue(value: string | undefined): boolean {\n return value?.trim().startsWith(\"sk_\") ?? false;\n}\n\n/**\n * Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those\n * into the browser bundle. The error names every offending variable and never\n * prints a value.\n *\n * @param env The environment to check.\n * @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.\n */\nexport function assertNoSecretInPublicEnv(env: EnvSource): void {\n const leaked = Object.keys(env)\n .filter(key => key.startsWith(\"NEXT_PUBLIC_\") && isSecretKeyValue(env[key]))\n .sort();\n if (leaked.length === 0) return;\n throw new ConfigError(\n `Invalid storefront configuration:\\n${leaked\n .map(key => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`)\n .join(\"\\n\")}`\n );\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAGA,SAAS,iBAAiB,OAAoC;AACnE,SAAO,OAAO,KAAK,EAAE,WAAW,KAAK,KAAK;AAC5C;AAUO,SAAS,0BAA0B,KAAsB;AAC9D,QAAM,SAAS,OAAO,KAAK,GAAG,EAC3B,OAAO,SAAO,IAAI,WAAW,cAAc,KAAK,iBAAiB,IAAI,GAAG,CAAC,CAAC,EAC1E,KAAK;AACR,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,OACnC,IAAI,SAAO,OAAO,GAAG,KAAK,wBAAwB,EAAE,EACpD,KAAK,IAAI,CAAC;AAAA,EACf;AACF;","names":[]}
|
package/dist/config/server.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "server-only";
|
|
2
2
|
import { resolveMode } from "./mode.js";
|
|
3
|
+
import { assertNoSecretInPublicEnv } from "./secret-guard.js";
|
|
3
4
|
import {
|
|
4
5
|
countOf,
|
|
5
6
|
envValue,
|
|
@@ -7,11 +8,18 @@ import {
|
|
|
7
8
|
parseOrThrow,
|
|
8
9
|
serverConfigSchema
|
|
9
10
|
} from "./schema.js";
|
|
11
|
+
function secretOf(env, name) {
|
|
12
|
+
const value = envValue(env, name);
|
|
13
|
+
if (value === void 0 && env.NEXT_PHASE === "phase-production-build") {
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
10
18
|
function parseMulti(env) {
|
|
11
19
|
return parseOrThrow(
|
|
12
20
|
serverConfigSchema,
|
|
13
21
|
{
|
|
14
|
-
|
|
22
|
+
secretKey: secretOf(env, "PLATFORM_SECRET_KEY"),
|
|
15
23
|
clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
|
|
16
24
|
appBaseUrl: envValue(env, "APP_BASE_URL") ?? "http://localhost:3002",
|
|
17
25
|
appEnv: envValue(env, "APP_ENV") ?? "unknown",
|
|
@@ -24,19 +32,17 @@ function parseMulti(env) {
|
|
|
24
32
|
)
|
|
25
33
|
},
|
|
26
34
|
{
|
|
27
|
-
|
|
35
|
+
secretKey: "PLATFORM_SECRET_KEY",
|
|
28
36
|
clientIpHeader: "CLIENT_IP_HEADER"
|
|
29
|
-
}
|
|
37
|
+
},
|
|
38
|
+
envValue(env, "PLATFORM_API_KEY") ? { secretKey: "(PLATFORM_API_KEY is retired)" } : {}
|
|
30
39
|
);
|
|
31
40
|
}
|
|
32
41
|
function parseSingle(env) {
|
|
33
42
|
return parseOrThrow(
|
|
34
43
|
serverConfigSchema,
|
|
35
44
|
{
|
|
36
|
-
|
|
37
|
-
// NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg
|
|
38
|
-
// still runs when the runtime env does not repeat it.
|
|
39
|
-
platformApiKey: envValue(env, "ECOMWEB_PUBLISHABLE_KEY") ?? envValue(env, "NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY"),
|
|
45
|
+
secretKey: secretOf(env, "ECOMWEB_SECRET_KEY"),
|
|
40
46
|
clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
|
|
41
47
|
appBaseUrl: envValue(env, "SITE_URL") ?? "http://localhost:3000",
|
|
42
48
|
appEnv: envValue(env, "APP_ENV") ?? "production",
|
|
@@ -47,12 +53,13 @@ function parseSingle(env) {
|
|
|
47
53
|
storeTrafficLogPerMinute: 0
|
|
48
54
|
},
|
|
49
55
|
{
|
|
50
|
-
|
|
56
|
+
secretKey: "ECOMWEB_SECRET_KEY",
|
|
51
57
|
clientIpHeader: "CLIENT_IP_HEADER"
|
|
52
58
|
}
|
|
53
59
|
);
|
|
54
60
|
}
|
|
55
61
|
function parseServerConfig(env) {
|
|
62
|
+
assertNoSecretInPublicEnv(env);
|
|
56
63
|
return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
|
|
57
64
|
}
|
|
58
65
|
let cached;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n
|
|
1
|
+
{"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport { assertNoSecretInPublicEnv } from \"./secret-guard\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\n/**\n * The secret key, from the runtime env only (never a NEXT_PUBLIC_ fallback).\n * `next build` gets none (hosted builds hold no secret), so while it runs a\n * missing key reads as empty; `storefrontSecretKey()` throws on an empty one.\n */\nfunction secretOf(env: EnvSource, name: string): string | undefined {\n const value = envValue(env, name);\n if (value === undefined && env.NEXT_PHASE === \"phase-production-build\") {\n return \"\";\n }\n return value;\n}\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"PLATFORM_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"APP_BASE_URL\") ?? \"http://localhost:3002\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"unknown\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n storeTrafficLogPerMinute: countOf(\n envValue(env, \"STORE_TRAFFIC_LOG_PER_MINUTE\"),\n 600\n ),\n },\n {\n secretKey: \"PLATFORM_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n },\n envValue(env, \"PLATFORM_API_KEY\")\n ? { secretKey: \"(PLATFORM_API_KEY is retired)\" }\n : {}\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"ECOMWEB_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"SITE_URL\") ?? \"http://localhost:3000\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"production\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n // One store per site: there are no neighbours to watch.\n storeTrafficLogPerMinute: 0,\n },\n {\n secretKey: \"ECOMWEB_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parseServerConfig(env: EnvSource): ServerConfig {\n assertNoSecretInPublicEnv(env);\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * The server's parsed configuration, read from the environment on the first\n * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`\n * in server code, never in a client component.\n *\n * @returns The validated server config.\n * @throws ConfigError when a required variable is missing or invalid.\n */\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAOP,SAAS,SAAS,KAAgB,MAAkC;AAClE,QAAM,QAAQ,SAAS,KAAK,IAAI;AAChC,MAAI,UAAU,UAAa,IAAI,eAAe,0BAA0B;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,WAAW,SAAS,KAAK,qBAAqB;AAAA,MAC9C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,cAAc,KAAK;AAAA,MAC7C,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA,MACrD,0BAA0B;AAAA,QACxB,SAAS,KAAK,8BAA8B;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE,WAAW;AAAA,MACX,gBAAgB;AAAA,IAClB;AAAA,IACA,SAAS,KAAK,kBAAkB,IAC5B,EAAE,WAAW,gCAAgC,IAC7C,CAAC;AAAA,EACP;AACF;AAEA,SAAS,YAAY,KAA8B;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,WAAW,SAAS,KAAK,oBAAoB;AAAA,MAC7C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,UAAU,KAAK;AAAA,MACzC,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA;AAAA,MAErD,0BAA0B;AAAA,IAC5B;AAAA,IACA;AAAA,MACE,WAAW;AAAA,MACX,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,4BAA0B,GAAG;AAC7B,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAEG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAUO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,GAAG,QAAQ;AAAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,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-B3nAYiwT.js';
|
|
2
|
+
export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-B3nAYiwT.js';
|
|
3
|
+
export { S as StorefrontMode, r as resolveMode } from './mode-oVZCQxrc.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/** Parses the variables of the mode `env` selects (see resolveMode). */
|
|
@@ -13,6 +13,16 @@ declare function resetPublicConfigForTests(): void;
|
|
|
13
13
|
*/
|
|
14
14
|
declare function publicConfig(): PublicConfig;
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those
|
|
18
|
+
* into the browser bundle. The error names every offending variable and never
|
|
19
|
+
* prints a value.
|
|
20
|
+
*
|
|
21
|
+
* @param env The environment to check.
|
|
22
|
+
* @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.
|
|
23
|
+
*/
|
|
24
|
+
declare function assertNoSecretInPublicEnv(env: EnvSource): void;
|
|
25
|
+
|
|
16
26
|
/**
|
|
17
27
|
* This package's version, baked in at build time. `dev` when the source runs
|
|
18
28
|
* without the define (the API ignores a version that isn't semver).
|
|
@@ -82,4 +92,4 @@ declare function formatClientVersionWarning(report: ClientVersionReport): string
|
|
|
82
92
|
*/
|
|
83
93
|
declare function checkClientVersions(options?: CheckClientVersionsOptions): Promise<ClientVersionReport | null>;
|
|
84
94
|
|
|
85
|
-
export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
|
|
95
|
+
export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, assertNoSecretInPublicEnv, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
|
package/dist/config.js
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
} from "./config/public.js";
|
|
6
6
|
import { resolveMode } from "./config/mode.js";
|
|
7
7
|
import { ConfigError } from "./config/schema.js";
|
|
8
|
+
import { assertNoSecretInPublicEnv } from "./config/secret-guard.js";
|
|
8
9
|
import { KIT_CLIENT_TOKEN, KIT_VERSION } from "./client-info.js";
|
|
9
10
|
import {
|
|
10
11
|
checkClientVersions,
|
|
@@ -14,6 +15,7 @@ export {
|
|
|
14
15
|
ConfigError,
|
|
15
16
|
KIT_CLIENT_TOKEN,
|
|
16
17
|
KIT_VERSION,
|
|
18
|
+
assertNoSecretInPublicEnv,
|
|
17
19
|
checkClientVersions,
|
|
18
20
|
formatClientVersionWarning,
|
|
19
21
|
parsePublicConfig,
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Parsing and types for the storefront's configuration: public (client-safe)\n * settings, the deployment mode, the build-time version check and\n * `ConfigError`.\n *\n * Import from `@ecomweb/storefront-kit/config` in `next.config` and config\n * code. It has no React or server-only dependency.\n *\n * @packageDocumentation\n */\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Parsing and types for the storefront's configuration: public (client-safe)\n * settings, the deployment mode, the build-time version check and\n * `ConfigError`.\n *\n * Import from `@ecomweb/storefront-kit/config` in `next.config` and config\n * code. It has no React or server-only dependency.\n *\n * @packageDocumentation\n */\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport { assertNoSecretInPublicEnv } from \"./config/secret-guard\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAO1C,SAAS,kBAAkB,mBAAmB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { ReactNode, ReactElement } from 'react';
|
|
4
4
|
import * as _ecomweb_sdk from '@ecomweb/sdk';
|
|
5
|
-
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, ShippingOption, OrderStatus, Order, CreateOrderRequest, ShipmentStatus, OrderShipmentSummary, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
|
|
5
|
+
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, ShippingOption, OrderStatus, Order, CreateOrderRequest, ShipmentStatus, OrderShipmentSummary, EcomwebServerSdk, EcomwebSdk, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
|
|
6
|
+
export { EcomwebSdk, EcomwebServerSdk } from '@ecomweb/sdk';
|
|
6
7
|
import currencyJs from 'currency.js';
|
|
7
8
|
import { AxiosRequestConfig, AxiosInstance } from 'axios';
|
|
8
9
|
export { AnyThemeDefinition, BlogIndexSlotProps, BlogPostSlotProps, CollectionPageSlotProps, CollectionSearchParams, ContentPageSlotProps, HomePageSlotProps, LayoutSlotProps, NotFoundProps, ProductCardProps, ProductPageSlotProps, ThemeClientComponents, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
|
|
@@ -583,6 +584,13 @@ declare class ApiClient implements AuthenticatedApiClient {
|
|
|
583
584
|
private setupInterceptors;
|
|
584
585
|
private handleResponse;
|
|
585
586
|
private handleError;
|
|
587
|
+
/**
|
|
588
|
+
* The direct, publishable-key client cannot call a private route: the API
|
|
589
|
+
* would refuse it, so refuse here, before the network. Logs the matched
|
|
590
|
+
* route pattern, never the raw path (it can carry a review token or an
|
|
591
|
+
* order code).
|
|
592
|
+
*/
|
|
593
|
+
private refusePrivateRoute;
|
|
586
594
|
get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
|
|
587
595
|
post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
|
|
588
596
|
put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
|
|
@@ -852,26 +860,13 @@ interface PollPaymentStateOptions {
|
|
|
852
860
|
declare function pollPaymentState(options: PollPaymentStateOptions): Promise<PollOutcome>;
|
|
853
861
|
|
|
854
862
|
/**
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
858
|
-
* (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),
|
|
859
|
-
* but that SDK PR is not yet merged to `main`, and this repo's lockfile
|
|
860
|
-
* pins an older `@ecomweb/sdk` commit that has no `payments` module at all
|
|
861
|
-
* — see `lib/checkout/initiate-gateway-payment.ts` for the full story
|
|
862
|
-
* (same pinned commit, same missing module). Running
|
|
863
|
-
* `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task
|
|
864
|
-
* — it is a deliberate later step in the plan.
|
|
863
|
+
* Reads where a payment stands for an order, from the browser, through the
|
|
864
|
+
* store's backend proxy (`createStoreSdk`), which adds the secret key. Browser
|
|
865
|
+
* only: the proxied SDK uses a relative URL. On a server use `getServerSdk()`.
|
|
865
866
|
*
|
|
866
|
-
*
|
|
867
|
-
*
|
|
868
|
-
*
|
|
869
|
-
* `payment-state-poll`'s caller, and call
|
|
870
|
-
* `sdk.payments.getPaymentState(...)` instead — the call site already reads
|
|
871
|
-
* as if it were doing that today.
|
|
872
|
-
*
|
|
873
|
-
* FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past
|
|
874
|
-
* `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.
|
|
867
|
+
* @param storeRef - the store's ref
|
|
868
|
+
* @param order_code - the order's code
|
|
869
|
+
* @returns the payment state of the order
|
|
875
870
|
*/
|
|
876
871
|
declare function getPaymentState(storeRef: string, order_code: string): Promise<PaymentStateResult>;
|
|
877
872
|
|
|
@@ -914,7 +909,7 @@ declare const publicOrdersApi: {
|
|
|
914
909
|
* `isAuth` comes from the caller's auth context — this module is not a
|
|
915
910
|
* component and must not read context or an httpOnly cookie itself.
|
|
916
911
|
*
|
|
917
|
-
* When true the SDK posts to `/
|
|
912
|
+
* When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which
|
|
918
913
|
* derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`
|
|
919
914
|
* (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no
|
|
920
915
|
* such fields to carry them in. The request reaches that guarded route
|
|
@@ -1027,58 +1022,20 @@ interface PromotionDescriptionData {
|
|
|
1027
1022
|
*/
|
|
1028
1023
|
declare function getPromotionDescription(promotion: PromotionDescriptionData, locale?: string, currency?: string): string;
|
|
1029
1024
|
|
|
1030
|
-
declare const sdk:
|
|
1031
|
-
products: _ecomweb_sdk.ProductsApi;
|
|
1032
|
-
collections: _ecomweb_sdk.CollectionsApi;
|
|
1033
|
-
categories: _ecomweb_sdk.CategoriesApi;
|
|
1034
|
-
cart: _ecomweb_sdk.CartApi;
|
|
1035
|
-
orders: _ecomweb_sdk.OrdersApi;
|
|
1036
|
-
blog: _ecomweb_sdk.BlogApi;
|
|
1037
|
-
stores: _ecomweb_sdk.StoresApi;
|
|
1038
|
-
themes: _ecomweb_sdk.ThemesApi;
|
|
1039
|
-
metaobjects: _ecomweb_sdk.MetaobjectsApi;
|
|
1040
|
-
search: _ecomweb_sdk.SearchApi;
|
|
1041
|
-
shipping: _ecomweb_sdk.ShippingApi;
|
|
1042
|
-
promotions: _ecomweb_sdk.PromotionsApi;
|
|
1043
|
-
paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
|
|
1044
|
-
payments: _ecomweb_sdk.PaymentsApi;
|
|
1045
|
-
reviews: _ecomweb_sdk.ReviewsApi;
|
|
1046
|
-
customers: _ecomweb_sdk.CustomersApi;
|
|
1047
|
-
addresses: _ecomweb_sdk.AddressesApi;
|
|
1048
|
-
contentPages: _ecomweb_sdk.ContentPagesApi;
|
|
1049
|
-
menus: _ecomweb_sdk.MenusApi;
|
|
1050
|
-
redirects: _ecomweb_sdk.RedirectsApi;
|
|
1051
|
-
};
|
|
1025
|
+
declare const sdk: EcomwebSdk;
|
|
1052
1026
|
/**
|
|
1053
|
-
* SDK bound to one store,
|
|
1054
|
-
*
|
|
1055
|
-
*
|
|
1027
|
+
* SDK bound to one store, for the browser. Public calls go straight to the
|
|
1028
|
+
* API with the publishable key; every private call (cart, orders, payments,
|
|
1029
|
+
* customers, addresses, shopper-side blog, review and metaobject calls, rate
|
|
1030
|
+
* calculation, promotion validation) goes to the same-origin proxy at
|
|
1031
|
+
* `/store/<ref>/api/backend` (`/api/backend` on a single-store site), which
|
|
1032
|
+
* adds the storefront secret key and turns the httpOnly session cookie into a
|
|
1033
|
+
* bearer token. The secret key never reaches the browser.
|
|
1056
1034
|
*
|
|
1057
1035
|
* Memoised per store so the returned object is referentially stable and safe to
|
|
1058
1036
|
* use in a React dependency array.
|
|
1059
1037
|
*/
|
|
1060
|
-
declare function createStoreSdk(storeRef: string):
|
|
1061
|
-
products: _ecomweb_sdk.ProductsApi;
|
|
1062
|
-
collections: _ecomweb_sdk.CollectionsApi;
|
|
1063
|
-
categories: _ecomweb_sdk.CategoriesApi;
|
|
1064
|
-
cart: _ecomweb_sdk.CartApi;
|
|
1065
|
-
orders: _ecomweb_sdk.OrdersApi;
|
|
1066
|
-
blog: _ecomweb_sdk.BlogApi;
|
|
1067
|
-
stores: _ecomweb_sdk.StoresApi;
|
|
1068
|
-
themes: _ecomweb_sdk.ThemesApi;
|
|
1069
|
-
metaobjects: _ecomweb_sdk.MetaobjectsApi;
|
|
1070
|
-
search: _ecomweb_sdk.SearchApi;
|
|
1071
|
-
shipping: _ecomweb_sdk.ShippingApi;
|
|
1072
|
-
promotions: _ecomweb_sdk.PromotionsApi;
|
|
1073
|
-
paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
|
|
1074
|
-
payments: _ecomweb_sdk.PaymentsApi;
|
|
1075
|
-
reviews: _ecomweb_sdk.ReviewsApi;
|
|
1076
|
-
customers: _ecomweb_sdk.CustomersApi;
|
|
1077
|
-
addresses: _ecomweb_sdk.AddressesApi;
|
|
1078
|
-
contentPages: _ecomweb_sdk.ContentPagesApi;
|
|
1079
|
-
menus: _ecomweb_sdk.MenusApi;
|
|
1080
|
-
redirects: _ecomweb_sdk.RedirectsApi;
|
|
1081
|
-
};
|
|
1038
|
+
declare function createStoreSdk(storeRef: string): EcomwebServerSdk;
|
|
1082
1039
|
|
|
1083
1040
|
/**
|
|
1084
1041
|
* Renders a shipping option's price for display: the free label when the
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Client-safe hooks, providers and helpers for building a storefront on\n * ecomweb: `StorefrontKitProvider`, `useCart`, `useAuth`, `useCheckout`,\n * the store hooks, and price and order formatting.\n *\n * Import from `@ecomweb/storefront-kit` in components and pages. Server-only\n * code lives in `@ecomweb/storefront-kit/server`.\n *\n * @packageDocumentation\n */\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 {\n pickBankTransfer,\n shouldShowBankTransferDetails,\n useBankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n BankAccountView,\n BankTransferDetails,\n} from \"./orders/bank-transfer\";\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 {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\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 {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} 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 BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AAUA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP;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;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Client-safe hooks, providers and helpers for building a storefront on\n * ecomweb: `StorefrontKitProvider`, `useCart`, `useAuth`, `useCheckout`,\n * the store hooks, and price and order formatting.\n *\n * Import from `@ecomweb/storefront-kit` in components and pages. Server-only\n * code lives in `@ecomweb/storefront-kit/server`.\n *\n * @packageDocumentation\n */\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 {\n pickBankTransfer,\n shouldShowBankTransferDetails,\n useBankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n BankAccountView,\n BankTransferDetails,\n} from \"./orders/bank-transfer\";\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 {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\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 {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport type { EcomwebSdk, EcomwebServerSdk } from \"@ecomweb/sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} 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 BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AAUA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP;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;AAKjC,S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publicNextUrl } from "../request/public-url.js";
|
|
2
2
|
import { REQUEST_PATH_HEADER } from "../request/request-path.js";
|
|
3
|
+
import { SERVED_STORE_HEADER } from "../request/served-store.js";
|
|
3
4
|
import {
|
|
4
5
|
applyThemePreview,
|
|
5
6
|
hasThemePreview,
|
|
@@ -75,6 +76,7 @@ function withoutInternalHeaders(req) {
|
|
|
75
76
|
const headers = new Headers(req.headers);
|
|
76
77
|
headers.delete(THEME_PREVIEW_HOST_HEADER);
|
|
77
78
|
headers.delete(STORE_PREVIEW_TOKEN_HEADER);
|
|
79
|
+
headers.delete(SERVED_STORE_HEADER);
|
|
78
80
|
return { request: { headers } };
|
|
79
81
|
}
|
|
80
82
|
function hasStorePreview(req, cookiePath) {
|
|
@@ -86,6 +88,11 @@ function hostLookupPreviewToken(req) {
|
|
|
86
88
|
req.cookies.get(themePreviewCookieName("/"))?.value
|
|
87
89
|
);
|
|
88
90
|
}
|
|
91
|
+
function isLocalDevelopmentHost(host) {
|
|
92
|
+
if (process.env.NODE_ENV === "production") return false;
|
|
93
|
+
const hostname = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
|
|
94
|
+
return ["localhost", "127.0.0.1", "[::1]"].includes(hostname.toLowerCase());
|
|
95
|
+
}
|
|
89
96
|
function storeRefFromPath(pathname) {
|
|
90
97
|
const match = /^\/store\/([^/]+)/.exec(pathname);
|
|
91
98
|
if (!match) return null;
|
|
@@ -139,7 +146,8 @@ async function multiTenant(req) {
|
|
|
139
146
|
return NextResponse.next(withoutInternalHeaders(req));
|
|
140
147
|
}
|
|
141
148
|
const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
|
|
142
|
-
const
|
|
149
|
+
const isLocalDevHost = isLocalDevelopmentHost(host);
|
|
150
|
+
const hostIdentifiesStore = !isLocalDevHost && host !== platformDomain && host !== `www.${platformDomain}`;
|
|
143
151
|
const isPlatformApex = host === platformDomain || host === `www.${platformDomain}`;
|
|
144
152
|
if (isPlatformApex) {
|
|
145
153
|
const apexStoreRef = storeRefFromPath(pathname);
|
|
@@ -240,7 +248,10 @@ async function multiTenant(req) {
|
|
|
240
248
|
req,
|
|
241
249
|
!!hostStoreRef,
|
|
242
250
|
storeRef,
|
|
243
|
-
rotated
|
|
251
|
+
rotated,
|
|
252
|
+
// A store host's own lookup decides (none if it failed). Only the local
|
|
253
|
+
// dev host is path-based; anywhere else the path names no served store.
|
|
254
|
+
isLocalDevHost ? storeRefFromPath(pathname) : hostIdentifiesStore ? hostStoreRef : null
|
|
244
255
|
);
|
|
245
256
|
downstream.set(
|
|
246
257
|
REQUEST_PATH_HEADER,
|
|
@@ -309,7 +320,7 @@ async function singleStore(req) {
|
|
|
309
320
|
const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);
|
|
310
321
|
const response = NextResponse.next({
|
|
311
322
|
request: {
|
|
312
|
-
headers: downstreamRequestHeaders(req, true, storeRef, rotated)
|
|
323
|
+
headers: downstreamRequestHeaders(req, true, storeRef, rotated, storeRef)
|
|
313
324
|
}
|
|
314
325
|
});
|
|
315
326
|
if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\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\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n firstLivePreviewToken,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-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 * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`; an expired one yields to the other. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\n );\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 * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\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 return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\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 - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\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 const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\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 if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\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 if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\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 =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\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 (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\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 // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\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))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\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, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\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, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\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,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,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;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAOlC,MAAM,+BAA+B;AAcrC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MACE,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAChD,gBAAgB,KAAK,eAAe,UAAU,IAAI,CAAC;AAEnD,WAAO;AAET,QAAM,WAAW,IAAI,QAAQ;AAC7B,QAAM,SAAS,qBAAqB,QAAQ;AAC5C,QAAM,cACJ,aAAa,UAAU,SAAS,WAAW,GAAG,MAAM,GAAG,IACnD,SAAS,MAAM,OAAO,MAAM,KAAK,MACjC;AACN,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA,IAAI,QAAQ;AAAA,EACd;AACA,MAAI,CAAC,OAAQ,QAAO;AAEpB,MAAI,WAAW,MAAM,OAAO,Q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UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU,KAAK,gBAAgB,KAAK,UAAU;AACrE,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,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","response"]}
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport { SERVED_STORE_HEADER } from \"../request/served-store\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\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\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n firstLivePreviewToken,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-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 * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n headers.delete(SERVED_STORE_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`; an expired one yields to the other. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\n );\n}\n\n/**\n * Path-based dev access: only outside production, and only the host named\n * exactly `localhost`, `127.0.0.1` or `[::1]` (port ignored). A look-alike such\n * as `mylocalhostshop.com` is a store host, so a client cannot choose the\n * served store through the path there.\n */\nfunction isLocalDevelopmentHost(host: string): boolean {\n if (process.env.NODE_ENV === \"production\") return false;\n const hostname = host.startsWith(\"[\")\n ? host.slice(0, host.indexOf(\"]\") + 1)\n : host.split(\":\")[0];\n return [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname.toLowerCase());\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 * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\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 return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\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 - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\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 isLocalDevHost = isLocalDevelopmentHost(host);\n const hostIdentifiesStore =\n !isLocalDevHost &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\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 if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\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 if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\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 =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated,\n // A store host's own lookup decides (none if it failed). Only the local\n // dev host is path-based; anywhere else the path names no served store.\n isLocalDevHost\n ? storeRefFromPath(pathname)\n : hostIdentifiesStore\n ? hostStoreRef\n : null\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\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 (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\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 // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\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))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\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, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated, storeRef),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\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, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\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,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,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;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAOlC,MAAM,+BAA+B;AAcrC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MACE,IAAI,QAAQ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