@storepecker/storefront-core 2.9.1 → 2.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 (65) hide show
  1. package/dist/address-BdIB6IuI.d.cts +42 -0
  2. package/dist/address-BdIB6IuI.d.ts +42 -0
  3. package/dist/api/index.cjs +16 -12
  4. package/dist/api/index.d.cts +13 -3
  5. package/dist/api/index.d.ts +13 -3
  6. package/dist/api/index.js +2 -2
  7. package/dist/{buy-now-BqVWXyy8.d.cts → buy-now-B_15RUVT.d.cts} +1 -1
  8. package/dist/{buy-now-DFdnuLjO.d.ts → buy-now-kII0KrhP.d.ts} +1 -1
  9. package/dist/checkout/index.cjs +108 -15
  10. package/dist/checkout/index.d.cts +25 -1
  11. package/dist/checkout/index.d.ts +25 -1
  12. package/dist/checkout/index.js +3 -2
  13. package/dist/{chunk-IG4BW3ZB.cjs → chunk-32X4SWN4.cjs} +3 -3
  14. package/dist/{chunk-RDUT4W3B.cjs → chunk-6APRQ2ED.cjs} +4 -1
  15. package/dist/{chunk-ICKTXS6B.js → chunk-6IXTFZFS.js} +3 -3
  16. package/dist/{chunk-7M5CVYZJ.js → chunk-A7EI7XLU.js} +8 -1
  17. package/dist/{chunk-CBKJ3Y2I.js → chunk-EWZ7TGI7.js} +11 -1
  18. package/dist/{chunk-5XVHYPOC.js → chunk-FF5N7PTB.js} +1 -1
  19. package/dist/{chunk-XFOUNOKO.cjs → chunk-KNG4OMS5.cjs} +8 -0
  20. package/dist/chunk-QED6QJZC.cjs +603 -0
  21. package/dist/{chunk-W6BDMNSU.js → chunk-QVO56X4E.js} +1 -1
  22. package/dist/{chunk-6LS5F4R3.cjs → chunk-SGJUMI3M.cjs} +11 -0
  23. package/dist/{chunk-YLLAP3H2.cjs → chunk-SGKLMS7W.cjs} +2 -2
  24. package/dist/{chunk-ZGMLOLTC.js → chunk-VRZRV2BR.js} +4 -1
  25. package/dist/{chunk-IVKJJLG7.cjs → chunk-WWJAPKRQ.cjs} +8 -8
  26. package/dist/chunk-Y4RNRPBC.js +545 -0
  27. package/dist/components/address-form.cjs +6 -6
  28. package/dist/components/address-form.d.cts +10 -6
  29. package/dist/components/address-form.d.ts +10 -6
  30. package/dist/components/address-form.js +5 -5
  31. package/dist/components/index.cjs +8 -8
  32. package/dist/components/index.d.cts +3 -3
  33. package/dist/components/index.d.ts +3 -3
  34. package/dist/components/index.js +6 -6
  35. package/dist/components/search-dropdown.d.cts +4 -4
  36. package/dist/components/search-dropdown.d.ts +4 -4
  37. package/dist/components/share-button.cjs +3 -3
  38. package/dist/components/share-button.js +2 -2
  39. package/dist/components/theme-data-initializer.d.cts +1 -1
  40. package/dist/components/theme-data-initializer.d.ts +1 -1
  41. package/dist/hooks/index.cjs +644 -20
  42. package/dist/hooks/index.d.cts +233 -9
  43. package/dist/hooks/index.d.ts +233 -9
  44. package/dist/hooks/index.js +624 -8
  45. package/dist/models/index.d.cts +3 -2
  46. package/dist/models/index.d.ts +3 -2
  47. package/dist/pincode-8u7yWLpQ.d.cts +29 -0
  48. package/dist/pincode-8u7yWLpQ.d.ts +29 -0
  49. package/dist/pincode-CHM-ZD3H.d.ts +179 -0
  50. package/dist/pincode-Ch3bZSJz.d.cts +179 -0
  51. package/dist/{pixelEvents-BtEO5QAR.d.cts → pixelEvents-COqZIgTu.d.cts} +1 -0
  52. package/dist/{pixelEvents-LsealscG.d.ts → pixelEvents-Ds6fwS9t.d.ts} +1 -0
  53. package/dist/store/index.d.cts +1 -1
  54. package/dist/store/index.d.ts +1 -1
  55. package/dist/{useAddressForm-DGbEn91-.d.cts → useAddressForm-fMOb5Z-a.d.ts} +6 -1
  56. package/dist/{useAddressForm-cO3Au33k.d.ts → useAddressForm-wleIo78M.d.cts} +6 -1
  57. package/dist/utils/index.cjs +58 -54
  58. package/dist/utils/index.d.cts +12 -3
  59. package/dist/utils/index.d.ts +12 -3
  60. package/dist/utils/index.js +3 -3
  61. package/package.json +1 -1
  62. package/dist/address-DwBZHzbI.d.cts +0 -19
  63. package/dist/address-DwBZHzbI.d.ts +0 -19
  64. package/dist/chunk-34Y7Y5FU.cjs +0 -246
  65. package/dist/chunk-VPTN4YXD.js +0 -232
@@ -5,22 +5,25 @@ var chunk2AHH3XBW_cjs = require('../chunk-2AHH3XBW.cjs');
5
5
  var chunkNOT6VKXA_cjs = require('../chunk-NOT6VKXA.cjs');
6
6
  var chunkNRPK5GCJ_cjs = require('../chunk-NRPK5GCJ.cjs');
7
7
  var chunkNQZ5GUOG_cjs = require('../chunk-NQZ5GUOG.cjs');
8
- var chunk34Y7Y5FU_cjs = require('../chunk-34Y7Y5FU.cjs');
9
- var chunkXFOUNOKO_cjs = require('../chunk-XFOUNOKO.cjs');
8
+ var chunkQED6QJZC_cjs = require('../chunk-QED6QJZC.cjs');
9
+ var chunkKNG4OMS5_cjs = require('../chunk-KNG4OMS5.cjs');
10
10
  require('../chunk-NSAHGMS7.cjs');
11
11
  var chunkH6FJYRO3_cjs = require('../chunk-H6FJYRO3.cjs');
12
- var chunkIVKJJLG7_cjs = require('../chunk-IVKJJLG7.cjs');
13
- var chunkRDUT4W3B_cjs = require('../chunk-RDUT4W3B.cjs');
14
- require('../chunk-LJUGNSQQ.cjs');
15
- var chunk6LS5F4R3_cjs = require('../chunk-6LS5F4R3.cjs');
12
+ var chunkWWJAPKRQ_cjs = require('../chunk-WWJAPKRQ.cjs');
13
+ var chunk6APRQ2ED_cjs = require('../chunk-6APRQ2ED.cjs');
14
+ var chunkSGJUMI3M_cjs = require('../chunk-SGJUMI3M.cjs');
16
15
  require('../chunk-BBRB475I.cjs');
17
- require('../chunk-TB72NPRM.cjs');
16
+ var chunkDODFO744_cjs = require('../chunk-DODFO744.cjs');
17
+ var chunkTB72NPRM_cjs = require('../chunk-TB72NPRM.cjs');
18
+ var chunkLJUGNSQQ_cjs = require('../chunk-LJUGNSQQ.cjs');
18
19
  require('../chunk-ECHV2JSY.cjs');
19
20
  require('../chunk-BBRXE57K.cjs');
20
21
  require('../chunk-NE3ZHELZ.cjs');
21
22
  require('../chunk-N3CTXRFT.cjs');
22
23
  var react = require('react');
23
24
  var axios = require('axios');
25
+ var formik = require('formik');
26
+ var libphonenumberJs = require('libphonenumber-js');
24
27
 
25
28
  var useAddress = () => {
26
29
  const [data, setData] = react.useState([]);
@@ -30,7 +33,7 @@ var useAddress = () => {
30
33
  const fetchData = react.useCallback(async () => {
31
34
  try {
32
35
  setIsLoading(true);
33
- const result = await chunkRDUT4W3B_cjs.getAddresses("/store/customer_address/");
36
+ const result = await chunk6APRQ2ED_cjs.getAddresses("/store/customer_address/");
34
37
  setData(result || []);
35
38
  setError(null);
36
39
  } catch (err) {
@@ -355,7 +358,7 @@ function useCheckoutPayment(options) {
355
358
  );
356
359
  const order = response.data;
357
360
  setOrderSummary(order);
358
- chunk34Y7Y5FU_cjs.processPayment(order, paymentMethod, callbacks);
361
+ chunkQED6QJZC_cjs.processPayment(order, paymentMethod, callbacks);
359
362
  } catch (error) {
360
363
  if (options.onPlaceOrderError?.(error) === true) return;
361
364
  setShowFailureModal(true);
@@ -636,7 +639,7 @@ function useInlineCheckoutPayment(options) {
636
639
  return;
637
640
  }
638
641
  setOrderSummary(order);
639
- chunk34Y7Y5FU_cjs.processPayment(order, paymentMethod, callbacks, { isPublic });
642
+ chunkQED6QJZC_cjs.processPayment(order, paymentMethod, callbacks, { isPublic });
640
643
  } catch (error) {
641
644
  if (options.onPlaceOrderError?.(error) === true) return;
642
645
  setShowFailureModal(true);
@@ -918,7 +921,7 @@ function useCheckoutCoupon(options) {
918
921
  const refreshCoupons = react.useCallback(async () => {
919
922
  setIsLoading(true);
920
923
  try {
921
- const coupons = await chunk34Y7Y5FU_cjs.fetchAvailableCoupons();
924
+ const coupons = await chunkQED6QJZC_cjs.fetchAvailableCoupons();
922
925
  setAvailableCoupons(coupons);
923
926
  } catch {
924
927
  } finally {
@@ -930,7 +933,7 @@ function useCheckoutCoupon(options) {
930
933
  setError(null);
931
934
  setIsApplying(true);
932
935
  try {
933
- const coupon = await chunk34Y7Y5FU_cjs.applyCheckoutCoupon(code, callbacks);
936
+ const coupon = await chunkQED6QJZC_cjs.applyCheckoutCoupon(code, callbacks);
934
937
  setAppliedCoupon(coupon);
935
938
  } catch (err) {
936
939
  setError(err instanceof Error ? err.message : "Failed to apply coupon");
@@ -943,7 +946,7 @@ function useCheckoutCoupon(options) {
943
946
  const removeCouponHandler = react.useCallback(async () => {
944
947
  if (!appliedCoupon) return;
945
948
  try {
946
- await chunk34Y7Y5FU_cjs.removeCheckoutCoupon(appliedCoupon.coupon_code, callbacks);
949
+ await chunkQED6QJZC_cjs.removeCheckoutCoupon(appliedCoupon.coupon_code, callbacks);
947
950
  setAppliedCoupon(null);
948
951
  setError(null);
949
952
  } catch {
@@ -1173,8 +1176,8 @@ function useShopCheckout(options) {
1173
1176
  setQuantity(value);
1174
1177
  }, []);
1175
1178
  const handleShare = react.useCallback(() => {
1176
- chunk6LS5F4R3_cjs.shareLink(
1177
- `Buy ${product.name} at ${chunk6LS5F4R3_cjs.convertToCurrency(
1179
+ chunkSGJUMI3M_cjs.shareLink(
1180
+ `Buy ${product.name} at ${chunkSGJUMI3M_cjs.convertToCurrency(
1178
1181
  Number(product.selling_price)
1179
1182
  )}`,
1180
1183
  product.name
@@ -1256,7 +1259,7 @@ function useCoupon(options = {}) {
1256
1259
  react.useEffect(() => {
1257
1260
  const fetchCoupons = async () => {
1258
1261
  try {
1259
- const response = await chunkXFOUNOKO_cjs.getCoupons();
1262
+ const response = await chunkKNG4OMS5_cjs.getCoupons();
1260
1263
  if (response.data) {
1261
1264
  setAvailableCoupons(response.data);
1262
1265
  }
@@ -1265,7 +1268,7 @@ function useCoupon(options = {}) {
1265
1268
  };
1266
1269
  const fetchAppliedCoupon2 = async () => {
1267
1270
  try {
1268
- const response = await chunkXFOUNOKO_cjs.getAppliedCoupon();
1271
+ const response = await chunkKNG4OMS5_cjs.getAppliedCoupon();
1269
1272
  if (response.data) {
1270
1273
  setAppliedCoupon(response.data);
1271
1274
  }
@@ -1286,7 +1289,7 @@ function useCoupon(options = {}) {
1286
1289
  try {
1287
1290
  setCouponApplyingLoading(true);
1288
1291
  setCouponApplyingError(null);
1289
- const response = await chunkXFOUNOKO_cjs.applyCoupon(code);
1292
+ const response = await chunkKNG4OMS5_cjs.applyCoupon(code);
1290
1293
  if (response.data) {
1291
1294
  onCouponStatusChange?.(response.data.coupon);
1292
1295
  setAppliedCoupon(response.data.coupon);
@@ -1304,7 +1307,7 @@ function useCoupon(options = {}) {
1304
1307
  const handleRemoveCoupon = react.useCallback(async () => {
1305
1308
  if (!appliedCoupon) return;
1306
1309
  try {
1307
- const response = await chunkXFOUNOKO_cjs.removeCoupon(appliedCoupon.coupon_code);
1310
+ const response = await chunkKNG4OMS5_cjs.removeCoupon(appliedCoupon.coupon_code);
1308
1311
  if (response.data) {
1309
1312
  setAppliedCoupon(null);
1310
1313
  onCouponStatusChange?.(null);
@@ -1326,26 +1329,647 @@ function useCoupon(options = {}) {
1326
1329
  };
1327
1330
  }
1328
1331
 
1332
+ // src/utils/once.ts
1333
+ var store = /* @__PURE__ */ new Map();
1334
+ function once(key, fn) {
1335
+ let promise = store.get(key);
1336
+ if (!promise) {
1337
+ promise = fn().catch((error) => {
1338
+ store.delete(key);
1339
+ throw error;
1340
+ });
1341
+ store.set(key, promise);
1342
+ }
1343
+ return promise;
1344
+ }
1345
+
1346
+ // src/hooks/useCountries.ts
1347
+ var NO_COUNTRIES = [];
1348
+ var NO_STATES = [];
1349
+ function useOnce(key, fetcher) {
1350
+ const [state, setState] = react.useState({ key: null });
1351
+ react.useEffect(() => {
1352
+ if (!key) return;
1353
+ let active = true;
1354
+ once(key, fetcher).then(
1355
+ (data) => active && setState({ key, data }),
1356
+ (error) => active && setState({ key, error })
1357
+ );
1358
+ return () => {
1359
+ active = false;
1360
+ };
1361
+ }, [key]);
1362
+ const current = state.key === key ? state : { data: void 0, error: void 0 };
1363
+ return {
1364
+ data: current.data,
1365
+ error: current.error,
1366
+ isLoading: !!key && current.data === void 0 && current.error === void 0
1367
+ };
1368
+ }
1369
+ var useCountries = () => {
1370
+ const { data, error, isLoading } = useOnce("utils/countries/", async () => (await chunk6APRQ2ED_cjs.getCountries()).data);
1371
+ return { countries: data ?? NO_COUNTRIES, error, isLoading };
1372
+ };
1373
+ var useSubdivisions = (countryId) => {
1374
+ const { data, error, isLoading } = useOnce(
1375
+ countryId ? `utils/subdivisions/:${countryId}` : null,
1376
+ async () => (await chunk6APRQ2ED_cjs.getSubdivisions(countryId)).data.results
1377
+ );
1378
+ return { states: data ?? NO_STATES, error, isLoading };
1379
+ };
1380
+ function useAddressFormat(countryCode) {
1381
+ const [state, setState] = react.useState({});
1382
+ react.useEffect(() => {
1383
+ if (!countryCode) return;
1384
+ let active = true;
1385
+ once(`address-format:${countryCode}`, () => chunkQED6QJZC_cjs.loadAddressFormat(countryCode)).then(
1386
+ (format) => active && setState({ code: countryCode, format }),
1387
+ (error) => active && setState({ code: countryCode, error })
1388
+ );
1389
+ return () => {
1390
+ active = false;
1391
+ };
1392
+ }, [countryCode]);
1393
+ const fallback = react.useMemo(() => chunkQED6QJZC_cjs.buildAddressFormat(countryCode ?? "", null), [countryCode]);
1394
+ const current = state.code === countryCode ? state : {};
1395
+ return {
1396
+ format: current.format ?? fallback,
1397
+ error: current.error,
1398
+ isLoading: !!countryCode && !current.format && current.error === void 0
1399
+ };
1400
+ }
1401
+ var NO_ANSWER = { key: "", invalid: false, match: null };
1402
+ var keyFor = (countryCode, pincode) => `${countryCode ?? ""}:${pincode.trim().toUpperCase()}`;
1403
+ function usePincodeLookup({
1404
+ countryCode,
1405
+ pincode,
1406
+ ready,
1407
+ states,
1408
+ stateId,
1409
+ onMatch,
1410
+ enabled: enabledOption
1411
+ }) {
1412
+ const storeEnabled = chunkDODFO744_cjs.useThemeData((s) => !!s.themeData?.pincode_validation_enabled);
1413
+ const enabled = enabledOption ?? storeEnabled;
1414
+ const [answer, setAnswer] = react.useState(NO_ANSWER);
1415
+ const [loading, setLoading] = react.useState(false);
1416
+ const key = keyFor(countryCode, pincode);
1417
+ const current = answer.key === key ? answer : NO_ANSWER;
1418
+ const onMatchRef = react.useRef(onMatch);
1419
+ onMatchRef.current = onMatch;
1420
+ const latest = react.useRef({ pincode, states, stateId });
1421
+ latest.current = { pincode, states, stateId };
1422
+ const requestRef = react.useRef(0);
1423
+ const lookUp = react.useCallback(
1424
+ async (value) => {
1425
+ const request = ++requestRef.current;
1426
+ setLoading(true);
1427
+ const result = await chunkQED6QJZC_cjs.validatePincode(value, countryCode);
1428
+ if (request === requestRef.current) {
1429
+ setLoading(false);
1430
+ setAnswer({ key: keyFor(countryCode, value), invalid: result.status === "invalid", match: result.match });
1431
+ }
1432
+ return result;
1433
+ },
1434
+ [countryCode]
1435
+ );
1436
+ react.useEffect(() => {
1437
+ if (!enabled || !ready) return;
1438
+ const value = pincode.trim();
1439
+ const timer = setTimeout(() => lookUp(value), chunkQED6QJZC_cjs.PINCODE_DEBOUNCE_MS);
1440
+ return () => {
1441
+ clearTimeout(timer);
1442
+ requestRef.current += 1;
1443
+ setLoading(false);
1444
+ };
1445
+ }, [enabled, ready, pincode, lookUp]);
1446
+ const { match } = current;
1447
+ react.useEffect(() => {
1448
+ if (match) onMatchRef.current(match, chunkQED6QJZC_cjs.findSubdivision(states, match));
1449
+ }, [match, states]);
1450
+ const mismatchState = react.useMemo(() => {
1451
+ if (!match || !stateId) return void 0;
1452
+ const pincodeState = chunkQED6QJZC_cjs.findSubdivision(states, match);
1453
+ return pincodeState && String(pincodeState.id) !== stateId ? pincodeState.name : void 0;
1454
+ }, [match, states, stateId]);
1455
+ const issue = react.useMemo(() => {
1456
+ if (current.serverMessage) return { kind: "server", message: current.serverMessage };
1457
+ if (current.invalid) return { kind: "invalid" };
1458
+ if (mismatchState) return { kind: "mismatch", stateName: mismatchState };
1459
+ return null;
1460
+ }, [current.serverMessage, current.invalid, mismatchState]);
1461
+ const checkNow = react.useCallback(() => {
1462
+ const value = latest.current.pincode.trim();
1463
+ if (enabled && value) lookUp(value);
1464
+ }, [enabled, lookUp]);
1465
+ const verify = react.useCallback(async () => {
1466
+ const value = latest.current.pincode.trim();
1467
+ if (!enabled || !value) return null;
1468
+ const result = await lookUp(value);
1469
+ const { states: currentStates, stateId: currentStateId } = latest.current;
1470
+ if (result.status === "invalid") return { kind: "invalid" };
1471
+ if (result.status === "valid" && currentStateId) {
1472
+ const pincodeState = chunkQED6QJZC_cjs.findSubdivision(currentStates, result.match);
1473
+ if (pincodeState && String(pincodeState.id) !== currentStateId) {
1474
+ return { kind: "mismatch", stateName: pincodeState.name };
1475
+ }
1476
+ }
1477
+ return null;
1478
+ }, [enabled, lookUp]);
1479
+ const setServerError = react.useCallback(
1480
+ (message) => setAnswer((prev) => {
1481
+ const serverKey = keyFor(countryCode, latest.current.pincode);
1482
+ return { ...prev.key === serverKey ? prev : NO_ANSWER, key: serverKey, serverMessage: message };
1483
+ }),
1484
+ [countryCode]
1485
+ );
1486
+ const areaOptions = react.useMemo(() => chunkQED6QJZC_cjs.getAreaOptions(match), [match]);
1487
+ return { enabled, loading, issue, areaOptions, checkNow, verify, setServerError };
1488
+ }
1489
+ var INDIA_ID = 105;
1490
+ var EMPTY_ADDRESS_FORM_VALUES = {
1491
+ customer_name: "",
1492
+ customer_email: "",
1493
+ customer_phone: "",
1494
+ customer_country_code: "",
1495
+ country_obj: "",
1496
+ country_name: "",
1497
+ state_obj: "",
1498
+ state_name: "",
1499
+ city: "",
1500
+ pincode: "",
1501
+ address: "",
1502
+ address_line_2: "",
1503
+ is_default: false
1504
+ };
1505
+ function toAddressPayload(values) {
1506
+ const phoneCountry = values.customer_country_code;
1507
+ return {
1508
+ customer_name: values.customer_name.trim(),
1509
+ customer_email: values.customer_email.trim(),
1510
+ customer_phone: chunkQED6QJZC_cjs.sanitizePhoneInput(values.customer_phone, values.customer_country_code),
1511
+ customer_country_code: phoneCountry ? `+${libphonenumberJs.getCountryCallingCode(phoneCountry)}` : "",
1512
+ address: chunkQED6QJZC_cjs.joinAddressLines(values.address, values.address_line_2),
1513
+ city: values.city.trim(),
1514
+ state_obj: values.state_obj,
1515
+ state: values.state_name,
1516
+ country_obj: Number(values.country_obj),
1517
+ country: values.country_name,
1518
+ pincode: values.pincode.trim() || chunkQED6QJZC_cjs.NO_POSTAL_CODE,
1519
+ is_default: values.is_default
1520
+ };
1521
+ }
1522
+ function isPincodeReady(format, value) {
1523
+ const code = value.trim();
1524
+ if (!format.hasPostal || !code || code === chunkQED6QJZC_cjs.NO_POSTAL_CODE) return false;
1525
+ if (format.postalStrict && format.postalPattern) return format.postalPattern.test(code);
1526
+ return code.length >= chunkQED6QJZC_cjs.PINCODE_MIN_LENGTH && (!format.postalPattern || format.postalPattern.test(code));
1527
+ }
1528
+ function isPincodeCheckableOnBlur(format, value) {
1529
+ const code = value.trim();
1530
+ if (!format.hasPostal || !code || code === chunkQED6QJZC_cjs.NO_POSTAL_CODE) return false;
1531
+ if (format.postalStrict || !format.postalPattern) return false;
1532
+ return format.postalPattern.test(code);
1533
+ }
1534
+ function describePincodeIssue(issue, format) {
1535
+ if (!issue) return void 0;
1536
+ const postal = chunkQED6QJZC_cjs.lowerLabel(format.postalLabel);
1537
+ if (issue.kind === "server") return issue.message;
1538
+ if (issue.kind === "invalid") return `We couldn't find this ${postal}. Check it and try again.`;
1539
+ return `This ${postal} is in ${issue.stateName}. Check the ${postal} or the ${chunkQED6QJZC_cjs.lowerLabel(format.regionLabel)}.`;
1540
+ }
1541
+ var dialCode = (iso) => `+${libphonenumberJs.getCountryCallingCode(iso)}`;
1542
+ function phoneIsoFromDialCode(dial, addressCountry, countries) {
1543
+ if (!dial) return addressCountry.tld_code;
1544
+ const normalized = dial.startsWith("+") ? dial : `+${dial}`;
1545
+ if (dialCode(addressCountry.tld_code) === normalized) return addressCountry.tld_code;
1546
+ return countries.find((c) => dialCode(c.tld_code) === normalized)?.tld_code ?? addressCountry.tld_code;
1547
+ }
1548
+ function resolveInitialValues(countries, address, draft, defaultCountryId, locationCacheKey) {
1549
+ const byId = (id) => countries.find((c) => c.id === Number(id));
1550
+ const byIso = (iso) => countries.find((c) => c.tld_code === iso);
1551
+ const fallback = byId(defaultCountryId) ?? countries[0];
1552
+ if (address) {
1553
+ const country2 = byId(address.country_obj) ?? countries.find((c) => c.name.toLowerCase() === address.country?.toLowerCase()) ?? fallback;
1554
+ const phoneIso = phoneIsoFromDialCode(address.customer_country_code, country2, countries);
1555
+ return {
1556
+ values: {
1557
+ ...EMPTY_ADDRESS_FORM_VALUES,
1558
+ customer_name: address.customer_name ?? "",
1559
+ customer_email: chunkQED6QJZC_cjs.usableEmail(address.customer_email),
1560
+ customer_phone: address.customer_phone ?? "",
1561
+ customer_country_code: phoneIso,
1562
+ country_obj: country2.id,
1563
+ country_name: country2.name,
1564
+ state_obj: address.state_obj ? String(address.state_obj) : "",
1565
+ state_name: address.state ?? "",
1566
+ city: address.city ?? "",
1567
+ pincode: address.pincode ?? "",
1568
+ address: address.address ?? "",
1569
+ is_default: !!address.is_default
1570
+ },
1571
+ phoneFollowsCountry: phoneIso === country2.tld_code
1572
+ };
1573
+ }
1574
+ if (draft) {
1575
+ const draftCountry = byId(draft.country_obj) ?? byIso(draft.country_obj);
1576
+ const country2 = draftCountry ?? fallback;
1577
+ const phoneIso = byIso(draft.customer_country_code)?.tld_code ?? country2.tld_code;
1578
+ const text = (value) => typeof value === "string" ? value : value == null ? "" : String(value);
1579
+ const values = {
1580
+ ...EMPTY_ADDRESS_FORM_VALUES,
1581
+ customer_name: text(draft.customer_name),
1582
+ customer_email: text(draft.customer_email),
1583
+ customer_phone: text(draft.customer_phone),
1584
+ customer_country_code: phoneIso,
1585
+ country_obj: country2.id,
1586
+ country_name: country2.name,
1587
+ state_obj: text(draft.state_obj),
1588
+ state_name: text(draft.state_name),
1589
+ city: text(draft.city),
1590
+ pincode: text(draft.pincode),
1591
+ address: text(draft.address),
1592
+ address_line_2: text(draft.address_line_2),
1593
+ is_default: !!draft.is_default
1594
+ };
1595
+ if (!draftCountry) {
1596
+ values.state_obj = "";
1597
+ values.state_name = "";
1598
+ values.pincode = "";
1599
+ }
1600
+ return { values, phoneFollowsCountry: phoneIso === country2.tld_code };
1601
+ }
1602
+ const location = chunkLJUGNSQQ_cjs.getCache(locationCacheKey);
1603
+ const country = byIso(location?.country_code) ?? fallback;
1604
+ return {
1605
+ values: {
1606
+ ...EMPTY_ADDRESS_FORM_VALUES,
1607
+ customer_country_code: country.tld_code,
1608
+ country_obj: country.id,
1609
+ country_name: country.name
1610
+ },
1611
+ phoneFollowsCountry: true
1612
+ };
1613
+ }
1614
+ function useCountryAwareAddressForm({
1615
+ address,
1616
+ loadDraft,
1617
+ onSubmit,
1618
+ profile,
1619
+ pincodeValidationEnabled,
1620
+ defaultCountryId = INDIA_ID,
1621
+ locationCacheKey = chunkTB72NPRM_cjs.IP_API_CACHE_KEY,
1622
+ messages,
1623
+ formatPincodeIssue,
1624
+ onInvalid
1625
+ }) {
1626
+ const { countries: allCountries, error: countriesError } = useCountries();
1627
+ const countries = react.useMemo(
1628
+ () => allCountries.filter((c) => libphonenumberJs.isSupportedCountry(c.tld_code)).sort((a, b) => a.id === defaultCountryId ? -1 : b.id === defaultCountryId ? 1 : 0),
1629
+ [allCountries, defaultCountryId]
1630
+ );
1631
+ const onSubmitRef = react.useRef(onSubmit);
1632
+ onSubmitRef.current = onSubmit;
1633
+ const onInvalidRef = react.useRef(onInvalid);
1634
+ onInvalidRef.current = onInvalid;
1635
+ const formRef = react.useRef(null);
1636
+ const reportInvalid = react.useCallback((errors) => {
1637
+ if (onInvalidRef.current) onInvalidRef.current(errors);
1638
+ else chunkSGJUMI3M_cjs.focusFirstInvalidField(errors, formRef.current);
1639
+ }, []);
1640
+ const loadDraftRef = react.useRef(loadDraft);
1641
+ loadDraftRef.current = loadDraft;
1642
+ const schemaRef = react.useRef();
1643
+ const formik$1 = formik.useFormik({
1644
+ initialValues: EMPTY_ADDRESS_FORM_VALUES,
1645
+ validationSchema: () => schemaRef.current,
1646
+ onSubmit: (values2) => onSubmitRef.current(toAddressPayload(values2), values2)
1647
+ });
1648
+ const { values, setValues, setFieldValue, setTouched, validateForm, resetForm, submitForm } = formik$1;
1649
+ const valuesRef = react.useRef(values);
1650
+ valuesRef.current = values;
1651
+ const touchedRef = react.useRef(formik$1.touched);
1652
+ touchedRef.current = formik$1.touched;
1653
+ const country = react.useMemo(() => countries.find((c) => c.id === Number(values.country_obj)), [countries, values.country_obj]);
1654
+ const countryCode = country?.tld_code;
1655
+ const countryCodeRef = react.useRef(countryCode);
1656
+ countryCodeRef.current = countryCode;
1657
+ const { format, error: formatError } = useAddressFormat(countryCode);
1658
+ const { states, isLoading: statesLoading, error: statesError } = useSubdivisions(country?.id);
1659
+ const statesRef = react.useRef(states);
1660
+ statesRef.current = states;
1661
+ const showState = statesLoading || !!statesError || states.length > 0;
1662
+ const requireState = !statesError && showState;
1663
+ const messagesRef = react.useRef(messages);
1664
+ messagesRef.current = messages;
1665
+ const schema = react.useMemo(
1666
+ () => chunkQED6QJZC_cjs.buildAddressSchema(format, { requireState, messages: messagesRef.current }),
1667
+ [format, requireState]
1668
+ );
1669
+ schemaRef.current = schema;
1670
+ const phoneFollowsCountryRef = react.useRef(true);
1671
+ const initialPincodeRef = react.useRef("");
1672
+ const initializedFor = react.useRef(null);
1673
+ const initKey = address?.id ?? "new";
1674
+ react.useEffect(() => {
1675
+ if (!countries.length || initializedFor.current === initKey) return;
1676
+ initializedFor.current = initKey;
1677
+ const draft = address ? null : loadDraftRef.current?.() ?? null;
1678
+ const { values: initial, phoneFollowsCountry } = resolveInitialValues(
1679
+ countries,
1680
+ address,
1681
+ draft,
1682
+ defaultCountryId,
1683
+ locationCacheKey
1684
+ );
1685
+ phoneFollowsCountryRef.current = phoneFollowsCountry;
1686
+ initialPincodeRef.current = initial.pincode;
1687
+ resetForm({ values: initial });
1688
+ }, [countries, initKey, resetForm]);
1689
+ const profileAppliedFor = react.useRef(null);
1690
+ react.useEffect(() => {
1691
+ const current = valuesRef.current;
1692
+ if (!profile || address || !current.country_obj || initializedFor.current !== initKey || profileAppliedFor.current === initKey) {
1693
+ return;
1694
+ }
1695
+ profileAppliedFor.current = initKey;
1696
+ const next = { ...current };
1697
+ if (!current.customer_name.trim() && profile.customer_name) next.customer_name = profile.customer_name.trim();
1698
+ if (!current.customer_email.trim()) next.customer_email = chunkQED6QJZC_cjs.usableEmail(profile.email);
1699
+ if (!current.customer_phone.trim() && profile.phone) {
1700
+ const delivery = countries.find((c) => c.id === Number(current.country_obj));
1701
+ const code = profile.country_code?.trim();
1702
+ const phoneIso = code && /^[A-Za-z]{2}$/.test(code) ? code.toUpperCase() : delivery ? phoneIsoFromDialCode(code, delivery, countries) : current.customer_country_code;
1703
+ next.customer_country_code = phoneIso;
1704
+ next.customer_phone = chunkQED6QJZC_cjs.sanitizePhoneInput(profile.phone, phoneIso);
1705
+ phoneFollowsCountryRef.current = phoneIso === delivery?.tld_code;
1706
+ }
1707
+ setValues(next, false);
1708
+ }, [profile, initKey, countries, values.country_obj, setValues]);
1709
+ react.useEffect(() => {
1710
+ if (!countryCode) return;
1711
+ const { pincode } = valuesRef.current;
1712
+ if (!format.hasPostal && pincode !== chunkQED6QJZC_cjs.NO_POSTAL_CODE) setFieldValue("pincode", chunkQED6QJZC_cjs.NO_POSTAL_CODE, false);
1713
+ else if (format.hasPostal && pincode === chunkQED6QJZC_cjs.NO_POSTAL_CODE) setFieldValue("pincode", "", false);
1714
+ }, [format, countryCode, setFieldValue]);
1715
+ react.useEffect(() => {
1716
+ const { state_obj, state_name } = valuesRef.current;
1717
+ if (!state_obj || statesLoading || statesError || !states.length) return;
1718
+ const byId = states.find((s) => String(s.id) === state_obj);
1719
+ const state = byId ?? chunkQED6QJZC_cjs.findStateByName(states, state_obj) ?? chunkQED6QJZC_cjs.findStateByName(states, state_name);
1720
+ if (state) {
1721
+ if (String(state.id) !== state_obj || state.name !== state_name) {
1722
+ setValues({ ...valuesRef.current, state_obj: String(state.id), state_name: state.name }, false);
1723
+ }
1724
+ } else {
1725
+ setValues({ ...valuesRef.current, state_obj: "", state_name: "" }, false);
1726
+ }
1727
+ }, [states, statesLoading, statesError, values.state_obj, setValues]);
1728
+ const errorsRef = react.useRef(formik$1.errors);
1729
+ errorsRef.current = formik$1.errors;
1730
+ react.useEffect(() => {
1731
+ if (Object.keys(errorsRef.current).length) validateForm();
1732
+ }, [schema, validateForm]);
1733
+ const [autofill, setAutofill] = react.useState({});
1734
+ const autofillRef = react.useRef(autofill);
1735
+ autofillRef.current = autofill;
1736
+ const applyMatch = react.useCallback(
1737
+ (match, state) => {
1738
+ const current = valuesRef.current;
1739
+ const filledBefore = autofillRef.current;
1740
+ const next = {};
1741
+ const filled = {};
1742
+ const city = countryCodeRef.current === "IN" ? match.district || match.city : match.city || match.district;
1743
+ if (city && (!current.city.trim() || current.city === filledBefore.city)) {
1744
+ filled.city = city;
1745
+ if (current.city !== city) next.city = city;
1746
+ }
1747
+ if (state && (!current.state_obj || current.state_obj === filledBefore.state_obj)) {
1748
+ filled.state_obj = String(state.id);
1749
+ if (current.state_obj !== filled.state_obj) {
1750
+ next.state_obj = filled.state_obj;
1751
+ next.state_name = state.name;
1752
+ }
1753
+ }
1754
+ if (Object.keys(next).length) setValues({ ...current, ...next }, true);
1755
+ if (filled.city !== filledBefore.city || filled.state_obj !== filledBefore.state_obj) {
1756
+ setAutofill((prev) => ({ ...prev, ...filled }));
1757
+ }
1758
+ },
1759
+ [setValues]
1760
+ );
1761
+ const pincodeLookup = usePincodeLookup({
1762
+ countryCode,
1763
+ pincode: values.pincode,
1764
+ // Opening a saved address shouldn't re-check a postcode it already has.
1765
+ ready: !!countryCode && values.pincode !== initialPincodeRef.current && isPincodeReady(format, values.pincode),
1766
+ states,
1767
+ stateId: values.state_obj,
1768
+ onMatch: applyMatch,
1769
+ enabled: pincodeValidationEnabled
1770
+ });
1771
+ const { verify: verifyPincode, setServerError: setPincodeServerError, checkNow: checkPincodeNow } = pincodeLookup;
1772
+ const pincodeIssue = pincodeLookup.issue ? (formatPincodeIssue ?? describePincodeIssue)(pincodeLookup.issue, format) : void 0;
1773
+ const changeCountry = react.useCallback(
1774
+ (iso) => {
1775
+ const next = countries.find((c) => c.tld_code === iso);
1776
+ const current = valuesRef.current;
1777
+ if (!next || next.id === current.country_obj) return;
1778
+ const cityWasFilled = !!autofillRef.current.city && current.city === autofillRef.current.city;
1779
+ setValues(
1780
+ {
1781
+ ...current,
1782
+ country_obj: next.id,
1783
+ country_name: next.name,
1784
+ state_obj: "",
1785
+ state_name: "",
1786
+ pincode: "",
1787
+ city: cityWasFilled ? "" : current.city,
1788
+ customer_country_code: phoneFollowsCountryRef.current ? next.tld_code : current.customer_country_code
1789
+ },
1790
+ false
1791
+ );
1792
+ setAutofill({});
1793
+ setTouched({ ...touchedRef.current, state_obj: false, pincode: false, city: false }, false);
1794
+ initialPincodeRef.current = "";
1795
+ },
1796
+ [countries, setValues, setTouched]
1797
+ );
1798
+ const changePhoneCountry = react.useCallback(
1799
+ (iso) => {
1800
+ const current = valuesRef.current;
1801
+ const deliveryIso = countries.find((c) => c.id === current.country_obj)?.tld_code;
1802
+ phoneFollowsCountryRef.current = iso === deliveryIso;
1803
+ setFieldValue("customer_country_code", String(iso));
1804
+ },
1805
+ [countries, setFieldValue]
1806
+ );
1807
+ const changeState = react.useCallback(
1808
+ (e) => {
1809
+ const id = e.target.value;
1810
+ const name = statesRef.current.find((s) => String(s.id) === id)?.name ?? "";
1811
+ setValues({ ...valuesRef.current, state_obj: id, state_name: name }, true);
1812
+ },
1813
+ [setValues]
1814
+ );
1815
+ const formatRef = react.useRef(format);
1816
+ formatRef.current = format;
1817
+ const changePostcode = react.useCallback(
1818
+ (e) => {
1819
+ setFieldValue("pincode", chunkQED6QJZC_cjs.normalizePostcode(formatRef.current, e.target.value));
1820
+ },
1821
+ [setFieldValue]
1822
+ );
1823
+ const handleBlur = formik$1.handleBlur;
1824
+ const blurPostcode = react.useCallback(
1825
+ (e) => {
1826
+ handleBlur(e);
1827
+ const { pincode } = valuesRef.current;
1828
+ const format2 = formatRef.current;
1829
+ if (pincode !== initialPincodeRef.current && !isPincodeReady(format2, pincode) && isPincodeCheckableOnBlur(format2, pincode)) {
1830
+ checkPincodeNow();
1831
+ }
1832
+ },
1833
+ [handleBlur, checkPincodeNow]
1834
+ );
1835
+ const addArea = react.useCallback(
1836
+ (area) => {
1837
+ const line1 = valuesRef.current.address.trim();
1838
+ if (line1.toLowerCase().includes(area.toLowerCase())) return;
1839
+ setFieldValue("address", line1 ? `${line1}, ${area}` : area);
1840
+ },
1841
+ [setFieldValue]
1842
+ );
1843
+ const showServerPincodeError = react.useCallback(
1844
+ (error) => {
1845
+ const postal = chunkQED6QJZC_cjs.lowerLabel(formatRef.current.postalLabel);
1846
+ const invalidMessage = formatPincodeIssue?.({ kind: "invalid" }, formatRef.current) ?? `We couldn't find this ${postal}. Check it and try again.`;
1847
+ const message = chunkQED6QJZC_cjs.getPincodeError(error, invalidMessage);
1848
+ if (!message) return false;
1849
+ setPincodeServerError(message);
1850
+ reportInvalid({ pincode: message });
1851
+ return true;
1852
+ },
1853
+ // formatPincodeIssue is read at call time; a new inline function shouldn't re-create this.
1854
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1855
+ [setPincodeServerError, reportInvalid]
1856
+ );
1857
+ const changePhone = react.useCallback(
1858
+ (e) => {
1859
+ const current = valuesRef.current;
1860
+ const foreign = chunkQED6QJZC_cjs.detectForeignPhone(e.target.value, current.customer_country_code);
1861
+ if (foreign && countries.some((c) => c.tld_code === foreign.country)) {
1862
+ const deliveryIso = countries.find((c) => c.id === current.country_obj)?.tld_code;
1863
+ phoneFollowsCountryRef.current = foreign.country === deliveryIso;
1864
+ setValues(
1865
+ { ...current, customer_country_code: foreign.country, customer_phone: foreign.nationalNumber },
1866
+ true
1867
+ );
1868
+ return;
1869
+ }
1870
+ setFieldValue("customer_phone", chunkQED6QJZC_cjs.sanitizePhoneInput(e.target.value, current.customer_country_code));
1871
+ },
1872
+ [countries, setValues, setFieldValue]
1873
+ );
1874
+ const inFlightRef = react.useRef(null);
1875
+ const [submitting, setSubmitting] = react.useState(false);
1876
+ const runSubmit = react.useCallback(async () => {
1877
+ setSubmitting(true);
1878
+ try {
1879
+ const errors = await validateForm();
1880
+ if (Object.keys(errors).length) {
1881
+ const allTouched = Object.fromEntries(Object.keys(valuesRef.current).map((key) => [key, true]));
1882
+ setTouched(allTouched, false);
1883
+ reportInvalid(errors);
1884
+ return false;
1885
+ }
1886
+ const issue = await verifyPincode();
1887
+ if (issue) {
1888
+ reportInvalid({ pincode: true });
1889
+ return false;
1890
+ }
1891
+ await submitForm();
1892
+ return true;
1893
+ } finally {
1894
+ inFlightRef.current = null;
1895
+ setSubmitting(false);
1896
+ }
1897
+ }, [validateForm, setTouched, submitForm, verifyPincode, reportInvalid]);
1898
+ const submit = react.useCallback(() => {
1899
+ if (!inFlightRef.current) inFlightRef.current = runSubmit();
1900
+ return inFlightRef.current;
1901
+ }, [runSubmit]);
1902
+ const countryOptions = react.useMemo(
1903
+ () => countries.map((c) => ({ value: c.tld_code, label: c.name })),
1904
+ [countries]
1905
+ );
1906
+ const phoneOptions = react.useMemo(
1907
+ () => countries.map((c) => {
1908
+ const dial = libphonenumberJs.getCountryCallingCode(c.tld_code);
1909
+ return { value: c.tld_code, label: `${c.name} (+${dial})`, dial };
1910
+ }),
1911
+ [countries]
1912
+ );
1913
+ return {
1914
+ formik: formik$1,
1915
+ formRef,
1916
+ submitting,
1917
+ country,
1918
+ format,
1919
+ formatError,
1920
+ countriesError,
1921
+ countriesLoading: !countries.length && !countriesError,
1922
+ states,
1923
+ statesError,
1924
+ showState,
1925
+ requireState,
1926
+ countryOptions,
1927
+ phoneOptions,
1928
+ cityAutofilled: !!autofill.city && values.city === autofill.city,
1929
+ stateAutofilled: !!autofill.state_obj && values.state_obj === autofill.state_obj,
1930
+ lookupLoading: pincodeLookup.loading,
1931
+ pincodeIssue,
1932
+ areaOptions: pincodeLookup.areaOptions,
1933
+ changeCountry,
1934
+ changePhoneCountry,
1935
+ changeState,
1936
+ changePostcode,
1937
+ blurPostcode,
1938
+ addArea,
1939
+ changePhone,
1940
+ showServerPincodeError,
1941
+ submit
1942
+ };
1943
+ }
1944
+
1329
1945
  Object.defineProperty(exports, "useAddressForm", {
1330
1946
  enumerable: true,
1331
- get: function () { return chunkIVKJJLG7_cjs.useAddressForm; }
1947
+ get: function () { return chunkWWJAPKRQ_cjs.useAddressForm; }
1332
1948
  });
1333
1949
  exports.BUY_NOW_PAYLOAD_KEY = BUY_NOW_PAYLOAD_KEY;
1950
+ exports.EMPTY_ADDRESS_FORM_VALUES = EMPTY_ADDRESS_FORM_VALUES;
1951
+ exports.describePincodeIssue = describePincodeIssue;
1952
+ exports.toAddressPayload = toAddressPayload;
1334
1953
  exports.useAddress = useAddress;
1954
+ exports.useAddressFormat = useAddressFormat;
1335
1955
  exports.useBuyNow = useBuyNow;
1336
1956
  exports.useCart = useCart;
1337
1957
  exports.useCheckoutCoupon = useCheckoutCoupon;
1338
1958
  exports.useCheckoutPayment = useCheckoutPayment;
1959
+ exports.useCountries = useCountries;
1960
+ exports.useCountryAwareAddressForm = useCountryAwareAddressForm;
1339
1961
  exports.useCoupon = useCoupon;
1340
1962
  exports.useGetProductCategories = useGetProductCategories;
1341
1963
  exports.useGetProductDetails = useGetProductDetails;
1342
1964
  exports.useGetProducts = useGetProducts;
1343
1965
  exports.useInlineCheckoutPayment = useInlineCheckoutPayment;
1344
1966
  exports.useOrders = useOrders;
1967
+ exports.usePincodeLookup = usePincodeLookup;
1345
1968
  exports.useProductDetailModal = useProductDetailModal;
1346
1969
  exports.usePublicCheckout = usePublicCheckout;
1347
1970
  exports.useServiceFormModal = useServiceFormModal;
1348
1971
  exports.useShopCheckout = useShopCheckout;
1972
+ exports.useSubdivisions = useSubdivisions;
1349
1973
  exports.useUserDetails = useUserDetails;
1350
1974
  exports.useVariantSelector = useVariantSelector;
1351
1975
  exports.useWishlist = useWishlist;