@tagadapay/headless-sdk 1.8.0-rc.0 → 1.8.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 (66) hide show
  1. package/README.md +216 -1
  2. package/dist/core/client.d.ts +68 -0
  3. package/dist/core/client.js +71 -0
  4. package/dist/core/errors.d.ts +46 -0
  5. package/dist/core/errors.js +57 -0
  6. package/dist/core/helpers/autocomplete.d.ts +89 -0
  7. package/dist/core/helpers/autocomplete.js +186 -0
  8. package/dist/core/helpers/countries.d.ts +45 -0
  9. package/dist/core/helpers/countries.js +65 -0
  10. package/dist/core/helpers/currency.d.ts +26 -0
  11. package/dist/core/helpers/currency.js +72 -0
  12. package/dist/core/helpers/index.d.ts +5 -0
  13. package/dist/core/helpers/index.js +5 -0
  14. package/dist/core/helpers/iso3166.d.ts +28 -0
  15. package/dist/core/helpers/iso3166.js +84 -0
  16. package/dist/core/http.d.ts +27 -0
  17. package/dist/core/http.js +116 -0
  18. package/dist/core/index.d.ts +15 -0
  19. package/dist/core/index.js +13 -0
  20. package/dist/core/modules/catalog.d.ts +27 -0
  21. package/dist/core/modules/catalog.js +38 -0
  22. package/dist/core/modules/checkout.d.ts +268 -0
  23. package/dist/core/modules/checkout.js +470 -0
  24. package/dist/core/modules/customer.d.ts +33 -0
  25. package/dist/core/modules/customer.js +53 -0
  26. package/dist/core/modules/funnel.d.ts +38 -0
  27. package/dist/core/modules/funnel.js +138 -0
  28. package/dist/core/modules/offers.d.ts +137 -0
  29. package/dist/core/modules/offers.js +141 -0
  30. package/dist/core/modules/payment.d.ts +298 -0
  31. package/dist/core/modules/payment.js +701 -0
  32. package/dist/core/modules/rx.d.ts +162 -0
  33. package/dist/core/modules/rx.js +46 -0
  34. package/dist/core/types.d.ts +505 -0
  35. package/dist/core/types.js +5 -0
  36. package/dist/react/hooks/useCatalog.d.ts +25 -0
  37. package/dist/react/hooks/useCatalog.js +58 -0
  38. package/dist/react/hooks/useCheckout.d.ts +58 -0
  39. package/dist/react/hooks/useCheckout.js +177 -0
  40. package/dist/react/hooks/useCustomer.d.ts +28 -0
  41. package/dist/react/hooks/useCustomer.js +77 -0
  42. package/dist/react/hooks/useGoogleAutocomplete.d.ts +26 -0
  43. package/dist/react/hooks/useGoogleAutocomplete.js +70 -0
  44. package/dist/react/hooks/useISOData.d.ts +23 -0
  45. package/dist/react/hooks/useISOData.js +63 -0
  46. package/dist/react/hooks/useOffers.d.ts +134 -0
  47. package/dist/react/hooks/useOffers.js +171 -0
  48. package/dist/react/hooks/usePayment.d.ts +108 -0
  49. package/dist/react/hooks/usePayment.js +233 -0
  50. package/dist/react/hooks/useRx.d.ts +64 -0
  51. package/dist/react/hooks/useRx.js +145 -0
  52. package/dist/react/index.d.ts +22 -0
  53. package/dist/react/index.js +12 -0
  54. package/dist/react/internal/redirectGuard.d.ts +9 -0
  55. package/dist/react/internal/redirectGuard.js +25 -0
  56. package/dist/react/provider.d.ts +31 -0
  57. package/dist/react/provider.js +32 -0
  58. package/dist/stripe/StripeExpressButton.d.ts +30 -0
  59. package/dist/stripe/StripeExpressButton.js +32 -0
  60. package/dist/stripe/StripeExpressCheckout.d.ts +98 -0
  61. package/dist/stripe/StripeExpressCheckout.js +198 -0
  62. package/dist/stripe/index.d.ts +8 -0
  63. package/dist/stripe/index.js +15 -0
  64. package/dist/stripe/useStripeExpress.d.ts +54 -0
  65. package/dist/stripe/useStripeExpress.js +126 -0
  66. package/package.json +2 -3
@@ -0,0 +1,15 @@
1
+ export { HeadlessClient, createHeadlessClient } from './client.js';
2
+ export { CheckoutModule } from './modules/checkout.js';
3
+ export { PaymentModule } from './modules/payment.js';
4
+ export { OffersModule } from './modules/offers.js';
5
+ export { CustomerModule } from './modules/customer.js';
6
+ export { CatalogModule } from './modules/catalog.js';
7
+ export { FunnelModule } from './modules/funnel.js';
8
+ export { RxModule } from './modules/rx.js';
9
+ export type { RxCaseStatus, RxRequiredForProduct, RxStorefrontPatient, RxIntakeAnswer, RxClinicalQuestion, RxQuestionsForProduct, RxSubmitCaseInput, RxSubmitCaseResult, RxCaseSummary, } from './modules/rx.js';
10
+ export { HttpClient } from './http.js';
11
+ export { TagadaError, TagadaAuthError, TagadaValidationError, TagadaNotFoundError, TagadaRateLimitError, TagadaPaymentError, TagadaNetworkError, } from './errors.js';
12
+ export { GoogleAutocompleteCore, loadGoogleMapsScript, ISODataCore, AVAILABLE_LANGUAGES, CurrencyUtils, formatMoney, ensureGeoDataLoaded, getCountries, getStatesForCountry, isLanguageLoaded, } from './helpers/index.js';
13
+ export type { GooglePrediction, GooglePlaceDetails, ExtractedAddress, FormattedAddress, SupportedLanguage, ISOCountry, ISORegion, Country, State, Currency, } from './helpers/index.js';
14
+ export type { Environment, HeadlessConfig, HttpRequestOptions, LineItem, CheckoutSession, CheckoutLineItem, CheckoutTotals, CheckoutCustomer, Address, ShippingRate, PaymentMethodConfig, PaymentSetupConfig, ExpressMethod, ExpressMethods, StoreConfig, PayResult, PayOptions, PayDirectOptions, ProcessPaymentOptions, ProcessPaymentResult, CreateInstrumentOptions, PaymentInstrument, ThreedsSession, PaymentStatus, Offer, OfferLineItem, OfferPreview, OfferPreviewItem, OfferPayResult, Customer, Order, OrderItem, Subscription, CatalogProduct, CatalogVariant, CatalogPrice, CurrencyOption, FunnelNavigateInput, FunnelNavigateResult, } from './types.js';
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,13 @@
1
+ export { HeadlessClient, createHeadlessClient } from './client.js';
2
+ export { CheckoutModule } from './modules/checkout.js';
3
+ export { PaymentModule } from './modules/payment.js';
4
+ export { OffersModule } from './modules/offers.js';
5
+ export { CustomerModule } from './modules/customer.js';
6
+ export { CatalogModule } from './modules/catalog.js';
7
+ export { FunnelModule } from './modules/funnel.js';
8
+ export { RxModule } from './modules/rx.js';
9
+ export { HttpClient } from './http.js';
10
+ export { TagadaError, TagadaAuthError, TagadaValidationError, TagadaNotFoundError, TagadaRateLimitError, TagadaPaymentError, TagadaNetworkError, } from './errors.js';
11
+ // Helpers: Google Autocomplete, ISO countries/regions, currency formatting
12
+ export { GoogleAutocompleteCore, loadGoogleMapsScript, ISODataCore, AVAILABLE_LANGUAGES, CurrencyUtils, formatMoney, ensureGeoDataLoaded, getCountries, getStatesForCountry, isLanguageLoaded, } from './helpers/index.js';
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,27 @@
1
+ import type { HttpClient } from '../http.js';
2
+ import type { CatalogProduct } from '../types.js';
3
+ /**
4
+ * Fetches the product catalog for a store.
5
+ *
6
+ * Uses the public `/api/v1/products` endpoint (no auth required).
7
+ */
8
+ export declare class CatalogModule {
9
+ private readonly http;
10
+ private readonly storeId;
11
+ constructor(http: HttpClient, storeId: string);
12
+ /**
13
+ * List all active products for the store, including variants and prices.
14
+ *
15
+ * @param opts.productIds Optional filter to specific product IDs.
16
+ * @param opts.variantIds Optional filter to products containing these variant IDs.
17
+ */
18
+ getProducts(opts?: {
19
+ productIds?: string[];
20
+ variantIds?: string[];
21
+ }): Promise<CatalogProduct[]>;
22
+ /**
23
+ * Get a single product by ID.
24
+ */
25
+ getProduct(productId: string): Promise<CatalogProduct | null>;
26
+ }
27
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Fetches the product catalog for a store.
3
+ *
4
+ * Uses the public `/api/v1/products` endpoint (no auth required).
5
+ */
6
+ export class CatalogModule {
7
+ constructor(http, storeId) {
8
+ this.http = http;
9
+ this.storeId = storeId;
10
+ }
11
+ /**
12
+ * List all active products for the store, including variants and prices.
13
+ *
14
+ * @param opts.productIds Optional filter to specific product IDs.
15
+ * @param opts.variantIds Optional filter to products containing these variant IDs.
16
+ */
17
+ async getProducts(opts) {
18
+ const body = {
19
+ storeId: this.storeId,
20
+ includeVariants: true,
21
+ includePrices: true,
22
+ };
23
+ if (opts?.productIds?.length)
24
+ body.productIds = opts.productIds;
25
+ if (opts?.variantIds?.length)
26
+ body.variantIds = opts.variantIds;
27
+ const res = await this.http.post('/api/v1/products', body);
28
+ return res.items ?? [];
29
+ }
30
+ /**
31
+ * Get a single product by ID.
32
+ */
33
+ async getProduct(productId) {
34
+ const items = await this.getProducts({ productIds: [productId] });
35
+ return items[0] ?? null;
36
+ }
37
+ }
38
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1,268 @@
1
+ import type { HttpClient } from '../http.js';
2
+ import type { CheckoutSession, LineItem, ShippingRate, Address, CheckoutCustomer } from '../types.js';
3
+ /**
4
+ * Result returned by `updateCart()`. Mirrors the
5
+ * `POST /checkout-sessions/:id/line-items` payload (mutation stats, NOT
6
+ * a refreshed session). Call `loadSession()` to get an updated session.
7
+ */
8
+ export interface UpdateCartResult {
9
+ success: boolean;
10
+ /** Number of existing line items updated. */
11
+ updated: number;
12
+ /** Number of new line items created. */
13
+ created: number;
14
+ /** Total number of line items in the cart after the mutation. */
15
+ total: number;
16
+ }
17
+ /**
18
+ * Manages checkout sessions — load, update cart, apply promo codes, handle shipping.
19
+ *
20
+ * Works for both **shipped** and **digital** products:
21
+ *
22
+ * **Shipped products** (physical goods):
23
+ * ```
24
+ * updateCustomer(id, { email, firstName, lastName })
25
+ * updateAddress(id, { shippingAddress: { line1, city, ... } })
26
+ * getShippingRates(id)
27
+ * selectShippingRate(id, rateId)
28
+ * ```
29
+ *
30
+ * **Digital products** (no shipping needed):
31
+ * ```
32
+ * updateCustomer(id, { email, firstName, lastName })
33
+ * updateAddress(id, { billingAddress: { line1, city, country } })
34
+ * // Skip shipping rates — go straight to payment
35
+ * ```
36
+ */
37
+ export declare class CheckoutModule {
38
+ private readonly http;
39
+ private readonly storeId;
40
+ private readonly onTokenChange?;
41
+ private sessionToken;
42
+ private customerEmail;
43
+ private customerFirstName;
44
+ private customerLastName;
45
+ private customerPhone;
46
+ /**
47
+ * Last session returned by `loadSession()`. Cached so sibling modules
48
+ * (e.g. `FunnelModule`) can read the cart without re-fetching. Cleared
49
+ * intentionally on no events — call `loadSession()` again to refresh.
50
+ */
51
+ private _currentSession;
52
+ constructor(http: HttpClient, storeId: string, onTokenChange?: ((token: string) => void) | undefined);
53
+ /**
54
+ * Returns the most recently loaded `CheckoutSession`, if any.
55
+ *
56
+ * Populated by `loadSession()`. Returns `undefined` if the SDK has not
57
+ * loaded a session yet. Used by `funnel.navigate()` to source the cart.
58
+ */
59
+ getCurrentSession(): CheckoutSession | undefined;
60
+ /**
61
+ * Load an existing checkout session by its checkout token.
62
+ *
63
+ * @param checkoutToken The checkout token (from URL param `checkoutToken`).
64
+ * @param sessionToken The JWT session token (from URL param `token`). Required for auth.
65
+ * @param opts.currency Optional presentment currency override (e.g. 'EUR').
66
+ * Only applied when the session has no currency set yet (first load).
67
+ * Once set, currency is locked to the session and this param is ignored.
68
+ *
69
+ * Both `checkoutToken` and `sessionToken` come from the redirect URL returned by `createSession()`.
70
+ * Example URL: `/checkout?checkoutToken=abc123&token=eyJ...`
71
+ */
72
+ loadSession(checkoutToken: string, sessionToken?: string, opts?: {
73
+ currency?: string;
74
+ }): Promise<CheckoutSession>;
75
+ /**
76
+ * Create a new checkout session.
77
+ *
78
+ * Returns a `checkoutToken` and `sessionToken` (JWT) needed for all subsequent calls.
79
+ * Also returns a `checkoutUrl` (the full Tagada-hosted checkout URL, for reference).
80
+ */
81
+ createSession(opts: {
82
+ items: LineItem[];
83
+ currency?: string;
84
+ returnUrl?: string;
85
+ customerEmail?: string;
86
+ customerFirstName?: string;
87
+ customerLastName?: string;
88
+ }): Promise<{
89
+ checkoutUrl: string;
90
+ checkoutToken: string;
91
+ sessionToken: string;
92
+ customerId: string;
93
+ }>;
94
+ /**
95
+ * Create a session and produce a self-hosted redirect URL.
96
+ *
97
+ * Convenience wrapper around `createSession()`. Builds a URL of the
98
+ * form `${origin}${checkoutPath}?checkoutToken=...&sessionToken=...`
99
+ * that you can navigate to from a Cart page. The receiving page reads
100
+ * the params via {@link CheckoutModule.parseTokensFromUrl} and calls
101
+ * {@link CheckoutModule.loadSession}.
102
+ *
103
+ * For Tagada-hosted checkouts use the `checkoutUrl` returned by
104
+ * `createSession()` directly — this helper is for **self-hosted**
105
+ * checkout pages.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * const { url } = await tagada.checkout.createSessionUrl({
110
+ * items: [{ variantId, quantity: 1 }],
111
+ * checkoutPath: '/checkout',
112
+ * });
113
+ * window.location.href = url;
114
+ * ```
115
+ */
116
+ createSessionUrl(opts: {
117
+ items: LineItem[];
118
+ currency?: string;
119
+ returnUrl?: string;
120
+ customerEmail?: string;
121
+ customerFirstName?: string;
122
+ customerLastName?: string;
123
+ /** Path on the current origin for the self-hosted checkout. Default: `/checkout`. */
124
+ checkoutPath?: string;
125
+ /** Origin to use. Defaults to `window.location.origin`. */
126
+ origin?: string;
127
+ }): Promise<{
128
+ url: string;
129
+ checkoutUrl: string;
130
+ checkoutToken: string;
131
+ sessionToken: string;
132
+ customerId: string;
133
+ }>;
134
+ /**
135
+ * Read `checkoutToken` and session token from a URL.
136
+ *
137
+ * Recognizes both the SDK convention (`?sessionToken=`) and the
138
+ * Tagada-hosted convention (`?token=`), so the same checkout page
139
+ * works whether the user came from `createSessionUrl()` or directly
140
+ * from a Tagada-hosted redirect.
141
+ *
142
+ * Returns `null` if `checkoutToken` is missing.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * const tokens = CheckoutModule.parseTokensFromUrl();
147
+ * if (!tokens) {
148
+ * window.location.href = '/cart';
149
+ * return;
150
+ * }
151
+ * const session = await tagada.checkout.loadSession(
152
+ * tokens.checkoutToken,
153
+ * tokens.sessionToken,
154
+ * );
155
+ * ```
156
+ */
157
+ static parseTokensFromUrl(url?: string): {
158
+ checkoutToken: string;
159
+ sessionToken: string;
160
+ } | null;
161
+ /**
162
+ * Add or update cart items on an existing session (upsert by product).
163
+ *
164
+ * Sends each item as `lineItems` to `POST /checkout-sessions/:id/line-items`.
165
+ * The endpoint UPSERTs by product: it adds new products and updates the
166
+ * variant/quantity of products already in the cart, but it does NOT remove
167
+ * products omitted from `items`, and an empty array is a no-op (it does not
168
+ * clear the cart). Each `quantity` must be >= 1 — removal is not supported by
169
+ * this endpoint.
170
+ *
171
+ * Returns a server-side mutation summary (counts of created/updated rows).
172
+ * It does NOT return the updated `CheckoutSession` — the underlying endpoint
173
+ * never has and the previous typing was a lie that quietly assigned
174
+ * `{ success, updated, ... }` into a `CheckoutSession` slot in `useCheckout`.
175
+ *
176
+ * Call `loadSession()` after this if you need the refreshed session
177
+ * (the React `useCheckout` hook does this for you).
178
+ */
179
+ updateCart(sessionId: string, items: LineItem[]): Promise<UpdateCartResult>;
180
+ /**
181
+ * Update customer identity (email, name, phone).
182
+ *
183
+ * Call this before `updateAddress()` — the SDK remembers the values and
184
+ * includes them automatically when addresses are submitted.
185
+ *
186
+ * If you prefer a single call, use `updateCustomerAndAddress()` instead.
187
+ */
188
+ updateCustomer(sessionId: string, customer: Partial<CheckoutCustomer>): Promise<void>;
189
+ /**
190
+ * Update shipping and/or billing address on the session.
191
+ *
192
+ * Automatically includes customer name/phone stored from `updateCustomer()`.
193
+ * Uses the same atomic API call as the production checkout, so email,
194
+ * customer name, and addresses are all persisted together.
195
+ *
196
+ * **Shipped products**: pass `shippingAddress`. If `billingAddress` is omitted,
197
+ * the shipping address is automatically used as billing.
198
+ *
199
+ * **Digital products**: pass only `billingAddress` (no shipping needed).
200
+ *
201
+ * @example
202
+ * // Shipped product — billing = shipping automatically
203
+ * await checkout.updateAddress(sessionId, {
204
+ * shippingAddress: { line1: '10 Rue de la Paix', city: 'Paris', postalCode: '75002', country: 'FR' },
205
+ * });
206
+ *
207
+ * @example
208
+ * // Digital product — billing only
209
+ * await checkout.updateAddress(sessionId, {
210
+ * billingAddress: { country: 'FR' },
211
+ * });
212
+ */
213
+ updateAddress(sessionId: string, addresses: {
214
+ shippingAddress?: Address;
215
+ billingAddress?: Address;
216
+ }): Promise<void>;
217
+ /**
218
+ * Set customer info + addresses in one call (mirrors production checkout).
219
+ *
220
+ * Equivalent to calling `updateCustomer()` then `updateAddress()`, but
221
+ * in a single network request.
222
+ */
223
+ updateCustomerAndAddress(sessionId: string, data: {
224
+ customer: Partial<CheckoutCustomer>;
225
+ shippingAddress?: Address;
226
+ billingAddress?: Address;
227
+ }): Promise<void>;
228
+ /** Map an SDK Address to the API shape, injecting stored customer fields. */
229
+ private mapAddress;
230
+ /** Apply a promotion code to the session. */
231
+ applyPromoCode(sessionId: string, code: string): Promise<void>;
232
+ /** Remove a promotion from the session by promotion ID. */
233
+ removePromoCode(sessionId: string, promotionId?: string): Promise<void>;
234
+ /**
235
+ * Fetch available shipping rates for the session's address.
236
+ * Only relevant for **shipped products** — digital products can skip this step.
237
+ *
238
+ * Requires a shipping address to be set first via `updateAddress()`.
239
+ * Returns an empty array if no rates are configured or address is missing.
240
+ */
241
+ getShippingRates(sessionId: string): Promise<ShippingRate[]>;
242
+ /**
243
+ * Normalize the v1 rates payload (`shippingRateName`, `estimatedDeliveryTime`)
244
+ * to the SDK's `ShippingRate` shape (`name`, `estimatedDays`). Without
245
+ * this the consumer's UI shows blank rate names — the demo's "Delivery"
246
+ * radios were rendering only the price, no label.
247
+ */
248
+ private normalizeShippingRate;
249
+ /**
250
+ * Select a shipping rate for the session.
251
+ * Only relevant for **shipped products** — digital products can skip this step.
252
+ */
253
+ selectShippingRate(sessionId: string, rateId: string): Promise<void>;
254
+ /**
255
+ * Normalize the raw v2 API response into a cleaner CheckoutSession shape.
256
+ * The raw response has nested `checkoutSession` + `summary` -- we flatten it.
257
+ */
258
+ private normalizeSession;
259
+ /**
260
+ * Map the raw API address shape (`address1`, `address2`, `postal`) onto
261
+ * the SDK's `Address` shape (`line1`, `line2`, `postalCode`). Without
262
+ * this, `session.shippingAddress.line1` is silently undefined after a
263
+ * reload — the type was lying about the actual key names — which is
264
+ * what makes the demo lose form state on refresh.
265
+ */
266
+ private normalizeAddress;
267
+ }
268
+ //# sourceMappingURL=checkout.d.ts.map