@ecomweb/storefront-kit 0.6.0 → 0.10.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 (79) hide show
  1. package/README.md +28 -1
  2. package/dist/api/proxy.js +5 -1
  3. package/dist/api/proxy.js.map +1 -1
  4. package/dist/api/server-client.js +7 -4
  5. package/dist/api/server-client.js.map +1 -1
  6. package/dist/auth/cookies.js +51 -33
  7. package/dist/auth/cookies.js.map +1 -1
  8. package/dist/auth/error-copy.js +5 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/route-handlers.js +2 -2
  11. package/dist/auth/route-handlers.js.map +1 -1
  12. package/dist/auth/session-refresh.js +11 -5
  13. package/dist/auth/session-refresh.js.map +1 -1
  14. package/dist/auth/session.js +8 -4
  15. package/dist/auth/session.js.map +1 -1
  16. package/dist/checkout/get-payment-state.js.map +1 -1
  17. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  18. package/dist/checkout/order-handoff.js +10 -1
  19. package/dist/checkout/order-handoff.js.map +1 -1
  20. package/dist/checkout/quote-changed.js +16 -0
  21. package/dist/checkout/quote-changed.js.map +1 -0
  22. package/dist/checkout/use-checkout.js +44 -7
  23. package/dist/checkout/use-checkout.js.map +1 -1
  24. package/dist/config/schema.js +12 -1
  25. package/dist/config/schema.js.map +1 -1
  26. package/dist/config/server.js +9 -2
  27. package/dist/config/server.js.map +1 -1
  28. package/dist/config.d.ts +3 -3
  29. package/dist/index.d.ts +167 -26
  30. package/dist/index.js +37 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/middleware/create-storefront-middleware.js +62 -26
  33. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  34. package/dist/middleware.d.ts +2 -2
  35. package/dist/{mode-YNx2aOtQ.d.ts → mode-Lm9t4qzX.d.ts} +1 -1
  36. package/dist/orders/index.js +17 -1
  37. package/dist/orders/index.js.map +1 -1
  38. package/dist/orders/shipment-tracking.js +80 -0
  39. package/dist/orders/shipment-tracking.js.map +1 -0
  40. package/dist/promotions/use-promotion-validation.js +19 -16
  41. package/dist/promotions/use-promotion-validation.js.map +1 -1
  42. package/dist/{schema-Tc0qRs-Q.d.ts → schema-Dg0ZflMW.d.ts} +1 -0
  43. package/dist/server.d.ts +8 -2
  44. package/dist/server.js +2 -0
  45. package/dist/server.js.map +1 -1
  46. package/dist/shipping/format-shipping-option.js +28 -0
  47. package/dist/shipping/format-shipping-option.js.map +1 -1
  48. package/dist/shipping/messages.js +2 -0
  49. package/dist/shipping/messages.js.map +1 -1
  50. package/dist/shipping/option-id.js +7 -0
  51. package/dist/shipping/option-id.js.map +1 -0
  52. package/dist/shipping/shipping-calculation-reducer.js +61 -10
  53. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  54. package/dist/shipping/use-shipping-calculation.js +38 -5
  55. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  56. package/dist/stores/get-store-by-host.js +41 -6
  57. package/dist/stores/get-store-by-host.js.map +1 -1
  58. package/dist/stores/store-subdomain.js +25 -0
  59. package/dist/stores/store-subdomain.js.map +1 -0
  60. package/dist/stores/store-traffic.js +50 -0
  61. package/dist/stores/store-traffic.js.map +1 -0
  62. package/dist/stores/ttl-cache.js +34 -0
  63. package/dist/stores/ttl-cache.js.map +1 -0
  64. package/dist/theme/define.js.map +1 -1
  65. package/dist/theme/index.js.map +1 -1
  66. package/dist/theme/preview-bridge.js +33 -0
  67. package/dist/theme/preview-bridge.js.map +1 -0
  68. package/dist/theme/preview-cookie.js +13 -6
  69. package/dist/theme/preview-cookie.js.map +1 -1
  70. package/dist/theme/preview-host.js +7 -0
  71. package/dist/theme/preview-host.js.map +1 -0
  72. package/dist/theme/read-preview-host.js +10 -0
  73. package/dist/theme/read-preview-host.js.map +1 -0
  74. package/dist/theme/read-preview-token.js +5 -3
  75. package/dist/theme/read-preview-token.js.map +1 -1
  76. package/dist/theme/settings-context.js +14 -1
  77. package/dist/theme/settings-context.js.map +1 -1
  78. package/dist/theme.d.ts +65 -5
  79. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | { type: \"CALCULATION_SUCCEEDED\"; options: ShippingOption[]; requestId: number }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n const first = options.length > 0 ? options[0] : null;\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the first option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with a rate_id guaranteed to belong to THIS response,\n // so a stale rate from an earlier quote can never linger.\n selectedShippingRate: first ? first.rate_id : null,\n shippingFee: first ? first.amount : 0,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n // Preserves the previous fee if the id doesn't match a known\n // option -- shouldn't happen in practice (the UI only ever\n // dispatches a rate_id it just rendered from shippingOptions),\n // kept explicit rather than silently coercing the fee to 0.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AA+BO,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAkBO,SAAS,2BACd,OACA,QAC0B;AAC1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,QACnB,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK,yBAAyB;AAC5B,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,YAAM,EAAE,QAAQ,IAAI;AACpB,YAAM,QAAQ,QAAQ,SAAS,IAAI,QAAQ,CAAC,IAAI;AAChD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,QAKvB,sBAAsB,QAAQ,MAAM,UAAU;AAAA,QAC9C,aAAa,QAAQ,MAAM,SAAS;AAAA,QACpC,mBAAmB;AAAA,MACrB;AAAA,IACF;AAAA,IAEA,KAAK;AACH,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,aAAa;AAAA,QACb,iBAAiB,CAAC;AAAA,QAClB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MACrB;AAAA,IAEF,KAAK,iBAAiB;AACpB,YAAM,SAAS,MAAM,gBAAgB;AAAA,QACnC,SAAO,IAAI,YAAY,OAAO;AAAA,MAChC;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,sBAAsB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,QAK7B,aAAa,SAAS,OAAO,SAAS,MAAM;AAAA,MAC9C;AAAA,IACF;AAAA,IAEA;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { optionIdOf } from \"./option-id\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n /** The `rate_id` of the selected option; kept for existing callers. */\n selectedShippingRate: number | null;\n /**\n * The selected option's identity (`optionIdOf`). Several carrier options\n * can share one `rate_id`, so this, not the rate id, picks the option.\n */\n selectedOptionId: string | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /**\n * The current quote was re-priced (e.g. the API reported a changed\n * quote). Judged against the current `requestId` like\n * CALCULATION_SUCCEEDED, and does not bump it. MERGES by option id: the\n * given options replace matching entries, other existing options are\n * kept (the API re-checks their amounts at placement), and new ones are\n * appended. Keeps `preferOptionId` selected when it is still offered, else\n * the cheapest option.\n */\n | {\n type: \"QUOTE_REPLACED\";\n options: ShippingOption[];\n requestId: number;\n preferOptionId: string | null;\n }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"OPTION_SELECTED\"; optionId: string }\n /** @deprecated Use OPTION_SELECTED. Selects the first option with this rate_id. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\ninterface Selection {\n optionId: string | null;\n rateId: number | null;\n fee: number;\n}\n\n/**\n * Picks `preferId` when it is among `options`, else the cheapest option\n * (the API's order breaks ties), as shoppers expect: a free rate is never\n * passed over for a paid one.\n */\nfunction selectFrom(\n options: ShippingOption[],\n preferId: string | null\n): Selection {\n const preferred =\n preferId === null\n ? undefined\n : options.find(option => optionIdOf(option) === preferId);\n const chosen =\n preferred ??\n options.reduce<ShippingOption | null>(\n (best, option) => (!best || option.amount < best.amount ? option : best),\n null\n );\n return chosen\n ? {\n optionId: optionIdOf(chosen),\n rateId: chosen.rate_id,\n fee: chosen.amount,\n }\n : { optionId: null, rateId: null, fee: 0 };\n}\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n const picked = selectFrom(options, null);\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with an option guaranteed to belong to THIS response,\n // so a stale selection from an earlier quote can never linger.\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"QUOTE_REPLACED\": {\n if (action.requestId !== state.requestId) return state;\n const incoming = new Map(action.options.map(o => [optionIdOf(o), o]));\n const merged = state.shippingOptions.map(\n o => incoming.get(optionIdOf(o)) ?? o\n );\n const known = new Set(state.shippingOptions.map(optionIdOf));\n for (const o of action.options) {\n if (!known.has(optionIdOf(o))) {\n known.add(optionIdOf(o));\n merged.push(o);\n }\n }\n const picked = selectFrom(merged, action.preferOptionId);\n return {\n ...state,\n shippingOptions: merged,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"OPTION_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => optionIdOf(opt) === action.optionId\n );\n // An id that isn't in the current quote is ignored: the UI only\n // dispatches ids it just rendered from shippingOptions.\n if (!option) return state;\n return {\n ...state,\n selectedOptionId: optionIdOf(option),\n selectedShippingRate: option.rate_id,\n shippingFee: option.amount,\n };\n }\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,\n // Preserves the previous fee if the id doesn't match a known option.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"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","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { sdk } from "../sdk.js";
2
- import { useReducer, useEffect, useCallback, useRef } from "react";
2
+ import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
3
3
  import { SHIPPING_MESSAGES } from "./messages.js";
4
4
  import { useNotify } from "../notices.js";
5
+ import { optionIdOf } from "./option-id.js";
5
6
  import {
6
7
  shippingCalculationReducer,
7
8
  initialShippingCalculationState
@@ -12,7 +13,8 @@ function useShippingCalculation({
12
13
  ward,
13
14
  subtotal,
14
15
  totalWeight,
15
- itemsCount
16
+ itemsCount,
17
+ includeCarrierOptions = false
16
18
  }) {
17
19
  const [state, dispatch] = useReducer(
18
20
  shippingCalculationReducer,
@@ -23,7 +25,7 @@ function useShippingCalculation({
23
25
  stateRef.current = state;
24
26
  useEffect(() => {
25
27
  dispatch({ type: "RESET" });
26
- }, [city, ward, subtotal, totalWeight]);
28
+ }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);
27
29
  const calculateShippingFee = useCallback(async () => {
28
30
  if (!city || !ward || itemsCount === 0) {
29
31
  dispatch({ type: "RESET" });
@@ -37,7 +39,8 @@ function useShippingCalculation({
37
39
  ward_id: ward,
38
40
  subtotal,
39
41
  currency: "VND",
40
- weight_gr: totalWeight
42
+ weight_gr: totalWeight,
43
+ ...includeCarrierOptions && { include_carrier_options: true }
41
44
  });
42
45
  dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
43
46
  } catch (error) {
@@ -51,7 +54,16 @@ function useShippingCalculation({
51
54
  description: SHIPPING_MESSAGES.failedHint
52
55
  });
53
56
  }
54
- }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);
57
+ }, [
58
+ city,
59
+ ward,
60
+ itemsCount,
61
+ storeRef,
62
+ subtotal,
63
+ totalWeight,
64
+ includeCarrierOptions,
65
+ notify
66
+ ]);
55
67
  useEffect(() => {
56
68
  const timeoutId = setTimeout(() => {
57
69
  calculateShippingFee();
@@ -61,6 +73,22 @@ function useShippingCalculation({
61
73
  const handleShippingRateSelect = useCallback((rateId) => {
62
74
  dispatch({ type: "RATE_SELECTED", rateId });
63
75
  }, []);
76
+ const handleShippingOptionSelect = useCallback((optionId) => {
77
+ dispatch({ type: "OPTION_SELECTED", optionId });
78
+ }, []);
79
+ const replaceOptions = useCallback(
80
+ (options, preferOptionId, requestId) => {
81
+ dispatch({ type: "QUOTE_REPLACED", options, requestId, preferOptionId });
82
+ },
83
+ []
84
+ );
85
+ const currentRequestId = useCallback(() => stateRef.current.requestId, []);
86
+ const selectedOption = useMemo(
87
+ () => state.selectedOptionId === null ? null : state.shippingOptions.find(
88
+ (o) => optionIdOf(o) === state.selectedOptionId
89
+ ) ?? null,
90
+ [state.shippingOptions, state.selectedOptionId]
91
+ );
64
92
  return {
65
93
  shippingFee: state.shippingFee,
66
94
  isCalculatingShipping: state.isCalculatingShipping,
@@ -68,6 +96,11 @@ function useShippingCalculation({
68
96
  shippingOptions: state.shippingOptions,
69
97
  selectedShippingRate: state.selectedShippingRate,
70
98
  calculationFailed: state.calculationFailed,
99
+ selectedOptionId: state.selectedOptionId,
100
+ selectedOption,
101
+ handleShippingOptionSelect,
102
+ replaceOptions,
103
+ currentRequestId,
71
104
  handleShippingRateSelect,
72
105
  /**
73
106
  * Re-run the quote with the inputs unchanged. The debounced effect only
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef } from \"react\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,cAAc;AAC3D,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAWA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YAAU,MAAM;AACd,aAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,EAC5B,GAAG,CAAC,MAAM,MAAM,UAAU,WAAW,CAAC;AAEtC,QAAM,uBAAuB,YAAY,YAAY;AACnD,QAAI,CAAC,QAAQ,CAAC,QAAQ,eAAe,GAAG;AACtC,eAAS,EAAE,MAAM,QAAQ,CAAC;AAC1B;AAAA,IACF;AAKA,UAAM,OAAO,SAAS,QAAQ,YAAY;AAC1C,aAAS,EAAE,MAAM,sBAAsB,CAAC;AAExC,QAAI;AACF,YAAM,UAAU,MAAM,IAAI,SAAS,UAAU,UAAU;AAAA,QACrD,aAAa;AAAA,QACb,SAAS;AAAA,QACT;AAAA,QACA,UAAU;AAAA,QACV,WAAW;AAAA,MACb,CAAC;AAED,eAAS,EAAE,MAAM,yBAAyB,SAAS,WAAW,KAAK,CAAC;AAAA,IACtE,SAAS,OAAO;AAMd,UAAI,SAAS,SAAS,QAAQ,UAAW;AAEzC,cAAQ,MAAM,qCAAqC,KAAK;AACxD,eAAS,EAAE,MAAM,sBAAsB,WAAW,KAAK,CAAC;AACxD,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO,kBAAkB;AAAA,QACzB,aAAa,kBAAkB;AAAA,MACjC,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,MAAM,MAAM,YAAY,UAAU,UAAU,aAAa,MAAM,CAAC;AAGpE,YAAU,MAAM;AACd,UAAM,YAAY,WAAW,MAAM;AACjC,2BAAqB;AAAA,IACvB,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"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","names":[]}
@@ -1,6 +1,20 @@
1
1
  import { sdk } from "../sdk.js";
2
2
  import { isStoreSuspendedError } from "./store-suspension.js";
3
3
  import { publicConfig } from "../config.js";
4
+ import { TtlCache } from "./ttl-cache.js";
5
+ const FOUND_TTL_MS = 3e4;
6
+ const NOT_FOUND_TTL_MS = 1e4;
7
+ const MAX_HOSTS = 1e4;
8
+ const byHost = new TtlCache(MAX_HOSTS);
9
+ function clearStoreByHostCache() {
10
+ byHost.clear();
11
+ }
12
+ function platformSubdomain(hostname, platformDomain) {
13
+ const suffix = `.${platformDomain}`;
14
+ if (!hostname.endsWith(suffix)) return null;
15
+ const label = hostname.slice(0, -suffix.length);
16
+ return label && !label.includes(".") ? label : null;
17
+ }
4
18
  async function getStoreByHost(host) {
5
19
  if (host.includes("localhost") || host.includes("127.0.0.1")) {
6
20
  return {
@@ -8,34 +22,55 @@ async function getStoreByHost(host) {
8
22
  domain: null,
9
23
  isSubDomain: false,
10
24
  suspended: false,
11
- externalUrl: null
25
+ externalUrl: null,
26
+ previewSlug: null
12
27
  };
13
28
  }
29
+ const key = host.toLowerCase();
30
+ const cached = byHost.get(key);
31
+ if (cached) return cached;
14
32
  let storeRef = null;
15
33
  let domain = null;
16
34
  let suspended = false;
17
35
  let externalUrl = null;
18
- const parts = host.split(".");
19
- const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
20
- const isSubDomain = host.indexOf(platformDomain) >= 0 && parts.length === 3;
36
+ let previewSlug = null;
37
+ let failed = false;
38
+ const hostname = key.split(":")[0];
39
+ const platformDomain = (publicConfig().platformDomainSuffix ?? "ecomsite.app").toLowerCase();
40
+ const subdomain = platformSubdomain(hostname, platformDomain);
41
+ const isSubDomain = subdomain !== null;
21
42
  try {
22
- const lookupValue = isSubDomain ? parts[0] : host;
43
+ const lookupValue = subdomain ?? host;
23
44
  const foundStore = await sdk.stores.getByDomain(lookupValue);
24
45
  if (foundStore?.ref) {
25
46
  storeRef = foundStore.ref;
26
47
  domain = foundStore.config?.custom_domain || null;
27
48
  externalUrl = foundStore.storefront_url || null;
49
+ previewSlug = foundStore.preview_slug || null;
28
50
  }
29
51
  } catch (error) {
30
52
  if (isStoreSuspendedError(error)) {
31
53
  suspended = true;
32
54
  } else {
55
+ failed = true;
33
56
  console.error("Store not found for host:", host);
34
57
  }
35
58
  }
36
- return { storeRef, domain, isSubDomain, suspended, externalUrl };
59
+ const result = {
60
+ storeRef,
61
+ domain,
62
+ isSubDomain,
63
+ suspended,
64
+ externalUrl,
65
+ previewSlug
66
+ };
67
+ if (!failed) {
68
+ byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);
69
+ }
70
+ return result;
37
71
  }
38
72
  export {
73
+ clearStoreByHostCache,
39
74
  getStoreByHost
40
75
  };
41
76
  //# sourceMappingURL=get-store-by-host.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n };\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n\n const parts = host.split(\".\");\n const platformDomain =\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const isSubDomain = host.indexOf(platformDomain) >= 0 && parts.length === 3;\n\n try {\n const lookupValue = isSubDomain ? parts[0] : host;\n const foundStore = await sdk.stores.getByDomain(lookupValue);\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else {\n console.error(\"Store not found for host:\", host);\n }\n }\n\n return { storeRef, domain, isSubDomain, suspended, externalUrl };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAM7B,eAAsB,eAAe,MAalC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,IACf;AAAA,EACF;AAEA,MAAI,WAA0B;AAC9B,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,cAA6B;AAEjC,QAAM,QAAQ,KAAK,MAAM,GAAG;AAC5B,QAAM,iBACJ,aAAa,EAAE,wBAAwB;AACzC,QAAM,cAAc,KAAK,QAAQ,cAAc,KAAK,KAAK,MAAM,WAAW;AAE1E,MAAI;AACF,UAAM,cAAc,cAAc,MAAM,CAAC,IAAI;AAC7C,UAAM,aAAa,MAAM,IAAI,OAAO,YAAY,WAAW;AAE3D,QAAI,YAAY,KAAK;AACnB,iBAAW,WAAW;AACtB,eAAS,WAAW,QAAQ,iBAAiB;AAC7C,oBAAc,WAAW,kBAAkB;AAAA,IAC7C;AAAA,EACF,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,GAAG;AAChC,kBAAY;AAAA,IACd,OAAO;AACL,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,QAAQ,aAAa,WAAW,YAAY;AACjE;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n };\n }\n\n const key = host.toLowerCase();\n const cached = byHost.get(key);\n if (cached) return cached;\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(lookupValue);\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n };\n if (!failed) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAWzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ;AACjD;AAMA,eAAsB,eAAe,MAelC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAAA,EACF;AAEA,QAAM,MAAM,KAAK,YAAY;AAC7B,QAAM,SAAS,OAAO,IAAI,GAAG;AAC7B,MAAI,OAAQ,QAAO;AAEnB,MAAI,WAA0B;AAC9B,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,cAA6B;AACjC,MAAI,cAA6B;AAEjC,MAAI,SAAS;AAEb,QAAM,WAAW,IAAI,MAAM,GAAG,EAAE,CAAC;AACjC,QAAM,kBACJ,aAAa,EAAE,wBAAwB,gBACvC,YAAY;AACd,QAAM,YAAY,kBAAkB,UAAU,cAAc;AAC5D,QAAM,cAAc,cAAc;AAElC,MAAI;AACF,UAAM,cAAc,aAAa;AACjC,UAAM,aAAa,MAAM,IAAI,OAAO,YAAY,WAAW;AAE3D,QAAI,YAAY,KAAK;AACnB,iBAAW,WAAW;AACtB,eAAS,WAAW,QAAQ,iBAAiB;AAC7C,oBAAc,WAAW,kBAAkB;AAC3C,oBAAc,WAAW,gBAAgB;AAAA,IAC3C;AAAA,EACF,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,GAAG;AAChC,kBAAY;AAAA,IACd,OAAO;AACL,eAAS;AACT,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,QAAQ;AACX,WAAO,IAAI,KAAK,QAAQ,WAAW,eAAe,gBAAgB;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,25 @@
1
+ import { sdk } from "../sdk.js";
2
+ import { TtlCache } from "./ttl-cache.js";
3
+ const TTL_MS = 6e4;
4
+ const MAX_REFS = 1e4;
5
+ const byRef = new TtlCache(MAX_REFS);
6
+ function clearStoreSubdomainCache() {
7
+ byRef.clear();
8
+ }
9
+ async function getStoreSubdomain(storeRef) {
10
+ const cached = byRef.get(storeRef);
11
+ if (cached !== void 0) return cached;
12
+ const store = await sdk.stores.getById(storeRef, {
13
+ includeConfig: true,
14
+ includeSettings: false,
15
+ includeEmbeddedScripts: false
16
+ });
17
+ const subdomain = store?.config?.subdomain || null;
18
+ byRef.set(storeRef, subdomain, TTL_MS);
19
+ return subdomain;
20
+ }
21
+ export {
22
+ clearStoreSubdomainCache,
23
+ getStoreSubdomain
24
+ };
25
+ //# sourceMappingURL=store-subdomain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/store-subdomain.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { TtlCache } from \"./ttl-cache\";\n\nconst TTL_MS = 60_000;\nconst MAX_REFS = 10_000;\n\nconst byRef = new TtlCache<string | null>(MAX_REFS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreSubdomainCache(): void {\n byRef.clear();\n}\n\n/**\n * The platform subdomain label of the store `storeRef`, or null when there\n * is no such store or it has none. Throws when the API cannot be reached, so\n * the caller can tell \"no store\" from \"don't know\" (only the former is\n * cached).\n */\nexport async function getStoreSubdomain(\n storeRef: string\n): Promise<string | null> {\n const cached = byRef.get(storeRef);\n if (cached !== undefined) return cached;\n\n const store = await sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: false,\n includeEmbeddedScripts: false,\n });\n const subdomain = store?.config?.subdomain || null;\n byRef.set(storeRef, subdomain, TTL_MS);\n return subdomain;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,gBAAgB;AAEzB,MAAM,SAAS;AACf,MAAM,WAAW;AAEjB,MAAM,QAAQ,IAAI,SAAwB,QAAQ;AAG3C,SAAS,2BAAiC;AAC/C,QAAM,MAAM;AACd;AAQA,eAAsB,kBACpB,UACwB;AACxB,QAAM,SAAS,MAAM,IAAI,QAAQ;AACjC,MAAI,WAAW,OAAW,QAAO;AAEjC,QAAM,QAAQ,MAAM,IAAI,OAAO,QAAQ,UAAU;AAAA,IAC/C,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,EAC1B,CAAC;AACD,QAAM,YAAY,OAAO,QAAQ,aAAa;AAC9C,QAAM,IAAI,UAAU,WAAW,MAAM;AACrC,SAAO;AACT;","names":[]}
@@ -0,0 +1,50 @@
1
+ import { serverConfig } from "../config/server.js";
2
+ const WINDOW_MS = 6e4;
3
+ class StoreTraffic {
4
+ constructor(threshold, log = console.warn) {
5
+ this.threshold = threshold;
6
+ this.log = log;
7
+ }
8
+ threshold;
9
+ log;
10
+ windowStart = null;
11
+ counts = /* @__PURE__ */ new Map();
12
+ hit(storeRef, now = Date.now()) {
13
+ if (this.threshold <= 0) return;
14
+ if (this.windowStart === null) this.windowStart = now;
15
+ if (now - this.windowStart >= WINDOW_MS) {
16
+ this.flush();
17
+ this.windowStart = now;
18
+ }
19
+ const count = (this.counts.get(storeRef) ?? 0) + 1;
20
+ this.counts.set(storeRef, count);
21
+ if (count === this.threshold) {
22
+ this.log(
23
+ `[store-traffic] over store=${storeRef} requests=${count} window=60s threshold=${this.threshold}`
24
+ );
25
+ }
26
+ }
27
+ flush() {
28
+ for (const [storeRef, count] of this.counts) {
29
+ if (count >= this.threshold) {
30
+ this.log(
31
+ `[store-traffic] peak store=${storeRef} requests=${count} window=60s threshold=${this.threshold}`
32
+ );
33
+ }
34
+ }
35
+ this.counts.clear();
36
+ }
37
+ }
38
+ let shared;
39
+ function recordStoreRequest(storeRef) {
40
+ try {
41
+ shared ??= new StoreTraffic(serverConfig().storeTrafficLogPerMinute);
42
+ shared.hit(storeRef);
43
+ } catch {
44
+ }
45
+ }
46
+ export {
47
+ StoreTraffic,
48
+ recordStoreRequest
49
+ };
50
+ //# sourceMappingURL=store-traffic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/store-traffic.ts"],"sourcesContent":["import { serverConfig } from \"../config/server\";\n\nconst WINDOW_MS = 60_000;\n\n/**\n * Requests per store on this server, in fixed one-minute windows: the data\n * for sizing a per-store limit on the shared storefront. Log only; nothing\n * is refused.\n *\n * - A store reaching the threshold is logged at once (\"over\").\n * - When a window closes, every store that reached it is logged with its\n * final count (\"peak\"). Windows close on the next request, so a server\n * that goes quiet logs its last window late.\n *\n * Counts are this server's share only: multiply by the pod count for the\n * whole fleet.\n */\nexport class StoreTraffic {\n private windowStart: number | null = null;\n private counts = new Map<string, number>();\n\n constructor(\n private readonly threshold: number,\n private readonly log: (line: string) => void = console.warn\n ) {}\n\n hit(storeRef: string, now = Date.now()): void {\n if (this.threshold <= 0) return;\n if (this.windowStart === null) this.windowStart = now;\n if (now - this.windowStart >= WINDOW_MS) {\n this.flush();\n this.windowStart = now;\n }\n\n const count = (this.counts.get(storeRef) ?? 0) + 1;\n this.counts.set(storeRef, count);\n if (count === this.threshold) {\n this.log(\n `[store-traffic] over store=${storeRef} requests=${count} window=60s threshold=${this.threshold}`\n );\n }\n }\n\n private flush(): void {\n for (const [storeRef, count] of this.counts) {\n if (count >= this.threshold) {\n this.log(\n `[store-traffic] peak store=${storeRef} requests=${count} window=60s threshold=${this.threshold}`\n );\n }\n }\n this.counts.clear();\n }\n}\n\nlet shared: StoreTraffic | undefined;\n\n/**\n * Counts one request to `storeRef` (see StoreTraffic). Never throws: this is\n * measurement, and must not take a page down.\n */\nexport function recordStoreRequest(storeRef: string): void {\n try {\n shared ??= new StoreTraffic(serverConfig().storeTrafficLogPerMinute);\n shared.hit(storeRef);\n } catch {\n // Unreadable config: count nothing (the page reports it elsewhere).\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAoB;AAE7B,MAAM,YAAY;AAeX,MAAM,aAAa;AAAA,EAIxB,YACmB,WACA,MAA8B,QAAQ,MACvD;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA,EALX,cAA6B;AAAA,EAC7B,SAAS,oBAAI,IAAoB;AAAA,EAOzC,IAAI,UAAkB,MAAM,KAAK,IAAI,GAAS;AAC5C,QAAI,KAAK,aAAa,EAAG;AACzB,QAAI,KAAK,gBAAgB,KAAM,MAAK,cAAc;AAClD,QAAI,MAAM,KAAK,eAAe,WAAW;AACvC,WAAK,MAAM;AACX,WAAK,cAAc;AAAA,IACrB;AAEA,UAAM,SAAS,KAAK,OAAO,IAAI,QAAQ,KAAK,KAAK;AACjD,SAAK,OAAO,IAAI,UAAU,KAAK;AAC/B,QAAI,UAAU,KAAK,WAAW;AAC5B,WAAK;AAAA,QACH,8BAA8B,QAAQ,aAAa,KAAK,yBAAyB,KAAK,SAAS;AAAA,MACjG;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,QAAc;AACpB,eAAW,CAAC,UAAU,KAAK,KAAK,KAAK,QAAQ;AAC3C,UAAI,SAAS,KAAK,WAAW;AAC3B,aAAK;AAAA,UACH,8BAA8B,QAAQ,aAAa,KAAK,yBAAyB,KAAK,SAAS;AAAA,QACjG;AAAA,MACF;AAAA,IACF;AACA,SAAK,OAAO,MAAM;AAAA,EACpB;AACF;AAEA,IAAI;AAMG,SAAS,mBAAmB,UAAwB;AACzD,MAAI;AACF,eAAW,IAAI,aAAa,aAAa,EAAE,wBAAwB;AACnE,WAAO,IAAI,QAAQ;AAAA,EACrB,QAAQ;AAAA,EAER;AACF;","names":[]}
@@ -0,0 +1,34 @@
1
+ class TtlCache {
2
+ constructor(maxEntries) {
3
+ this.maxEntries = maxEntries;
4
+ }
5
+ maxEntries;
6
+ entries = /* @__PURE__ */ new Map();
7
+ get(key, now = Date.now()) {
8
+ const entry = this.entries.get(key);
9
+ if (!entry) return void 0;
10
+ this.entries.delete(key);
11
+ if (entry.expires <= now) return void 0;
12
+ this.entries.set(key, entry);
13
+ return entry.value;
14
+ }
15
+ set(key, value, ttlMs, now = Date.now()) {
16
+ this.entries.delete(key);
17
+ this.entries.set(key, { value, expires: now + ttlMs });
18
+ while (this.entries.size > this.maxEntries) {
19
+ const oldest = this.entries.keys().next().value;
20
+ if (oldest === void 0) break;
21
+ this.entries.delete(oldest);
22
+ }
23
+ }
24
+ clear() {
25
+ this.entries.clear();
26
+ }
27
+ get size() {
28
+ return this.entries.size;
29
+ }
30
+ }
31
+ export {
32
+ TtlCache
33
+ };
34
+ //# sourceMappingURL=ttl-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/ttl-cache.ts"],"sourcesContent":["/**\n * A small in-process cache with per-entry expiry and a size bound.\n *\n * The middleware resolves the store on every request; without this each one\n * is a round trip to the API (which caches in Redis, but the hop remains).\n * The bound matters because the key is the request's Host: random hosts\n * under the platform domain would otherwise grow the map without limit.\n *\n * Map keeps insertion order, so the first key is the oldest write; a hit\n * re-inserts its entry, which makes eviction least-recently-used.\n */\nexport class TtlCache<V> {\n private readonly entries = new Map<string, { value: V; expires: number }>();\n\n constructor(private readonly maxEntries: number) {}\n\n get(key: string, now = Date.now()): V | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n this.entries.delete(key);\n if (entry.expires <= now) return undefined;\n this.entries.set(key, entry);\n return entry.value;\n }\n\n set(key: string, value: V, ttlMs: number, now = Date.now()): void {\n this.entries.delete(key);\n this.entries.set(key, { value, expires: now + ttlMs });\n while (this.entries.size > this.maxEntries) {\n const oldest = this.entries.keys().next().value;\n if (oldest === undefined) break;\n this.entries.delete(oldest);\n }\n }\n\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n"],"mappings":"AAWO,MAAM,SAAY;AAAA,EAGvB,YAA6B,YAAoB;AAApB;AAAA,EAAqB;AAAA,EAArB;AAAA,EAFZ,UAAU,oBAAI,IAA2C;AAAA,EAI1E,IAAI,KAAa,MAAM,KAAK,IAAI,GAAkB;AAChD,UAAM,QAAQ,KAAK,QAAQ,IAAI,GAAG;AAClC,QAAI,CAAC,MAAO,QAAO;AACnB,SAAK,QAAQ,OAAO,GAAG;AACvB,QAAI,MAAM,WAAW,IAAK,QAAO;AACjC,SAAK,QAAQ,IAAI,KAAK,KAAK;AAC3B,WAAO,MAAM;AAAA,EACf;AAAA,EAEA,IAAI,KAAa,OAAU,OAAe,MAAM,KAAK,IAAI,GAAS;AAChE,SAAK,QAAQ,OAAO,GAAG;AACvB,SAAK,QAAQ,IAAI,KAAK,EAAE,OAAO,SAAS,MAAM,MAAM,CAAC;AACrD,WAAO,KAAK,QAAQ,OAAO,KAAK,YAAY;AAC1C,YAAM,SAAS,KAAK,QAAQ,KAAK,EAAE,KAAK,EAAE;AAC1C,UAAI,WAAW,OAAW;AAC1B,WAAK,QAAQ,OAAO,MAAM;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEA,IAAI,OAAe;AACjB,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/define.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type {\n Banner,\n StoreConfigurationInfo,\n ThemeSchema,\n ThemeSettingsOf,\n} from \"@ecomweb/sdk\";\n\n/**\n * The theme contract (spec: schema-driven themes §5.2). A theme declares its\n * settings with `defineSchema` and fills the slots the shared routes render.\n * Routes load data through the kit and pass it in: a theme is presentation.\n */\n\nexport function defineSchema<const S extends ThemeSchema>(schema: S): S {\n return schema;\n}\n\nexport interface ThemeInfo {\n id: string;\n name: string;\n version: string;\n author: string;\n}\n\n/** A slot may be a server component (async) or a plain one. */\nexport type ThemeSlot<P> = (props: P) => ReactNode | Promise<ReactNode>;\n\nexport interface ThemeSlotProps<V> {\n store: StoreConfigurationInfo;\n storeRef: string;\n settings: V;\n}\n\nexport interface LayoutSlotProps<V> extends ThemeSlotProps<V> {\n children: ReactNode;\n}\n\nexport interface HomePageSlotProps<V> extends ThemeSlotProps<V> {\n banners: Banner[];\n}\n\nexport interface ThemeComponents<V> {\n Layout?: ThemeSlot<LayoutSlotProps<V>>;\n HomePage?: ThemeSlot<HomePageSlotProps<V>>;\n}\n\nexport type ThemeSlotName = keyof ThemeComponents<unknown>;\n\nexport interface ThemeDefinition<S extends ThemeSchema = ThemeSchema> {\n info: ThemeInfo;\n schema: S;\n components: ThemeComponents<ThemeSettingsOf<S>>;\n /** CSS custom properties for :root, from the resolved settings. */\n styles?: (settings: ThemeSettingsOf<S>) => Record<string, string>;\n}\n\n/**\n * A theme of unknown schema, as the registry holds it. Its slots are called\n * with settings resolved against its own schema.\n */\nexport interface AnyThemeDefinition {\n info: ThemeInfo;\n schema: ThemeSchema;\n components: ThemeComponents<any>;\n styles?: (settings: any) => Record<string, string>;\n}\n\nexport function defineTheme<const S extends ThemeSchema>(\n theme: ThemeDefinition<S>\n): ThemeDefinition<S> {\n return theme;\n}\n"],"mappings":"AAcO,SAAS,aAA0C,QAAc;AACtE,SAAO;AACT;AAoDO,SAAS,YACd,OACoB;AACpB,SAAO;AACT;","names":[]}
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 +1 @@
1
- {"version":3,"sources":["../../src/theme/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit/theme: authoring a theme (schema, definition, slot\n// types). No side effects, so build tools such as CI's theme export can import\n// it without a storefront configuration.\nexport { defineSchema, defineTheme } from \"./define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./define\";\n"],"mappings":"AAGA,SAAS,cAAc,mBAAmB;","names":[]}
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":[]}
@@ -0,0 +1,33 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ const THEME_PREVIEW_MESSAGE = "ecomweb:theme-preview";
4
+ const THEME_PREVIEW_FRAME_ATTR = "data-theme-preview-frame";
5
+ function ThemePreviewBridge({ onRefresh }) {
6
+ const refresh = useRef(onRefresh);
7
+ refresh.current = onRefresh;
8
+ useEffect(() => {
9
+ const parent = window.parent;
10
+ if (!parent || parent === window) return;
11
+ const root = document.documentElement;
12
+ root.setAttribute(THEME_PREVIEW_FRAME_ATTR, "");
13
+ const onMessage = (event) => {
14
+ if (event.source !== parent) return;
15
+ const data = event.data;
16
+ if (data?.type !== THEME_PREVIEW_MESSAGE) return;
17
+ if (data.action === "refresh") refresh.current();
18
+ };
19
+ window.addEventListener("message", onMessage);
20
+ parent.postMessage({ type: THEME_PREVIEW_MESSAGE, action: "ready" }, "*");
21
+ return () => {
22
+ window.removeEventListener("message", onMessage);
23
+ root.removeAttribute(THEME_PREVIEW_FRAME_ATTR);
24
+ };
25
+ }, []);
26
+ return null;
27
+ }
28
+ export {
29
+ THEME_PREVIEW_FRAME_ATTR,
30
+ THEME_PREVIEW_MESSAGE,
31
+ ThemePreviewBridge
32
+ };
33
+ //# sourceMappingURL=preview-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/theme/preview-bridge.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n/** The messages the dashboard's theme editor and its preview frame trade. */\nexport const THEME_PREVIEW_MESSAGE = \"ecomweb:theme-preview\";\n\n/** Set on <html> while the preview is inside the theme editor's frame. */\nexport const THEME_PREVIEW_FRAME_ATTR = \"data-theme-preview-frame\";\n\n/**\n * The storefront side of the theme editor's live preview. Inside the\n * editor's frame it says it is ready, then calls onRefresh each time the\n * editor has sent its unsaved values to the API, which the preview token\n * reads them back from. The app re-renders the page in place (router.refresh:\n * server components again, scroll and client state kept); routing is the\n * app's, not the kit's. Only the frame's parent is listened to; outside a\n * frame it does nothing.\n */\nexport function ThemePreviewBridge({ onRefresh }: { onRefresh: () => void }) {\n // The latest callback, without listening again each render.\n const refresh = useRef(onRefresh);\n refresh.current = onRefresh;\n\n useEffect(() => {\n const parent = window.parent;\n if (!parent || parent === window) return;\n const root = document.documentElement;\n root.setAttribute(THEME_PREVIEW_FRAME_ATTR, \"\");\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== parent) return;\n const data = event.data as { type?: unknown; action?: unknown } | null;\n if (data?.type !== THEME_PREVIEW_MESSAGE) return;\n if (data.action === \"refresh\") refresh.current();\n };\n window.addEventListener(\"message\", onMessage);\n // The editor holds back live updates until a storefront says it can.\n parent.postMessage({ type: THEME_PREVIEW_MESSAGE, action: \"ready\" }, \"*\");\n return () => {\n window.removeEventListener(\"message\", onMessage);\n root.removeAttribute(THEME_PREVIEW_FRAME_ATTR);\n };\n }, []);\n\n return null;\n}\n"],"mappings":";AAEA,SAAS,WAAW,cAAc;AAG3B,MAAM,wBAAwB;AAG9B,MAAM,2BAA2B;AAWjC,SAAS,mBAAmB,EAAE,UAAU,GAA8B;AAE3E,QAAM,UAAU,OAAO,SAAS;AAChC,UAAQ,UAAU;AAElB,YAAU,MAAM;AACd,UAAM,SAAS,OAAO;AACtB,QAAI,CAAC,UAAU,WAAW,OAAQ;AAClC,UAAM,OAAO,SAAS;AACtB,SAAK,aAAa,0BAA0B,EAAE;AAE9C,UAAM,YAAY,CAAC,UAAwB;AACzC,UAAI,MAAM,WAAW,OAAQ;AAC7B,YAAM,OAAO,MAAM;AACnB,UAAI,MAAM,SAAS,sBAAuB;AAC1C,UAAI,KAAK,WAAW,UAAW,SAAQ,QAAQ;AAAA,IACjD;AACA,WAAO,iBAAiB,WAAW,SAAS;AAE5C,WAAO,YAAY,EAAE,MAAM,uBAAuB,QAAQ,QAAQ,GAAG,GAAG;AACxE,WAAO,MAAM;AACX,aAAO,oBAAoB,WAAW,SAAS;AAC/C,WAAK,gBAAgB,wBAAwB;AAAA,IAC/C;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;","names":[]}
@@ -1,9 +1,13 @@
1
1
  import { NextResponse } from "next/server";
2
+ import { hostOnlyCookieName, secureCookies } from "../auth/cookies.js";
2
3
  import { publicNextUrl } from "../request/public-url.js";
3
4
  const THEME_PREVIEW_COOKIE = "ecomweb_theme_preview";
4
5
  const THEME_PREVIEW_PARAM = "preview_theme";
5
6
  const MAX_TOKEN_LENGTH = 2048;
6
7
  const MAX_AGE_SECONDS = 24 * 60 * 60;
8
+ function themePreviewCookieName(cookiePath) {
9
+ return hostOnlyCookieName(THEME_PREVIEW_COOKIE, cookiePath);
10
+ }
7
11
  function applyThemePreview(req, cookiePath) {
8
12
  const value = req.nextUrl.searchParams.get(THEME_PREVIEW_PARAM);
9
13
  if (value === null) return null;
@@ -11,22 +15,25 @@ function applyThemePreview(req, cookiePath) {
11
15
  url.searchParams.delete(THEME_PREVIEW_PARAM);
12
16
  const res = NextResponse.redirect(url, 307);
13
17
  const valid = value !== "exit" && value.length > 0 && value.length <= MAX_TOKEN_LENGTH;
14
- res.cookies.set(THEME_PREVIEW_COOKIE, valid ? value : "", {
18
+ const production = secureCookies();
19
+ res.cookies.set(themePreviewCookieName(cookiePath), valid ? value : "", {
15
20
  httpOnly: true,
16
- secure: process.env.NODE_ENV === "production",
17
- sameSite: "lax",
21
+ // Locally the dashboard and the store share a site (localhost), and
22
+ // SameSite=None needs https.
23
+ ...production ? { secure: true, sameSite: "none", partitioned: true } : { secure: false, sameSite: "lax" },
18
24
  path: cookiePath,
19
25
  maxAge: valid ? MAX_AGE_SECONDS : 0
20
26
  });
21
27
  return res;
22
28
  }
23
- function hasThemePreview(req) {
24
- return !!req.cookies.get(THEME_PREVIEW_COOKIE)?.value;
29
+ function hasThemePreview(req, cookiePath) {
30
+ return !!req.cookies.get(themePreviewCookieName(cookiePath))?.value;
25
31
  }
26
32
  export {
27
33
  THEME_PREVIEW_COOKIE,
28
34
  THEME_PREVIEW_PARAM,
29
35
  applyThemePreview,
30
- hasThemePreview
36
+ hasThemePreview,
37
+ themePreviewCookieName
31
38
  };
32
39
  //# sourceMappingURL=preview-cookie.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { publicNextUrl } from \"../request/public-url\";\n\nexport const THEME_PREVIEW_COOKIE = \"ecomweb_theme_preview\";\nexport const THEME_PREVIEW_PARAM = \"preview_theme\";\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/**\n * A dashboard preview link (`?preview_theme=<token>`) becomes an httpOnly\n * cookie scoped to the store, then a redirect to the clean URL, so the token\n * never stays in the address bar or in shared links. `preview_theme=exit`\n * clears it. The API validates the token on every render (themes spec §6.1).\n */\nexport function applyThemePreview(\n req: NextRequest,\n cookiePath: string\n): NextResponse | null {\n const value = req.nextUrl.searchParams.get(THEME_PREVIEW_PARAM);\n if (value === null) return null;\n const url = publicNextUrl(req);\n url.searchParams.delete(THEME_PREVIEW_PARAM);\n const res = NextResponse.redirect(url, 307);\n const valid =\n value !== \"exit\" && value.length > 0 && value.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(THEME_PREVIEW_COOKIE, valid ? value : \"\", {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\nexport function hasThemePreview(req: NextRequest): boolean {\n return !!req.cookies.get(THEME_PREVIEW_COOKIE)?.value;\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAEvB,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AACnC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAQ3B,SAAS,kBACd,KACA,YACqB;AACrB,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB;AAC9D,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,aAAa,OAAO,mBAAmB;AAC3C,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QACJ,UAAU,UAAU,MAAM,SAAS,KAAK,MAAM,UAAU;AAC1D,MAAI,QAAQ,IAAI,sBAAsB,QAAQ,QAAQ,IAAI;AAAA,IACxD,UAAU;AAAA,IACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,IACjC,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAEO,SAAS,gBAAgB,KAA2B;AACzD,SAAO,CAAC,CAAC,IAAI,QAAQ,IAAI,oBAAoB,GAAG;AAClD;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { hostOnlyCookieName, secureCookies } from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\n\nexport const THEME_PREVIEW_COOKIE = \"ecomweb_theme_preview\";\nexport const THEME_PREVIEW_PARAM = \"preview_theme\";\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/**\n * A dashboard preview link (`?preview_theme=<token>`) becomes an httpOnly\n * cookie scoped to the store, then a redirect to the clean URL, so the token\n * never stays in the address bar or in shared links. `preview_theme=exit`\n * clears it. The API validates the token on every render (themes spec §6.1).\n * In production the cookie also works inside the dashboard's theme editor,\n * which frames the store from another site: SameSite=None, partitioned by\n * the top-level site (CHIPS), so it never follows the store anywhere else.\n */\n/** The preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function themePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(THEME_PREVIEW_COOKIE, cookiePath);\n}\n\nexport function applyThemePreview(\n req: NextRequest,\n cookiePath: string\n): NextResponse | null {\n const value = req.nextUrl.searchParams.get(THEME_PREVIEW_PARAM);\n if (value === null) return null;\n const url = publicNextUrl(req);\n url.searchParams.delete(THEME_PREVIEW_PARAM);\n const res = NextResponse.redirect(url, 307);\n const valid =\n value !== \"exit\" && value.length > 0 && value.length <= MAX_TOKEN_LENGTH;\n const production = secureCookies();\n res.cookies.set(themePreviewCookieName(cookiePath), valid ? value : \"\", {\n httpOnly: true,\n // Locally the dashboard and the store share a site (localhost), and\n // SameSite=None needs https.\n ...(production\n ? { secure: true, sameSite: \"none\" as const, partitioned: true }\n : { secure: false, sameSite: \"lax\" as const }),\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\nexport function hasThemePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(themePreviewCookieName(cookiePath))?.value;\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,qBAAqB;AAEvB,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;AACnC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAY3B,SAAS,uBAAuB,YAA4B;AACjE,SAAO,mBAAmB,sBAAsB,UAAU;AAC5D;AAEO,SAAS,kBACd,KACA,YACqB;AACrB,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB;AAC9D,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,aAAa,OAAO,mBAAmB;AAC3C,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QACJ,UAAU,UAAU,MAAM,SAAS,KAAK,MAAM,UAAU;AAC1D,QAAM,aAAa,cAAc;AACjC,MAAI,QAAQ,IAAI,uBAAuB,UAAU,GAAG,QAAQ,QAAQ,IAAI;AAAA,IACtE,UAAU;AAAA;AAAA;AAAA,IAGV,GAAI,aACA,EAAE,QAAQ,MAAM,UAAU,QAAiB,aAAa,KAAK,IAC7D,EAAE,QAAQ,OAAO,UAAU,MAAe;AAAA,IAC9C,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAEO,SAAS,gBAAgB,KAAkB,YAA6B;AAC7E,SAAO,CAAC,CAAC,IAAI,QAAQ,IAAI,uBAAuB,UAAU,CAAC,GAAG;AAChE;","names":[]}
@@ -0,0 +1,7 @@
1
+ const THEME_PREVIEW_HOST_HEADER = "x-ecomweb-preview-slug";
2
+ const PREVIEW_HOST_ROBOTS = "User-agent: *\nDisallow: /\n";
3
+ export {
4
+ PREVIEW_HOST_ROBOTS,
5
+ THEME_PREVIEW_HOST_HEADER
6
+ };
7
+ //# sourceMappingURL=preview-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/theme/preview-host.ts"],"sourcesContent":["/**\n * Theme preview hosts: every store theme has its own p-<slug>.<suffix>,\n * where the shared storefront renders that theme (a build's runs on its own\n * pods instead). The middleware names the slug to the page in this request\n * header; it always drops one sent by the client.\n */\nexport const THEME_PREVIEW_HOST_HEADER = \"x-ecomweb-preview-slug\";\n\n/** The robots.txt of a preview host: nothing there is for search engines. */\nexport const PREVIEW_HOST_ROBOTS = \"User-agent: *\\nDisallow: /\\n\";\n"],"mappings":"AAMO,MAAM,4BAA4B;AAGlC,MAAM,sBAAsB;","names":[]}
@@ -0,0 +1,10 @@
1
+ import "server-only";
2
+ import { headers } from "next/headers";
3
+ import { THEME_PREVIEW_HOST_HEADER } from "./preview-host.js";
4
+ async function readPreviewHostSlug() {
5
+ return (await headers()).get(THEME_PREVIEW_HOST_HEADER) || null;
6
+ }
7
+ export {
8
+ readPreviewHostSlug
9
+ };
10
+ //# sourceMappingURL=read-preview-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/theme/read-preview-host.ts"],"sourcesContent":["import \"server-only\";\nimport { headers } from \"next/headers\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"./preview-host\";\n\n/**\n * The theme preview host's slug when this request came in on one (server\n * components only); the middleware sets it, never the client.\n */\nexport async function readPreviewHostSlug(): Promise<string | null> {\n return (await headers()).get(THEME_PREVIEW_HOST_HEADER) || null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,eAAe;AACxB,SAAS,iCAAiC;AAM1C,eAAsB,sBAA8C;AAClE,UAAQ,MAAM,QAAQ,GAAG,IAAI,yBAAyB,KAAK;AAC7D;","names":[]}
@@ -1,8 +1,10 @@
1
1
  import "server-only";
2
- import { cookies } from "next/headers";
3
- import { THEME_PREVIEW_COOKIE } from "./preview-cookie.js";
2
+ import { cookies, headers } from "next/headers";
3
+ import { isHostMappedRequest } from "../auth/cookies.js";
4
+ import { THEME_PREVIEW_COOKIE, themePreviewCookieName } from "./preview-cookie.js";
4
5
  async function readThemePreviewToken() {
5
- return (await cookies()).get(THEME_PREVIEW_COOKIE)?.value || null;
6
+ const name = isHostMappedRequest({ headers: await headers() }) ? themePreviewCookieName("/") : THEME_PREVIEW_COOKIE;
7
+ return (await cookies()).get(name)?.value || null;
6
8
  }
7
9
  export {
8
10
  readThemePreviewToken
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/theme/read-preview-token.ts"],"sourcesContent":["import \"server-only\";\nimport { cookies } from \"next/headers\";\nimport { THEME_PREVIEW_COOKIE } from \"./preview-cookie\";\n\n/** The open theme preview's token, if any (server components only). */\nexport async function readThemePreviewToken(): Promise<string | null> {\n return (await cookies()).get(THEME_PREVIEW_COOKIE)?.value || null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,eAAe;AACxB,SAAS,4BAA4B;AAGrC,eAAsB,wBAAgD;AACpE,UAAQ,MAAM,QAAQ,GAAG,IAAI,oBAAoB,GAAG,SAAS;AAC/D;","names":[]}
1
+ {"version":3,"sources":["../../src/theme/read-preview-token.ts"],"sourcesContent":["import \"server-only\";\nimport { cookies, headers } from \"next/headers\";\nimport { isHostMappedRequest } from \"../auth/cookies\";\nimport { THEME_PREVIEW_COOKIE, themePreviewCookieName } from \"./preview-cookie\";\n\n/** The open theme preview's token, if any (server components only). */\nexport async function readThemePreviewToken(): Promise<string | null> {\n // Host-mapped requests keep the cookie at `/` (authCookiePath), the one\n // path whose name differs; on the shared host it is path-scoped and bare.\n const name = isHostMappedRequest({ headers: await headers() })\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return (await cookies()).get(name)?.value || null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,SAAS,eAAe;AACjC,SAAS,2BAA2B;AACpC,SAAS,sBAAsB,8BAA8B;AAG7D,eAAsB,wBAAgD;AAGpE,QAAM,OAAO,oBAAoB,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC,IACzD,uBAAuB,GAAG,IAC1B;AACJ,UAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,GAAG,SAAS;AAC/C;","names":[]}