@ecomweb/storefront-kit 0.14.0 → 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.
Files changed (90) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +39 -0
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/response.js.map +1 -1
  16. package/dist/api/server-sdk.js +41 -0
  17. package/dist/api/server-sdk.js.map +1 -0
  18. package/dist/api/store-preview-header.js.map +1 -1
  19. package/dist/auth/context.js.map +1 -1
  20. package/dist/auth/sdk.js +15 -5
  21. package/dist/auth/sdk.js.map +1 -1
  22. package/dist/auth/session-refresh.js +7 -4
  23. package/dist/auth/session-refresh.js.map +1 -1
  24. package/dist/cart/api.js.map +1 -1
  25. package/dist/cart/server-context.js.map +1 -1
  26. package/dist/checkout/get-payment-state.js +4 -8
  27. package/dist/checkout/get-payment-state.js.map +1 -1
  28. package/dist/checkout/initiate-gateway-payment.js +5 -7
  29. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  30. package/dist/checkout/order-handoff.js.map +1 -1
  31. package/dist/checkout/payment-redirect.js.map +1 -1
  32. package/dist/checkout/use-checkout.js.map +1 -1
  33. package/dist/client-info.js +1 -1
  34. package/dist/config/public.js +2 -0
  35. package/dist/config/public.js.map +1 -1
  36. package/dist/config/schema.js +16 -4
  37. package/dist/config/schema.js.map +1 -1
  38. package/dist/config/secret-guard.js +20 -0
  39. package/dist/config/secret-guard.js.map +1 -0
  40. package/dist/config/server.js +15 -8
  41. package/dist/config/server.js.map +1 -1
  42. package/dist/config/version-check.js.map +1 -1
  43. package/dist/config.d.ts +22 -4
  44. package/dist/config.js +2 -0
  45. package/dist/config.js.map +1 -1
  46. package/dist/currency.js.map +1 -1
  47. package/dist/index.d.ts +331 -69
  48. package/dist/index.js.map +1 -1
  49. package/dist/logging.js.map +1 -1
  50. package/dist/middleware/create-storefront-middleware.js +14 -3
  51. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  52. package/dist/middleware.d.ts +2 -2
  53. package/dist/middleware.js.map +1 -1
  54. package/dist/{mode-Lm9t4qzX.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  55. package/dist/orders/api-client.js +3 -3
  56. package/dist/orders/api-client.js.map +1 -1
  57. package/dist/orders/bank-transfer.js +1 -1
  58. package/dist/orders/bank-transfer.js.map +1 -1
  59. package/dist/orders/shipment-tracking.js.map +1 -1
  60. package/dist/orders/use-order-status.js +2 -2
  61. package/dist/orders/use-order-status.js.map +1 -1
  62. package/dist/promotions/use-promotion-validation.js +2 -2
  63. package/dist/promotions/use-promotion-validation.js.map +1 -1
  64. package/dist/provider.js.map +1 -1
  65. package/dist/request/served-store.js +5 -0
  66. package/dist/request/served-store.js.map +1 -0
  67. package/dist/{schema-Dg0ZflMW.d.ts → schema-B3nAYiwT.d.ts} +5 -1
  68. package/dist/sdk.js +3 -3
  69. package/dist/sdk.js.map +1 -1
  70. package/dist/server/routes.js +16 -9
  71. package/dist/server/routes.js.map +1 -1
  72. package/dist/server.d.ts +46 -5
  73. package/dist/server.js +2 -0
  74. package/dist/server.js.map +1 -1
  75. package/dist/shipping/location-areas.js.map +1 -1
  76. package/dist/shipping/use-shipping-calculation.js +2 -2
  77. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  78. package/dist/storage.js.map +1 -1
  79. package/dist/store/store-context.js.map +1 -1
  80. package/dist/store-scope/index.js.map +1 -1
  81. package/dist/stores/basic-settings.js.map +1 -1
  82. package/dist/stores/cached.js.map +1 -1
  83. package/dist/theme/define.js.map +1 -1
  84. package/dist/theme/index.js.map +1 -1
  85. package/dist/theme/settings-context.js.map +1 -1
  86. package/dist/theme/style.js.map +1 -1
  87. package/dist/theme.d.ts +33 -0
  88. package/package.json +6 -2
  89. package/dist/api/server-client.js +0 -162
  90. package/dist/api/server-client.js.map +0 -1
@@ -1,7 +1,11 @@
1
1
  import "server-only";
2
- import { NextResponse } from "next/server";
3
2
  import { redirect } from "next/navigation";
4
3
  import { handleBackendProxy } from "../api/proxy.js";
4
+ import {
5
+ isSameOriginRequest,
6
+ proxyNotFound,
7
+ servedStoreRef
8
+ } from "../api/proxy-guard.js";
5
9
  import { handleAuthRoute } from "../auth/route-handlers.js";
6
10
  import { getServerIdentity } from "../auth/session.js";
7
11
  import { resolveStoreRef } from "../store-scope/index.js";
@@ -12,18 +16,20 @@ async function storeRefFor(params) {
12
16
  }
13
17
  return resolveRootStoreRef();
14
18
  }
15
- function storeNotFound() {
16
- return NextResponse.json(
17
- { error: { message: "Store not found for host" } },
18
- { status: 404 }
19
- );
20
- }
21
19
  const segments = (v) => Array.isArray(v) ? v : v ? [v] : [];
20
+ function servesRouteStore(req, params) {
21
+ if (params.storeRef === void 0) return true;
22
+ return servedStoreRef(req) === params.storeRef;
23
+ }
22
24
  function createAuthRoutes() {
23
25
  const handle = async (req, { params }) => {
24
26
  const p = await params;
27
+ if (!servesRouteStore(req, p)) return proxyNotFound();
28
+ if (req.method !== "GET" && !isSameOriginRequest(req)) {
29
+ return proxyNotFound();
30
+ }
25
31
  const storeRef = await storeRefFor(p);
26
- if (!storeRef) return storeNotFound();
32
+ if (!storeRef) return proxyNotFound();
27
33
  return handleAuthRoute(req, storeRef, segments(p.route));
28
34
  };
29
35
  return { GET: handle, POST: handle };
@@ -31,8 +37,9 @@ function createAuthRoutes() {
31
37
  function createBackendProxy() {
32
38
  const handle = async (req, { params }) => {
33
39
  const p = await params;
40
+ if (!servesRouteStore(req, p)) return proxyNotFound();
34
41
  const storeRef = await storeRefFor(p);
35
- if (!storeRef) return storeNotFound();
42
+ if (!storeRef) return proxyNotFound();
36
43
  return handleBackendProxy(req, storeRef, segments(p.path));
37
44
  };
38
45
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\nimport { handleAuthRoute } from \"../auth/route-handlers\";\nimport { getServerIdentity } from \"../auth/session\";\nimport { resolveStoreRef } from \"../store-scope\";\nimport { resolveRootStoreRef } from \"../store-scope/root\";\n\ntype Params = Record<string, string | string[] | undefined>;\nexport type RouteContext = { params: Promise<Params> };\nexport type RouteHandler = (\n req: NextRequest,\n ctx: RouteContext\n) => Promise<Response>;\n\n/**\n * The store a route serves: the /store/<ref> segment when the route has one,\n * otherwise whatever the host (or, single-store, the config) names.\n */\nasync function storeRefFor(params: Params): Promise<string | null> {\n if (typeof params.storeRef === \"string\") {\n return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));\n }\n return resolveRootStoreRef();\n}\n\nfunction storeNotFound(): Response {\n return NextResponse.json(\n { error: { message: \"Store not found for host\" } },\n { status: 404 }\n );\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\n return handleAuthRoute(req, storeRef, segments(p.route));\n };\n return { GET: handle, POST: handle };\n}\n\n/**\n * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`\n * in api/backend/[...path].\n */\nexport function createBackendProxy(): Record<\n \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n RouteHandler\n> {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\n return handleBackendProxy(req, storeRef, segments(p.path));\n };\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n };\n}\n\nexport type CustomerIdentity = NonNullable<\n Awaited<ReturnType<typeof getServerIdentity>>\n>;\n\n/**\n * The signed-in customer, or a redirect to `redirectTo`. An anonymous\n * identity holds a valid token but no customer profile, so it redirects too.\n */\nexport async function requireSession(\n storeRef: string,\n redirectTo: string\n): Promise<CustomerIdentity> {\n const identity = await getServerIdentity(storeRef);\n if (!identity || identity.is_anonymous) redirect(redirectTo);\n return identity;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,oBAAsC;AAC/C,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAapC,eAAe,YAAY,QAAwC;AACjE,MAAI,OAAO,OAAO,aAAa,UAAU;AACvC,WAAO,gBAAgB,QAAQ,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;AAAA,EACvE;AACA,SAAO,oBAAoB;AAC7B;AAEA,SAAS,gBAA0B;AACjC,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,2BAA2B,EAAE;AAAA,IACjD,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAG7B,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,gBAAgB,KAAK,UAAU,SAAS,EAAE,KAAK,CAAC;AAAA,EACzD;AACA,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AAMO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,mBAAmB,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAUA,eAAsB,eACpB,UACA,YAC2B;AAC3B,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,MAAI,CAAC,YAAY,SAAS,aAAc,UAAS,UAAU;AAC3D,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport type { NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\nimport {\n isSameOriginRequest,\n proxyNotFound,\n servedStoreRef,\n} from \"../api/proxy-guard\";\nimport { handleAuthRoute } from \"../auth/route-handlers\";\nimport { getServerIdentity } from \"../auth/session\";\nimport { resolveStoreRef } from \"../store-scope\";\nimport { resolveRootStoreRef } from \"../store-scope/root\";\n\ntype Params = Record<string, string | string[] | undefined>;\nexport type RouteContext = { params: Promise<Params> };\nexport type RouteHandler = (\n req: NextRequest,\n ctx: RouteContext\n) => Promise<Response>;\n\n/**\n * The store a route serves: the /store/<ref> segment when the route has one,\n * otherwise whatever the host (or, single-store, the config) names.\n */\nasync function storeRefFor(params: Params): Promise<string | null> {\n if (typeof params.storeRef === \"string\") {\n return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));\n }\n return resolveRootStoreRef();\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/**\n * False when the route names a store (`/store/<ref>/...`) other than the one\n * the middleware stamped for this request, or when it stamped none. Routes\n * without the param take the store from the host or config instead.\n */\nfunction servesRouteStore(req: NextRequest, params: Params): boolean {\n if (params.storeRef === undefined) return true;\n return servedStoreRef(req) === params.storeRef;\n}\n\n/**\n * `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].\n * These routes sign every shopper-auth call with the storefront secret key,\n * so they answer 404 for a `/store/<ref>` other than the one this request\n * serves, and for any non-GET request that is not same-origin (GETs stay\n * open: Google's OAuth callback arrives cross-site).\n */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n if (req.method !== \"GET\" && !isSameOriginRequest(req)) {\n return proxyNotFound();\n }\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleAuthRoute(req, storeRef, segments(p.route));\n };\n return { GET: handle, POST: handle };\n}\n\n/**\n * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`\n * in api/backend/[...path]. It carries every private browser call under the\n * storefront secret key, so it forwards only same-origin calls to routes in\n * `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers\n * every other request 404 `NOT_FOUND`.\n */\nexport function createBackendProxy(): Record<\n \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n RouteHandler\n> {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleBackendProxy(req, storeRef, segments(p.path));\n };\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n };\n}\n\nexport type CustomerIdentity = NonNullable<\n Awaited<ReturnType<typeof getServerIdentity>>\n>;\n\n/**\n * The signed-in customer, or a redirect to `redirectTo`. An anonymous\n * identity holds a valid token but no customer profile, so it redirects too.\n */\nexport async function requireSession(\n storeRef: string,\n redirectTo: string\n): Promise<CustomerIdentity> {\n const identity = await getServerIdentity(storeRef);\n if (!identity || identity.is_anonymous) redirect(redirectTo);\n return identity;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAapC,eAAe,YAAY,QAAwC;AACjE,MAAI,OAAO,OAAO,aAAa,UAAU;AACvC,WAAO,gBAAgB,QAAQ,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;AAAA,EACvE;AACA,SAAO,oBAAoB;AAC7B;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAOpC,SAAS,iBAAiB,KAAkB,QAAyB;AACnE,MAAI,OAAO,aAAa,OAAW,QAAO;AAC1C,SAAO,eAAe,GAAG,MAAM,OAAO;AACxC;AASO,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,QAAI,IAAI,WAAW,SAAS,CAAC,oBAAoB,GAAG,GAAG;AACrD,aAAO,cAAc;AAAA,IACvB;AACA,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,gBAAgB,KAAK,UAAU,SAAS,EAAE,KAAK,CAAC;AAAA,EACzD;AACA,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AASO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,mBAAmB,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAUA,eAAsB,eACpB,UACA,YAC2B;AAC3B,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,MAAI,CAAC,YAAY,SAAS,aAAc,UAAS,UAAU;AAC3D,SAAO;AACT;","names":[]}
package/dist/server.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { NextRequest } from 'next/server';
2
- import { CurrentIdentity } from '@ecomweb/sdk';
3
- import { E as EnvSource, S as ServerConfig } from './schema-Dg0ZflMW.js';
2
+ import { CurrentIdentity, EcomwebServerSdk } from '@ecomweb/sdk';
3
+ export { EcomwebSdk, EcomwebServerSdk } from '@ecomweb/sdk';
4
+ import { E as EnvSource, S as ServerConfig } from './schema-B3nAYiwT.js';
4
5
  import 'zod';
5
6
 
6
7
  /**
@@ -27,14 +28,23 @@ type RouteContext = {
27
28
  params: Promise<Params>;
28
29
  };
29
30
  type RouteHandler = (req: NextRequest, ctx: RouteContext) => Promise<Response>;
30
- /** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */
31
+ /**
32
+ * `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].
33
+ * These routes sign every shopper-auth call with the storefront secret key,
34
+ * so they answer 404 for a `/store/<ref>` other than the one this request
35
+ * serves, and for any non-GET request that is not same-origin (GETs stay
36
+ * open: Google's OAuth callback arrives cross-site).
37
+ */
31
38
  declare function createAuthRoutes(): {
32
39
  GET: RouteHandler;
33
40
  POST: RouteHandler;
34
41
  };
35
42
  /**
36
43
  * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`
37
- * in api/backend/[...path].
44
+ * in api/backend/[...path]. It carries every private browser call under the
45
+ * storefront secret key, so it forwards only same-origin calls to routes in
46
+ * `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers
47
+ * every other request 404 `NOT_FOUND`.
38
48
  */
39
49
  declare function createBackendProxy(): Record<"GET" | "POST" | "PUT" | "PATCH" | "DELETE", RouteHandler>;
40
50
  type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>>>;
@@ -44,8 +54,39 @@ type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>
44
54
  */
45
55
  declare function requireSession(storeRef: string, redirectTo: string): Promise<CustomerIdentity>;
46
56
 
57
+ /**
58
+ * The server SDK for the current request, signed with the storefront secret
59
+ * key, for private reads in server components and route handlers (for example
60
+ * a review invitation by token). The shopper's IP and the store preview token
61
+ * are taken from the request.
62
+ *
63
+ * Shopper-side methods (cart, orders, addresses and the like) do not work
64
+ * here: a server has no shopper session, so they reject with
65
+ * `SDK_SHOPPER_CALL_ON_SERVER`. Use `createStoreSdk(storeRef)` in the browser.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { getServerSdk } from "@ecomweb/storefront-kit/server";
70
+ *
71
+ * const sdk = await getServerSdk();
72
+ * const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);
73
+ * ```
74
+ *
75
+ * @returns The server SDK for this request
76
+ * @throws Error when the storefront secret key is not set
77
+ */
78
+ declare function getServerSdk(): Promise<EcomwebServerSdk>;
79
+
47
80
  /** Parses the variables of the mode `env` selects (see resolveMode). */
48
81
  declare function parseServerConfig(env: EnvSource): ServerConfig;
82
+ /**
83
+ * The server's parsed configuration, read from the environment on the first
84
+ * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`
85
+ * in server code, never in a client component.
86
+ *
87
+ * @returns The validated server config.
88
+ * @throws ConfigError when a required variable is missing or invalid.
89
+ */
49
90
  declare function serverConfig(): ServerConfig;
50
91
 
51
92
  /**
@@ -101,4 +142,4 @@ declare function resolveComingSoonStore(): Promise<{
101
142
  name: string | null;
102
143
  } | null>;
103
144
 
104
- export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
145
+ export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, getServerSdk, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  createBackendProxy,
5
5
  requireSession
6
6
  } from "./server/routes.js";
7
+ import { getServerSdk } from "./api/server-sdk.js";
7
8
  import { hasCustomerSession } from "./auth/session.js";
8
9
  import { parseServerConfig, serverConfig } from "./config/server.js";
9
10
  import { resolveRootStoreRef } from "./store-scope/root.js";
@@ -16,6 +17,7 @@ export {
16
17
  createAuthRoutes,
17
18
  createBackendProxy,
18
19
  externalThemeRedirectFor,
20
+ getServerSdk,
19
21
  hasCustomerSession,
20
22
  parseServerConfig,
21
23
  readPreviewHostSlug,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-only route handlers and helpers: the auth routes, the backend proxy,\n * session checks and the server config.\n *\n * Import from `@ecomweb/storefront-kit/server` in route handlers and server\n * components only; the entry imports `server-only` and fails in a client\n * bundle.\n *\n * @packageDocumentation\n */\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { getServerSdk } from \"./api/server-sdk\";\nexport type { EcomwebSdk, EcomwebServerSdk } from \"@ecomweb/sdk\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AAUA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/location-areas.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { LocationArea, LocationAreasResponse } from \"@ecomweb/sdk\";\nimport { LEVEL_PROVINCE } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Location data is fetched in two steps rather than all at once: the 34\n * provinces up front, then one province's wards when something actually\n * needs them. Fetching everything cost 751 KB and every ward in the\n * country on a page that shows at most one province's worth.\n *\n * Caches hold the in-flight promise, not just the result, so concurrent\n * callers (a checkout page mounts several) share one request. A failure\n * is evicted so it is never cached.\n */\ntype Fetcher = (\n storeRef: string,\n query: { level?: number; parent_code?: string }\n) => Promise<LocationAreasResponse>;\n\nconst defaultFetcher: Fetcher = (storeRef, query) =>\n sdk.shipping.listLocationAreas(storeRef, query);\n\nconst provinceCache = new Map<string, Promise<LocationArea[]>>();\nconst wardCache = new Map<string, Promise<LocationArea[]>>();\n\n/** Test seam. Never called by application code. */\nexport function __resetLocationCaches() {\n provinceCache.clear();\n wardCache.clear();\n}\n\nexport function loadProvinces(\n storeRef: string,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n let pending = provinceCache.get(storeRef);\n if (!pending) {\n pending = fetcher(storeRef, { level: LEVEL_PROVINCE })\n .then(r => r.areas)\n .catch(error => {\n provinceCache.delete(storeRef);\n throw error;\n });\n provinceCache.set(storeRef, pending);\n }\n return pending;\n}\n\nexport function loadWards(\n storeRef: string,\n provinceCode: string | undefined,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n if (!provinceCode) return Promise.resolve([]);\n\n const key = `${storeRef}:${provinceCode}`;\n let pending = wardCache.get(key);\n if (!pending) {\n pending = fetcher(storeRef, { parent_code: provinceCode })\n .then(r => r.areas)\n .catch(error => {\n wardCache.delete(key);\n throw error;\n });\n wardCache.set(key, pending);\n }\n return pending;\n}\n\nexport function useProvinces(storeRef: string) {\n const [provinces, setProvinces] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n loadProvinces(storeRef)\n .then(areas => {\n if (!cancelled) setProvinces(areas);\n })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load provinces:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef]);\n\n return { provinces, loading };\n}\n\nexport function useWards(storeRef: string, provinceCode: string | undefined) {\n const [wards, setWards] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(false);\n\n useEffect(() => {\n // Drop the previous province's wards up front. Keeping them until the\n // new list arrives leaves wards from the wrong province selectable,\n // and on a failed request it leaves them there for good.\n setWards([]);\n\n if (!provinceCode) {\n setLoading(false);\n return;\n }\n let cancelled = false;\n setLoading(true);\n loadWards(storeRef, provinceCode)\n .then(areas => {\n if (!cancelled) setWards(areas);\n })\n .catch(error => {\n if (!cancelled) setWards([]);\n // eslint-disable-next-line no-console\n console.error(\"Failed to load wards:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef, provinceCode]);\n\n return { wards, loading };\n}\n\n/**\n * The string a combobox filters on. cmdk matches against a CommandItem's\n * `value`, so putting the code there alone meant a shopper had to type\n * \"12\" to find Hồ Chí Minh. This puts the names in, plus the slug with\n * its hyphens spaced out so typing without accents (\"ho chi minh\") still\n * matches. The code stays searchable for anyone who knows it.\n */\nexport function searchTextFor(area: LocationArea): string {\n return [\n area.name_with_type,\n area.name,\n (area.slug || \"\").replace(/-/g, \" \"),\n area.code,\n ]\n .filter(Boolean)\n .join(\" \");\n}\n\n/** Look up one area by code within a list, for display labels. */\nexport function byCode(areas: LocationArea[], code: string | undefined) {\n if (!code) return undefined;\n return areas.find(area => area.code === code);\n}\n\nexport function useAreaLabel(areas: LocationArea[], code: string | undefined) {\n return useMemo(() => byCode(areas, code), [areas, code]);\n}\n"],"mappings":";AAEA,SAAS,WAAW,SAAS,gBAAgB;AAE7C,SAAS,sBAAsB;AAC/B,SAAS,WAAW;AAiBpB,MAAM,iBAA0B,CAAC,UAAU,UACzC,IAAI,SAAS,kBAAkB,UAAU,KAAK;AAEhD,MAAM,gBAAgB,oBAAI,IAAqC;AAC/D,MAAM,YAAY,oBAAI,IAAqC;AAGpD,SAAS,wBAAwB;AACtC,gBAAc,MAAM;AACpB,YAAU,MAAM;AAClB;AAEO,SAAS,cACd,UACA,UAAmB,gBACM;AACzB,MAAI,UAAU,cAAc,IAAI,QAAQ;AACxC,MAAI,CAAC,SAAS;AACZ,cAAU,QAAQ,UAAU,EAAE,OAAO,eAAe,CAAC,EAClD,KAAK,OAAK,EAAE,KAAK,EACjB,MAAM,WAAS;AACd,oBAAc,OAAO,QAAQ;AAC7B,YAAM;AAAA,IACR,CAAC;AACH,kBAAc,IAAI,UAAU,OAAO;AAAA,EACrC;AACA,SAAO;AACT;AAEO,SAAS,UACd,UACA,cACA,UAAmB,gBACM;AACzB,MAAI,CAAC,aAAc,QAAO,QAAQ,QAAQ,CAAC,CAAC;AAE5C,QAAM,MAAM,GAAG,QAAQ,IAAI,YAAY;AACvC,MAAI,UAAU,UAAU,IAAI,GAAG;AAC/B,MAAI,CAAC,SAAS;AACZ,cAAU,QAAQ,UAAU,EAAE,aAAa,aAAa,CAAC,EACtD,KAAK,OAAK,EAAE,KAAK,EACjB,MAAM,WAAS;AACd,gBAAU,OAAO,GAAG;AACpB,YAAM;AAAA,IACR,CAAC;AACH,cAAU,IAAI,KAAK,OAAO;AAAA,EAC5B;AACA,SAAO;AACT;AAEO,SAAS,aAAa,UAAkB;AAC7C,QAAM,CAAC,WAAW,YAAY,IAAI,SAAyB,CAAC,CAAC;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAE3C,YAAU,MAA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SAAS,OAAO,OAAuB,MAA0B;AACtE,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,MAAM,KAAK,UAAQ,KAAK,SAAS,IAAI;AAC9C;AAEO,SAAS,aAAa,OAAuB,MAA0B;AAC5E,SAAO,QAAQ,MAAM,OAAO,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC;AACzD;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/location-areas.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { LocationArea, LocationAreasResponse } from \"@ecomweb/sdk\";\nimport { LEVEL_PROVINCE } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Location data is fetched in two steps rather than all at once: the 34\n * provinces up front, then one province's wards when something actually\n * needs them. Fetching everything cost 751 KB and every ward in the\n * country on a page that shows at most one province's worth.\n *\n * Caches hold the in-flight promise, not just the result, so concurrent\n * callers (a checkout page mounts several) share one request. A failure\n * is evicted so it is never cached.\n */\ntype Fetcher = (\n storeRef: string,\n query: { level?: number; parent_code?: string }\n) => Promise<LocationAreasResponse>;\n\nconst defaultFetcher: Fetcher = (storeRef, query) =>\n sdk.shipping.listLocationAreas(storeRef, query);\n\nconst provinceCache = new Map<string, Promise<LocationArea[]>>();\nconst wardCache = new Map<string, Promise<LocationArea[]>>();\n\n/** Test seam. Never called by application code. */\nexport function __resetLocationCaches() {\n provinceCache.clear();\n wardCache.clear();\n}\n\nexport function loadProvinces(\n storeRef: string,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n let pending = provinceCache.get(storeRef);\n if (!pending) {\n pending = fetcher(storeRef, { level: LEVEL_PROVINCE })\n .then(r => r.areas)\n .catch(error => {\n provinceCache.delete(storeRef);\n throw error;\n });\n provinceCache.set(storeRef, pending);\n }\n return pending;\n}\n\n/**\n * Loads the wards of a province. Results are cached per store and province,\n * and a failed request is not cached.\n *\n * @param storeRef - The store's ref.\n * @param provinceCode - The province to list wards for.\n * @param fetcher - Replaces the request that loads the areas (tests).\n * @returns The wards, or an empty list when `provinceCode` is empty.\n */\nexport function loadWards(\n storeRef: string,\n provinceCode: string | undefined,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n if (!provinceCode) return Promise.resolve([]);\n\n const key = `${storeRef}:${provinceCode}`;\n let pending = wardCache.get(key);\n if (!pending) {\n pending = fetcher(storeRef, { parent_code: provinceCode })\n .then(r => r.areas)\n .catch(error => {\n wardCache.delete(key);\n throw error;\n });\n wardCache.set(key, pending);\n }\n return pending;\n}\n\n/**\n * Loads the store's provinces for an address form. Needs no provider; the\n * list is cached per store.\n *\n * @param storeRef - The store's ref.\n * @returns `provinces`, the list loaded so far, and `loading`, `true` until the first request ends.\n */\nexport function useProvinces(storeRef: string) {\n const [provinces, setProvinces] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n loadProvinces(storeRef)\n .then(areas => {\n if (!cancelled) setProvinces(areas);\n })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load provinces:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef]);\n\n return { provinces, loading };\n}\n\n/**\n * Loads the wards of the selected province for an address form. The list is\n * emptied while a new province loads. Needs no provider.\n *\n * @param storeRef - The store's ref.\n * @param provinceCode - The selected province; wards load only once it is set.\n * @returns `wards`, the list for that province, and `loading`.\n */\nexport function useWards(storeRef: string, provinceCode: string | undefined) {\n const [wards, setWards] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(false);\n\n useEffect(() => {\n // Drop the previous province's wards up front. Keeping them until the\n // new list arrives leaves wards from the wrong province selectable,\n // and on a failed request it leaves them there for good.\n setWards([]);\n\n if (!provinceCode) {\n setLoading(false);\n return;\n }\n let cancelled = false;\n setLoading(true);\n loadWards(storeRef, provinceCode)\n .then(areas => {\n if (!cancelled) setWards(areas);\n })\n .catch(error => {\n if (!cancelled) setWards([]);\n // eslint-disable-next-line no-console\n console.error(\"Failed to load wards:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef, provinceCode]);\n\n return { wards, loading };\n}\n\n/**\n * The string a combobox filters on. cmdk matches against a CommandItem's\n * `value`, so putting the code there alone meant a shopper had to type\n * \"12\" to find Hồ Chí Minh. This puts the names in, plus the slug with\n * its hyphens spaced out so typing without accents (\"ho chi minh\") still\n * matches. The code stays searchable for anyone who knows it.\n */\nexport function searchTextFor(area: LocationArea): string {\n return [\n area.name_with_type,\n area.name,\n (area.slug || \"\").replace(/-/g, \" \"),\n area.code,\n ]\n .filter(Boolean)\n .join(\" \");\n}\n\n/** Look up one area by code within a list, for display labels. */\nexport function byCode(areas: LocationArea[], code: string | undefined) {\n if (!code) return undefined;\n return areas.find(area => area.code === code);\n}\n\nexport function useAreaLabel(areas: LocationArea[], code: string | undefined) {\n return useMemo(() => byCode(areas, code), [areas, code]);\n}\n"],"mappings":";AAEA,SAAS,WAAW,SAAS,gBAAgB;AAE7C,SAAS,sBAAsB;AAC/B,SAAS,WAAW;AAiBpB,MAAM,iBAA0B,CAAC,UAAU,UACzC,IAAI,SAAS,kBAAkB,UAAU,KAAK;AAEhD,MAAM,gBAAgB,oBAAI,IAAqC;AAC/D,MAAM,YAAY,oBAAI,IAAqC;AAGpD,SAAS,wBAAwB;AACtC,gBAAc,MAAM;AACpB,YAAU,MAAM;AAClB;AAEO,SAAS,cACd,UACA,UAAmB,gBACM;AACzB,MAAI,UAAU,cAAc,IAAI,QAAQ;AACxC,MAAI,CAAC,SAAS;AACZ,cAAU,QAAQ,UAAU,EAAE,OAAO,eAAe,CAAC,EAClD,KAAK,OAAK,EAAE,KAAK,EACjB,MAAM,WAAS;AACd,oBAAc,OAAO,QAAQ;AAC7B,YAAM;AAAA,IACR,CAAC;AACH,kBAAc,IAAI,UAAU,OAAO;AAAA,EACrC;AACA,SAAO;AACT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K,WAAS;AACb,UAAI,CAAC,UAAW,UAAS,KAAK;AAAA,IAChC,CAAC,EACA,MAAM,WAAS;AACd,UAAI,CAAC,UAAW,UAAS,CAAC,CAAC;AAE3B,cAAQ,MAAM,yBAAyB,KAAK;AAAA,IAC9C,CAAC,EACA,QAAQ,MAAM;AACb,UAAI,CAAC,UAAW,YAAW,KAAK;AAAA,IAClC,CAAC;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,UAAU,YAAY,CAAC;AAE3B,SAAO,EAAE,OAAO,QAAQ;AAC1B;AASO,SAAS,cAAc,MAA4B;AACxD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,KACJ,KAAK,QAAQ,IAAI,QAAQ,MAAM,GAAG;AAAA,IACnC,KAAK;AAAA,EACP,EACG,OAAO,OAAO,EACd,KAAK,GAAG;AACb;AAGO,SAAS,OAAO,OAAuB,MAA0B;AACtE,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,MAAM,KAAK,UAAQ,KAAK,SAAS,IAAI;AAC9C;AAEO,SAAS,aAAa,OAAuB,MAA0B;AAC5E,SAAO,QAAQ,MAAM,OAAO,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC;AACzD;","names":[]}
@@ -1,4 +1,4 @@
1
- import { sdk } from "../sdk.js";
1
+ import { createStoreSdk } from "../sdk.js";
2
2
  import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
3
3
  import { SHIPPING_MESSAGES } from "./messages.js";
4
4
  import { useNotify } from "../notices.js";
@@ -42,7 +42,7 @@ function useShippingCalculation({
42
42
  const next = stateRef.current.requestId + 1;
43
43
  dispatch({ type: "CALCULATION_STARTED" });
44
44
  try {
45
- const options = await sdk.shipping.calculate(storeRef, {
45
+ const options = await createStoreSdk(storeRef).shipping.calculate(storeRef, {
46
46
  province_id: city,
47
47
  ward_id: ward,
48
48
  subtotal,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { isStoreComingSoonError } from \"../stores/store-coming-soon\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // A store preview is read-only and the API refuses this POST with\n // STORE_COMING_SOON, which would show as a shipping error. Say it is a\n // preview instead, like the cart and checkout writes do.\n if (isBrowserStorePreview()) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n if (isStoreComingSoonError(error)) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAA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,CAAC;AAGD,YAAU,MAAM;AACd,UAAM,YAAY,WAAW,MAAM;AACjC,2BAAqB;AAAA,IACvB,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,QAAM,6BAA6B,YAAY,CAAC,aAAqB;AACnE,aAAS,EAAE,MAAM,mBAAmB,SAAS,CAAC;AAAA,EAChD,GAAG,CAAC,CAAC;AAEL,QAAM,iBAAiB;AAAA,IACrB,CACE,SACA,gBACA,cACG;AACH,eAAS,EAAE,MAAM,kBAAkB,SAAS,WAAW,eAAe,CAAC;AAAA,IACzE;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,YAAY,MAAM,SAAS,QAAQ,WAAW,CAAC,CAAC;AAEzE,QAAM,iBAAiB;AAAA,IACrB,MACE,MAAM,qBAAqB,OACvB,OACC,MAAM,gBAAgB;AAAA,MACrB,OAAK,WAAW,CAAC,MAAM,MAAM;AAAA,IAC/B,KAAK;AAAA,IACX,CAAC,MAAM,iBAAiB,MAAM,gBAAgB;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { isStoreComingSoonError } from \"../stores/store-coming-soon\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // A store preview is read-only and the API refuses this POST with\n // STORE_COMING_SOON, which would show as a shipping error. Say it is a\n // preview instead, like the cart and checkout writes do.\n if (isBrowserStorePreview()) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await createStoreSdk(storeRef).shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n if (isStoreComingSoonError(error)) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAC/B,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YA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M,YAAY,WAAW,MAAM;AACjC,2BAAqB;AAAA,IACvB,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,QAAM,6BAA6B,YAAY,CAAC,aAAqB;AACnE,aAAS,EAAE,MAAM,mBAAmB,SAAS,CAAC;AAAA,EAChD,GAAG,CAAC,CAAC;AAEL,QAAM,iBAAiB;AAAA,IACrB,CACE,SACA,gBACA,cACG;AACH,eAAS,EAAE,MAAM,kBAAkB,SAAS,WAAW,eAAe,CAAC;AAAA,IACzE;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,YAAY,MAAM,SAAS,QAAQ,WAAW,CAAC,CAAC;AAEzE,QAAM,iBAAiB;AAAA,IACrB,MACE,MAAM,qBAAqB,OACvB,OACC,MAAM,gBAAgB;AAAA,MACrB,OAAK,WAAW,CAAC,MAAM,MAAM;AAAA,IAC/B,KAAK;AAAA,IACX,CAAC,MAAM,iBAAiB,MAAM,gBAAgB;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["// ---------------------------------------------\n// Image URL helpers\n// ---------------------------------------------\n//\n// The storefront does not talk to a storage SDK. Object URLs are plain strings,\n// so there was nothing here a client library was needed for: getPublicUrl()\n// only ever concatenated base + bucket + path.\n//\n// Everything is built against NEXT_PUBLIC_ASSET_BASE_URL, which points at our\n// own API (e.g. https://apibase.ecomweb.app). The path shapes below are the\n// ones the API serves and the ones already stored in the database.\n//\n// Crucially, a stored URL's ORIGIN is ignored and rebuilt. Rows written before\n// the storage migration carry whatever host was configured at the time —\n// locally that is Kong on :8000, or an older Supabase on :54321 — and those\n// hosts no longer serve anything. Rebuilding is what lets old and new rows\n// resolve identically with no database backfill.\n//\n// The browser-side upload/delete helpers that used to live here wrote directly\n// to supabase/storage-api, which has been retired. They had no callers and were\n// removed; uploads go through the API's asset endpoints.\n\nconst OBJECT_PREFIX = \"/storage/v1/object/public/\";\nimport { publicConfig } from \"./config\";\nconst RENDER_PREFIX = \"/storage/v1/render/image/public/\";\n\nconst DEFAULT_BUCKET = \"public-cdn\";\n\ntype ResizeMode = \"cover\" | \"contain\" | \"inside\" | \"outside\";\ntype ImageFormat = \"origin\" | \"avif\" | \"webp\" | \"png\" | \"jpeg\";\n\nexport interface ImageTransformOptions {\n width?: number;\n height?: number;\n resize?: ResizeMode; // default: cover\n quality?: number; // 1..100, default: 80\n format?: ImageFormat; // default: origin\n}\n\nfunction assetBaseUrl(): string {\n return publicConfig().assetBaseUrl;\n}\n\nfunction transformationsEnabled(): boolean {\n const flag = publicConfig().imageTransformationsFlag;\n if (typeof flag === \"string\" && flag !== \"\") {\n return [\"1\", \"true\", \"yes\", \"on\"].includes(flag.toLowerCase());\n }\n // Local stacks may not run the image renderer, so serve originals.\n return !/localhost|127\\.0\\.0\\.1/.test(assetBaseUrl());\n}\n\nfunction buildTransformQuery(opts?: ImageTransformOptions): string {\n if (!opts) return \"\";\n const params = new URLSearchParams();\n if (opts.width && Number.isFinite(opts.width))\n params.set(\"width\", String(opts.width));\n if (opts.height && Number.isFinite(opts.height))\n params.set(\"height\", String(opts.height));\n if (opts.resize) params.set(\"resize\", opts.resize);\n if (opts.quality && Number.isFinite(opts.quality))\n params.set(\"quality\", String(opts.quality));\n if (opts.format) params.set(\"format\", opts.format);\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\n/**\n * Pull bucket + object path out of a storage URL, whatever host it names.\n * Accepts both the object and render path shapes.\n */\nfunction parseStorageUrl(\n url: string\n): { bucket: string; path: string } | null {\n try {\n const { pathname } = new URL(url);\n const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find((p) =>\n pathname.includes(p)\n );\n if (!prefix) return null;\n\n const parts = pathname.split(prefix)[1].split(\"/\");\n const bucket = parts.shift();\n if (!bucket || parts.length === 0) return null;\n\n return { bucket, path: parts.join(\"/\") };\n } catch {\n return null;\n }\n}\n\nfunction buildAssetUrl(\n bucket: string,\n path: string,\n opts?: ImageTransformOptions\n): string | null {\n const base = assetBaseUrl();\n if (!base) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[storage] NEXT_PUBLIC_ASSET_BASE_URL is not set — image URLs cannot be resolved.\"\n );\n }\n return null;\n }\n\n const normalizedPath = path.replace(/^\\//, \"\");\n\n if (transformationsEnabled()) {\n const query = buildTransformQuery({ resize: \"cover\", quality: 80, ...opts });\n return `${base}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;\n }\n\n return `${base}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;\n}\n\n/**\n * Resolve any image reference (full URL or bare storage object path) into a\n * URL, applying transformation params when enabled.\n *\n * - A full http(s) URL that is not a storage URL is returned as-is.\n * - A storage URL is rebuilt against the configured base, ignoring its host.\n * - A bare object path is resolved within `defaultBucket`.\n */\nexport function resolveTransformedImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions,\n defaultBucket: \"public-cdn\" = DEFAULT_BUCKET\n): string | null {\n if (!imagePathOrUrl) return null;\n\n if (/^https?:\\/\\//i.test(imagePathOrUrl)) {\n const parsed = parseStorageUrl(imagePathOrUrl);\n if (!parsed) return imagePathOrUrl;\n return buildAssetUrl(parsed.bucket, parsed.path, opts) ?? imagePathOrUrl;\n }\n\n // Starts with / -> a local app asset, not storage. Leave untouched.\n if (imagePathOrUrl.startsWith(\"/\")) {\n return imagePathOrUrl;\n }\n\n return buildAssetUrl(defaultBucket, imagePathOrUrl, opts);\n}\n\n/** Object URL without any transformation. */\nfunction resolveObjectUrl(\n imagePath: string | null | undefined\n): string | null {\n if (!imagePath) return null;\n\n if (imagePath.startsWith(\"http://\") || imagePath.startsWith(\"https://\")) {\n const parsed = parseStorageUrl(imagePath);\n if (!parsed) return imagePath;\n const base = assetBaseUrl();\n return base\n ? `${base}${OBJECT_PREFIX}${parsed.bucket}/${parsed.path}`\n : imagePath;\n }\n\n if (imagePath.startsWith(\"/\")) return imagePath;\n\n const base = assetBaseUrl();\n return base ? `${base}${OBJECT_PREFIX}${DEFAULT_BUCKET}/${imagePath}` : null;\n}\n\nexport function resolvePublicUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\nexport function resolveStoreLogoUrl(\n logoPath: string | null | undefined\n): string | null {\n return resolveObjectUrl(logoPath);\n}\n\nexport function resolveBlogUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\n// Convenience wrappers with sensible defaults per bucket\nexport function resolveTransformedProductImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\nexport function resolveTransformedStoreLogoUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\nexport function resolveTransformedBlogUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\n/**\n * Null-safe wrapper for use directly in `src={...}`.\n *\n * Rebuilds against the current NEXT_PUBLIC_ASSET_BASE_URL regardless of the\n * stored host, and passes non-storage URLs through untouched.\n */\nexport function resolveAssetSrc(\n url: string | null | undefined,\n opts?: ImageTransformOptions\n): string {\n return resolveTransformedImageUrl(url, opts) ?? \"\";\n}\n"],"mappings":"AAsBA,MAAM,gBAAgB;AACtB,SAAS,oBAAoB;AAC7B,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB;AAavB,SAAS,eAAuB;AAC9B,SAAO,aAAa,EAAE;AACxB;AAEA,SAAS,yBAAkC;AACzC,QAAM,OAAO,aAAa,EAAE;AAC5B,MAAI,OAAO,SAAS,YAAY,SAAS,IAAI;AAC3C,WAAO,CAAC,KAAK,QAAQ,OAAO,IAAI,EAAE,SAAS,KAAK,YAAY,CAAC;AAAA,EAC/D;AAEA,SAAO,CAAC,yBAAyB,KAAK,aAAa,CAAC;AACtD;AAEA,SAAS,oBAAoB,MAAsC;AACjE,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,SAAS,IAAI,gBAAgB;AACnC,MAAI,KAAK,SAAS,OAAO,SAAS,KAAK,KAAK;AAC1C,WAAO,IAAI,SAAS,OAAO,KAAK,KAAK,CAAC;AACxC,MAAI,KAAK,UAAU,OAAO,SAAS,KAAK,MAAM;AAC5C,WAAO,IAAI,UAAU,OAAO,KAAK,MAAM,CAAC;AAC1C,MAAI,KAAK,OAAQ,QAAO,IAAI,UAAU,KAAK,MAAM;AACjD,MAAI,KAAK,WAAW,OAAO,SAAS,KAAK,OAAO;AAC9C,WAAO,IAAI,WAAW,OAAO,KAAK,OAAO,CAAC;AAC5C,MAAI,KAAK,OAAQ,QAAO,IAAI,UAAU,KAAK,MAAM;AACjD,QAAM,KAAK,OAAO,SAAS;AAC3B,SAAO,KAAK,IAAI,EAAE,KAAK;AACzB;AAMA,SAAS,gBACP,KACyC;AACzC,MAAI;AACF,UAAM,EAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAChC,UAAM,SAAS,CAAC,eAAe,aAAa,EAAE;AAAA,M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AAU,WAAW,SAAS,KAAK,UAAU,WAAW,UAAU,GAAG;AACvE,UAAM,SAAS,gBAAgB,SAAS;AACxC,QAAI,CAAC,OAAQ,QAAO;AACpB,UAAMA,QAAO,aAAa;AAC1B,WAAOA,QACH,GAAGA,KAAI,GAAG,aAAa,GAAG,OAAO,MAAM,IAAI,OAAO,IAAI,KACtD;AAAA,EACN;AAEA,MAAI,UAAU,WAAW,GAAG,EAAG,QAAO;AAEtC,QAAM,OAAO,aAAa;AAC1B,SAAO,OAAO,GAAG,IAAI,GAAG,aAAa,GAAG,cAAc,IAAI,SAAS,KAAK;AAC1E;AAEO,SAAS,iBACd,WACe;AACf,SAAO,iBAAiB,SAAS;AACnC;AAEO,SAAS,oBACd,UACe;AACf,SAAO,iBAAiB,QAAQ;AAClC;AAEO,SAAS,eACd,WACe;AACf,SAAO,iBAAiB,SAAS;AACnC;AAGO,SAAS,kCACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AAEO,SAAS,+BACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AAEO,SAAS,0BACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AAQO,SAAS,gBACd,KACA,MACQ;AACR,SAAO,2BAA2B,KAAK,IAAI,KAAK;AAClD;","names":["base"]}
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["// ---------------------------------------------\n// Image URL helpers\n// ---------------------------------------------\n//\n// The storefront does not talk to a storage SDK. Object URLs are plain strings,\n// so there was nothing here a client library was needed for: getPublicUrl()\n// only ever concatenated base + bucket + path.\n//\n// Everything is built against NEXT_PUBLIC_ASSET_BASE_URL, which points at our\n// own API (e.g. https://apibase.ecomweb.app). The path shapes below are the\n// ones the API serves and the ones already stored in the database.\n//\n// Crucially, a stored URL's ORIGIN is ignored and rebuilt. Rows written before\n// the storage migration carry whatever host was configured at the time —\n// locally that is Kong on :8000, or an older Supabase on :54321 — and those\n// hosts no longer serve anything. Rebuilding is what lets old and new rows\n// resolve identically with no database backfill.\n//\n// The browser-side upload/delete helpers that used to live here wrote directly\n// to supabase/storage-api, which has been retired. They had no callers and were\n// removed; uploads go through the API's asset endpoints.\n\nconst OBJECT_PREFIX = \"/storage/v1/object/public/\";\nimport { publicConfig } from \"./config\";\nconst RENDER_PREFIX = \"/storage/v1/render/image/public/\";\n\nconst DEFAULT_BUCKET = \"public-cdn\";\n\ntype ResizeMode = \"cover\" | \"contain\" | \"inside\" | \"outside\";\ntype ImageFormat = \"origin\" | \"avif\" | \"webp\" | \"png\" | \"jpeg\";\n\nexport interface ImageTransformOptions {\n width?: number;\n height?: number;\n resize?: ResizeMode; // default: cover\n quality?: number; // 1..100, default: 80\n format?: ImageFormat; // default: origin\n}\n\nfunction assetBaseUrl(): string {\n return publicConfig().assetBaseUrl;\n}\n\nfunction transformationsEnabled(): boolean {\n const flag = publicConfig().imageTransformationsFlag;\n if (typeof flag === \"string\" && flag !== \"\") {\n return [\"1\", \"true\", \"yes\", \"on\"].includes(flag.toLowerCase());\n }\n // Local stacks may not run the image renderer, so serve originals.\n return !/localhost|127\\.0\\.0\\.1/.test(assetBaseUrl());\n}\n\nfunction buildTransformQuery(opts?: ImageTransformOptions): string {\n if (!opts) return \"\";\n const params = new URLSearchParams();\n if (opts.width && Number.isFinite(opts.width))\n params.set(\"width\", String(opts.width));\n if (opts.height && Number.isFinite(opts.height))\n params.set(\"height\", String(opts.height));\n if (opts.resize) params.set(\"resize\", opts.resize);\n if (opts.quality && Number.isFinite(opts.quality))\n params.set(\"quality\", String(opts.quality));\n if (opts.format) params.set(\"format\", opts.format);\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\n/**\n * Pull bucket + object path out of a storage URL, whatever host it names.\n * Accepts both the object and render path shapes.\n */\nfunction parseStorageUrl(\n url: string\n): { bucket: string; path: string } | null {\n try {\n const { pathname } = new URL(url);\n const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find((p) =>\n pathname.includes(p)\n );\n if (!prefix) return null;\n\n const parts = pathname.split(prefix)[1].split(\"/\");\n const bucket = parts.shift();\n if (!bucket || parts.length === 0) return null;\n\n return { bucket, path: parts.join(\"/\") };\n } catch {\n return null;\n }\n}\n\nfunction buildAssetUrl(\n bucket: string,\n path: string,\n opts?: ImageTransformOptions\n): string | null {\n const base = assetBaseUrl();\n if (!base) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[storage] NEXT_PUBLIC_ASSET_BASE_URL is not set — image URLs cannot be resolved.\"\n );\n }\n return null;\n }\n\n const normalizedPath = path.replace(/^\\//, \"\");\n\n if (transformationsEnabled()) {\n const query = buildTransformQuery({ resize: \"cover\", quality: 80, ...opts });\n return `${base}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;\n }\n\n return `${base}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;\n}\n\n/**\n * Resolve any image reference (full URL or bare storage object path) into a\n * URL, applying transformation params when enabled.\n *\n * - A full http(s) URL that is not a storage URL is returned as-is.\n * - A storage URL is rebuilt against the configured base, ignoring its host.\n * - A bare object path is resolved within `defaultBucket`.\n */\nexport function resolveTransformedImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions,\n defaultBucket: \"public-cdn\" = DEFAULT_BUCKET\n): string | null {\n if (!imagePathOrUrl) return null;\n\n if (/^https?:\\/\\//i.test(imagePathOrUrl)) {\n const parsed = parseStorageUrl(imagePathOrUrl);\n if (!parsed) return imagePathOrUrl;\n return buildAssetUrl(parsed.bucket, parsed.path, opts) ?? imagePathOrUrl;\n }\n\n // Starts with / -> a local app asset, not storage. Leave untouched.\n if (imagePathOrUrl.startsWith(\"/\")) {\n return imagePathOrUrl;\n }\n\n return buildAssetUrl(defaultBucket, imagePathOrUrl, opts);\n}\n\n/** Object URL without any transformation. */\nfunction resolveObjectUrl(\n imagePath: string | null | undefined\n): string | null {\n if (!imagePath) return null;\n\n if (imagePath.startsWith(\"http://\") || imagePath.startsWith(\"https://\")) {\n const parsed = parseStorageUrl(imagePath);\n if (!parsed) return imagePath;\n const base = assetBaseUrl();\n return base\n ? `${base}${OBJECT_PREFIX}${parsed.bucket}/${parsed.path}`\n : imagePath;\n }\n\n if (imagePath.startsWith(\"/\")) return imagePath;\n\n const base = assetBaseUrl();\n return base ? `${base}${OBJECT_PREFIX}${DEFAULT_BUCKET}/${imagePath}` : null;\n}\n\nexport function resolvePublicUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\nexport function resolveStoreLogoUrl(\n logoPath: string | null | undefined\n): string | null {\n return resolveObjectUrl(logoPath);\n}\n\nexport function resolveBlogUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\n// Convenience wrappers with sensible defaults per bucket\n/**\n * Builds the URL of a product image, optionally resized.\n *\n * @param imagePathOrUrl - The image's stored path or full URL.\n * @param opts - Size and format options.\n * @returns The image URL, or `null` when there is no image.\n */\nexport function resolveTransformedProductImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\n/**\n * Builds the URL of a store logo, optionally resized.\n *\n * @param imagePathOrUrl - The logo's stored path or full URL.\n * @param opts - Size and format options.\n * @returns The logo URL, or `null` when there is no logo.\n */\nexport function resolveTransformedStoreLogoUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\nexport function resolveTransformedBlogUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\n/**\n * Null-safe wrapper for use directly in `src={...}`.\n *\n * Rebuilds against the current NEXT_PUBLIC_ASSET_BASE_URL regardless of the\n * stored host, and passes non-storage URLs through untouched.\n */\nexport function resolveAssetSrc(\n url: string | null | undefined,\n opts?: ImageTransformOptions\n): string {\n return resolveTransformedImageUrl(url, opts) ?? \"\";\n}\n"],"mappings":"AAsBA,MAAM,gBAAgB;AACtB,SAAS,oBAAoB;AAC7B,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB;AAavB,SAAS,eAAuB;AAC9B,SAAO,aAAa,EAAE;AACxB;AAEA,SAAS,yBAAkC;AACzC,QAAM,OAAO,aAAa,EAAE;AAC5B,MAAI,OAAO,SAAS,YAAY,SAAS,IAAI;AAC3C,WAAO,CAAC,KAAK,QAAQ,OAAO,IAAI,EAAE,SAAS,KAAK,YAAY,CAAC;AAAA,EAC/D;AAEA,SAAO,CAAC,yBAAyB,KAAK,aAAa,CAAC;AACtD;AAEA,SAAS,oBAAoB,MAAsC;AACjE,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,SAAS,IAAI,gBAAgB;AACnC,MAAI,KAAK,SAAS,OAAO,SAAS,KAAK,KAAK;AAC1C,WAAO,IAAI,SAAS,OAAO,KAAK,KAAK,CAAC;AACxC,MAAI,KAAK,UAAU,OAAO,SAAS,KAAK,MAAM;AAC5C,WAAO,IAAI,UAAU,OAAO,KAAK,MAAM,CAAC;AAC1C,MAAI,KAAK,OAAQ,QAAO,IAAI,UAAU,KAAK,MAAM;AACjD,MAAI,KAAK,WAAW,OAAO,SAAS,KAAK,OAAO;AAC9C,WAAO,IAAI,WAAW,OAAO,KAAK,OAAO,CAAC;AAC5C,MAAI,KAAK,OAAQ,QAAO,IAAI,UAAU,KAAK,MAAM;AACjD,QAAM,KAAK,OAAO,SAAS;AAC3B,SAAO,KAAK,IAAI,EAAE,KAAK;AACzB;AAMA,SAAS,gBACP,KACyC;AACzC,MAAI;AACF,UAAM,EAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAChC,UAAM,SAAS,CAAC,eAAe,aAAa,EAAE;AAAA,MAAK,CAAC,MAClD,SAAS,SAAS,CAAC;AAAA,I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AAG;AACvE,UAAM,SAAS,gBAAgB,SAAS;AACxC,QAAI,CAAC,OAAQ,QAAO;AACpB,UAAMA,QAAO,aAAa;AAC1B,WAAOA,QACH,GAAGA,KAAI,GAAG,aAAa,GAAG,OAAO,MAAM,IAAI,OAAO,IAAI,KACtD;AAAA,EACN;AAEA,MAAI,UAAU,WAAW,GAAG,EAAG,QAAO;AAEtC,QAAM,OAAO,aAAa;AAC1B,SAAO,OAAO,GAAG,IAAI,GAAG,aAAa,GAAG,cAAc,IAAI,SAAS,KAAK;AAC1E;AAEO,SAAS,iBACd,WACe;AACf,SAAO,iBAAiB,SAAS;AACnC;AAEO,SAAS,oBACd,UACe;AACf,SAAO,iBAAiB,QAAQ;AAClC;AAEO,SAAS,eACd,WACe;AACf,SAAO,iBAAiB,SAAS;AACnC;AAUO,SAAS,kCACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AASO,SAAS,+BACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AAEO,SAAS,0BACd,gBACA,MACe;AACf,SAAO,2BAA2B,gBAAgB,MAAM,cAAc;AACxE;AAQO,SAAS,gBACd,KACA,MACQ;AACR,SAAO,2BAA2B,KAAK,IAAI,KAAK;AAClD;","names":["base"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/store/store-context.tsx"],"sourcesContent":["\"use client\";\n\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { createContext, useContext, ReactNode } from \"react\";\n\nimport {\n SupportedCurrency,\n getDefaultLocale,\n isSupportedCurrency,\n} from \"../currency\";\n\ninterface StoreContextData {\n store: StoreConfigurationInfo;\n}\n\ninterface StoreProviderProps {\n children: ReactNode;\n store: StoreConfigurationInfo;\n}\n\nconst StoreContext = createContext<StoreContextData | undefined>(undefined);\n\nexport function StoreProvider({ children, store }: StoreProviderProps) {\n const value: StoreContextData = {\n store,\n };\n\n return (\n <StoreContext.Provider value={value}>{children}</StoreContext.Provider>\n );\n}\n\nexport function useStore() {\n const context = useContext(StoreContext);\n if (!context) {\n throw new Error(\"useStore must be used within a StoreProvider\");\n }\n return context;\n}\n\n// Export specific hooks for convenience\nexport function useStoreData() {\n const { store } = useStore();\n return store;\n}\n\n/** The store ref, or null outside a StoreProvider (e.g. a store-level 404). */\nexport function useOptionalStoreId(): string | null {\n return useContext(StoreContext)?.store.ref ?? null;\n}\n\nexport function useStoreId() {\n const { store } = useStore();\n return store.ref;\n}\n\nexport function useStoreSettings() {\n const { store } = useStore();\n return store.settings;\n}\n\nexport function useStoreConfig() {\n const { store } = useStore();\n return store.config;\n}\n\nexport function useBlogSettings() {\n const { store } = useStore();\n\n // Blog settings live in store settings.\n return {\n blogEnabled: store.settings?.is_blog_enabled ?? false,\n blogTitle: store.settings?.blog_title ?? \"Blog\",\n };\n}\n\nexport function useStoreCurrency(): SupportedCurrency {\n const { store } = useStore();\n const currencyCode = store.settings?.currency_code;\n\n // Default to VND for anything we cannot price in.\n if (!currencyCode || !isSupportedCurrency(currencyCode)) {\n return \"VND\";\n }\n\n return currencyCode;\n}\n\nexport function useStoreLocale(): string {\n const currency = useStoreCurrency();\n return getDefaultLocale(currency);\n}\n"],"mappings":";AA4BI;AAzBJ,SAAS,eAAe,kBAA6B;AAErD;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AAWP,MAAM,eAAe,cAA4C,MAAS;AAEnE,SAAS,cAAc,EAAE,UAAU,MAAM,GAAuB;AACrE,QAAM,QAA0B;AAAA,IAC9B;AAAA,EACF;AAEA,SACE,oBAAC,aAAa,UAAb,EAAsB,OAAe,UAAS;AAEnD;AAEO,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;AAGO,SAAS,eAAe;AAC7B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO;AACT;AAGO,SAAS,qBAAoC;AAClD,SAAO,WAAW,YAAY,GAAG,MAAM,OAAO;AAChD;AAEO,SAAS,aAAa;AAC3B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,mBAAmB;AACjC,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,iBAAiB;AAC/B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO,MAAM;AACf;AAEO,SAAS,kBAAkB;AAChC,QAAM,EAAE,MAAM,IAAI,SAAS;AAG3B,SAAO;AAAA,IACL,aAAa,MAAM,UAAU,mBAAmB;AAAA,IAChD,WAAW,MAAM,UAAU,cAAc;AAAA,EAC3C;AACF;AAEO,SAAS,mBAAsC;AACpD,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,QAAM,eAAe,MAAM,UAAU;AAGrC,MAAI,CAAC,gBAAgB,CAAC,oBAAoB,YAAY,GAAG;AACvD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEO,SAAS,iBAAyB;AACvC,QAAM,WAAW,iBAAiB;AAClC,SAAO,iBAAiB,QAAQ;AAClC;","names":[]}
1
+ {"version":3,"sources":["../../src/store/store-context.tsx"],"sourcesContent":["\"use client\";\n\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { createContext, useContext, ReactNode } from \"react\";\n\nimport {\n SupportedCurrency,\n getDefaultLocale,\n isSupportedCurrency,\n} from \"../currency\";\n\ninterface StoreContextData {\n store: StoreConfigurationInfo;\n}\n\ninterface StoreProviderProps {\n children: ReactNode;\n store: StoreConfigurationInfo;\n}\n\nconst StoreContext = createContext<StoreContextData | undefined>(undefined);\n\nexport function StoreProvider({ children, store }: StoreProviderProps) {\n const value: StoreContextData = {\n store,\n };\n\n return (\n <StoreContext.Provider value={value}>{children}</StoreContext.Provider>\n );\n}\n\n/**\n * The store this page belongs to, as `{ store }`.\n *\n * Must run under {@link StorefrontKitProvider} (or the kit's store provider).\n *\n * @returns The store context.\n * @throws When used outside the provider.\n */\nexport function useStore() {\n const context = useContext(StoreContext);\n if (!context) {\n throw new Error(\"useStore must be used within a StoreProvider\");\n }\n return context;\n}\n\n// Export specific hooks for convenience\n/**\n * The store's configuration: ref, name, settings and config. Same as\n * `useStore().store`.\n *\n * Must run under {@link StorefrontKitProvider}.\n *\n * @returns The store configuration.\n * @throws When used outside the provider.\n */\nexport function useStoreData() {\n const { store } = useStore();\n return store;\n}\n\n/** The store ref, or null outside a StoreProvider (e.g. a store-level 404). */\nexport function useOptionalStoreId(): string | null {\n return useContext(StoreContext)?.store.ref ?? null;\n}\n\n/**\n * The store's ref.\n *\n * Must run under {@link StorefrontKitProvider}.\n *\n * @returns The store ref.\n * @throws When used outside the provider.\n */\nexport function useStoreId() {\n const { store } = useStore();\n return store.ref;\n}\n\nexport function useStoreSettings() {\n const { store } = useStore();\n return store.settings;\n}\n\nexport function useStoreConfig() {\n const { store } = useStore();\n return store.config;\n}\n\nexport function useBlogSettings() {\n const { store } = useStore();\n\n // Blog settings live in store settings.\n return {\n blogEnabled: store.settings?.is_blog_enabled ?? false,\n blogTitle: store.settings?.blog_title ?? \"Blog\",\n };\n}\n\n/**\n * The store's currency code, `VND` when the store sets none or one the kit\n * does not support.\n *\n * Must run under {@link StorefrontKitProvider}.\n *\n * @returns The currency code.\n * @throws When used outside the provider.\n */\nexport function useStoreCurrency(): SupportedCurrency {\n const { store } = useStore();\n const currencyCode = store.settings?.currency_code;\n\n // Default to VND for anything we cannot price in.\n if (!currencyCode || !isSupportedCurrency(currencyCode)) {\n return \"VND\";\n }\n\n return currencyCode;\n}\n\n/**\n * The locale to format prices and numbers in for this store, from its\n * currency.\n *\n * Must run under {@link StorefrontKitProvider}.\n *\n * @returns A BCP 47 locale tag.\n * @throws When used outside the provider.\n */\nexport function useStoreLocale(): string {\n const currency = useStoreCurrency();\n return getDefaultLocale(currency);\n}\n"],"mappings":";AA4BI;AAzBJ,SAAS,eAAe,kBAA6B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ig } from \"../config/public\";\n\n/**\n * The one place that knows which store a request serves and what its URLs look\n * like.\n * - multi: every store lives under /store/<ref>, the ref comes from the route.\n * - single: the store (ECOMWEB_STORE_REF) is the whole site, so pages live at\n * the root and same-origin API routes under /api.\n */\n\nconst isSingle = () => publicConfig().mode === \"single\";\n\nexport async function resolveStoreRef(\n params?: Promise<{ storeRef?: string }>\n): Promise<string> {\n if (isSingle()) return publicConfig().storeRef as string;\n const { storeRef } = (await params) ?? {};\n return storeRef as string;\n}\n\nfunction normalize(path: string): string {\n if (!path) return \"\";\n return path.startsWith(\"/\") || path.startsWith(\"?\") || path.startsWith(\"#\")\n ? path\n : `/${path}`;\n}\n\n/** The multi-tenant path, whatever the configured mode (middleware uses it). */\nexport function multiTenantStorePath(storeRef: string, path = \"\"): string {\n return `/store/${encodeURIComponent(storeRef)}${normalize(path)}`;\n}\n\nexport function storePath(storeRef: string, path = \"\"): string {\n if (isSingle()) {\n const p = normalize(path);\n return p.startsWith(\"/\") ? p : `/${p}`;\n }\n return multiTenantStorePath(storeRef, path);\n}\n\nexport function storeApiPath(storeRef: string, subpath: string): string {\n const rest = subpath.replace(/^\\/+/, \"\");\n if (isSingle()) return `/api/${rest}`;\n return `/store/${encodeURIComponent(storeRef)}/api/${rest}`;\n}\n"],"mappings":"AAAA,SAAS,oBAAoB;AAU7B,MAAM,WAAW,MAAM,aAAa,EAAE,SAAS;AAE/C,eAAsB,gBACpB,QACiB;AACjB,MAAI,SAAS,EAAG,QAAO,aAAa,EAAE;AACtC,QAAM,EAAE,SAAS,IAAK,MAAM,UAAW,CAAC;AACxC,SAAO;AACT;AAEA,SAAS,UAAU,MAAsB;AACvC,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,IACtE,OACA,IAAI,IAAI;AACd;AAGO,SAAS,qBAAqB,UAAkB,OAAO,IAAY;AACxE,SAAO,UAAU,mBAAmB,QAAQ,CAAC,GAAG,UAAU,IAAI,CAAC;AACjE;AAEO,SAAS,UAAU,UAAkB,OAAO,IAAY;AAC7D,MAAI,SAAS,GAAG;AACd,UAAM,IAAI,UAAU,IAAI;AACxB,WAAO,EAAE,WAAW,GAAG,IAAI,IAAI,IAAI,CAAC;AAAA,EACtC;AACA,SAAO,qBAAqB,UAAU,IAAI;AAC5C;AAEO,SAAS,aAAa,UAAkB,SAAyB;AACtE,QAAM,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AACvC,MAAI,SAAS,EAAG,QAAO,QAAQ,IAAI;AACnC,SAAO,UAAU,mBAAmB,QAAQ,CAAC,QAAQ,IAAI;AAC3D;","names":[]}
1
+ {"version":3,"sources":["../../src/store-scope/index.ts"],"sourcesContent":["import { publicConfig } from \"../config/public\";\n\n/**\n * The one place that knows which store a request serves and what its URLs look\n * like.\n * - multi: every store lives under /store/<ref>, the ref comes from the route.\n * - single: the store (ECOMWEB_STORE_REF) is the whole site, so pages live at\n * the root and same-origin API routes under /api.\n */\n\nconst isSingle = () => publicConfig().mode === \"single\";\n\n/**\n * Finds the ref of the store a request serves. In single-store mode it is\n * `ECOMWEB_STORE_REF`; in multi-store mode it comes from the route's\n * `storeRef` param.\n *\n * @param params - The page's `params` promise; only read in multi-store mode.\n * @returns The store ref.\n */\nexport async function resolveStoreRef(\n params?: Promise<{ storeRef?: string }>\n): Promise<string> {\n if (isSingle()) return publicConfig().storeRef as string;\n const { storeRef } = (await params) ?? {};\n return storeRef as string;\n}\n\nfunction normalize(path: string): string {\n if (!path) return \"\";\n return path.startsWith(\"/\") || path.startsWith(\"?\") || path.startsWith(\"#\")\n ? path\n : `/${path}`;\n}\n\n/** The multi-tenant path, whatever the configured mode (middleware uses it). */\nexport function multiTenantStorePath(storeRef: string, path = \"\"): string {\n return `/store/${encodeURIComponent(storeRef)}${normalize(path)}`;\n}\n\n/**\n * Builds a page path for a store: `/store/<ref>/…` in multi-store mode, the\n * path from the site root in single-store mode.\n *\n * @param storeRef - The store's ref.\n * @param path - Path under the store, such as `/cart`; defaults to its home.\n * @returns The path to link to.\n */\nexport function storePath(storeRef: string, path = \"\"): string {\n if (isSingle()) {\n const p = normalize(path);\n return p.startsWith(\"/\") ? p : `/${p}`;\n }\n return multiTenantStorePath(storeRef, path);\n}\n\n/**\n * Builds the path of the storefront's own API routes for a store:\n * `/store/<ref>/api/…` in multi-store mode, `/api/…` in single-store mode.\n *\n * @param storeRef - The store's ref.\n * @param subpath - Route under the API prefix, such as `auth/session`.\n * @returns The path to request.\n */\nexport function storeApiPath(storeRef: string, subpath: string): string {\n const rest = subpath.replace(/^\\/+/, \"\");\n if (isSingle()) return `/api/${rest}`;\n return `/store/${encodeURIComponent(storeRef)}/api/${rest}`;\n}\n"],"mappings":"AAAA,SAAS,oBAAoB;AAU7B,MAAM,WAAW,MAAM,aAAa,EAAE,SAAS;AAU/C,eAAsB,gBACpB,QACiB;AACjB,MAAI,SAAS,EAAG,QAAO,aAAa,EAAE;AACtC,QAAM,EAAE,SAAS,IAAK,MAAM,UAAW,CAAC;AACxC,SAAO;AACT;AAEA,SAAS,UAAU,MAAsB;AACvC,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,IACtE,OACA,IAAI,IAAI;AACd;AAGO,SAAS,qBAAqB,UAAkB,OAAO,IAAY;AACxE,SAAO,UAAU,mBAAmB,QAAQ,CAAC,GAAG,UAAU,IAAI,CAAC;AACjE;AAUO,SAAS,UAAU,UAAkB,OAAO,IAAY;AAC7D,MAAI,SAAS,GAAG;AACd,UAAM,IAAI,UAAU,IAAI;AACxB,WAAO,EAAE,WAAW,GAAG,IAAI,IAAI,IAAI,CAAC;AAAA,EACtC;AACA,SAAO,qBAAqB,UAAU,IAAI;AAC5C;AAUO,SAAS,aAAa,UAAkB,SAAyB;AACtE,QAAM,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AACvC,MAAI,SAAS,EAAG,QAAO,QAAQ,IAAI;AACnC,SAAO,UAAU,mBAAmB,QAAQ,CAAC,QAAQ,IAAI;AAC3D;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/basic-settings.ts"],"sourcesContent":["/**\n * The store's checkout and register legal links, from `settings.legal_links`.\n * Everything else the page builder's theme_config held is a theme setting\n * now (`useThemeSettings`).\n */\n\ntype Loose = Record<string, any>;\n\nexport interface StoreLike {\n settings?: Loose | null;\n}\n\nexport interface BasicSettings {\n legalLinks: { termsLink: string | null; policyLink: string | null };\n}\n\nfunction str(v: unknown): string | null {\n return typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : null;\n}\n\n/** @deprecated Read `store.settings.legal_links` directly. */\nexport function readBasicSettings(store: StoreLike): BasicSettings {\n const legal: Loose = store.settings?.legal_links ?? {};\n return {\n legalLinks: {\n termsLink: str(legal.terms),\n policyLink: str(legal.privacy),\n },\n };\n}\n\nexport function resolveLegalHref(\n link: string | null,\n fallbackPath: string | null,\n toStoreUrl: (path: string) => string\n): string {\n const target = link ?? fallbackPath;\n if (!target) return \"#\";\n if (/^https?:\\/\\//i.test(target)) return target;\n return toStoreUrl(target.startsWith(\"/\") ? target : `/${target}`);\n}\n"],"mappings":"AAgBA,SAAS,IAAI,GAA2B;AACtC,SAAO,OAAO,MAAM,YAAY,EAAE,KAAK,MAAM,KAAK,EAAE,KAAK,IAAI;AAC/D;AAGO,SAAS,kBAAkB,OAAiC;AACjE,QAAM,QAAe,MAAM,UAAU,eAAe,CAAC;AACrD,SAAO;AAAA,IACL,YAAY;AAAA,MACV,WAAW,IAAI,MAAM,KAAK;AAAA,MAC1B,YAAY,IAAI,MAAM,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;AAEO,SAAS,iBACd,MACA,cACA,YACQ;AACR,QAAM,SAAS,QAAQ;AACvB,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,gBAAgB,KAAK,MAAM,EAAG,QAAO;AACzC,SAAO,WAAW,OAAO,WAAW,GAAG,IAAI,SAAS,IAAI,MAAM,EAAE;AAClE;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/basic-settings.ts"],"sourcesContent":["/**\n * The store's checkout and register legal links, from `settings.legal_links`.\n * Everything else the page builder's theme_config held is a theme setting\n * now (`useThemeSettings`).\n */\n\ntype Loose = Record<string, any>;\n\nexport interface StoreLike {\n settings?: Loose | null;\n}\n\nexport interface BasicSettings {\n legalLinks: { termsLink: string | null; policyLink: string | null };\n}\n\nfunction str(v: unknown): string | null {\n return typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : null;\n}\n\n/**\n * Reads the store's terms and privacy links from its settings.\n *\n * @param store - A store with a `settings` object.\n * @returns The links, `null` where the store sets none.\n * @deprecated Read `store.settings.legal_links` directly.\n */\nexport function readBasicSettings(store: StoreLike): BasicSettings {\n const legal: Loose = store.settings?.legal_links ?? {};\n return {\n legalLinks: {\n termsLink: str(legal.terms),\n policyLink: str(legal.privacy),\n },\n };\n}\n\n/**\n * Turns a legal link into the URL to put in an anchor. A full URL is kept; a\n * path is made store-relative.\n *\n * @param link - The store's own link, or `null`.\n * @param fallbackPath - Path to use when the store sets no link.\n * @param toStoreUrl - Builds a store URL from a path, for example with {@link storePath}.\n * @returns The URL, or `#` when there is neither link nor fallback.\n */\nexport function resolveLegalHref(\n link: string | null,\n fallbackPath: string | null,\n toStoreUrl: (path: string) => string\n): string {\n const target = link ?? fallbackPath;\n if (!target) return \"#\";\n if (/^https?:\\/\\//i.test(target)) return target;\n return toStoreUrl(target.startsWith(\"/\") ? target : `/${target}`);\n}\n"],"mappings":"AAgBA,SAAS,IAAI,GAA2B;AACtC,SAAO,OAAO,MAAM,YAAY,EAAE,KAAK,MAAM,KAAK,EAAE,KAAK,IAAI;AAC/D;AASO,SAAS,kBAAkB,OAAiC;AACjE,QAAM,QAAe,MAAM,UAAU,eAAe,CAAC;AACrD,SAAO;AAAA,IACL,YAAY;AAAA,MACV,WAAW,IAAI,MAAM,KAAK;AAAA,MAC1B,YAAY,IAAI,MAAM,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;AAWO,SAAS,iBACd,MACA,cACA,YACQ;AACR,QAAM,SAAS,QAAQ;AACvB,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,gBAAgB,KAAK,MAAM,EAAG,QAAO;AACzC,SAAO,WAAW,OAAO,WAAW,GAAG,IAAI,SAAS,IAAI,MAAM,EAAE;AAClE;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/cached.ts"],"sourcesContent":["import type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { cache } from \"react\";\n\nconst getCachedStoreInternal = cache(\n async (storeRef: string): Promise<StoreConfigurationInfo | null> => {\n return sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: true,\n includeEmbeddedScripts: true,\n });\n }\n);\n\nexport const getCachedStore = cache(\n async (\n storeRef: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- public signature (in etc/index.api.md); accepted for compatibility, the full config is always fetched\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeBlogSettings?: boolean;\n }\n ): Promise<StoreConfigurationInfo | null> => {\n return getCachedStoreInternal(storeRef);\n }\n);\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,aAAa;AAEtB,MAAM,yBAAyB;AAAA,EAC7B,OAAO,aAA6D;AAClE,WAAO,IAAI,OAAO,QAAQ,UAAU;AAAA,MAClC,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAEO,MAAM,iBAAiB;AAAA,EAC5B,OACE,UAEA,YAK2C;AAC3C,WAAO,uBAAuB,QAAQ;AAAA,EACxC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/cached.ts"],"sourcesContent":["import type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { cache } from \"react\";\n\nconst getCachedStoreInternal = cache(\n async (storeRef: string): Promise<StoreConfigurationInfo | null> => {\n return sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: true,\n includeEmbeddedScripts: true,\n });\n }\n);\n\n/**\n * Loads a store's configuration, settings and embedded scripts. Server-side;\n * calls with the same ref during one request share a single fetch.\n *\n * @param storeRef - The store's ref.\n * @param options - Accepted for compatibility and ignored; the full configuration is always fetched.\n * @returns The store, or `null` when it does not exist.\n */\nexport const getCachedStore = cache(\n async (\n storeRef: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- public signature (in etc/index.api.md); accepted for compatibility, the full config is always fetched\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeBlogSettings?: boolean;\n }\n ): Promise<StoreConfigurationInfo | null> => {\n return getCachedStoreInternal(storeRef);\n }\n);\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,aAAa;AAEtB,MAAM,yBAAyB;AAAA,EAC7B,OAAO,aAA6D;AAClE,WAAO,IAAI,OAAO,QAAQ,UAAU;AAAA,MAClC,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAUO,MAAM,iBAAiB;AAAA,EAC5B,OACE,UAEA,YAK2C;AAC3C,WAAO,uBAAuB,QAAQ;AAAA,EACxC;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/define.ts"],"sourcesContent":["import type { ComponentType, ReactNode } from \"react\";\nimport type {\n BlogCategory,\n BlogPost,\n Collection,\n ContentPage,\n Product,\n ProductDetail,\n ProductWithVariants,\n SearchProduct,\n StoreConfigurationInfo,\n ThemeSchema,\n ThemeSettingsOf,\n} from \"@ecomweb/sdk\";\n\n/**\n * The theme contract (spec: schema-driven themes §5.2). A theme declares its\n * settings with `defineSchema` and fills the slots the shared routes render.\n * Routes load data through the kit and pass it in: a theme is presentation.\n */\n\nexport function defineSchema<const S extends ThemeSchema>(schema: S): S {\n return schema;\n}\n\nexport interface ThemeInfo {\n id: string;\n name: string;\n version: string;\n author: string;\n}\n\n/** A slot may be a server component (async) or a plain one. */\nexport type ThemeSlot<P> = (props: P) => ReactNode | Promise<ReactNode>;\n\nexport interface ThemeSlotProps<V> {\n store: StoreConfigurationInfo;\n storeRef: string;\n settings: V;\n}\n\nexport interface LayoutSlotProps<V> extends ThemeSlotProps<V> {\n children: ReactNode;\n}\n\n/** Banners and the shop introduction are theme settings (default@1.1.0). */\nexport type HomePageSlotProps<V> = ThemeSlotProps<V>;\n\nexport interface ProductPageSlotProps<V> extends ThemeSlotProps<V> {\n product: ProductDetail;\n}\n\n/** The collection route's query string, as the filters read it. */\nexport interface CollectionSearchParams {\n q?: string;\n category?: string;\n page?: string;\n sort?: string;\n min_price?: string;\n max_price?: string;\n has_promotion?: string;\n}\n\nexport interface CollectionPageSlotProps<V> extends ThemeSlotProps<V> {\n slug: string;\n /** Null for the \"all\" pseudo-collection. */\n collection: Collection | null;\n searchParams: CollectionSearchParams;\n}\n\nexport interface ContentPageSlotProps<V> extends ThemeSlotProps<V> {\n page: ContentPage;\n isPreview: boolean;\n}\n\nexport interface BlogIndexSlotProps<V> extends ThemeSlotProps<V> {\n blogTitle: string;\n posts: BlogPost[];\n categories: BlogCategory[];\n total: number;\n page: number;\n totalPages: number;\n /** Category id filter from the query string, \"\" when none. */\n category: string;\n search: string;\n}\n\nexport interface BlogPostSlotProps<V> extends ThemeSlotProps<V> {\n blogTitle: string;\n post: BlogPost;\n /** The post's linked products, in the post's order. */\n products: SearchProduct[];\n}\n\nexport interface ThemeComponents<V> {\n Layout?: ThemeSlot<LayoutSlotProps<V>>;\n HomePage?: ThemeSlot<HomePageSlotProps<V>>;\n ProductPage?: ThemeSlot<ProductPageSlotProps<V>>;\n CollectionPage?: ThemeSlot<CollectionPageSlotProps<V>>;\n ContentPage?: ThemeSlot<ContentPageSlotProps<V>>;\n BlogIndex?: ThemeSlot<BlogIndexSlotProps<V>>;\n BlogPost?: ThemeSlot<BlogPostSlotProps<V>>;\n}\n\n/**\n * Components rendered inside client components, so they cannot be resolved\n * on the server per request. The app keeps a registry keyed by theme id.\n */\nexport interface ProductCardProps {\n product: Product | ProductWithVariants | SearchProduct;\n storeRef?: string;\n}\n\nexport interface NotFoundProps {\n /** Null when the store itself was not found. */\n storeRef: string | null;\n}\n\nexport interface ThemeClientComponents {\n ProductCard?: ComponentType<ProductCardProps>;\n NotFound?: ComponentType<NotFoundProps>;\n}\n\nexport type ThemeSlotName = keyof ThemeComponents<unknown>;\n\nexport interface ThemeDefinition<S extends ThemeSchema = ThemeSchema> {\n info: ThemeInfo;\n schema: S;\n components: ThemeComponents<ThemeSettingsOf<S>>;\n /** CSS custom properties for :root, from the resolved settings. */\n styles?: (settings: ThemeSettingsOf<S>) => Record<string, string>;\n}\n\n/**\n * A theme of unknown schema, as the registry holds it. Its slots are called\n * with settings resolved against its own schema.\n */\nexport interface AnyThemeDefinition {\n info: ThemeInfo;\n schema: ThemeSchema;\n components: ThemeComponents<any>;\n styles?: (settings: any) => Record<string, string>;\n}\n\nexport function defineTheme<const S extends ThemeSchema>(\n theme: ThemeDefinition<S>\n): ThemeDefinition<S> {\n return theme;\n}\n"],"mappings":"AAqBO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;AAyHO,SAAS,YACd,OACoB;AACpB,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/define.ts"],"sourcesContent":["import type { ComponentType, ReactNode } from \"react\";\nimport type {\n BlogCategory,\n BlogPost,\n Collection,\n ContentPage,\n Product,\n ProductDetail,\n ProductWithVariants,\n SearchProduct,\n StoreConfigurationInfo,\n ThemeSchema,\n ThemeSettingsOf,\n} from \"@ecomweb/sdk\";\n\n/**\n * The theme contract (spec: schema-driven themes §5.2). A theme declares its\n * settings with `defineSchema` and fills the slots the shared routes render.\n * Routes load data through the kit and pass it in: a theme is presentation.\n */\n\nexport function defineSchema<const S extends ThemeSchema>(schema: S): S {\n return schema;\n}\n\nexport interface ThemeInfo {\n id: string;\n name: string;\n version: string;\n author: string;\n}\n\n/** A slot may be a server component (async) or a plain one. */\nexport type ThemeSlot<P> = (props: P) => ReactNode | Promise<ReactNode>;\n\nexport interface ThemeSlotProps<V> {\n store: StoreConfigurationInfo;\n storeRef: string;\n settings: V;\n}\n\nexport interface LayoutSlotProps<V> extends ThemeSlotProps<V> {\n children: ReactNode;\n}\n\n/** Banners and the shop introduction are theme settings (default@1.1.0). */\nexport type HomePageSlotProps<V> = ThemeSlotProps<V>;\n\nexport interface ProductPageSlotProps<V> extends ThemeSlotProps<V> {\n product: ProductDetail;\n}\n\n/** The collection route's query string, as the filters read it. */\nexport interface CollectionSearchParams {\n q?: string;\n category?: string;\n page?: string;\n sort?: string;\n min_price?: string;\n max_price?: string;\n has_promotion?: string;\n}\n\nexport interface CollectionPageSlotProps<V> extends ThemeSlotProps<V> {\n slug: string;\n /** Null for the \"all\" pseudo-collection. */\n collection: Collection | null;\n searchParams: CollectionSearchParams;\n}\n\nexport interface ContentPageSlotProps<V> extends ThemeSlotProps<V> {\n page: ContentPage;\n isPreview: boolean;\n}\n\nexport interface BlogIndexSlotProps<V> extends ThemeSlotProps<V> {\n blogTitle: string;\n posts: BlogPost[];\n categories: BlogCategory[];\n total: number;\n page: number;\n totalPages: number;\n /** Category id filter from the query string, \"\" when none. */\n category: string;\n search: string;\n}\n\nexport interface BlogPostSlotProps<V> extends ThemeSlotProps<V> {\n blogTitle: string;\n post: BlogPost;\n /** The post's linked products, in the post's order. */\n products: SearchProduct[];\n}\n\nexport interface ThemeComponents<V> {\n Layout?: ThemeSlot<LayoutSlotProps<V>>;\n HomePage?: ThemeSlot<HomePageSlotProps<V>>;\n ProductPage?: ThemeSlot<ProductPageSlotProps<V>>;\n CollectionPage?: ThemeSlot<CollectionPageSlotProps<V>>;\n ContentPage?: ThemeSlot<ContentPageSlotProps<V>>;\n BlogIndex?: ThemeSlot<BlogIndexSlotProps<V>>;\n BlogPost?: ThemeSlot<BlogPostSlotProps<V>>;\n}\n\n/**\n * Components rendered inside client components, so they cannot be resolved\n * on the server per request. The app keeps a registry keyed by theme id.\n */\nexport interface ProductCardProps {\n product: Product | ProductWithVariants | SearchProduct;\n storeRef?: string;\n}\n\nexport interface NotFoundProps {\n /** Null when the store itself was not found. */\n storeRef: string | null;\n}\n\nexport interface ThemeClientComponents {\n ProductCard?: ComponentType<ProductCardProps>;\n NotFound?: ComponentType<NotFoundProps>;\n}\n\nexport type ThemeSlotName = keyof ThemeComponents<unknown>;\n\nexport interface ThemeDefinition<S extends ThemeSchema = ThemeSchema> {\n info: ThemeInfo;\n schema: S;\n components: ThemeComponents<ThemeSettingsOf<S>>;\n /** CSS custom properties for :root, from the resolved settings. */\n styles?: (settings: ThemeSettingsOf<S>) => Record<string, string>;\n}\n\n/**\n * A theme of unknown schema, as the registry holds it. Its slots are called\n * with settings resolved against its own schema.\n */\nexport interface AnyThemeDefinition {\n info: ThemeInfo;\n schema: ThemeSchema;\n components: ThemeComponents<any>;\n styles?: (settings: any) => Record<string, string>;\n}\n\n/**\n * Declares a theme: its info, its settings schema, the slot components it\n * renders and, optionally, the CSS custom properties its settings produce.\n * The theme module default-exports the result, and the storefront's routes\n * render its slots with the store's saved settings. Returns the theme\n * unchanged; it only types the settings from the schema.\n *\n * @param theme - The theme definition.\n * @returns The same definition.\n *\n * @example\n * ```tsx\n * import { defineSchema, defineTheme } from \"@ecomweb/storefront-kit/theme\";\n *\n * const schema = defineSchema([\n * {\n * name: \"Colors\",\n * settings: [\n * { type: \"color\", id: \"primary\", label: \"Primary\", default: \"#111111\" },\n * ],\n * },\n * ]);\n *\n * export default defineTheme({\n * info: { id: \"my-theme\", name: \"My theme\", version: \"1.0.0\", author: \"Me\" },\n * schema,\n * styles: s => ({ \"--primary\": s.primary }),\n * components: {\n * Layout: ({ children }) => <main>{children}</main>,\n * },\n * });\n * ```\n */\nexport function defineTheme<const S extends ThemeSchema>(\n theme: ThemeDefinition<S>\n): ThemeDefinition<S> {\n return theme;\n}\n"],"mappings":"AAqBO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;AA0JO,SAAS,YACd,OACoB;AACpB,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit/theme: authoring a theme (schema, definition, slot\n// types). No side effects, so build tools such as CI's theme export can import\n// it without a storefront configuration.\nexport { defineSchema, defineTheme } from \"./define\";\nexport type {\n AnyThemeDefinition,\n 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 \"./define\";\n"],"mappings":"AAGA,SAAS,cAAc,mBAAmB;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/index.ts"],"sourcesContent":["/**\n * Authoring a theme: `defineSchema`, `defineTheme` and the slot prop types.\n * No side effects, so build tools such as CI's theme export can import it\n * without a storefront configuration.\n *\n * Import from `@ecomweb/storefront-kit/theme` in a theme's source files.\n *\n * @packageDocumentation\n */\nexport { defineSchema, defineTheme } from \"./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 \"./define\";\n"],"mappings":"AASA,SAAS,cAAc,mBAAmB;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/settings-context.tsx"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { ThemeValues } from \"@ecomweb/sdk\";\n\ninterface ThemeSettingsContextValue {\n themeId: string;\n /** The registry key of the code rendering, e.g. \"meridian@1\" (theme majors). */\n themeKey?: string;\n settings: ThemeValues;\n}\n\nconst ThemeSettingsContext = createContext<ThemeSettingsContextValue | null>(\n null\n);\n\n/** The published (or previewed) theme's resolved settings, for client components. */\nexport function ThemeSettingsProvider({\n themeId,\n themeKey,\n settings,\n children,\n}: ThemeSettingsContextValue & { children: ReactNode }) {\n const value = useMemo(\n () => ({ themeId, themeKey, settings }),\n [themeId, themeKey, settings]\n );\n return (\n <ThemeSettingsContext.Provider value={value}>\n {children}\n </ThemeSettingsContext.Provider>\n );\n}\n\nfunction useThemeSettingsContext(hook: string): ThemeSettingsContextValue {\n const ctx = useContext(ThemeSettingsContext);\n if (!ctx) {\n throw new Error(`${hook} must be used inside a ThemeSettingsProvider`);\n }\n return ctx;\n}\n\n/** Pass the theme's settings type: `useThemeSettings<MyThemeSettings>()`. */\nexport function useThemeSettings<T = ThemeValues>(): T {\n return useThemeSettingsContext(\"useThemeSettings\").settings as T;\n}\n\nexport function useThemeId(): string {\n return useThemeSettingsContext(\"useThemeId\").themeId;\n}\n\n/** The theme id, or null outside a ThemeSettingsProvider (e.g. a store 404). */\nexport function useOptionalThemeId(): string | null {\n return useContext(ThemeSettingsContext)?.themeId ?? null;\n}\n\n/**\n * The registry key of the theme code rendering (\"meridian@1\"), else its id;\n * null outside a ThemeSettingsProvider. Client registries look up by it.\n */\nexport function useOptionalThemeKey(): string | null {\n const ctx = useContext(ThemeSettingsContext);\n return ctx ? (ctx.themeKey ?? ctx.themeId) : null;\n}\n"],"mappings":";AA4BI;AA1BJ,SAAS,eAAe,YAAY,eAA+B;AAUnE,MAAM,uBAAuB;AAAA,EAC3B;AACF;AAGO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAwD;AACtD,QAAM,QAAQ;AAAA,IACZ,OAAO,EAAE,SAAS,UAAU,SAAS;AAAA,IACrC,CAAC,SAAS,UAAU,QAAQ;AAAA,EAC9B;AACA,SACE,oBAAC,qBAAqB,UAArB,EAA8B,OAC5B,UACH;AAEJ;AAEA,SAAS,wBAAwB,MAAyC;AACxE,QAAM,MAAM,WAAW,oBAAoB;AAC3C,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,GAAG,IAAI,8CAA8C;AAAA,EACvE;AACA,SAAO;AACT;AAGO,SAAS,mBAAuC;AACrD,SAAO,wBAAwB,kBAAkB,EAAE;AACrD;AAEO,SAAS,aAAqB;AACnC,SAAO,wBAAwB,YAAY,EAAE;AAC/C;AAGO,SAAS,qBAAoC;AAClD,SAAO,WAAW,oBAAoB,GAAG,WAAW;AACtD;AAMO,SAAS,sBAAqC;AACnD,QAAM,MAAM,WAAW,oBAAoB;AAC3C,SAAO,MAAO,IAAI,YAAY,IAAI,UAAW;AAC/C;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/settings-context.tsx"],"sourcesContent":["\"use client\";\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { ThemeValues } from \"@ecomweb/sdk\";\n\ninterface ThemeSettingsContextValue {\n themeId: string;\n /** The registry key of the code rendering, e.g. \"meridian@1\" (theme majors). */\n themeKey?: string;\n settings: ThemeValues;\n}\n\nconst ThemeSettingsContext = createContext<ThemeSettingsContextValue | null>(\n null\n);\n\n/** The published (or previewed) theme's resolved settings, for client components. */\nexport function ThemeSettingsProvider({\n themeId,\n themeKey,\n settings,\n children,\n}: ThemeSettingsContextValue & { children: ReactNode }) {\n const value = useMemo(\n () => ({ themeId, themeKey, settings }),\n [themeId, themeKey, settings]\n );\n return (\n <ThemeSettingsContext.Provider value={value}>\n {children}\n </ThemeSettingsContext.Provider>\n );\n}\n\nfunction useThemeSettingsContext(hook: string): ThemeSettingsContextValue {\n const ctx = useContext(ThemeSettingsContext);\n if (!ctx) {\n throw new Error(`${hook} must be used inside a ThemeSettingsProvider`);\n }\n return ctx;\n}\n\n/** Pass the theme's settings type: `useThemeSettings<MyThemeSettings>()`. */\nexport function useThemeSettings<T = ThemeValues>(): T {\n return useThemeSettingsContext(\"useThemeSettings\").settings as T;\n}\n\n/**\n * The id of the theme rendering the store.\n *\n * Must run under the theme settings provider the storefront's layout sets up.\n *\n * @returns The theme id.\n * @throws When used outside that provider.\n */\nexport function useThemeId(): string {\n return useThemeSettingsContext(\"useThemeId\").themeId;\n}\n\n/** The theme id, or null outside a ThemeSettingsProvider (e.g. a store 404). */\nexport function useOptionalThemeId(): string | null {\n return useContext(ThemeSettingsContext)?.themeId ?? null;\n}\n\n/**\n * The registry key of the theme code rendering (\"meridian@1\"), else its id;\n * null outside a ThemeSettingsProvider. Client registries look up by it.\n */\nexport function useOptionalThemeKey(): string | null {\n const ctx = useContext(ThemeSettingsContext);\n return ctx ? (ctx.themeKey ?? ctx.themeId) : null;\n}\n"],"mappings":";AA4BI;AA1BJ,SAAS,eAAe,YAAY,eAA+B;AAUnE,MAAM,uBAAuB;AAAA,EAC3B;AACF;AAGO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAwD;AACtD,QAAM,QAAQ;AAAA,IACZ,OAAO,EAAE,SAAS,UAAU,SAAS;AAAA,IACrC,CAAC,SAAS,UAAU,QAAQ;AAAA,EAC9B;AACA,SACE,oBAAC,qBAAqB,UAArB,EAA8B,OAC5B,UACH;AAEJ;AAEA,SAAS,wBAAwB,MAAyC;AACxE,QAAM,MAAM,WAAW,oBAAoB;AAC3C,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,GAAG,IAAI,8CAA8C;AAAA,EACvE;AACA,SAAO;AACT;AAGO,SAAS,mBAAuC;AACrD,SAAO,wBAAwB,kBAAkB,EAAE;AACrD;AAUO,SAAS,aAAqB;AACnC,SAAO,wBAAwB,YAAY,EAAE;AAC/C;AAGO,SAAS,qBAAoC;AAClD,SAAO,WAAW,oBAAoB,GAAG,WAAW;AACtD;AAMO,SAAS,sBAAqC;AACnD,QAAM,MAAM,WAAW,oBAAoB;AAC3C,SAAO,MAAO,IAAI,YAAY,IAAI,UAAW;AAC/C;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/style.tsx"],"sourcesContent":["const VAR_NAME = /^--[a-zA-Z0-9-]+$/;\n/** Anything that could end the declaration, the rule or the <style> tag. */\nconst UNSAFE_VALUE = /[<>{};\\\\\\r\\n]/;\n\n/** A `:root{…}` rule from a theme's custom properties; null when empty. */\nexport function themeStyleCss(\n vars: Record<string, string> | null | undefined\n): string | null {\n if (!vars) return null;\n const declarations = Object.entries(vars)\n .filter(\n ([name, value]) =>\n VAR_NAME.test(name) &&\n typeof value === \"string\" &&\n value.trim() !== \"\" &&\n !UNSAFE_VALUE.test(value)\n )\n .map(([name, value]) => `${name}:${value.trim()}`);\n return declarations.length ? `:root{${declarations.join(\";\")}}` : null;\n}\n\nexport function ThemeStyle({\n vars,\n}: {\n vars: Record<string, string> | null | undefined;\n}) {\n const css = themeStyleCss(vars);\n return css ? <style dangerouslySetInnerHTML={{ __html: css }} /> : null;\n}\n"],"mappings":"AA2Be;AA3Bf,MAAM,WAAW;AAEjB,MAAM,eAAe;AAGd,SAAS,cACd,MACe;AACf,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,eAAe,OAAO,QAAQ,IAAI,EACrC;AAAA,IACC,CAAC,CAAC,MAAM,KAAK,MACX,SAAS,KAAK,IAAI,KAClB,OAAO,UAAU,YACjB,MAAM,KAAK,MAAM,MACjB,CAAC,aAAa,KAAK,KAAK;AAAA,EAC5B,EACC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,MAAM,KAAK,CAAC,EAAE;AACnD,SAAO,aAAa,SAAS,SAAS,aAAa,KAAK,GAAG,CAAC,MAAM;AACpE;AAEO,SAAS,WAAW;AAAA,EACzB;AACF,GAEG;AACD,QAAM,MAAM,cAAc,IAAI;AAC9B,SAAO,MAAM,oBAAC,WAAM,yBAAyB,EAAE,QAAQ,IAAI,GAAG,IAAK;AACrE;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/style.tsx"],"sourcesContent":["const VAR_NAME = /^--[a-zA-Z0-9-]+$/;\n/** Anything that could end the declaration, the rule or the <style> tag. */\nconst UNSAFE_VALUE = /[<>{};\\\\\\r\\n]/;\n\n/** A `:root{…}` rule from a theme's custom properties; null when empty. */\nexport function themeStyleCss(\n vars: Record<string, string> | null | undefined\n): string | null {\n if (!vars) return null;\n const declarations = Object.entries(vars)\n .filter(\n ([name, value]) =>\n VAR_NAME.test(name) &&\n typeof value === \"string\" &&\n value.trim() !== \"\" &&\n !UNSAFE_VALUE.test(value)\n )\n .map(([name, value]) => `${name}:${value.trim()}`);\n return declarations.length ? `:root{${declarations.join(\";\")}}` : null;\n}\n\n/**\n * Renders a theme's CSS custom properties as a `:root` style tag. Names that\n * are not `--custom-properties` and unsafe values are dropped.\n *\n * @param props.vars - The properties by name, for example from the theme's `styles` function.\n * @returns A `<style>` element, or `null` when no property is usable.\n */\nexport function ThemeStyle({\n vars,\n}: {\n vars: Record<string, string> | null | undefined;\n}) {\n const css = themeStyleCss(vars);\n return css ? <style dangerouslySetInnerHTML={{ __html: css }} /> : null;\n}\n"],"mappings":"AAkCe;AAlCf,MAAM,WAAW;AAEjB,MAAM,eAAe;AAGd,SAAS,cACd,MACe;AACf,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,eAAe,OAAO,QAAQ,IAAI,EACrC;AAAA,IACC,CAAC,CAAC,MAAM,KAAK,MACX,SAAS,KAAK,IAAI,KAClB,OAAO,UAAU,YACjB,MAAM,KAAK,MAAM,MACjB,CAAC,aAAa,KAAK,KAAK;AAAA,EAC5B,EACC,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,MAAM,KAAK,CAAC,EAAE;AACnD,SAAO,aAAa,SAAS,SAAS,aAAa,KAAK,GAAG,CAAC,MAAM;AACpE;AASO,SAAS,WAAW;AAAA,EACzB;AACF,GAEG;AACD,QAAM,MAAM,cAAc,IAAI;AAC9B,SAAO,MAAM,oBAAC,WAAM,yBAAyB,EAAE,QAAQ,IAAI,GAAG,IAAK;AACrE;","names":[]}
package/dist/theme.d.ts CHANGED
@@ -108,6 +108,39 @@ interface AnyThemeDefinition {
108
108
  components: ThemeComponents<any>;
109
109
  styles?: (settings: any) => Record<string, string>;
110
110
  }
111
+ /**
112
+ * Declares a theme: its info, its settings schema, the slot components it
113
+ * renders and, optionally, the CSS custom properties its settings produce.
114
+ * The theme module default-exports the result, and the storefront's routes
115
+ * render its slots with the store's saved settings. Returns the theme
116
+ * unchanged; it only types the settings from the schema.
117
+ *
118
+ * @param theme - The theme definition.
119
+ * @returns The same definition.
120
+ *
121
+ * @example
122
+ * ```tsx
123
+ * import { defineSchema, defineTheme } from "@ecomweb/storefront-kit/theme";
124
+ *
125
+ * const schema = defineSchema([
126
+ * {
127
+ * name: "Colors",
128
+ * settings: [
129
+ * { type: "color", id: "primary", label: "Primary", default: "#111111" },
130
+ * ],
131
+ * },
132
+ * ]);
133
+ *
134
+ * export default defineTheme({
135
+ * info: { id: "my-theme", name: "My theme", version: "1.0.0", author: "Me" },
136
+ * schema,
137
+ * styles: s => ({ "--primary": s.primary }),
138
+ * components: {
139
+ * Layout: ({ children }) => <main>{children}</main>,
140
+ * },
141
+ * });
142
+ * ```
143
+ */
111
144
  declare function defineTheme<const S extends ThemeSchema>(theme: ThemeDefinition<S>): ThemeDefinition<S>;
112
145
 
113
146
  export { type AnyThemeDefinition, type BlogIndexSlotProps, type BlogPostSlotProps, type CollectionPageSlotProps, type CollectionSearchParams, type ContentPageSlotProps, type HomePageSlotProps, type LayoutSlotProps, type NotFoundProps, type ProductCardProps, type ProductPageSlotProps, type ThemeClientComponents, type ThemeComponents, type ThemeDefinition, type ThemeInfo, type ThemeSlot, type ThemeSlotName, type ThemeSlotProps, defineSchema, defineTheme };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,7 +39,11 @@
39
39
  "publishConfig": {
40
40
  "access": "public"
41
41
  },
42
+ "bin": {
43
+ "ecomweb-check-client-bundle": "./bin/check-client-bundle.mjs"
44
+ },
42
45
  "files": [
46
+ "bin",
43
47
  "dist",
44
48
  "README.md",
45
49
  "LICENSE"
@@ -49,7 +53,7 @@
49
53
  "currency.js": "^2.0.4",
50
54
  "server-only": "^0.0.1",
51
55
  "zod": "^4.1.12",
52
- "@ecomweb/sdk": "^0.14.0"
56
+ "@ecomweb/sdk": "^0.15.0"
53
57
  },
54
58
  "peerDependencies": {
55
59
  "next": ">=16",