@ecomweb/storefront-kit 0.13.1 → 0.14.1

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 (42) hide show
  1. package/README.md +26 -0
  2. package/dist/api/response.js.map +1 -1
  3. package/dist/auth/context.js.map +1 -1
  4. package/dist/auth/sdk.js +6 -2
  5. package/dist/auth/sdk.js.map +1 -1
  6. package/dist/cart/server-context.js.map +1 -1
  7. package/dist/checkout/use-checkout.js.map +1 -1
  8. package/dist/client-info.js +7 -0
  9. package/dist/client-info.js.map +1 -0
  10. package/dist/config/schema.js.map +1 -1
  11. package/dist/config/server.js.map +1 -1
  12. package/dist/config/version-check.js +94 -0
  13. package/dist/config/version-check.js.map +1 -0
  14. package/dist/config.d.ts +73 -4
  15. package/dist/config.js +9 -0
  16. package/dist/config.js.map +1 -1
  17. package/dist/currency.js.map +1 -1
  18. package/dist/index.d.ts +306 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/logging.js.map +1 -1
  21. package/dist/middleware.d.ts +2 -2
  22. package/dist/middleware.js.map +1 -1
  23. package/dist/{mode-Lm9t4qzX.d.ts → mode-DXo-EhTJ.d.ts} +1 -1
  24. package/dist/orders/shipment-tracking.js.map +1 -1
  25. package/dist/provider.js.map +1 -1
  26. package/dist/{schema-Dg0ZflMW.d.ts → schema-DIF0CZNV.d.ts} +4 -0
  27. package/dist/sdk.js +5 -2
  28. package/dist/sdk.js.map +1 -1
  29. package/dist/server.d.ts +9 -1
  30. package/dist/server.js.map +1 -1
  31. package/dist/shipping/location-areas.js.map +1 -1
  32. package/dist/storage.js.map +1 -1
  33. package/dist/store/store-context.js.map +1 -1
  34. package/dist/store-scope/index.js.map +1 -1
  35. package/dist/stores/basic-settings.js.map +1 -1
  36. package/dist/stores/cached.js.map +1 -1
  37. package/dist/theme/define.js.map +1 -1
  38. package/dist/theme/index.js.map +1 -1
  39. package/dist/theme/settings-context.js.map +1 -1
  40. package/dist/theme/style.js.map +1 -1
  41. package/dist/theme.d.ts +33 -0
  42. package/package.json +5 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/middleware.ts"],"sourcesContent":["// @ecomweb/storefront-kit/middleware: the storefront's proxy.ts.\nexport {\n createStorefrontMiddleware,\n storefrontMiddlewareConfig,\n} from \"./middleware/create-storefront-middleware\";\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
1
+ {"version":3,"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * The storefront's request middleware (`proxy.ts`): store routing and the\n * checks that run before a page renders.\n *\n * Import from `@ecomweb/storefront-kit/middleware` in the storefront's\n * `proxy.ts` (or `middleware.ts`).\n *\n * @packageDocumentation\n */\nexport {\n createStorefrontMiddleware,\n storefrontMiddlewareConfig,\n} from \"./middleware/create-storefront-middleware\";\n"],"mappings":"AASA;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
@@ -1,4 +1,4 @@
1
- import { E as EnvSource } from './schema-Dg0ZflMW.js';
1
+ import { E as EnvSource } from './schema-DIF0CZNV.js';
2
2
 
3
3
  /**
4
4
  * multi: the shared platform storefront, every store under /store/<ref> or
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AACb;AAEO,MAAM,oBAAoB;AAAA,EAC/B,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,eAAe;AACjB;AAYA,MAAM,uBAAuB,CAAC,WAAW,aAAa,YAAY;AAClE,MAAM,iBAA2B,CAAC,aAAa,UAAU,UAAU;AAEnE,SAAS,eAAe,MAAgD;AACtE,SAAO,QAAQ,gBAAgB,KAAK,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,IAAI;AACnE;AAEA,SAAS,YAAY,QAAkD;AACrE,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,OAAO,UAAU,eAAe,KAAK,wBAAwB,MAAM,IACtE,uBAAuB,MAAwB,IAC/C;AACN;AAEO,SAAS,uBACd,OAC6B;AAC7B,QAAM,WAAW,MAAM;AAIvB,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,UAAU;AACZ,WAAO;AAAA,MACL,aAAa,SAAS,gBAAgB;AAAA,MACtC,gBAAgB,eAAe,SAAS,gBAAgB;AAAA,MACxD,aAAa,SAAS,gBAAgB;AAAA,MACtC,gBAAgB,SAAS,mBAAmB;AAAA,MAC5C,WAAW,eAAe,SAAS,UAAU;AAAA,MAC7C,aAAa,YAAY,SAAS,MAAM;AAAA,MACxC,QAAQ,SAAS,UAAU,CAAC;AAAA,IAC9B;AAAA,EACF;AACA,MAAI,MAAM,oBAAoB,MAAM,iBAAiB;AACnD,WAAO;AAAA,MACL,aAAa,MAAM,oBAAoB;AAAA,MACvC,gBAAgB;AAAA,MAChB,aAAa;AAAA,MACb,gBAAgB,MAAM,mBAAmB;AAAA,MACzC,WAAW;AAAA,MACX,aAAa;AAAA,MACb,QAAQ,CAAC;AAAA,IACX;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,kBAAkB,OAAuB;AACvD,MAAI,OAAO,MAAM,eAAe,UAAW,QAAO,MAAM;AACxD,SAAO,qBAAqB,SAAS,MAAM,YAAY;AACzD;AAEO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,SAAS,MAAM,UAAU;AAC/B,SAAO,CAAC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\n/**\n * Builds the shipment details to show for an order: carrier, tracking number,\n * tracking link, status and events. Uses the order's `shipment` when the API\n * sends one and falls back to the order's carrier and tracking fields for an\n * older API.\n *\n * @param order - The order to read.\n * @returns The shipment view, or `null` when there is nothing to show.\n */\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\n/**\n * Tells whether the shopper may still cancel the order. Follows the API's\n * `can_cancel` flag when present, else the order status.\n *\n * @param order - The order to check.\n * @returns `true` when the order can be cancelled.\n */\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\n/**\n * Tells whether the order's shipment has been handed to a carrier and is not\n * cancelled, failed or returned.\n *\n * @param order - The order to check.\n * @returns `true` while the shipment is with a carrier.\n */\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AACb;AAEO,MAAM,oBAAoB;AAAA,EAC/B,OAAO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M,SAAS,MAAM,UAAU;AAC/B,SAAO,CAAC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA8DI;AA5DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAoCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\n/** Props of {@link StorefrontKitProvider}. */\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA+DI;AA7DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAqCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
@@ -46,6 +46,10 @@ declare const serverConfigSchema: z.ZodObject<{
46
46
  storeTrafficLogPerMinute: z.ZodNumber;
47
47
  }, z.core.$strip>;
48
48
  type ServerConfig = z.infer<typeof serverConfigSchema>;
49
+ /**
50
+ * Thrown when the storefront's environment variables are missing or invalid.
51
+ * The message names the variable behind every bad field.
52
+ */
49
53
  declare class ConfigError extends Error {
50
54
  constructor(message: string);
51
55
  }
package/dist/sdk.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createEcomwebSdk } from "@ecomweb/sdk";
2
2
  import { createStoreApiClient, publicApiClient } from "./api/client.js";
3
+ import { KIT_CLIENT_TOKEN } from "./client-info.js";
3
4
  function requireStoreScopedSdk() {
4
5
  const fail = async () => ({
5
6
  success: false,
@@ -13,7 +14,8 @@ function requireStoreScopedSdk() {
13
14
  }
14
15
  const sdk = createEcomwebSdk({
15
16
  publicHttp: publicApiClient,
16
- authHttp: requireStoreScopedSdk()
17
+ authHttp: requireStoreScopedSdk(),
18
+ clientInfo: KIT_CLIENT_TOKEN
17
19
  });
18
20
  const storeSdks = /* @__PURE__ */ new Map();
19
21
  function createStoreSdk(storeRef) {
@@ -21,7 +23,8 @@ function createStoreSdk(storeRef) {
21
23
  if (cached) return cached;
22
24
  const created = createEcomwebSdk({
23
25
  publicHttp: publicApiClient,
24
- authHttp: createStoreApiClient(storeRef)
26
+ authHttp: createStoreApiClient(storeRef),
27
+ clientInfo: KIT_CLIENT_TOKEN
25
28
  });
26
29
  storeSdks.set(storeRef, created);
27
30
  return created;
package/dist/sdk.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AAQtD,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAClC,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,EACzC,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\nimport { KIT_CLIENT_TOKEN } from \"./client-info\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n clientInfo: KIT_CLIENT_TOKEN,\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n clientInfo: KIT_CLIENT_TOKEN,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AACtD,SAAS,wBAAwB;AAQjC,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAAA,EAChC,YAAY;AACd,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,IACvC,YAAY;AAAA,EACd,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextRequest } from 'next/server';
2
2
  import { CurrentIdentity } from '@ecomweb/sdk';
3
- import { E as EnvSource, S as ServerConfig } from './schema-Dg0ZflMW.js';
3
+ import { E as EnvSource, S as ServerConfig } from './schema-DIF0CZNV.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -46,6 +46,14 @@ declare function requireSession(storeRef: string, redirectTo: string): Promise<C
46
46
 
47
47
  /** Parses the variables of the mode `env` selects (see resolveMode). */
48
48
  declare function parseServerConfig(env: EnvSource): ServerConfig;
49
+ /**
50
+ * The server's parsed configuration, read from the environment on the first
51
+ * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`
52
+ * in server code, never in a client component.
53
+ *
54
+ * @returns The validated server config.
55
+ * @throws ConfigError when a required variable is missing or invalid.
56
+ */
49
57
  declare function serverConfig(): ServerConfig;
50
58
 
51
59
  /**
@@ -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 { 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,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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AC,cAAc;AACjB,iBAAW,KAAK;AAChB;AAAA,IACF;AACA,QAAI,YAAY;AAChB,eAAW,IAAI;AACf,cAAU,UAAU,YAAY,EAC7B,KAAK,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
+ {"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;AAWO,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;AASO,SAAS,aAAa,UAAkB;AAC7C,QAAM,CAAC,WAAW,YAAY,IAAI,SAAyB,CAAC,CAAC;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAE3C,YAAU,MAAM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AAS,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 +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,MAA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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,KAA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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;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;AAUO,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;AAYO,SAAS,eAAe;AAC7B,QAAM,EAAE,MAAM,IAAI,SAAS;AAC3B,SAAO;AACT;AAGO,SAAS,qBAAoC;AAClD,SAAO,WAAW,YAAY,GAAG,MAAM,OAAO;AAChD;AAUO,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;AAWO,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;AAWO,SAAS,iBAAyB;AACvC,QAAM,WAAW,iBAAiB;AAClC,SAAO,iBAAiB,QAAQ;AAClC;","names":[]}
@@ -1 +1 @@
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\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,15 +1,17 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.13.1",
3
+ "version": "0.14.1",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/ecomwebai/ecomweb-storefront.git",
10
+ "url": "https://github.com/ecomwebai/ecomweb-storefront-sdk.git",
11
11
  "directory": "packages/storefront-kit"
12
12
  },
13
+ "homepage": "https://github.com/ecomwebai/ecomweb-storefront-sdk/tree/main/packages/storefront-kit#readme",
14
+ "bugs": "https://github.com/ecomwebai/ecomweb-storefront-sdk/issues",
13
15
  "main": "./dist/index.js",
14
16
  "types": "./dist/index.d.ts",
15
17
  "exports": {
@@ -47,7 +49,7 @@
47
49
  "currency.js": "^2.0.4",
48
50
  "server-only": "^0.0.1",
49
51
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.13.1"
52
+ "@ecomweb/sdk": "^0.14.1"
51
53
  },
52
54
  "peerDependencies": {
53
55
  "next": ">=16",