@tagadapay/headless-sdk 1.2.0 → 1.3.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 (42) hide show
  1. package/dist/core/helpers/autocomplete.d.ts +89 -0
  2. package/dist/core/helpers/autocomplete.d.ts.map +1 -0
  3. package/dist/core/helpers/autocomplete.js +186 -0
  4. package/dist/core/helpers/autocomplete.js.map +1 -0
  5. package/dist/core/helpers/countries.d.ts +45 -0
  6. package/dist/core/helpers/countries.d.ts.map +1 -0
  7. package/dist/core/helpers/countries.js +65 -0
  8. package/dist/core/helpers/countries.js.map +1 -0
  9. package/dist/core/helpers/currency.d.ts +26 -0
  10. package/dist/core/helpers/currency.d.ts.map +1 -0
  11. package/dist/core/helpers/currency.js +72 -0
  12. package/dist/core/helpers/currency.js.map +1 -0
  13. package/dist/core/helpers/index.d.ts +5 -0
  14. package/dist/core/helpers/index.d.ts.map +1 -0
  15. package/dist/core/helpers/index.js +5 -0
  16. package/dist/core/helpers/index.js.map +1 -0
  17. package/dist/core/helpers/iso3166.d.ts +28 -0
  18. package/dist/core/helpers/iso3166.d.ts.map +1 -0
  19. package/dist/core/helpers/iso3166.js +84 -0
  20. package/dist/core/helpers/iso3166.js.map +1 -0
  21. package/dist/core/index.d.ts +2 -0
  22. package/dist/core/index.d.ts.map +1 -1
  23. package/dist/core/index.js +2 -0
  24. package/dist/core/index.js.map +1 -1
  25. package/dist/react/hooks/useGoogleAutocomplete.d.ts +26 -0
  26. package/dist/react/hooks/useGoogleAutocomplete.d.ts.map +1 -0
  27. package/dist/react/hooks/useGoogleAutocomplete.js +70 -0
  28. package/dist/react/hooks/useGoogleAutocomplete.js.map +1 -0
  29. package/dist/react/hooks/useISOData.d.ts +23 -0
  30. package/dist/react/hooks/useISOData.d.ts.map +1 -0
  31. package/dist/react/hooks/useISOData.js +63 -0
  32. package/dist/react/hooks/useISOData.js.map +1 -0
  33. package/dist/react/index.d.ts +6 -0
  34. package/dist/react/index.d.ts.map +1 -1
  35. package/dist/react/index.js +4 -0
  36. package/dist/react/index.js.map +1 -1
  37. package/dist/tagada-headless-react.min.js +2 -2
  38. package/dist/tagada-headless-react.min.js.map +4 -4
  39. package/dist/tagada-headless.js +470 -2
  40. package/dist/tagada-headless.min.js +2 -2
  41. package/dist/tagada-headless.min.js.map +4 -4
  42. package/package.json +1 -1
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Geodata — CDN-backed country/region data.
3
+ *
4
+ * Fetches slim JSON from Vercel Blob CDN on demand:
5
+ * - countries.json (~10KB) — fetched once on first getCountries() call
6
+ * - regions.json (~95KB) — fetched lazily on first getStatesForCountry() call
7
+ *
8
+ * Both are cached in memory after first fetch.
9
+ */
10
+ const GEODATA_CDN_BASE = 'https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1';
11
+ export const AVAILABLE_LANGUAGES = ['en', 'ru', 'de', 'da', 'fr', 'es', 'zh', 'hi', 'pt', 'ja', 'ar', 'it', 'he'];
12
+ const countriesCache = new Map();
13
+ const regionsCache = new Map();
14
+ const inflightCountries = new Map();
15
+ const inflightRegions = new Map();
16
+ async function fetchCountriesRaw(language) {
17
+ const cached = countriesCache.get(language);
18
+ if (cached)
19
+ return cached;
20
+ let inflight = inflightCountries.get(language);
21
+ if (inflight)
22
+ return inflight;
23
+ inflight = (async () => {
24
+ const url = `${GEODATA_CDN_BASE}/${language}/countries.json`;
25
+ const res = await fetch(url);
26
+ if (!res.ok)
27
+ throw new Error(`Geodata fetch failed: ${url} (${res.status})`);
28
+ const data = await res.json();
29
+ countriesCache.set(language, data);
30
+ inflightCountries.delete(language);
31
+ return data;
32
+ })();
33
+ inflightCountries.set(language, inflight);
34
+ return inflight;
35
+ }
36
+ async function fetchRegionsRaw(language) {
37
+ const cached = regionsCache.get(language);
38
+ if (cached)
39
+ return cached;
40
+ let inflight = inflightRegions.get(language);
41
+ if (inflight)
42
+ return inflight;
43
+ inflight = (async () => {
44
+ const url = `${GEODATA_CDN_BASE}/${language}/regions.json`;
45
+ const res = await fetch(url);
46
+ if (!res.ok)
47
+ throw new Error(`Geodata fetch failed: ${url} (${res.status})`);
48
+ const data = await res.json();
49
+ regionsCache.set(language, data);
50
+ inflightRegions.delete(language);
51
+ return data;
52
+ })();
53
+ inflightRegions.set(language, inflight);
54
+ return inflight;
55
+ }
56
+ function getCountriesCached(language) {
57
+ return countriesCache.get(language) || countriesCache.get('en') || {};
58
+ }
59
+ function getRegionsCached(language) {
60
+ return regionsCache.get(language) || regionsCache.get('en') || {};
61
+ }
62
+ /** Fetch countries + regions from CDN for a language. Call before sync getters. */
63
+ export async function ensureGeoDataLoaded(language = 'en') {
64
+ await Promise.all([fetchCountriesRaw(language), fetchRegionsRaw(language)]);
65
+ }
66
+ export const getCountries = (language = 'en') => {
67
+ const raw = getCountriesCached(language);
68
+ return Object.entries(raw)
69
+ .map(([code, c]) => ({ code, name: c.n, iso3: c.i3, numeric: c.nu }))
70
+ .sort((a, b) => a.name.localeCompare(b.name));
71
+ };
72
+ export const getStatesForCountry = (countryCode, language = 'en') => {
73
+ const raw = getRegionsCached(language);
74
+ const tuples = raw[countryCode];
75
+ if (!tuples)
76
+ return [];
77
+ return tuples
78
+ .map(([iso, name]) => ({ code: iso, name, countryCode }))
79
+ .sort((a, b) => a.name.localeCompare(b.name));
80
+ };
81
+ export function isLanguageLoaded(language) {
82
+ return countriesCache.has(language);
83
+ }
84
+ //# sourceMappingURL=iso3166.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"iso3166.js","sourceRoot":"","sources":["../../../src/core/helpers/iso3166.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,gBAAgB,GAAG,oEAAoE,CAAC;AAE9F,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE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AAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACtC,CAAC"}
@@ -6,5 +6,7 @@ export { CustomerModule } from './modules/customer.js';
6
6
  export { CatalogModule } from './modules/catalog.js';
7
7
  export { HttpClient } from './http.js';
8
8
  export { TagadaError, TagadaAuthError, TagadaValidationError, TagadaNotFoundError, TagadaRateLimitError, TagadaPaymentError, TagadaNetworkError, } from './errors.js';
9
+ export { GoogleAutocompleteCore, loadGoogleMapsScript, ISODataCore, AVAILABLE_LANGUAGES, CurrencyUtils, formatMoney, ensureGeoDataLoaded, getCountries, getStatesForCountry, isLanguageLoaded, } from './helpers/index.js';
10
+ export type { GooglePrediction, GooglePlaceDetails, ExtractedAddress, FormattedAddress, SupportedLanguage, ISOCountry, ISORegion, Country, State, Currency, } from './helpers/index.js';
9
11
  export type { Environment, HeadlessConfig, HttpRequestOptions, LineItem, CheckoutSession, CheckoutLineItem, CheckoutTotals, CheckoutCustomer, Address, ShippingRate, PaymentMethodConfig, PaymentSetupConfig, ExpressMethod, ExpressMethods, StoreConfig, PayResult, PayOptions, PayDirectOptions, CreateInstrumentOptions, PaymentInstrument, ThreedsSession, PaymentStatus, Offer, OfferLineItem, OfferPreview, OfferPreviewItem, OfferPayResult, Customer, Order, OrderItem, Subscription, CatalogProduct, CatalogVariant, CatalogPrice, CurrencyOption, } from './types.js';
10
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EACL,WAAW,EACX,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,YAAY,EACV,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,WAAW,EACX,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,uBAAuB,EACvB,iBAAiB,EACjB,cAAc,EACd,aAAa,EACb,KAAK,EACL,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,QAAQ,EACR,KAAK,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EACd,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EACL,WAAW,EACX,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,WAAW,EACX,mBAAmB,EACnB,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EACV,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,SAAS,EACT,OAAO,EACP,KAAK,EACL,QAAQ,GACT,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EACV,WAAW,EACX,cAAc,EACd,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,WAAW,EACX,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,uBAAuB,EACvB,iBAAiB,EACjB,cAAc,EACd,aAAa,EACb,KAAK,EACL,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,QAAQ,EACR,KAAK,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EACd,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,YAAY,CAAC"}
@@ -6,4 +6,6 @@ export { CustomerModule } from './modules/customer.js';
6
6
  export { CatalogModule } from './modules/catalog.js';
7
7
  export { HttpClient } from './http.js';
8
8
  export { TagadaError, TagadaAuthError, TagadaValidationError, TagadaNotFoundError, TagadaRateLimitError, TagadaPaymentError, TagadaNetworkError, } from './errors.js';
9
+ // Helpers: Google Autocomplete, ISO countries/regions, currency formatting
10
+ export { GoogleAutocompleteCore, loadGoogleMapsScript, ISODataCore, AVAILABLE_LANGUAGES, CurrencyUtils, formatMoney, ensureGeoDataLoaded, getCountries, getStatesForCountry, isLanguageLoaded, } from './helpers/index.js';
9
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EACL,WAAW,EACX,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EACL,WAAW,EACX,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,2EAA2E;AAC3E,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,WAAW,EACX,mBAAmB,EACnB,aAAa,EACb,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * React hook for Google Places Autocomplete — handles script injection,
3
+ * debounced prediction search, place detail fetching, and address extraction.
4
+ */
5
+ import { type GooglePrediction, type GooglePlaceDetails, type ExtractedAddress, type FormattedAddress } from '../../core/helpers/autocomplete.js';
6
+ export type { GooglePrediction, GooglePlaceDetails, ExtractedAddress, FormattedAddress };
7
+ export interface UseGoogleAutocompleteOptions {
8
+ apiKey: string;
9
+ language?: string;
10
+ region?: string;
11
+ version?: string;
12
+ /** Defer script loading until searchPlaces() is first called. Default: false. */
13
+ defer?: boolean;
14
+ }
15
+ export interface UseGoogleAutocompleteReturn {
16
+ predictions: GooglePrediction[];
17
+ isLoading: boolean;
18
+ isScriptLoaded: boolean;
19
+ searchPlaces: (input: string, countryRestriction?: string) => void;
20
+ getPlaceDetails: (placeId: string) => Promise<GooglePlaceDetails | null>;
21
+ extractAddressComponents: (place: GooglePlaceDetails) => ExtractedAddress;
22
+ extractFormattedAddress: (place: GooglePlaceDetails) => FormattedAddress;
23
+ clearPredictions: () => void;
24
+ }
25
+ export declare function useGoogleAutocomplete(options: UseGoogleAutocompleteOptions): UseGoogleAutocompleteReturn;
26
+ //# sourceMappingURL=useGoogleAutocomplete.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGoogleAutocomplete.d.ts","sourceRoot":"","sources":["../../../src/react/hooks/useGoogleAutocomplete.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAGL,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACtB,MAAM,oCAAoC,CAAC;AAE5C,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;AAEzF,MAAM,WAAW,4BAA4B;IAC3C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,2BAA2B;IAC1C,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,EAAE,OAAO,CAAC;IACxB,YAAY,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,kBAAkB,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACnE,eAAe,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;IACzE,wBAAwB,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,gBAAgB,CAAC;IAC1E,uBAAuB,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,gBAAgB,CAAC;IACzE,gBAAgB,EAAE,MAAM,IAAI,CAAC;CAC9B;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,2BAA2B,CA8ExG"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * React hook for Google Places Autocomplete — handles script injection,
3
+ * debounced prediction search, place detail fetching, and address extraction.
4
+ */
5
+ import { useCallback, useEffect, useRef, useState } from 'react';
6
+ import { GoogleAutocompleteCore, loadGoogleMapsScript, } from '../../core/helpers/autocomplete.js';
7
+ export function useGoogleAutocomplete(options) {
8
+ const { apiKey, language, region, version, defer = false } = options;
9
+ const [predictions, setPredictions] = useState([]);
10
+ const [isLoading, setIsLoading] = useState(false);
11
+ const [isScriptLoaded, setIsScriptLoaded] = useState(false);
12
+ const debounceRef = useRef(null);
13
+ const pendingRef = useRef(null);
14
+ const inject = useCallback(() => {
15
+ loadGoogleMapsScript(apiKey, { language, region, version }).then(() => setIsScriptLoaded(true));
16
+ }, [apiKey, language, region, version]);
17
+ // Eager load unless defer
18
+ useEffect(() => {
19
+ if (!apiKey || defer)
20
+ return;
21
+ inject();
22
+ }, [apiKey, defer, inject]);
23
+ // Replay pending search after deferred load
24
+ useEffect(() => {
25
+ if (isScriptLoaded && pendingRef.current) {
26
+ const { input, country } = pendingRef.current;
27
+ pendingRef.current = null;
28
+ doSearch(input, country);
29
+ }
30
+ // eslint-disable-next-line react-hooks/exhaustive-deps
31
+ }, [isScriptLoaded]);
32
+ const doSearch = useCallback((input, countryRestriction) => {
33
+ if (!isScriptLoaded) {
34
+ if (defer) {
35
+ pendingRef.current = { input, country: countryRestriction };
36
+ inject();
37
+ }
38
+ return;
39
+ }
40
+ if (input.length < 3) {
41
+ setPredictions([]);
42
+ return;
43
+ }
44
+ if (debounceRef.current)
45
+ clearTimeout(debounceRef.current);
46
+ debounceRef.current = setTimeout(async () => {
47
+ setIsLoading(true);
48
+ const results = await GoogleAutocompleteCore.searchPlaces(input, {
49
+ componentRestrictions: countryRestriction ? { country: countryRestriction.toLowerCase() } : undefined,
50
+ });
51
+ setPredictions(results);
52
+ setIsLoading(false);
53
+ }, 300);
54
+ }, [isScriptLoaded, defer, inject]);
55
+ const getPlaceDetails = useCallback((placeId) => GoogleAutocompleteCore.getPlaceDetails(placeId), []);
56
+ const extractAddressComponents = useCallback((place) => GoogleAutocompleteCore.extractAddressComponents(place), []);
57
+ const extractFormattedAddress = useCallback((place) => GoogleAutocompleteCore.extractFormattedAddress(place), []);
58
+ const clearPredictions = useCallback(() => setPredictions([]), []);
59
+ return {
60
+ predictions,
61
+ isLoading,
62
+ isScriptLoaded,
63
+ searchPlaces: doSearch,
64
+ getPlaceDetails,
65
+ extractAddressComponents,
66
+ extractFormattedAddress,
67
+ clearPredictions,
68
+ };
69
+ }
70
+ //# sourceMappingURL=useGoogleAutocomplete.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGoogleAutocomplete.js","sourceRoot":"","sources":["../../../src/react/hooks/useGoogleAutocomplete.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,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AW,CACjC,CAAC,OAAe,EAAE,EAAE,CAAC,sBAAsB,CAAC,eAAe,CAAC,OAAO,CAAC,EACpE,EAAE,CACH,CAAC;IAEF,MAAM,wBAAwB,GAAG,WAAW,CAC1C,CAAC,KAAyB,EAAE,EAAE,CAAC,sBAAsB,CAAC,wBAAwB,CAAC,KAAK,CAAC,EACrF,EAAE,CACH,CAAC;IAEF,MAAM,uBAAuB,GAAG,WAAW,CACzC,CAAC,KAAyB,EAAE,EAAE,CAAC,sBAAsB,CAAC,uBAAuB,CAAC,KAAK,CAAC,EACpF,EAAE,CACH,CAAC;IAEF,MAAM,gBAAgB,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;IAEnE,OAAO;QACL,WAAW;QACX,SAAS;QACT,cAAc;QACd,YAAY,EAAE,QAAQ;QACtB,eAAe;QACf,wBAAwB;QACxB,uBAAuB;QACvB,gBAAgB;KACjB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * React hooks for ISO country/region data — CDN-backed,
3
+ * with Google Places → ISO region mapping.
4
+ */
5
+ import { type ISOCountry, type ISORegion, type SupportedLanguage } from '../../core/helpers/countries.js';
6
+ export type { ISOCountry, ISORegion, SupportedLanguage };
7
+ export interface UseISODataReturn {
8
+ countries: Record<string, ISOCountry>;
9
+ getRegions: (countryCode: string) => ISORegion[];
10
+ findRegion: (countryCode: string, regionCode: string) => ISORegion | null;
11
+ mapGoogleToISO: (googleState: string, googleStateLong: string, countryCode: string) => ISORegion | null;
12
+ isLoaded: boolean;
13
+ }
14
+ export declare function useISOData(language?: SupportedLanguage): UseISODataReturn;
15
+ export declare function useCountryOptions(language?: SupportedLanguage): Array<{
16
+ value: string;
17
+ label: string;
18
+ }>;
19
+ export declare function useRegionOptions(countryCode: string, language?: SupportedLanguage): Array<{
20
+ value: string;
21
+ label: string;
22
+ }>;
23
+ //# sourceMappingURL=useISOData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useISOData.d.ts","sourceRoot":"","sources":["../../../src/react/hooks/useISOData.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,iBAAiB,EACvB,MAAM,iCAAiC,CAAC;AAGzC,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,iBAAiB,EAAE,CAAC;AAMzD,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACtC,UAAU,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,SAAS,EAAE,CAAC;IACjD,UAAU,EAAE,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,SAAS,GAAG,IAAI,CAAC;IAC1E,cAAc,EAAE,CAAC,WAAW,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,SAAS,GAAG,IAAI,CAAC;IACxG,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,UAAU,CAAC,QAAQ,GAAE,iBAAwB,GAAG,gBAAgB,CA8B/E;AAMD,wBAAgB,iBAAiB,CAAC,QAAQ,GAAE,iBAAwB,GAAG,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAQ7G;AAMD,wBAAgB,gBAAgB,CAC9B,WAAW,EAAE,MAAM,EACnB,QAAQ,GAAE,iBAAwB,GACjC,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAQzC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * React hooks for ISO country/region data — CDN-backed,
3
+ * with Google Places → ISO region mapping.
4
+ */
5
+ import { useEffect, useMemo, useState } from 'react';
6
+ import { ISODataCore, } from '../../core/helpers/countries.js';
7
+ import { ensureGeoDataLoaded, isLanguageLoaded } from '../../core/helpers/iso3166.js';
8
+ export function useISOData(language = 'en') {
9
+ const [isLoaded, setIsLoaded] = useState(isLanguageLoaded(language));
10
+ useEffect(() => {
11
+ let cancelled = false;
12
+ ensureGeoDataLoaded(language)
13
+ .then(() => { if (!cancelled)
14
+ setIsLoaded(true); })
15
+ .catch((err) => console.error('[headless-sdk] Failed to load geodata:', err));
16
+ return () => { cancelled = true; };
17
+ }, [language]);
18
+ return useMemo(() => {
19
+ if (!isLoaded) {
20
+ return {
21
+ countries: {},
22
+ getRegions: () => [],
23
+ findRegion: () => null,
24
+ mapGoogleToISO: () => null,
25
+ isLoaded: false,
26
+ };
27
+ }
28
+ return {
29
+ countries: ISODataCore.getCountries(language),
30
+ getRegions: (cc) => ISODataCore.getRegions(cc, language),
31
+ findRegion: (cc, rc) => ISODataCore.findRegion(cc, rc, language),
32
+ mapGoogleToISO: (gs, gsl, cc) => ISODataCore.mapGoogleToISO(gs, gsl, cc, language),
33
+ isLoaded: true,
34
+ };
35
+ }, [language, isLoaded]);
36
+ }
37
+ // ---------------------------------------------------------------------------
38
+ // useCountryOptions — countries as select options
39
+ // ---------------------------------------------------------------------------
40
+ export function useCountryOptions(language = 'en') {
41
+ const { countries, isLoaded } = useISOData(language);
42
+ return useMemo(() => {
43
+ if (!isLoaded)
44
+ return [];
45
+ return Object.values(countries)
46
+ .map((c) => ({ value: c.iso, label: c.name }))
47
+ .sort((a, b) => a.label.localeCompare(b.label));
48
+ }, [countries, isLoaded]);
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // useRegionOptions — regions/states for a country as select options
52
+ // ---------------------------------------------------------------------------
53
+ export function useRegionOptions(countryCode, language = 'en') {
54
+ const { getRegions, isLoaded } = useISOData(language);
55
+ return useMemo(() => {
56
+ if (!isLoaded || !countryCode)
57
+ return [];
58
+ return getRegions(countryCode)
59
+ .map((r) => ({ value: r.iso, label: r.name }))
60
+ .sort((a, b) => a.label.localeCompare(b.label));
61
+ }, [countryCode, getRegions, isLoaded]);
62
+ }
63
+ //# sourceMappingURL=useISOData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useISOData.js","sourceRoot":"","sources":["../../../src/react/hooks/useISOData.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAe,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAClE,OAAO,EACL,WAAW,GAIZ,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAgBtF,MAAM,UAAU,UAAU,CAAC,WAA8B,IAAI;IAC3D,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,GAAG,QAAQ,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAErE,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,mBAAmB,CAAC,QAAQ,CAAC;aAC1B,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS;YAAE,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;aAClD,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,GAAG,CAAC,CAAC,CAAC;QAChF,OAAO,GAAG,EAAE,GAAG,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACrC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEf,OAAO,OAAO,CAAC,GAAG,EAAE;QAClB,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO;gBACL,SAAS,EAAE,EAAE;gBACb,UAAU,EAAE,GAAG,EAAE,CAAC,EAAE;gBACpB,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI;gBACtB,cAAc,EAAE,GAAG,EAAE,CAAC,IAAI;gBAC1B,QAAQ,EAAE,KAAK;aAChB,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;AAC9E,oEAAoE;AACpE,8EAA8E;AAE9E,MAAM,UAAU,gBAAgB,CAC9B,WAAmB,EACnB,WAA8B,IAAI;IAElC,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;IACtD,OAAO,OAAO,CAAC,GAAG,EAAE;QAClB,IAAI,CAAC,QAAQ,IAAI,CAAC,WAAW;YAAE,OAAO,EAAE,CAAC;QACzC,OAAO,UAAU,CAAC,WAAW,CAAC;aAC3B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;aAC7C,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IACpD,CAAC,EAAE,CAAC,WAAW,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC1C,CAAC"}
@@ -10,5 +10,11 @@ export { useCustomer } from './hooks/useCustomer.js';
10
10
  export type { UseCustomerReturn } from './hooks/useCustomer.js';
11
11
  export { useCatalog } from './hooks/useCatalog.js';
12
12
  export type { UseCatalogReturn } from './hooks/useCatalog.js';
13
+ export { useGoogleAutocomplete } from './hooks/useGoogleAutocomplete.js';
14
+ export type { UseGoogleAutocompleteOptions, UseGoogleAutocompleteReturn } from './hooks/useGoogleAutocomplete.js';
15
+ export { useISOData, useCountryOptions, useRegionOptions } from './hooks/useISOData.js';
16
+ export type { UseISODataReturn } from './hooks/useISOData.js';
17
+ export type { GooglePrediction, GooglePlaceDetails, ExtractedAddress, FormattedAddress, SupportedLanguage, ISOCountry, ISORegion, Currency, } from '../core/helpers/index.js';
18
+ export { formatMoney, CurrencyUtils, ISODataCore, GoogleAutocompleteCore, loadGoogleMapsScript } from '../core/helpers/index.js';
13
19
  export type { HeadlessConfig, Environment, CheckoutSession, CheckoutLineItem, CheckoutTotals, CheckoutCustomer, Address, ShippingRate, LineItem, PaymentSetupConfig, PaymentMethodConfig, ExpressMethods, ExpressMethod, StoreConfig, PayResult, PayOptions, PaymentStatus, Offer, OfferLineItem, OfferPreview, OfferPreviewItem, OfferPayResult, Customer, Order, Subscription, CatalogProduct, CatalogVariant, CatalogPrice, CurrencyOption, } from '../core/types.js';
14
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC1E,YAAY,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAEjE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,YAAY,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,YAAY,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,YAAY,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,YAAY,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,YAAY,EACV,cAAc,EACd,WAAW,EACX,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,WAAW,EACX,SAAS,EACT,UAAU,EACV,aAA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AS,EACT,QAAQ,GACT,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAEjI,YAAY,EACV,cAAc,EACd,WAAW,EACX,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,WAAW,EACX,SAAS,EACT,UAAU,EACV,aAAa,EACb,KAAK,EACL,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,QAAQ,EACR,KAAK,EACL,YAAY,EACZ,cAAc,EACd,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,kBAAkB,CAAC"}
@@ -4,4 +4,8 @@ export { usePayment } from './hooks/usePayment.js';
4
4
  export { useOffers } from './hooks/useOffers.js';
5
5
  export { useCustomer } from './hooks/useCustomer.js';
6
6
  export { useCatalog } from './hooks/useCatalog.js';
7
+ // Helpers hooks
8
+ export { useGoogleAutocomplete } from './hooks/useGoogleAutocomplete.js';
9
+ export { useISOData, useCountryOptions, useRegionOptions } from './hooks/useISOData.js';
10
+ export { formatMoney, CurrencyUtils, ISODataCore, GoogleAutocompleteCore, loadGoogleMapsScript } from '../core/helpers/index.js';
7
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAG1E,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAGrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAGrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/react/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAG1E,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAGrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAGrD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGnD,gBAAgB;AAChB,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAGzE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAexF,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC"}
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.2.0
2
+ * @tagadapay/headless-sdk v1.3.0
3
3
  * Headless checkout, payments, analytics, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessReactBundle=(()=>{var oe=Object.create;var M=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty;var E=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var de=(s,e)=>{for(var t in e)M(s,t,{get:e[t],enumerable:!0})},G=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ae(e))!ue.call(s,n)&&n!==t&&M(s,n,{get:()=>e[n],enumerable:!(r=ie(e,n))||r.enumerable});return s};var le=(s,e,t)=>(t=s!=null?oe(ce(s)):{},G(e||!s||!s.__esModule?M(t,"default",{value:s,enumerable:!0}):t,s)),me=s=>G(M({},"__esModule",{value:!0}),s);var pe={};de(pe,{TagadaHeadlessProvider:()=>X,useCatalog:()=>se,useCheckout:()=>Z,useCustomer:()=>re,useHeadlessClient:()=>T,useOffers:()=>te,usePayment:()=>ee});var A=E("react");var R=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},N=class extends R{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},q=class extends R{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},j=class extends R{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},L=class extends R{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var H=class extends R{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var V={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},$=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??V[e]??V.production}async request(e,t={}){var k;let{method:r="GET",body:n,headers:u={},params:o,token:m,signal:d}=t,a=`${this.baseUrl}${e}`;if(o){let p=new URLSearchParams;for(let[g,i]of Object.entries(o))i!==void 0&&p.set(g,String(i));let h=p.toString();h&&(a+=`?${h}`)}let l={"Content-Type":"application/json",...u},f=m??this.apiKey??((k=this.getToken)==null?void 0:k.call(this));f&&(l["x-cms-token"]=f);let P=new AbortController,w=setTimeout(()=>P.abort(),this.timeout);try{let p=await fetch(a,{method:r,headers:l,body:n!=null?JSON.stringify(n):void 0,signal:d??P.signal});if(clearTimeout(w),p.ok){let h=await p.text();return h?JSON.parse(h):{}}throw await this.handleErrorResponse(p,e),new R("Unexpected error","unknown",p.status)}catch(p){throw clearTimeout(w),p instanceof R?p:p instanceof DOMException&&p.name==="AbortError"?new H(`Request to ${e} timed out after ${this.timeout}ms.`):new H(p instanceof Error?p.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new N(n);case 404:throw new j(t,"");case 422:{let u=Array.isArray(r.errors)?r.errors:[];throw new q(n,u)}case 429:{let u=Number(e.headers.get("Retry-After")??"1")*1e3;throw new L(u)}default:throw new R(n,"api_error",e.status,r)}}};var _=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var n;t&&(this.sessionToken=t,(n=this.onTokenChange)==null||n.call(this,t));let r=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(r)}async createSession(e){var m;let t=e.items.map(d=>({variantId:d.variantId,priceId:d.priceId,quantity:d.quantity})),r={storeId:this.storeId,lineItems:t};e.currency&&(r.currency=e.currency),e.returnUrl&&(r.returnUrl=e.returnUrl),e.customerEmail&&(r.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let n=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(n.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((m=this.onTokenChange)==null||m.call(this,o)),{checkoutUrl:n.checkoutUrl,checkoutToken:n.checkoutToken,sessionToken:o,customerId:n.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,partial:!0,customerData:{email:t.email},shippingAddress:{firstName:t.firstName,lastName:t.lastName,phone:t.phone},billingAddress:{},differentBillingAddress:!1},{token:this.sessionToken})}async updateAddress(e,t){let r=n=>{if(n)return{address1:n.line1,address2:n.line2,city:n.city,state:n.state,postal:n.postalCode,country:n.country}};await this.http.post(`/api/v1/checkout-sessions/${e}/address`,{checkoutSessionId:e,data:{shippingAddress:r(t.shippingAddress)??{},billingAddress:r(t.billingAddress)}},{token:this.sessionToken})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},u=t.sessionLineItems??[],o=t.customer,m=u.map(a=>{let l=a.price,f=(l==null?void 0:l.variant)??{},P=f.product??{},w=(l==null?void 0:l.currencyOptions)??{},k=w.USD??w[Object.keys(w)[0]];return{id:a.id,variantId:a.variantId,priceId:a.priceId,productName:P.name??"",variantName:f.name??"",quantity:a.quantity??1,unitAmount:(k==null?void 0:k.amount)??0,totalAmount:((k==null?void 0:k.amount)??0)*(a.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:f.imageUrl??""}}),d=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:m,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??d.reduce((a,l)=>a+(l.amount??0),0),currency:n.currency??t.selectedPresentmentCurrency??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var D=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r={};for(let n of t.methods??[]){let u=n.provider?`${n.method}:${n.provider}`:n.method;r[u]=n}return r}async getExpressMethods(e){var n,u;let t=await this.getPaymentSetup(e),r={};for(let[,o]of Object.entries(t)){if(!o.enabled||!o.express)continue;let m=o.method,d={type:m,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(m==="apple_pay"||o.type==="apple_pay"){let a=typeof window<"u"&&"ApplePaySession"in window&&((u=(n=window.ApplePaySession)==null?void 0:n.canMakePayments)==null?void 0:u.call(n));r.applePay={...d,available:!!a}}else m==="google_pay"||o.type==="google_pay"?r.googlePay=d:m==="paypal"?r.paypal=d:m==="klarna"||m==="klarna_express"?r.klarna=d:m==="link"&&(r.link=d)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let[u,o]=await Promise.all([r.tokenizeCard(n),r.tokenizeCardRaw(n)]);return{tagadaToken:u,rawToken:o}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,u=Date.now();for(;Date.now()-u<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(m=>setTimeout(m,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var z=class{constructor(e,t){this.http=e;this.storeId=t}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var u;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(u=e==null?void 0:e.ids)!=null&&u.length)for(let o of e.ids)r.push(`ids=${encodeURIComponent(o)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var F=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var B=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,u;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.length&&(t.productIds=e.productIds),(u=e==null?void 0:e.variantIds)!=null&&u.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var K=class{constructor(e){let t=e.environment??"production",r=$.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new $({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=u=>{this._sessionToken=u};this.checkout=new _(this.http,this.config.storeId,n),this.payment=new D(this.http,this.config.storeId,t),this.offers=new z(this.http,this.config.storeId),this.customer=new F(this.http,this.config.storeId),this.catalog=new B(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function W(s){return new K(s)}var Y=E("react/jsx-runtime"),Q=(0,A.createContext)(null);function X({storeId:s,environment:e,apiKey:t,baseUrl:r,config:n,children:u}){let o=(0,A.useMemo)(()=>W(n??{storeId:s,environment:e,apiKey:t,baseUrl:r}),[s,e,t,r,n]),m=(0,A.useMemo)(()=>({client:o}),[o]);return(0,Y.jsx)(Q.Provider,{value:m,children:u})}function T(){let s=(0,A.useContext)(Q);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var S=E("react");function Z(s,e){let t=T(),[r,n]=(0,S.useState)(null),[u,o]=(0,S.useState)(!1),[m,d]=(0,S.useState)(null),a=(0,S.useCallback)(async()=>{if(s){o(!0),d(null);try{let i=await t.checkout.loadSession(s,e);n(i)}catch(i){d(i instanceof Error?i:new Error(String(i)))}finally{o(!1)}}},[t,s,e]);(0,S.useEffect)(()=>{a()},[a]);let l=(0,S.useCallback)(async i=>{o(!0),d(null);try{let c=await t.checkout.createSession(i),x=new URL(window.location.href);x.searchParams.set("checkoutToken",c.checkoutToken),x.searchParams.set("token",c.sessionToken),window.history.replaceState({},"",x.toString());let J=await t.checkout.loadSession(c.checkoutToken,c.sessionToken);n(J)}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}},[t]),f=(0,S.useCallback)(async i=>{if(!r)return;let c=await t.checkout.updateCart(r.id,i);n(c)},[t,r]),P=(0,S.useCallback)(async i=>{if(r){o(!0);try{await t.checkout.updateCustomer(r.id,i),await a()}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}}},[t,r,a]),w=(0,S.useCallback)(async i=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,i),await a()}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}}},[t,r,a]),k=(0,S.useCallback)(async i=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,i),await a()}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}}},[t,r,a]),p=(0,S.useCallback)(async i=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,i),await a()}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}}},[t,r,a]),h=(0,S.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),g=(0,S.useCallback)(async i=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,i),await a()}catch(c){d(c instanceof Error?c:new Error(String(c)))}finally{o(!1)}}},[t,r,a]);return{session:r,isLoading:u,error:m,refresh:a,createSession:l,updateCart:f,updateCustomer:P,updateAddress:w,applyPromo:k,removePromo:p,getShippingRates:h,selectShippingRate:g}}var I=E("react");function ee(){let s=T(),[e,t]=(0,I.useState)(null),[r,n]=(0,I.useState)(null),[u,o]=(0,I.useState)(null),[m,d]=(0,I.useState)(!1),[a,l]=(0,I.useState)(null),[f,P]=(0,I.useState)(null),w=(0,I.useRef)(!1),k=(0,I.useCallback)(async C=>{if(!w.current){w.current=!0;try{let[y,v,ne]=await Promise.all([s.payment.getPaymentSetup(C),s.payment.getExpressMethods(C),s.payment.getStoreConfig()]);t(y),n(v),o(ne)}catch(y){w.current=!1,P(y instanceof Error?y:new Error(String(y)))}}},[s]),p=(0,I.useCallback)(C=>async()=>{d(!0),P(null);try{return await C()}catch(y){let v=y instanceof Error?y:new Error(String(y));throw P(v),v}finally{d(!1)}},[]),h=(0,I.useCallback)(async C=>{d(!0),P(null);try{let y=await s.payment.pay(C);return l(y),y}catch(y){let v=y instanceof Error?y:new Error(String(y));throw P(v),v}finally{d(!1)}},[s]),g=(0,I.useCallback)(C=>s.payment.tokenizeCard(C),[s]),i=(0,I.useCallback)(async C=>{let v=await p(()=>s.payment.processApplePay(C))();return l(v),v},[s,p]),c=(0,I.useCallback)(async C=>{let v=await p(()=>s.payment.processGooglePay(C))();return l(v),v},[s,p]),x=(0,I.useCallback)(async C=>{let v=await p(()=>s.payment.processApm(C))();return l(v),v},[s,p]),J=(0,I.useCallback)(C=>s.payment.pollPaymentStatus(C),[s]);return{paymentSetup:e,expressMethods:r,storeConfig:u,isProcessing:m,result:a,error:f,loadPaymentSetup:k,pay:h,tokenizeCard:g,processApplePay:i,processGooglePay:c,processApm:x,pollStatus:J}}var b=E("react");function te(){let s=T(),[e,t]=(0,b.useState)(null),[r,n]=(0,b.useState)(null),[u,o]=(0,b.useState)(!1),[m,d]=(0,b.useState)(null),a=(0,b.useCallback)(async i=>{o(!0),d(null);try{return await i()}catch(c){let x=c instanceof Error?c:new Error(String(c));throw d(x),x}finally{o(!1)}},[]),l=(0,b.useCallback)(i=>a(async()=>{let c=await s.offers.getOffer(i);return t(c),c}),[s,a]),f=(0,b.useCallback)(i=>s.offers.listOffers(i),[s]),P=(0,b.useCallback)(i=>a(async()=>{let c=await s.offers.previewOffer(i);return n(c),c}),[s,a]),w=(0,b.useCallback)(i=>a(()=>s.offers.payPreviewedOffer(i)),[s,a]),k=(0,b.useCallback)(i=>s.offers.toggleOrderBump(i),[s]),p=(0,b.useCallback)(i=>s.offers.listPostPurchaseOffers(i),[s]),h=(0,b.useCallback)(i=>a(()=>s.offers.acceptPostPurchaseOffer(i)),[s,a]),g=(0,b.useCallback)(i=>a(()=>s.offers.declinePostPurchaseOffer(i)),[s,a]);return{offer:e,preview:r,isLoading:u,error:m,getOffer:l,listOffers:f,previewOffer:P,payPreviewedOffer:w,toggleOrderBump:k,listPostPurchaseOffers:p,acceptPostPurchaseOffer:h,declinePostPurchaseOffer:g}}var O=E("react");function re(s){let e=T(),[t,r]=(0,O.useState)(null),[n,u]=(0,O.useState)([]),[o,m]=(0,O.useState)([]),[d,a]=(0,O.useState)(!1),[l,f]=(0,O.useState)(null),P=(0,O.useCallback)(async h=>{a(!0),f(null);try{let g=await e.customer.getProfile(h);r(g)}catch(g){f(g instanceof Error?g:new Error(String(g)))}finally{a(!1)}},[e]),w=(0,O.useCallback)(async h=>{try{let g=await e.customer.getOrders(h);u(g.orders)}catch(g){f(g instanceof Error?g:new Error(String(g)))}},[e]),k=(0,O.useCallback)(async h=>{try{let g=await e.customer.getSubscriptions(h);m(g)}catch(g){f(g instanceof Error?g:new Error(String(g)))}},[e]),p=(0,O.useCallback)(async(h,g)=>{try{let i=await e.customer.updateProfile(h,g);r(i)}catch(i){f(i instanceof Error?i:new Error(String(i)))}},[e]);return(0,O.useEffect)(()=>{s&&P(s)},[s,P]),{customer:t,orders:n,subscriptions:o,isLoading:d,error:l,loadCustomer:P,loadOrders:w,loadSubscriptions:k,updateProfile:p}}var U=E("react");function se(){let s=T(),[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(!1),[u,o]=(0,U.useState)(null),m=(0,U.useCallback)(async a=>{n(!0),o(null);try{let l=await s.catalog.getProducts(a);return t(l),l}catch(l){let f=l instanceof Error?l:new Error(String(l));throw o(f),f}finally{n(!1)}},[s]),d=(0,U.useCallback)(async a=>{n(!0),o(null);try{return await s.catalog.getProduct(a)}catch(l){let f=l instanceof Error?l:new Error(String(l));throw o(f),f}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:u,loadProducts:m,loadProduct:d}}return me(pe);})();
6
+ "use strict";var TagadaHeadlessReactBundle=(()=>{var Le=Object.create;var B=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var L=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Ne=(s,e)=>{for(var t in e)B(s,t,{get:e[t],enumerable:!0})},pe=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Ue.call(s,n)&&n!==t&&B(s,n,{get:()=>e[n],enumerable:!(r=Ee(e,n))||r.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?Le(De(s)):{},pe(e||!s||!s.__esModule?B(t,"default",{value:s,enumerable:!0}):t,s)),Ge=s=>pe(B({},"__esModule",{value:!0}),s);var Be={};Ne(Be,{CurrencyUtils:()=>H,GoogleAutocompleteCore:()=>T,ISODataCore:()=>D,TagadaHeadlessProvider:()=>ye,formatMoney:()=>le,loadGoogleMapsScript:()=>j,useCatalog:()=>Ce,useCheckout:()=>Pe,useCountryOptions:()=>be,useCustomer:()=>we,useGoogleAutocomplete:()=>Re,useHeadlessClient:()=>x,useISOData:()=>ne,useOffers:()=>Ie,usePayment:()=>Se,useRegionOptions:()=>Oe});var $=L("react");var E=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},z=class extends E{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},J=class extends E{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},Y=class extends E{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},V=class extends E{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var M=class extends E{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var me={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},_=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??me[e]??me.production}async request(e,t={}){var f;let{method:r="GET",body:n,headers:i={},params:o,token:c,signal:u}=t,a=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[P,l]of Object.entries(o))l!==void 0&&y.set(P,String(l));let S=y.toString();S&&(a+=`?${S}`)}let d={"Content-Type":"application/json",...i},g=c??this.apiKey??((f=this.getToken)==null?void 0:f.call(this));g&&(d["x-cms-token"]=g);let h=new AbortController,p=setTimeout(()=>h.abort(),this.timeout);try{let y=await fetch(a,{method:r,headers:d,body:n!=null?JSON.stringify(n):void 0,signal:u??h.signal});if(clearTimeout(p),y.ok){let S=await y.text();return S?JSON.parse(S):{}}throw await this.handleErrorResponse(y,e),new E("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof E?y:y instanceof DOMException&&y.name==="AbortError"?new M(`Request to ${e} timed out after ${this.timeout}ms.`):new M(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new z(n);case 404:throw new Y(t,"");case 422:{let i=Array.isArray(r.errors)?r.errors:[];throw new J(n,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new V(i)}default:throw new E(n,"api_error",e.status,r)}}};var W=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var n;t&&(this.sessionToken=t,(n=this.onTokenChange)==null||n.call(this,t));let r=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(r)}async createSession(e){var c;let t=e.items.map(u=>({variantId:u.variantId,priceId:u.priceId,quantity:u.quantity})),r={storeId:this.storeId,lineItems:t};e.currency&&(r.currency=e.currency),e.returnUrl&&(r.returnUrl=e.returnUrl),e.customerEmail&&(r.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let n=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(n.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((c=this.onTokenChange)==null||c.call(this,o)),{checkoutUrl:n.checkoutUrl,checkoutToken:n.checkoutToken,sessionToken:o,customerId:n.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,partial:!0,customerData:{email:t.email},shippingAddress:{firstName:t.firstName,lastName:t.lastName,phone:t.phone},billingAddress:{},differentBillingAddress:!1},{token:this.sessionToken})}async updateAddress(e,t){let r=n=>{if(n)return{address1:n.line1,address2:n.line2,city:n.city,state:n.state,postal:n.postalCode,country:n.country}};await this.http.post(`/api/v1/checkout-sessions/${e}/address`,{checkoutSessionId:e,data:{shippingAddress:r(t.shippingAddress)??{},billingAddress:r(t.billingAddress)}},{token:this.sessionToken})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,c=i.map(a=>{let d=a.price,g=(d==null?void 0:d.variant)??{},h=g.product??{},p=(d==null?void 0:d.currencyOptions)??{},f=p.USD??p[Object.keys(p)[0]];return{id:a.id,variantId:a.variantId,priceId:a.priceId,productName:h.name??"",variantName:g.name??"",quantity:a.quantity??1,unitAmount:(f==null?void 0:f.amount)??0,totalAmount:((f==null?void 0:f.amount)??0)*(a.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:g.imageUrl??""}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??u.reduce((a,d)=>a+(d.amount??0),0),currency:n.currency??t.selectedPresentmentCurrency??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var Z=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r={};for(let n of t.methods??[]){let i=n.provider?`${n.method}:${n.provider}`:n.method;r[i]=n}return r}async getExpressMethods(e){var n,i;let t=await this.getPaymentSetup(e),r={};for(let[,o]of Object.entries(t)){if(!o.enabled||!o.express)continue;let c=o.method,u={type:c,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(c==="apple_pay"||o.type==="apple_pay"){let a=typeof window<"u"&&"ApplePaySession"in window&&((i=(n=window.ApplePaySession)==null?void 0:n.canMakePayments)==null?void 0:i.call(n));r.applePay={...u,available:!!a}}else c==="google_pay"||o.type==="google_pay"?r.googlePay=u:c==="paypal"?r.paypal=u:c==="klarna"||c==="klarna_express"?r.klarna=u:c==="link"&&(r.link=u)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let[i,o]=await Promise.all([r.tokenizeCard(n),r.tokenizeCardRaw(n)]);return{tagadaToken:i,rawToken:o}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}):this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata})}async payDirect(e){return this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId})}async processApplePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:n}=await r.tokenizeGooglePay(e.googlePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:n,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId})}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(c=>setTimeout(c,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var Q=class{constructor(e,t){this.http=e;this.storeId=t}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var i;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(i=e==null?void 0:e.ids)!=null&&i.length)for(let o of e.ids)r.push(`ids=${encodeURIComponent(o)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var X=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var ee=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var oe=class{constructor(e){let t=e.environment??"production",r=_.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new _({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=i=>{this._sessionToken=i};this.checkout=new W(this.http,this.config.storeId,n),this.payment=new Z(this.http,this.config.storeId,t),this.offers=new Q(this.http,this.config.storeId),this.customer=new X(this.http,this.config.storeId),this.catalog=new ee(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function ge(s){return new oe(s)}var he=L("react/jsx-runtime"),fe=(0,$.createContext)(null);function ye({storeId:s,environment:e,apiKey:t,baseUrl:r,config:n,children:i}){let o=(0,$.useMemo)(()=>ge(n??{storeId:s,environment:e,apiKey:t,baseUrl:r}),[s,e,t,r,n]),c=(0,$.useMemo)(()=>({client:o}),[o]);return(0,he.jsx)(fe.Provider,{value:c,children:i})}function x(){let s=(0,$.useContext)(fe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var A=L("react");function Pe(s,e){let t=x(),[r,n]=(0,A.useState)(null),[i,o]=(0,A.useState)(!1),[c,u]=(0,A.useState)(null),a=(0,A.useCallback)(async()=>{if(s){o(!0),u(null);try{let l=await t.checkout.loadSession(s,e);n(l)}catch(l){u(l instanceof Error?l:new Error(String(l)))}finally{o(!1)}}},[t,s,e]);(0,A.useEffect)(()=>{a()},[a]);let d=(0,A.useCallback)(async l=>{o(!0),u(null);try{let m=await t.checkout.createSession(l),I=new URL(window.location.href);I.searchParams.set("checkoutToken",m.checkoutToken),I.searchParams.set("token",m.sessionToken),window.history.replaceState({},"",I.toString());let U=await t.checkout.loadSession(m.checkoutToken,m.sessionToken);n(U)}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}},[t]),g=(0,A.useCallback)(async l=>{if(!r)return;let m=await t.checkout.updateCart(r.id,l);n(m)},[t,r]),h=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.updateCustomer(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),p=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),f=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),y=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]),S=(0,A.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),P=(0,A.useCallback)(async l=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,l),await a()}catch(m){u(m instanceof Error?m:new Error(String(m)))}finally{o(!1)}}},[t,r,a]);return{session:r,isLoading:i,error:c,refresh:a,createSession:d,updateCart:g,updateCustomer:h,updateAddress:p,applyPromo:f,removePromo:y,getShippingRates:S,selectShippingRate:P}}var k=L("react");function Se(){let s=x(),[e,t]=(0,k.useState)(null),[r,n]=(0,k.useState)(null),[i,o]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),[a,d]=(0,k.useState)(null),[g,h]=(0,k.useState)(null),p=(0,k.useRef)(!1),f=(0,k.useCallback)(async C=>{if(!p.current){p.current=!0;try{let[w,R,xe]=await Promise.all([s.payment.getPaymentSetup(C),s.payment.getExpressMethods(C),s.payment.getStoreConfig()]);t(w),n(R),o(xe)}catch(w){p.current=!1,h(w instanceof Error?w:new Error(String(w)))}}},[s]),y=(0,k.useCallback)(C=>async()=>{u(!0),h(null);try{return await C()}catch(w){let R=w instanceof Error?w:new Error(String(w));throw h(R),R}finally{u(!1)}},[]),S=(0,k.useCallback)(async C=>{u(!0),h(null);try{let w=await s.payment.pay(C);return d(w),w}catch(w){let R=w instanceof Error?w:new Error(String(w));throw h(R),R}finally{u(!1)}},[s]),P=(0,k.useCallback)(C=>s.payment.tokenizeCard(C),[s]),l=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processApplePay(C))();return d(R),R},[s,y]),m=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processGooglePay(C))();return d(R),R},[s,y]),I=(0,k.useCallback)(async C=>{let R=await y(()=>s.payment.processApm(C))();return d(R),R},[s,y]),U=(0,k.useCallback)(C=>s.payment.pollPaymentStatus(C),[s]);return{paymentSetup:e,expressMethods:r,storeConfig:i,isProcessing:c,result:a,error:g,loadPaymentSetup:f,pay:S,tokenizeCard:P,processApplePay:l,processGooglePay:m,processApm:I,pollStatus:U}}var b=L("react");function Ie(){let s=x(),[e,t]=(0,b.useState)(null),[r,n]=(0,b.useState)(null),[i,o]=(0,b.useState)(!1),[c,u]=(0,b.useState)(null),a=(0,b.useCallback)(async l=>{o(!0),u(null);try{return await l()}catch(m){let I=m instanceof Error?m:new Error(String(m));throw u(I),I}finally{o(!1)}},[]),d=(0,b.useCallback)(l=>a(async()=>{let m=await s.offers.getOffer(l);return t(m),m}),[s,a]),g=(0,b.useCallback)(l=>s.offers.listOffers(l),[s]),h=(0,b.useCallback)(l=>a(async()=>{let m=await s.offers.previewOffer(l);return n(m),m}),[s,a]),p=(0,b.useCallback)(l=>a(()=>s.offers.payPreviewedOffer(l)),[s,a]),f=(0,b.useCallback)(l=>s.offers.toggleOrderBump(l),[s]),y=(0,b.useCallback)(l=>s.offers.listPostPurchaseOffers(l),[s]),S=(0,b.useCallback)(l=>a(()=>s.offers.acceptPostPurchaseOffer(l)),[s,a]),P=(0,b.useCallback)(l=>a(()=>s.offers.declinePostPurchaseOffer(l)),[s,a]);return{offer:e,preview:r,isLoading:i,error:c,getOffer:d,listOffers:g,previewOffer:h,payPreviewedOffer:p,toggleOrderBump:f,listPostPurchaseOffers:y,acceptPostPurchaseOffer:S,declinePostPurchaseOffer:P}}var O=L("react");function we(s){let e=x(),[t,r]=(0,O.useState)(null),[n,i]=(0,O.useState)([]),[o,c]=(0,O.useState)([]),[u,a]=(0,O.useState)(!1),[d,g]=(0,O.useState)(null),h=(0,O.useCallback)(async S=>{a(!0),g(null);try{let P=await e.customer.getProfile(S);r(P)}catch(P){g(P instanceof Error?P:new Error(String(P)))}finally{a(!1)}},[e]),p=(0,O.useCallback)(async S=>{try{let P=await e.customer.getOrders(S);i(P.orders)}catch(P){g(P instanceof Error?P:new Error(String(P)))}},[e]),f=(0,O.useCallback)(async S=>{try{let P=await e.customer.getSubscriptions(S);c(P)}catch(P){g(P instanceof Error?P:new Error(String(P)))}},[e]),y=(0,O.useCallback)(async(S,P)=>{try{let l=await e.customer.updateProfile(S,P);r(l)}catch(l){g(l instanceof Error?l:new Error(String(l)))}},[e]);return(0,O.useEffect)(()=>{s&&h(s)},[s,h]),{customer:t,orders:n,subscriptions:o,isLoading:u,error:d,loadCustomer:h,loadOrders:p,loadSubscriptions:f,updateProfile:y}}var G=L("react");function Ce(){let s=x(),[e,t]=(0,G.useState)([]),[r,n]=(0,G.useState)(!1),[i,o]=(0,G.useState)(null),c=(0,G.useCallback)(async a=>{n(!0),o(null);try{let d=await s.catalog.getProducts(a);return t(d),d}catch(d){let g=d instanceof Error?d:new Error(String(d));throw o(g),g}finally{n(!1)}},[s]),u=(0,G.useCallback)(async a=>{n(!0),o(null);try{return await s.catalog.getProduct(a)}catch(d){let g=d instanceof Error?d:new Error(String(d));throw o(g),g}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:c,loadProduct:u}}var v=L("react");var ke=!1,ve=!1,te=[];function ie(){ve=!0;for(let s of te)s();te.length=0}function j(s,e={}){var t,r;return ve||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(ie(),Promise.resolve()):ke?new Promise(n=>te.push(n)):(ke=!0,new Promise((n,i)=>{if(te.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let a=()=>{var d,g;(g=(d=window.google)==null?void 0:d.maps)!=null&&g.places?ie():setTimeout(a,100)};a();return}let c=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&c.set("language",e.language),e.region&&c.set("region",e.region);let u=document.createElement("script");u.src=`https://maps.googleapis.com/maps/api/js?${c}`,u.async=!0,u.defer=!0,u.onload=()=>ie(),u.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(u)}))}var T=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(c,u)=>{var a,d,g;o(u===((g=(d=(a=window.google)==null?void 0:a.maps)==null?void 0:d.places)==null?void 0:g.PlacesServiceStatus.OK)&&c?c:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,c)=>{var u,a,d;i(c===((d=(a=(u=window.google)==null?void 0:u.maps)==null?void 0:a.places)==null?void 0:d.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",o="",c="",u="",a="",d="";for(let p of e.address_components??[]){let f=p.types;f.includes("subpremise")&&(t.subpremise=p.long_name),f.includes("street_number")&&(t.streetNumber=p.long_name),f.includes("premise")&&(r=p.long_name),f.includes("route")&&(t.route=p.long_name),f.includes("neighborhood")&&(n=p.long_name),f.includes("sublocality_level_5")&&(i=p.long_name),f.includes("sublocality_level_4")&&(o=p.long_name),f.includes("sublocality_level_3")&&(c=p.long_name),f.includes("sublocality_level_2")&&(u=p.long_name),f.includes("sublocality_level_1")&&(a=p.long_name),f.includes("locality")&&(t.locality=p.long_name),f.includes("postal_town")&&(d=p.long_name),f.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),f.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),f.includes("country")&&(t.country=p.short_name),f.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=d||u||a||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let g=t.streetNumber||r,h=t.route||i||o||c||n;if(t.subpremise&&g&&h)t.fullStreetAddress=`${t.subpremise}/${g} ${h}`;else if(g&&h)if(r&&o&&c){let p=`${c}-${o}-${r}`;u&&(p=`${p} ${u}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${g} ${h}`;else h?t.fullStreetAddress=h:g&&(t.fullStreetAddress=g);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};function Re(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,c]=(0,v.useState)([]),[u,a]=(0,v.useState)(!1),[d,g]=(0,v.useState)(!1),h=(0,v.useRef)(null),p=(0,v.useRef)(null),f=(0,v.useCallback)(()=>{j(e,{language:t,region:r,version:n}).then(()=>g(!0))},[e,t,r,n]);(0,v.useEffect)(()=>{!e||i||f()},[e,i,f]),(0,v.useEffect)(()=>{if(d&&p.current){let{input:I,country:U}=p.current;p.current=null,y(I,U)}},[d]);let y=(0,v.useCallback)((I,U)=>{if(!d){i&&(p.current={input:I,country:U},f());return}if(I.length<3){c([]);return}h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{a(!0);let C=await T.searchPlaces(I,{componentRestrictions:U?{country:U.toLowerCase()}:void 0});c(C),a(!1)},300)},[d,i,f]),S=(0,v.useCallback)(I=>T.getPlaceDetails(I),[]),P=(0,v.useCallback)(I=>T.extractAddressComponents(I),[]),l=(0,v.useCallback)(I=>T.extractFormattedAddress(I),[]),m=(0,v.useCallback)(()=>c([]),[]);return{predictions:o,isLoading:u,isScriptLoaded:d,searchPlaces:y,getPlaceDetails:S,extractAddressComponents:P,extractFormattedAddress:l,clearPredictions:m}}var N=L("react");var Ae="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",ue=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],K=new Map,re=new Map,ae=new Map,ce=new Map;async function He(s){let e=K.get(s);if(e)return e;let t=ae.get(s);return t||(t=(async()=>{let r=`${Ae}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return K.set(s,i),ae.delete(s),i})(),ae.set(s,t),t)}async function Me(s){let e=re.get(s);if(e)return e;let t=ce.get(s);return t||(t=(async()=>{let r=`${Ae}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return re.set(s,i),ce.delete(s),i})(),ce.set(s,t),t)}function _e(s){return K.get(s)||K.get("en")||{}}function je(s){return re.get(s)||re.get("en")||{}}async function F(s="en"){await Promise.all([He(s),Me(s)])}var se=(s="en")=>{let e=_e(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},de=(s,e="en")=>{let r=je(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function q(s){return K.has(s)}var D=class s{static ensureLoaded(e="en"){return F(e)}static getCountries(e="en"){let t=se(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return se(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return de(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);if(i.length===0)return null;let o=i.find(c=>c.iso===e);return o||(o=i.find(c=>c.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(c=>c.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(c=>c.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(c.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return q(e)}static getAvailableLanguages(){return ue}};function ne(s="en"){let[e,t]=(0,N.useState)(q(s));return(0,N.useEffect)(()=>{let r=!1;return F(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,N.useMemo)(()=>e?{countries:D.getCountries(s),getRegions:r=>D.getRegions(r,s),findRegion:(r,n)=>D.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>D.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function be(s="en"){let{countries:e,isLoaded:t}=ne(s);return(0,N.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function Oe(s,e="en"){let{getRegions:t,isLoaded:r}=ne(e);return(0,N.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var Ke={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Fe={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},qe=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),H=class s{static getSymbol(e){return Ke[e]??e}static getName(e){return Fe[e]??e}static getDecimalPlaces(e){return qe.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function le(s,e="USD",t="en-US"){let r=H.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${H.getSymbol(e)}${n.toFixed(r)}`}}return Ge(Be);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessReactBundle){ window.TagadaHeadlessReact=TagadaHeadlessReactBundle;}
8
8
  //# sourceMappingURL=tagada-headless-react.min.js.map