@ecomweb/storefront-kit 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +57 -2
  2. package/dist/api/client.js +32 -1
  3. package/dist/api/client.js.map +1 -1
  4. package/dist/api/proxy.js +29 -4
  5. package/dist/api/proxy.js.map +1 -1
  6. package/dist/api/store-preview-header.js +42 -0
  7. package/dist/api/store-preview-header.js.map +1 -0
  8. package/dist/auth/error-copy.js +2 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/session-refresh.js +2 -0
  11. package/dist/auth/session-refresh.js.map +1 -1
  12. package/dist/cart/server-context.js +26 -0
  13. package/dist/cart/server-context.js.map +1 -1
  14. package/dist/checkout/use-checkout.js +9 -0
  15. package/dist/checkout/use-checkout.js.map +1 -1
  16. package/dist/index.d.ts +69 -3
  17. package/dist/index.js +14 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/middleware/create-storefront-middleware.js +58 -11
  20. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  21. package/dist/middleware.d.ts +5 -2
  22. package/dist/provider.js +22 -0
  23. package/dist/provider.js.map +1 -1
  24. package/dist/redirects/lookup-redirect.js +2 -1
  25. package/dist/redirects/lookup-redirect.js.map +1 -1
  26. package/dist/server.d.ts +20 -1
  27. package/dist/server.js +4 -0
  28. package/dist/server.js.map +1 -1
  29. package/dist/stores/get-store-by-host.js +34 -7
  30. package/dist/stores/get-store-by-host.js.map +1 -1
  31. package/dist/stores/metadata.js +17 -0
  32. package/dist/stores/metadata.js.map +1 -1
  33. package/dist/stores/read-store-preview-token.js +10 -0
  34. package/dist/stores/read-store-preview-token.js.map +1 -0
  35. package/dist/stores/resolve-coming-soon.js +30 -0
  36. package/dist/stores/resolve-coming-soon.js.map +1 -0
  37. package/dist/stores/store-coming-soon.js +21 -0
  38. package/dist/stores/store-coming-soon.js.map +1 -0
  39. package/dist/stores/store-preview-cookie.js +64 -0
  40. package/dist/stores/store-preview-cookie.js.map +1 -0
  41. package/dist/stores/store-preview-guard.js +12 -0
  42. package/dist/stores/store-preview-guard.js.map +1 -0
  43. package/dist/stores/store-subdomain.js +10 -5
  44. package/dist/stores/store-subdomain.js.map +1 -1
  45. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n const items: CartItem[] = cart.items.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n loadCart();\n }, [loadCart]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAiWI;AA/VJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAE1B,SAAS,sBAAoD;AAqB7D,MAAM,cAAc,CAAC,OAAkB,WAAkC;AACvE,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,OAAO;AAAA,MACpB;AAAA,IAEF,KAAK,aAAa;AAChB,YAAM,OAAO,OAAO;AACpB,YAAM,QAAoB,KAAK,MAAM,IAAI,CAAC,UAAuB;AAAA,QAC/D,IAAI,KAAK;AAAA,QACT,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,cAAc;AAAA,QAC9B,MAAM,KAAK;AAAA,QACX,OAAO,KAAK;AAAA,QACZ,eAAe,KAAK;AAAA,QACpB,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,YAAY,KAAK;AAAA,QACjB,eAAe,KAAK;AAAA,MACtB,EAAE;AAEF,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,kBAAkB,KAAK;AAAA,QACvB,gBAAgB,KAAK;AAAA,QACrB,aAAa,KAAK;AAAA,QAClB,WAAW,KAAK;AAAA,QAChB,QAAQ,KAAK;AAAA,QACb,WAAW;AAAA,MACb;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C;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,cAAc,YAAY;AAC9B,UAAM,SAAS;AAAA,EACjB;AAEA,QAAM,aAAa,OAAO,YAAoB;AAC5C,QAAI,CAAC,YAAY,CAAC,MAAM,UAAW;AAEnC,QAAI;AACF,YAAM,eAAe,WAAW,QAAQ;AAGxC,YAAM,SAAS;AAEf,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,KAAK;AAC7C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SACE;AAAA,IAAC,YAAY;AAAA,IAAZ;AAAA,MACC,OAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
1
+ {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n const items: CartItem[] = cart.items.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n loadCart();\n }, [loadCart]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AA2XI;AAzXJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAE/C,SAAS,sBAAoD;AAqB7D,MAAM,cAAc,CAAC,OAAkB,WAAkC;AACvE,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,OAAO;AAAA,MACpB;AAAA,IAEF,KAAK,aAAa;AAChB,YAAM,OAAO,OAAO;AACpB,YAAM,QAAoB,KAAK,MAAM,IAAI,CAAC,UAAuB;AAAA,QAC/D,IAAI,KAAK;AAAA,QACT,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,cAAc;AAAA,QAC9B,MAAM,KAAK;AAAA,QACX,OAAO,KAAK;AAAA,QACZ,eAAe,KAAK;AAAA,QACpB,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,YAAY,KAAK;AAAA,QACjB,eAAe,KAAK;AAAA,MACtB,EAAE;AAEF,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,kBAAkB,KAAK;AAAA,QACvB,gBAAgB,KAAK;AAAA,QAC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A,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
3
3
  import {
4
4
  SHIPPING_ERROR_CODES
5
5
  } from "@ecomweb/sdk";
6
+ import { isBrowserStorePreview } from "../api/store-preview-header.js";
6
7
  import { useAuth } from "../auth/context.js";
7
8
  import { useCart } from "../cart/server-context.js";
8
9
  import { useNotify } from "../notices.js";
@@ -11,6 +12,7 @@ import { usePromotionValidation } from "../promotions/use-promotion-validation.j
11
12
  import { sdk } from "../sdk.js";
12
13
  import { useShippingCalculation } from "../shipping/use-shipping-calculation.js";
13
14
  import { useStoreData } from "../store/store-context.js";
15
+ import { STORE_PREVIEW_READ_ONLY_MESSAGE } from "../stores/store-preview-guard.js";
14
16
  import { initiateGatewayPayment } from "./initiate-gateway-payment.js";
15
17
  import { writeOrderHandoff } from "./order-handoff.js";
16
18
  import {
@@ -112,6 +114,13 @@ function useCheckout({
112
114
  if (inFlight.current) {
113
115
  return { kind: "busy" };
114
116
  }
117
+ if (isBrowserStorePreview()) {
118
+ return {
119
+ kind: "error",
120
+ message: STORE_PREVIEW_READ_ONLY_MESSAGE,
121
+ code: "STORE_COMING_SOON"
122
+ };
123
+ }
115
124
  inFlight.current = true;
116
125
  setIsSubmitting(true);
117
126
  setStockIssues({});
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AA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AAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,EACxB,oBAAoB;AACtB,GAAuB;AACrB,QAAM,QAAQ,aAAa;AAC3B,QAAM,SAAS,UAAU;AACzB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAC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IACA;AAAA,IACA,UAAU;AAAA,MACR,KAAK,cAAc;AAAA,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA;AAAA,MAEjC,YAAY,cAAc;AAAA,MAC1B,kBAAkB,cAAc;AAAA,MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -32,13 +32,38 @@ interface StorefrontKitProviderProps {
32
32
  storeRef?: string;
33
33
  /** Receives the kit's notices (item added, request failed, …). */
34
34
  onNotice?: NoticeHandler;
35
+ /**
36
+ * The store preview token the browser's kit clients send as
37
+ * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout
38
+ * passes it only while the store is coming soon, else null.
39
+ *
40
+ * Why the browser gets it: the preview cookie stays httpOnly, but without
41
+ * the token the client-side fetches on the home, collection and product
42
+ * pages would get the API's 403 during a preview. It is one of three
43
+ * tokens: the store preview cookie's (the dashboard's preview link), a
44
+ * theme preview host's (`p-<slug>`, from the host lookup), or the theme
45
+ * preview cookie's (`?preview_theme=` on the store's own host). Each is
46
+ * read-only (the API opens GET and HEAD only) and bound to one store.
47
+ * Merchant scripts are off during a store preview, so they never see it.
48
+ */
49
+ storePreviewToken?: string | null;
50
+ /**
51
+ * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.
52
+ * The app passes it only on a theme preview host, whose token lasts 1 h:
53
+ * the layout does not re-render on client navigation, so the first
54
+ * render's token would run out in a long editor session. While both are
55
+ * set, the kit calls it every 30 minutes, and when a read is refused with
56
+ * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h
57
+ * cookie is not renewed.
58
+ */
59
+ onStorePreviewRenew?: () => void;
35
60
  children: ReactNode;
36
61
  }
37
62
  /**
38
63
  * The kit's providers in their required order: auth reads the store, and the
39
64
  * cart reads the signed-in identity from auth.
40
65
  */
41
- declare function StorefrontKitProvider({ store, storeRef, onNotice, children, }: StorefrontKitProviderProps): react_jsx_runtime.JSX.Element;
66
+ declare function StorefrontKitProvider({ store, storeRef, onNotice, storePreviewToken, onStorePreviewRenew, children, }: StorefrontKitProviderProps): react_jsx_runtime.JSX.Element;
42
67
 
43
68
  interface CartItem {
44
69
  id: string;
@@ -1115,15 +1140,23 @@ declare const getCachedStore: (storeRef: string, options?: {
1115
1140
  includeBlogSettings?: boolean;
1116
1141
  }) => Promise<StoreConfigurationInfo | null>;
1117
1142
 
1143
+ /** Shared copy: the coming soon metadata description and the coming soon page. */
1144
+ declare const COMING_SOON_STORE_DESCRIPTION = "C\u1EEDa h\u00E0ng \u0111ang chu\u1EA9n b\u1ECB v\u00E0 s\u1EBD s\u1EDBm m\u1EDF c\u1EEDa.";
1118
1145
  /**
1119
1146
  * The metadata Next.js shows for a store's suspended pages. Never includes
1120
1147
  * `platform_suspension_reason` -- it's internal, written by an admin for
1121
1148
  * other admins.
1122
1149
  */
1123
1150
  declare const SUSPENDED_STORE_METADATA: Metadata;
1151
+ /**
1152
+ * The metadata for a store the merchant has not opened yet. `name` comes from
1153
+ * the coming soon error's details and may be missing.
1154
+ */
1155
+ declare function comingSoonStoreMetadata(name: string | null): Metadata;
1124
1156
  /**
1125
1157
  * Wraps a leaf page's `generateMetadata` body so a STORE_SUSPENDED lookup
1126
- * doesn't crash the whole route.
1158
+ * doesn't crash the whole route. A STORE_COMING_SOON lookup gets
1159
+ * `comingSoonStoreMetadata` the same way.
1127
1160
  *
1128
1161
  * Next.js resolves every matched segment's `generateMetadata` unconditionally
1129
1162
  * to build <head> -- this happens independently of whatever the parent
@@ -1144,6 +1177,17 @@ declare function withSuspendedStoreMetadataFallback(fn: () => Promise<Metadata>)
1144
1177
  */
1145
1178
  declare function refFromPathname(pathname: string): string | null;
1146
1179
 
1180
+ /**
1181
+ * What the shopper sees when a store preview refuses a write. A preview is
1182
+ * read-only: the API opens GET and HEAD for a preview token and answers
1183
+ * every write on a coming soon store with `STORE_COMING_SOON`. So the cart
1184
+ * and checkout refuse in the browser first, without sending the request
1185
+ * (`isBrowserStorePreview()` in `api/store-preview-header.ts`).
1186
+ *
1187
+ * `placeOrder` returns the message; the cart writes notify the notice.
1188
+ */
1189
+ declare const STORE_PREVIEW_READ_ONLY_MESSAGE = "\u0110ang xem tr\u01B0\u1EDBc: ch\u01B0a th\u1EC3 \u0111\u1EB7t h\u00E0ng khi c\u1EEDa h\u00E0ng ch\u01B0a m\u1EDF c\u1EEDa.";
1190
+
1147
1191
  /**
1148
1192
  * True when `error` is the backend's signal that a PLATFORM admin suspended
1149
1193
  * this store (`STORE_SUSPENDED`, 403) — distinct from the store simply not
@@ -1158,6 +1202,28 @@ declare function refFromPathname(pathname: string): string | null;
1158
1202
  */
1159
1203
  declare function isStoreSuspendedError(error: unknown): boolean;
1160
1204
 
1205
+ /**
1206
+ * True when `error` is the backend's signal that the merchant has not opened
1207
+ * this store yet (`STORE_COMING_SOON`, 403, details `{ name }`). Unlike
1208
+ * `STORE_SUSPENDED`, this is a merchant-controlled state, and the API lifts
1209
+ * it for a request carrying a valid `X-Store-Preview` token.
1210
+ *
1211
+ * Both `getCachedStore` and `getStoreByHost` surface it as an
1212
+ * `ApiClientError`, so this is the one place that decides "was that coming
1213
+ * soon" for both entry points.
1214
+ */
1215
+ declare function isStoreComingSoonError(error: unknown): boolean;
1216
+ /**
1217
+ * The store name the API puts in a coming soon error's `details`, or null
1218
+ * when the error is not coming soon or carries no usable name.
1219
+ */
1220
+ declare function comingSoonStoreNameOf(error: unknown): string | null;
1221
+ /**
1222
+ * Where the axios interceptor (lib/api/client.ts) sends the browser when a
1223
+ * client-side call discovers mid-session that the store is coming soon.
1224
+ */
1225
+ declare const STORE_COMING_SOON_REDIRECT_PATH = "/coming-soon";
1226
+
1161
1227
  /**
1162
1228
  * Lightweight logging helpers: log levels + console filtering.
1163
1229
  * - Defaults to 'warn' in production and 'debug' in development
@@ -1168,4 +1234,4 @@ declare function getLogLevel(): LogLevel;
1168
1234
  declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
1169
1235
  declare function applyConsoleFilter(level?: LogLevel): void;
1170
1236
 
1171
- export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPMENT_STATUS_LABELS, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, type ShipmentTrackingView, type ShippingOptionDisplay, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, TRACKING_MESSAGES, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, canCustomerCancel, createStoreSdk, deriveOrderProgress, deriveShipmentTracking, describeShippingOption, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isCarrierShipment, isHandedToCarrier, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, optionIdOf, pollPaymentState, publicApiClient, quoteChangedOptionsFrom, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shipmentEventLabel, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
1237
+ export { type BankAccountView, COMING_SOON_STORE_DESCRIPTION, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPMENT_STATUS_LABELS, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, STORE_COMING_SOON_REDIRECT_PATH, STORE_PREVIEW_READ_ONLY_MESSAGE, SUSPENDED_STORE_METADATA, type ShipmentTrackingView, type ShippingOptionDisplay, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, TRACKING_MESSAGES, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, canCustomerCancel, comingSoonStoreMetadata, comingSoonStoreNameOf, createStoreSdk, deriveOrderProgress, deriveShipmentTracking, describeShippingOption, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isCarrierShipment, isHandedToCarrier, isStoreComingSoonError, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, optionIdOf, pollPaymentState, publicApiClient, quoteChangedOptionsFrom, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shipmentEventLabel, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
package/dist/index.js CHANGED
@@ -98,13 +98,22 @@ import {
98
98
  } from "./theme/preview-bridge.js";
99
99
  import { getCachedStore } from "./stores/cached.js";
100
100
  import {
101
+ COMING_SOON_STORE_DESCRIPTION,
102
+ comingSoonStoreMetadata,
101
103
  SUSPENDED_STORE_METADATA,
102
104
  withSuspendedStoreMetadataFallback
103
105
  } from "./stores/metadata.js";
104
106
  import { refFromPathname } from "./stores/store-path.js";
107
+ import { STORE_PREVIEW_READ_ONLY_MESSAGE } from "./stores/store-preview-guard.js";
105
108
  import { isStoreSuspendedError } from "./stores/store-suspension.js";
109
+ import {
110
+ comingSoonStoreNameOf,
111
+ isStoreComingSoonError,
112
+ STORE_COMING_SOON_REDIRECT_PATH
113
+ } from "./stores/store-coming-soon.js";
106
114
  import { applyConsoleFilter, getLogLevel, shouldLog } from "./logging.js";
107
115
  export {
116
+ COMING_SOON_STORE_DESCRIPTION,
108
117
  DEFAULT_REDIRECT,
109
118
  ORDER_PROGRESS_STEPS,
110
119
  RichText,
@@ -112,6 +121,8 @@ export {
112
121
  SHIPPING_MESSAGES,
113
122
  STATUS_OPTIONS,
114
123
  STOCK_ISSUE_TOAST_DESCRIPTION,
124
+ STORE_COMING_SOON_REDIRECT_PATH,
125
+ STORE_PREVIEW_READ_ONLY_MESSAGE,
115
126
  SUSPENDED_STORE_METADATA,
116
127
  StorefrontKitProvider,
117
128
  THEME_PREVIEW_FRAME_ATTR,
@@ -123,6 +134,8 @@ export {
123
134
  applyConsoleFilter,
124
135
  buildStoreUrl,
125
136
  canCustomerCancel,
137
+ comingSoonStoreMetadata,
138
+ comingSoonStoreNameOf,
126
139
  createStoreSdk,
127
140
  defineSchema,
128
141
  defineTheme,
@@ -149,6 +162,7 @@ export {
149
162
  getPromotionDescription,
150
163
  isCarrierShipment,
151
164
  isHandedToCarrier,
165
+ isStoreComingSoonError,
152
166
  isStoreSuspendedError,
153
167
  loadWards,
154
168
  metafield,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAqB1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;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AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uCAAuC;AAChD,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
@@ -3,7 +3,8 @@ import { REQUEST_PATH_HEADER } from "../request/request-path.js";
3
3
  import {
4
4
  applyThemePreview,
5
5
  hasThemePreview,
6
- THEME_PREVIEW_PARAM
6
+ THEME_PREVIEW_PARAM,
7
+ themePreviewCookieName
7
8
  } from "../theme/preview-cookie.js";
8
9
  import {
9
10
  externalStorefrontUrl,
@@ -19,6 +20,13 @@ import { publicConfig } from "../config/public.js";
19
20
  import { lookupRedirect } from "../redirects/lookup-redirect.js";
20
21
  import { multiTenantStorePath } from "../store-scope/index.js";
21
22
  import { getStoreByHost } from "../stores/get-store-by-host.js";
23
+ import { STORE_COMING_SOON_REDIRECT_PATH } from "../stores/store-coming-soon.js";
24
+ import {
25
+ applyStorePreview,
26
+ STORE_PREVIEW_PATH,
27
+ STORE_PREVIEW_TOKEN_HEADER,
28
+ storePreviewCookieName
29
+ } from "../stores/store-preview-cookie.js";
22
30
  import { getStoreSubdomain } from "../stores/store-subdomain.js";
23
31
  import { recordStoreRequest } from "../stores/store-traffic.js";
24
32
  import {
@@ -54,13 +62,25 @@ function externalThemeResponse(req, host, storeRef, externalUrl) {
54
62
  const url = req.nextUrl.clone();
55
63
  url.pathname = DOMAIN_NOT_CONNECTED_PATH;
56
64
  url.search = "";
57
- const res = NextResponse.rewrite(url);
65
+ const res = NextResponse.rewrite(url, withoutInternalHeaders(req));
58
66
  res.headers.set("x-robots-tag", "noindex");
59
67
  return res;
60
68
  }
61
69
  const safe = req.method === "GET" || req.method === "HEAD";
62
70
  return NextResponse.redirect(target, { status: safe ? 302 : 307 });
63
71
  }
72
+ function withoutInternalHeaders(req) {
73
+ const headers = new Headers(req.headers);
74
+ headers.delete(THEME_PREVIEW_HOST_HEADER);
75
+ headers.delete(STORE_PREVIEW_TOKEN_HEADER);
76
+ return { request: { headers } };
77
+ }
78
+ function hasStorePreview(req, cookiePath) {
79
+ return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;
80
+ }
81
+ function hostLookupPreviewToken(req) {
82
+ return req.cookies.get(storePreviewCookieName("/"))?.value || req.cookies.get(themePreviewCookieName("/"))?.value || null;
83
+ }
64
84
  function storeRefFromPath(pathname) {
65
85
  const match = /^\/store\/([^/]+)/.exec(pathname);
66
86
  if (!match) return null;
@@ -86,7 +106,7 @@ async function apexStoreResponse(req, storeRef, platformDomain) {
86
106
  const url = req.nextUrl.clone();
87
107
  url.pathname = "/404";
88
108
  url.search = "";
89
- return NextResponse.rewrite(url);
109
+ return NextResponse.rewrite(url, withoutInternalHeaders(req));
90
110
  }
91
111
  const prefix = multiTenantStorePath(storeRef);
92
112
  const pathname = req.nextUrl.pathname;
@@ -102,7 +122,7 @@ async function multiTenant(req) {
102
122
  const pathname = req.nextUrl.pathname;
103
123
  const isMetadataFile = METADATA_FILES.includes(pathname);
104
124
  if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {
105
- return NextResponse.next();
125
+ return NextResponse.next(withoutInternalHeaders(req));
106
126
  }
107
127
  const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
108
128
  const hostIdentifiesStore = !host.includes("localhost") && !host.includes("127.0.0.1") && host !== platformDomain && host !== `www.${platformDomain}`;
@@ -112,19 +132,28 @@ async function multiTenant(req) {
112
132
  if (apexStoreRef)
113
133
  return apexStoreResponse(req, apexStoreRef, platformDomain);
114
134
  }
135
+ if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {
136
+ return applyStorePreview(req, "/", "/");
137
+ }
115
138
  let hostStoreRef = null;
116
139
  let hostResolved = false;
117
140
  let hostStoreSuspended = false;
141
+ let hostStoreComingSoon = false;
118
142
  let previewSlug = null;
119
- if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();
143
+ let storePreviewToken = null;
144
+ if (isMetadataFile && !hostIdentifiesStore)
145
+ return NextResponse.next(withoutInternalHeaders(req));
120
146
  if (hostIdentifiesStore) {
121
147
  try {
122
- const lookup = await getStoreByHost(host);
148
+ const previewToken = hostLookupPreviewToken(req);
149
+ const lookup = previewToken ? await getStoreByHost(host, { previewToken }) : await getStoreByHost(host);
123
150
  const { storeRef: storeRef2, domain, isSubDomain, suspended, externalUrl } = lookup;
124
151
  hostResolved = true;
125
152
  hostStoreRef = storeRef2 || null;
126
153
  hostStoreSuspended = suspended;
154
+ hostStoreComingSoon = !storeRef2 && !!lookup.comingSoon;
127
155
  previewSlug = storeRef2 ? lookup.previewSlug : null;
156
+ storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;
128
157
  if (previewSlug && isMetadataFile) {
129
158
  return pathname === "/robots.txt" ? new NextResponse(PREVIEW_HOST_ROBOTS, {
130
159
  headers: { "content-type": "text/plain" }
@@ -139,7 +168,7 @@ async function multiTenant(req) {
139
168
  );
140
169
  if (external) return external;
141
170
  }
142
- if (isMetadataFile) return NextResponse.next();
171
+ if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));
143
172
  if (storeRef2) {
144
173
  if (isSubDomain && domain && domain !== host && !previewSlug) {
145
174
  const url = publicNextUrl(req);
@@ -157,17 +186,24 @@ async function multiTenant(req) {
157
186
  }
158
187
  } catch (error) {
159
188
  console.debug("Middleware error:", error);
160
- if (isMetadataFile) return NextResponse.next();
189
+ if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));
161
190
  hostResolved = false;
162
191
  hostStoreRef = null;
163
192
  }
164
193
  }
165
194
  const storeRef = hostStoreRef ?? storeRefFromPath(pathname);
166
195
  if (storeRef) recordStoreRequest(storeRef);
196
+ if (hostStoreComingSoon) {
197
+ const preview = applyThemePreview(req, "/");
198
+ if (preview) return preview;
199
+ }
167
200
  const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;
168
201
  if (storeRef && cookiePath) {
169
202
  const preview = applyThemePreview(req, cookiePath);
170
203
  if (preview) return preview;
204
+ if (!hostIdentifiesStore && pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)) {
205
+ return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));
206
+ }
171
207
  }
172
208
  if (!hostStoreRef && storeRef) {
173
209
  const prefix = multiTenantStorePath(storeRef);
@@ -195,6 +231,8 @@ async function multiTenant(req) {
195
231
  `${req.nextUrl.pathname}${req.nextUrl.search}`
196
232
  );
197
233
  if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);
234
+ if (previewSlug && storePreviewToken)
235
+ downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);
198
236
  const init = { request: { headers: downstream } };
199
237
  let response;
200
238
  if (hostStoreRef) {
@@ -209,6 +247,11 @@ async function multiTenant(req) {
209
247
  const url = req.nextUrl.clone();
210
248
  url.pathname = "/store-suspended";
211
249
  response = NextResponse.rewrite(url, init);
250
+ } else if (hostStoreComingSoon) {
251
+ const url = req.nextUrl.clone();
252
+ url.pathname = STORE_COMING_SOON_REDIRECT_PATH;
253
+ response = NextResponse.rewrite(url, init);
254
+ response.headers.set("x-robots-tag", "noindex");
212
255
  } else if (hostResolved) {
213
256
  console.debug("Store not found for host:", host);
214
257
  const url = req.nextUrl.clone();
@@ -217,7 +260,8 @@ async function multiTenant(req) {
217
260
  } else {
218
261
  response = NextResponse.next(init);
219
262
  }
220
- if (previewSlug || cookiePath && hasThemePreview(req, cookiePath)) {
263
+ const storePreviewPath = hostIdentifiesStore ? "/" : cookiePath;
264
+ if (previewSlug || cookiePath && hasThemePreview(req, cookiePath) || storePreviewPath && hasStorePreview(req, storePreviewPath)) {
221
265
  response.headers.set("x-robots-tag", "noindex");
222
266
  }
223
267
  if (rotated && storeRef && cookiePath) {
@@ -227,9 +271,12 @@ async function multiTenant(req) {
227
271
  }
228
272
  async function singleStore(req) {
229
273
  const pathname = req.nextUrl.pathname;
230
- if (METADATA_FILES.includes(pathname)) return NextResponse.next();
274
+ if (METADATA_FILES.includes(pathname))
275
+ return NextResponse.next(withoutInternalHeaders(req));
231
276
  const storeRef = publicConfig().storeRef;
232
277
  const cookiePath = authCookiePath(storeRef, true);
278
+ if (pathname === STORE_PREVIEW_PATH)
279
+ return applyStorePreview(req, cookiePath, "/");
233
280
  const preview = applyThemePreview(req, cookiePath);
234
281
  if (preview) return preview;
235
282
  try {
@@ -248,7 +295,7 @@ async function singleStore(req) {
248
295
  headers: downstreamRequestHeaders(req, true, storeRef, rotated)
249
296
  }
250
297
  });
251
- if (hasThemePreview(req, cookiePath))
298
+ if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))
252
299
  response.headers.set("x-robots-tag", "noindex");
253
300
  if (rotated) {
254
301
  writeAuthCookies(response, storeRef, rotated, cookiePath);