@cimplify/sdk 0.16.2 → 0.17.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 (37) hide show
  1. package/dist/advanced.d.mts +2 -2
  2. package/dist/advanced.d.ts +2 -2
  3. package/dist/advanced.js +90 -2906
  4. package/dist/advanced.mjs +3 -2886
  5. package/dist/chunk-FLPI2VVJ.js +72 -0
  6. package/dist/chunk-G6KNFYJD.mjs +687 -0
  7. package/dist/chunk-GFKBH7R2.mjs +2759 -0
  8. package/dist/chunk-J65U5SED.js +714 -0
  9. package/dist/chunk-LM3CJ4L7.mjs +69 -0
  10. package/dist/chunk-OITG2SEN.js +692 -0
  11. package/dist/chunk-OVM5YWM5.mjs +674 -0
  12. package/dist/chunk-REPTMTQ4.js +2810 -0
  13. package/dist/chunk-S6TU55KP.js +170 -0
  14. package/dist/chunk-WDIMISRC.mjs +166 -0
  15. package/dist/{client-DTTtSSmQ.d.ts → client-BaolRdB4.d.mts} +3 -3
  16. package/dist/{client-Cb7r8u6t.d.mts → client-C59R79gx.d.ts} +3 -3
  17. package/dist/index.d.mts +4 -4
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +401 -4412
  20. package/dist/index.mjs +5 -4317
  21. package/dist/{payment-Dvd7nRmk.d.mts → payment-C6ULw3K-.d.mts} +1 -1
  22. package/dist/{payment-Dvd7nRmk.d.ts → payment-C6ULw3K-.d.ts} +1 -1
  23. package/dist/{price-DrfhwHpw.d.ts → price-Bd6JBV8W.d.ts} +1 -1
  24. package/dist/{price-BDZNXiLS.d.mts → price-CbR6DCt0.d.mts} +1 -1
  25. package/dist/react.d.mts +12 -7
  26. package/dist/react.d.ts +12 -7
  27. package/dist/react.js +377 -3961
  28. package/dist/react.mjs +326 -3913
  29. package/dist/utils.d.mts +2 -2
  30. package/dist/utils.d.ts +2 -2
  31. package/dist/utils.js +122 -720
  32. package/dist/utils.mjs +2 -694
  33. package/package.json +1 -1
  34. package/registry/add-on-selector.json +1 -1
  35. package/registry/checkout-page.json +1 -1
  36. package/registry/composite-selector.json +1 -1
  37. package/registry/product-grid.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,4317 +1,5 @@
1
- import { parsePhoneNumberFromString } from 'libphonenumber-js';
2
-
3
- // src/types/common.ts
4
- function money(value) {
5
- return typeof value === "string" ? parseFloat(value) || 0 : value;
6
- }
7
- function moneyFromNumber(value) {
8
- return value;
9
- }
10
- var ZERO = 0;
11
- var SUPPORTED_CURRENCY_CODES = /* @__PURE__ */ new Set([
12
- "USD",
13
- "EUR",
14
- "GBP",
15
- "JPY",
16
- "CNY",
17
- "CHF",
18
- "CAD",
19
- "AUD",
20
- "GHS",
21
- "NGN",
22
- "KES",
23
- "ZAR",
24
- "XOF",
25
- "XAF",
26
- "EGP",
27
- "TZS",
28
- "UGX",
29
- "RWF",
30
- "ETB",
31
- "ZMW",
32
- "BWP",
33
- "MUR",
34
- "NAD",
35
- "MWK",
36
- "AOA",
37
- "CDF",
38
- "GMD",
39
- "GNF",
40
- "LRD",
41
- "SLL",
42
- "MZN",
43
- "BIF",
44
- "INR",
45
- "BRL",
46
- "MXN",
47
- "KRW",
48
- "TRY",
49
- "THB",
50
- "MYR",
51
- "PHP",
52
- "IDR",
53
- "VND",
54
- "SGD",
55
- "HKD",
56
- "TWD",
57
- "AED",
58
- "SAR",
59
- "ILS"
60
- ]);
61
- function isSupportedCurrency(code) {
62
- return SUPPORTED_CURRENCY_CODES.has(code);
63
- }
64
- function currencyCode(value) {
65
- return value;
66
- }
67
- var ErrorCode = {
68
- UNKNOWN_ERROR: "UNKNOWN_ERROR",
69
- NETWORK_ERROR: "NETWORK_ERROR",
70
- TIMEOUT: "TIMEOUT",
71
- UNAUTHORIZED: "UNAUTHORIZED",
72
- FORBIDDEN: "FORBIDDEN",
73
- NOT_FOUND: "NOT_FOUND",
74
- VALIDATION_ERROR: "VALIDATION_ERROR",
75
- CART_EMPTY: "CART_EMPTY",
76
- CART_EXPIRED: "CART_EXPIRED",
77
- CART_NOT_FOUND: "CART_NOT_FOUND",
78
- ITEM_UNAVAILABLE: "ITEM_UNAVAILABLE",
79
- VARIANT_NOT_FOUND: "VARIANT_NOT_FOUND",
80
- VARIANT_OUT_OF_STOCK: "VARIANT_OUT_OF_STOCK",
81
- ADDON_REQUIRED: "ADDON_REQUIRED",
82
- ADDON_MAX_EXCEEDED: "ADDON_MAX_EXCEEDED",
83
- CHECKOUT_VALIDATION_FAILED: "CHECKOUT_VALIDATION_FAILED",
84
- DELIVERY_ADDRESS_REQUIRED: "DELIVERY_ADDRESS_REQUIRED",
85
- CUSTOMER_INFO_REQUIRED: "CUSTOMER_INFO_REQUIRED",
86
- QUOTE_NOT_FOUND: "QUOTE_NOT_FOUND",
87
- QUOTE_EXPIRED: "QUOTE_EXPIRED",
88
- QUOTE_CONSUMED: "QUOTE_CONSUMED",
89
- QUOTE_STORAGE_UNAVAILABLE: "QUOTE_STORAGE_UNAVAILABLE",
90
- PAYMENT_FAILED: "PAYMENT_FAILED",
91
- PAYMENT_CANCELLED: "PAYMENT_CANCELLED",
92
- INSUFFICIENT_FUNDS: "INSUFFICIENT_FUNDS",
93
- CARD_DECLINED: "CARD_DECLINED",
94
- INVALID_OTP: "INVALID_OTP",
95
- OTP_EXPIRED: "OTP_EXPIRED",
96
- AUTHORIZATION_FAILED: "AUTHORIZATION_FAILED",
97
- PAYMENT_ACTION_NOT_COMPLETED: "PAYMENT_ACTION_NOT_COMPLETED",
98
- SLOT_UNAVAILABLE: "SLOT_UNAVAILABLE",
99
- BOOKING_CONFLICT: "BOOKING_CONFLICT",
100
- SERVICE_NOT_FOUND: "SERVICE_NOT_FOUND",
101
- OUT_OF_STOCK: "OUT_OF_STOCK",
102
- INSUFFICIENT_QUANTITY: "INSUFFICIENT_QUANTITY"
103
- };
104
- var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
105
- function docsUrlForCode(code) {
106
- return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
107
- }
108
- var ERROR_SUGGESTIONS = {
109
- UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
110
- NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
111
- TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
112
- UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
113
- FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
114
- NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
115
- VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
116
- CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
117
- CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
118
- CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
119
- ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
120
- VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
121
- VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
122
- ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
123
- ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
124
- CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
125
- DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
126
- CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
127
- QUOTE_NOT_FOUND: "Quote could not be found. Refresh pricing and create a new quote before checkout.",
128
- QUOTE_EXPIRED: "Quote has expired. Re-fetch pricing to generate a new quote with a valid expiry window.",
129
- QUOTE_CONSUMED: "Quote has already been used. Request a fresh quote to prevent duplicate checkout attempts.",
130
- QUOTE_STORAGE_UNAVAILABLE: "Quote storage is temporarily unavailable. Retry shortly and avoid charging until quote fetch succeeds.",
131
- PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
132
- PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
133
- INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
134
- CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
135
- INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
136
- OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
137
- AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
138
- PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
139
- SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
140
- BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
141
- SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
142
- OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
143
- INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
144
- BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
145
- INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
146
- ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
147
- NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
148
- PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
149
- AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
150
- AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
151
- ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
152
- CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
153
- CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
154
- REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
155
- POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
156
- FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
157
- };
158
- var ERROR_HINTS = Object.fromEntries(
159
- Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
160
- code,
161
- {
162
- docs_url: docsUrlForCode(code),
163
- suggestion
164
- }
165
- ])
166
- );
167
- var CimplifyError = class extends Error {
168
- constructor(code, message, retryable = false, docs_url, suggestion) {
169
- super(message);
170
- this.code = code;
171
- this.retryable = retryable;
172
- this.docs_url = docs_url;
173
- this.suggestion = suggestion;
174
- this.name = "CimplifyError";
175
- }
176
- get userMessage() {
177
- return this.message;
178
- }
179
- };
180
- function isCimplifyError(error) {
181
- return error instanceof CimplifyError;
182
- }
183
- function getErrorHint(code) {
184
- return ERROR_HINTS[code];
185
- }
186
- function enrichError(error, options = {}) {
187
- const hint = getErrorHint(error.code);
188
- if (hint) {
189
- if (!error.docs_url) {
190
- error.docs_url = hint.docs_url;
191
- }
192
- if (!error.suggestion) {
193
- error.suggestion = hint.suggestion;
194
- }
195
- } else if (!error.docs_url) {
196
- error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
197
- }
198
- if (options.isTestMode && !error.message.includes("pk_test_")) {
199
- error.message = `${error.message}
200
-
201
- \u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
202
- }
203
- return error;
204
- }
205
- function isRetryableError(error) {
206
- if (isCimplifyError(error)) {
207
- return error.retryable;
208
- }
209
- if (error instanceof Error) {
210
- const msg = error.message.toLowerCase();
211
- return msg.includes("network") || msg.includes("timeout") || msg.includes("fetch");
212
- }
213
- return false;
214
- }
215
-
216
- // src/types/result.ts
217
- function ok(value) {
218
- return { ok: true, value };
219
- }
220
- function err(error) {
221
- return { ok: false, error };
222
- }
223
- function isOk(result) {
224
- return result.ok === true;
225
- }
226
- function isErr(result) {
227
- return result.ok === false;
228
- }
229
- function mapResult(result, fn) {
230
- return result.ok ? ok(fn(result.value)) : result;
231
- }
232
- function mapError(result, fn) {
233
- return result.ok ? result : err(fn(result.error));
234
- }
235
- function flatMap(result, fn) {
236
- return result.ok ? fn(result.value) : result;
237
- }
238
- function getOrElse(result, defaultFn) {
239
- return result.ok ? result.value : defaultFn();
240
- }
241
- function unwrap(result) {
242
- if (result.ok) {
243
- return result.value;
244
- }
245
- throw result.error;
246
- }
247
- function toNullable(result) {
248
- return result.ok ? result.value : void 0;
249
- }
250
- async function fromPromise(promise, mapError2) {
251
- try {
252
- const value = await promise;
253
- return ok(value);
254
- } catch (error) {
255
- return err(mapError2(error));
256
- }
257
- }
258
- function tryCatch(fn, mapError2) {
259
- try {
260
- return ok(fn());
261
- } catch (error) {
262
- return err(mapError2(error));
263
- }
264
- }
265
- function combine(results) {
266
- const values = [];
267
- for (const result of results) {
268
- if (!result.ok) {
269
- return result;
270
- }
271
- values.push(result.value);
272
- }
273
- return ok(values);
274
- }
275
- function combineObject(results) {
276
- const values = {};
277
- for (const [key, result] of Object.entries(results)) {
278
- if (!result.ok) {
279
- return result;
280
- }
281
- values[key] = result.value;
282
- }
283
- return ok(values);
284
- }
285
-
286
- // src/internal/safe.ts
287
- function toCimplifyError(error) {
288
- if (error instanceof CimplifyError) return enrichError(error);
289
- if (error instanceof Error) {
290
- return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
291
- }
292
- return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
293
- }
294
- async function safe(promise) {
295
- try {
296
- return ok(await promise);
297
- } catch (error) {
298
- return err(toCimplifyError(error));
299
- }
300
- }
301
-
302
- // src/catalogue.ts
303
- function withQuery(path, params) {
304
- const query2 = new URLSearchParams();
305
- for (const [key, value] of Object.entries(params)) {
306
- if (value === void 0) continue;
307
- query2.set(key, String(value));
308
- }
309
- const queryString = query2.toString();
310
- return queryString ? `${path}?${queryString}` : path;
311
- }
312
- function isRecord(value) {
313
- return typeof value === "object" && value !== null;
314
- }
315
- function readFinalPrice(value) {
316
- if (!isRecord(value)) return void 0;
317
- const finalPrice = value.final_price;
318
- if (typeof finalPrice === "string" || typeof finalPrice === "number") {
319
- return finalPrice;
320
- }
321
- return void 0;
322
- }
323
- function normalizeAddOnPayload(addOn) {
324
- if (!isRecord(addOn)) return addOn;
325
- const normalizedAddOn = { ...addOn };
326
- const options = normalizedAddOn["options"];
327
- if (!Array.isArray(options)) return normalizedAddOn;
328
- normalizedAddOn["options"] = options.map((option) => {
329
- if (!isRecord(option)) return option;
330
- const normalizedOption = { ...option };
331
- const optionPrice = normalizedOption["default_price"];
332
- if (optionPrice === void 0 || optionPrice === null || optionPrice === "") {
333
- normalizedOption["default_price"] = readFinalPrice(normalizedOption["default_price_info"]) || readFinalPrice(normalizedOption["price_info"]) || "0";
334
- }
335
- return normalizedOption;
336
- });
337
- return normalizedAddOn;
338
- }
339
- function normalizeCatalogueProductPayload(product) {
340
- const normalized = { ...product };
341
- const defaultPrice = normalized["default_price"];
342
- if (defaultPrice === void 0 || defaultPrice === null || defaultPrice === "") {
343
- const derivedDefaultPrice = readFinalPrice(normalized["default_price_info"]) || readFinalPrice(normalized["price_info"]) || (typeof normalized["final_price"] === "string" || typeof normalized["final_price"] === "number" ? normalized["final_price"] : void 0);
344
- normalized["default_price"] = derivedDefaultPrice ?? "0";
345
- }
346
- const addOns = normalized["add_ons"];
347
- if (Array.isArray(addOns)) {
348
- normalized["add_ons"] = addOns.map((addOn) => normalizeAddOnPayload(addOn));
349
- }
350
- return normalized;
351
- }
352
- function toFiniteNumber(value) {
353
- if (typeof value === "number" && Number.isFinite(value)) {
354
- return value;
355
- }
356
- if (typeof value === "string" && value.trim().length > 0) {
357
- const parsed = Number(value);
358
- if (Number.isFinite(parsed)) {
359
- return parsed;
360
- }
361
- }
362
- return void 0;
363
- }
364
- function normalizePagination(value) {
365
- if (!isRecord(value)) {
366
- return void 0;
367
- }
368
- const totalCount = toFiniteNumber(value.total_count);
369
- const currentPage = toFiniteNumber(value.current_page);
370
- const pageSize = toFiniteNumber(value.page_size);
371
- const totalPages = toFiniteNumber(value.total_pages);
372
- if (totalCount === void 0 || currentPage === void 0 || pageSize === void 0 || totalPages === void 0) {
373
- return void 0;
374
- }
375
- return {
376
- total_count: totalCount,
377
- current_page: currentPage,
378
- page_size: pageSize,
379
- total_pages: totalPages,
380
- has_more: value.has_more === true,
381
- next_cursor: typeof value.next_cursor === "string" ? value.next_cursor : void 0
382
- };
383
- }
384
- function normalizeCatalogueResult(payload) {
385
- if (Array.isArray(payload)) {
386
- return {
387
- items: payload.map((product) => normalizeCatalogueProductPayload(product)),
388
- is_complete: true
389
- };
390
- }
391
- if (!isRecord(payload)) {
392
- return {
393
- items: [],
394
- is_complete: true
395
- };
396
- }
397
- const rawItems = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
398
- return {
399
- items: rawItems.map((product) => normalizeCatalogueProductPayload(product)),
400
- is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
401
- total_available: toFiniteNumber(payload.total_available),
402
- pagination: normalizePagination(payload.pagination)
403
- };
404
- }
405
- function normalizeCatalogueSnapshot(payload) {
406
- if (Array.isArray(payload)) {
407
- return {
408
- categories: [],
409
- products: payload.map((product) => normalizeCatalogueProductPayload(product)),
410
- add_ons: [],
411
- is_complete: true
412
- };
413
- }
414
- if (!isRecord(payload)) {
415
- return {
416
- categories: [],
417
- products: [],
418
- add_ons: [],
419
- is_complete: true
420
- };
421
- }
422
- const rawProducts = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
423
- const rawCategories = Array.isArray(payload.categories) ? payload.categories : [];
424
- const rawAddOns = Array.isArray(payload.add_ons) ? payload.add_ons : [];
425
- return {
426
- categories: rawCategories,
427
- products: rawProducts.map((product) => normalizeCatalogueProductPayload(product)),
428
- add_ons: rawAddOns.map((addOn) => normalizeAddOnPayload(addOn)),
429
- is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
430
- total_available: toFiniteNumber(payload.total_available),
431
- pagination: normalizePagination(payload.pagination)
432
- };
433
- }
434
- var CatalogueQueries = class {
435
- constructor(client) {
436
- this.client = client;
437
- }
438
- async getCatalogue() {
439
- const result = await safe(this.client.get("/api/v1/catalogue"));
440
- if (!result.ok) return result;
441
- return ok(normalizeCatalogueSnapshot(result.value));
442
- }
443
- async getProducts(options) {
444
- const path = withQuery("/api/v1/catalogue/products", {
445
- category_id: options?.category,
446
- taxonomy_id: options?.taxonomy,
447
- search: options?.search,
448
- page: options?.page,
449
- tags: options?.tags?.join(","),
450
- featured: options?.featured,
451
- in_stock: options?.in_stock,
452
- min_price: options?.min_price,
453
- max_price: options?.max_price,
454
- sort_by: options?.sort_by,
455
- sort_order: options?.sort_order,
456
- limit: options?.limit,
457
- offset: options?.offset,
458
- cursor: options?.cursor
459
- });
460
- const result = await safe(this.client.get(path));
461
- if (!result.ok) return result;
462
- return ok(normalizeCatalogueResult(result.value));
463
- }
464
- async getProduct(id) {
465
- const encodedId = encodeURIComponent(id);
466
- const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
467
- if (!result.ok) return result;
468
- return ok(normalizeCatalogueProductPayload(result.value));
469
- }
470
- async getProductBySlug(slug) {
471
- const encodedSlug = encodeURIComponent(slug);
472
- const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
473
- if (!result.ok) return result;
474
- return ok(normalizeCatalogueProductPayload(result.value));
475
- }
476
- async getVariants(productId) {
477
- const encodedId = encodeURIComponent(productId);
478
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
479
- }
480
- async getVariantAxes(productId) {
481
- const encodedId = encodeURIComponent(productId);
482
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
483
- }
484
- async getVariantByAxisSelections(productId, selections) {
485
- const encodedId = encodeURIComponent(productId);
486
- return safe(
487
- this.client.post(
488
- `/api/v1/catalogue/products/${encodedId}/variants/find`,
489
- { axis_selections: selections }
490
- )
491
- );
492
- }
493
- async getVariantById(productId, variantId) {
494
- const encodedProductId = encodeURIComponent(productId);
495
- const encodedVariantId = encodeURIComponent(variantId);
496
- return safe(
497
- this.client.get(
498
- `/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
499
- )
500
- );
501
- }
502
- async getAddOns(productId) {
503
- const encodedId = encodeURIComponent(productId);
504
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
505
- }
506
- async getCategories() {
507
- return safe(this.client.get("/api/v1/catalogue/categories"));
508
- }
509
- async getCategory(id) {
510
- const encodedId = encodeURIComponent(id);
511
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
512
- }
513
- async getCategoryBySlug(slug) {
514
- const encodedSlug = encodeURIComponent(slug);
515
- return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
516
- }
517
- async getCategoryProducts(categoryId) {
518
- const encodedId = encodeURIComponent(categoryId);
519
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
520
- }
521
- async getCollections() {
522
- return safe(this.client.get("/api/v1/catalogue/collections"));
523
- }
524
- async getCollection(id) {
525
- const encodedId = encodeURIComponent(id);
526
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
527
- }
528
- async getCollectionBySlug(slug) {
529
- const encodedSlug = encodeURIComponent(slug);
530
- return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
531
- }
532
- async getCollectionProducts(collectionId) {
533
- const encodedId = encodeURIComponent(collectionId);
534
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
535
- }
536
- async searchCollections(query2, limit = 20) {
537
- const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
538
- return safe(this.client.get(path));
539
- }
540
- async getBundles() {
541
- return safe(this.client.get("/api/v1/catalogue/bundles"));
542
- }
543
- async searchBundles(query2, limit = 20) {
544
- const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
545
- return safe(this.client.get(path));
546
- }
547
- async getComposites(options) {
548
- const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
549
- return safe(this.client.get(path));
550
- }
551
- async calculateCompositePrice(compositeId, selections, locationId) {
552
- const encodedId = encodeURIComponent(compositeId);
553
- return safe(
554
- this.client.post(
555
- `/api/v1/catalogue/composites/${encodedId}/calculate-price`,
556
- {
557
- selections,
558
- location_id: locationId
559
- }
560
- )
561
- );
562
- }
563
- async fetchQuote(input) {
564
- return safe(this.client.post("/api/v1/catalogue/quotes", input));
565
- }
566
- async getQuote(quoteId) {
567
- const encodedQuoteId = encodeURIComponent(quoteId);
568
- return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
569
- }
570
- async refreshQuote(input) {
571
- const encodedQuoteId = encodeURIComponent(input.quote_id);
572
- return safe(
573
- this.client.post(
574
- `/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
575
- input
576
- )
577
- );
578
- }
579
- async getTaxonomies(parentId) {
580
- const path = withQuery("/api/v1/catalogue/taxonomies", { parent_id: parentId });
581
- return safe(this.client.get(path));
582
- }
583
- async getTaxonomy(id) {
584
- const encodedId = encodeURIComponent(id);
585
- return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}`));
586
- }
587
- async getTaxonomyPath(id) {
588
- const encodedId = encodeURIComponent(id);
589
- return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}/path`));
590
- }
591
- async searchTaxonomies(query2, limit) {
592
- const path = withQuery("/api/v1/catalogue/taxonomies/search", { q: query2, limit });
593
- return safe(this.client.get(path));
594
- }
595
- async getProductSchedules(productId) {
596
- const encodedId = encodeURIComponent(productId);
597
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/schedules`));
598
- }
599
- async checkProductAvailableNow(productId, locationId) {
600
- const encodedId = encodeURIComponent(productId);
601
- const path = withQuery(`/api/v1/catalogue/products/${encodedId}/available-now`, { location_id: locationId });
602
- return safe(this.client.get(path));
603
- }
604
- async getDeals(locationId) {
605
- const path = withQuery("/api/v1/catalogue/deals", { location_id: locationId });
606
- return safe(this.client.get(path));
607
- }
608
- async getProductsOnSale() {
609
- return safe(this.client.get("/api/v1/catalogue/deals/on-sale"));
610
- }
611
- async getProductDeals(productId) {
612
- const encodedId = encodeURIComponent(productId);
613
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/deals`));
614
- }
615
- async getCategoryDeals(categoryId) {
616
- const encodedId = encodeURIComponent(categoryId);
617
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/deals`));
618
- }
619
- async getCollectionDeals(collectionId) {
620
- const encodedId = encodeURIComponent(collectionId);
621
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/deals`));
622
- }
623
- async validateDiscountCode(code, orderSubtotal, locationId) {
624
- return safe(
625
- this.client.post("/api/v1/catalogue/deals/validate", {
626
- discount_code: code,
627
- order_subtotal: orderSubtotal,
628
- location_id: locationId
629
- })
630
- );
631
- }
632
- async search(query2, options) {
633
- const result = await this.getProducts({
634
- search: query2,
635
- category: options?.category,
636
- limit: options?.limit ?? 20
637
- });
638
- if (!result.ok) return result;
639
- return ok(result.value.items);
640
- }
641
- async searchProducts(query2, options) {
642
- return this.search(query2, options);
643
- }
644
- async getMenu(options) {
645
- const path = withQuery("/api/v1/catalogue/menu", {
646
- category_id: options?.category,
647
- limit: options?.limit
648
- });
649
- return safe(this.client.get(path));
650
- }
651
- async getMenuCategory(categoryId) {
652
- const encodedId = encodeURIComponent(categoryId);
653
- return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
654
- }
655
- async getMenuItem(itemId) {
656
- const encodedId = encodeURIComponent(itemId);
657
- return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
658
- }
659
- async getTags(options) {
660
- const path = withQuery("/api/v1/catalogue/tags", {
661
- tag_group: options?.tag_group,
662
- search: options?.search,
663
- min_usage: options?.min_usage,
664
- limit: options?.limit,
665
- offset: options?.offset
666
- });
667
- return safe(this.client.get(path));
668
- }
669
- };
670
-
671
- // src/cart.ts
672
- function isUICartResponse(value) {
673
- return "cart" in value;
674
- }
675
- function unwrapEnrichedCart(value) {
676
- return isUICartResponse(value) ? value.cart : value;
677
- }
678
- var CartOperations = class {
679
- constructor(client) {
680
- this.client = client;
681
- }
682
- async get() {
683
- const result = await safe(this.client.get("/api/v1/cart"));
684
- if (!result.ok) return result;
685
- return ok(unwrapEnrichedCart(result.value));
686
- }
687
- async getRaw() {
688
- return safe(this.client.get("/api/v1/cart"));
689
- }
690
- async getItems() {
691
- return safe(this.client.get("/api/v1/cart/items"));
692
- }
693
- async getCount() {
694
- return safe(this.client.get("/api/v1/cart/count"));
695
- }
696
- async getTotal() {
697
- return safe(this.client.get("/api/v1/cart/total"));
698
- }
699
- async getSummary() {
700
- const cartResult = await this.get();
701
- if (!cartResult.ok) return cartResult;
702
- const cart = cartResult.value;
703
- return ok({
704
- item_count: cart.items.length,
705
- total_items: cart.items.reduce((sum, item) => sum + item.quantity, 0),
706
- subtotal: cart.pricing.subtotal,
707
- discount_amount: cart.pricing.total_discounts,
708
- tax_amount: cart.pricing.tax_amount,
709
- total: cart.pricing.total_price,
710
- currency: cart.pricing.currency
711
- });
712
- }
713
- async addItem(input) {
714
- return safe(this.client.post("/api/v1/cart/items", input));
715
- }
716
- async updateItem(cartItemId, updates) {
717
- if (typeof updates.quantity === "number") {
718
- return this.updateQuantity(cartItemId, updates.quantity);
719
- }
720
- const encodedId = encodeURIComponent(cartItemId);
721
- return safe(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
722
- }
723
- async updateQuantity(cartItemId, quantity) {
724
- const encodedId = encodeURIComponent(cartItemId);
725
- return safe(
726
- this.client.patch(`/api/v1/cart/items/${encodedId}`, {
727
- quantity
728
- })
729
- );
730
- }
731
- async removeItem(cartItemId) {
732
- const encodedId = encodeURIComponent(cartItemId);
733
- return safe(this.client.delete(`/api/v1/cart/items/${encodedId}`));
734
- }
735
- async clear() {
736
- return safe(this.client.delete("/api/v1/cart"));
737
- }
738
- async applyCoupon(code) {
739
- return safe(
740
- this.client.post("/api/v1/cart/coupons", {
741
- coupon_code: code
742
- })
743
- );
744
- }
745
- async removeCoupon() {
746
- return safe(this.client.delete("/api/v1/cart/coupons/current"));
747
- }
748
- async isEmpty() {
749
- const countResult = await this.getCount();
750
- if (!countResult.ok) return countResult;
751
- return ok(countResult.value === 0);
752
- }
753
- async hasItem(productId, variantId) {
754
- const itemsResult = await this.getItems();
755
- if (!itemsResult.ok) return itemsResult;
756
- const found = itemsResult.value.some((item) => {
757
- const matchesProduct = item.item_id === productId;
758
- if (!variantId) return matchesProduct;
759
- const config = item.configuration;
760
- if ("variant" in config && config.variant) {
761
- return matchesProduct && config.variant.variant_id === variantId;
762
- }
763
- return matchesProduct;
764
- });
765
- return ok(found);
766
- }
767
- async findItem(productId, variantId) {
768
- const itemsResult = await this.getItems();
769
- if (!itemsResult.ok) return itemsResult;
770
- const found = itemsResult.value.find((item) => {
771
- const matchesProduct = item.item_id === productId;
772
- if (!variantId) return matchesProduct;
773
- const config = item.configuration;
774
- if ("variant" in config && config.variant) {
775
- return matchesProduct && config.variant.variant_id === variantId;
776
- }
777
- return matchesProduct;
778
- });
779
- return ok(found);
780
- }
781
- };
782
-
783
- // src/constants.ts
784
- var CHECKOUT_MODE = {
785
- LINK: "link",
786
- GUEST: "guest"
787
- };
788
- var ORDER_TYPE = {
789
- DELIVERY: "delivery",
790
- PICKUP: "pickup",
791
- DINE_IN: "dine-in",
792
- WALK_IN: "walk-in"
793
- };
794
- var PAYMENT_METHOD = {
795
- MOBILE_MONEY: "mobile_money",
796
- CARD: "card"
797
- };
798
- var CHECKOUT_STEP = {
799
- AUTHENTICATION: "authentication",
800
- ORDER_DETAILS: "order_details",
801
- PAYMENT_METHOD: "payment_method",
802
- PAYMENT: "payment",
803
- CONFIRMATION: "confirmation"
804
- };
805
- var PAYMENT_STATE = {
806
- INITIAL: "initial",
807
- PREPARING: "preparing",
808
- PROCESSING: "processing",
809
- VERIFYING: "verifying",
810
- AWAITING_AUTHORIZATION: "awaiting_authorization",
811
- SUCCESS: "success",
812
- ERROR: "error",
813
- TIMEOUT: "timeout"
814
- };
815
- var PICKUP_TIME_TYPE = {
816
- ASAP: "asap",
817
- SCHEDULED: "scheduled"
818
- };
819
- var MOBILE_MONEY_PROVIDER = {
820
- MTN: "mtn",
821
- VODAFONE: "vodafone",
822
- AIRTEL: "airtel"
823
- };
824
- var AUTHORIZATION_TYPE = {
825
- OTP: "otp",
826
- PIN: "pin",
827
- PHONE: "phone",
828
- BIRTHDAY: "birthday",
829
- ADDRESS: "address"
830
- };
831
- var DEVICE_TYPE = {
832
- MOBILE: "mobile",
833
- DESKTOP: "desktop",
834
- TABLET: "tablet"
835
- };
836
- var CONTACT_TYPE = {
837
- PHONE: "phone",
838
- EMAIL: "email"
839
- };
840
- var LINK_QUERY = {
841
- DATA: "link.data",
842
- ADDRESSES: "link.addresses",
843
- MOBILE_MONEY: "link.mobile_money",
844
- PREFERENCES: "link.preferences",
845
- SESSIONS: "link.sessions"
846
- };
847
- var LINK_MUTATION = {
848
- CHECK_STATUS: "link.check_status",
849
- ENROLL: "link.enroll",
850
- ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
851
- UPDATE_PREFERENCES: "link.update_preferences",
852
- CREATE_ADDRESS: "link.create_address",
853
- UPDATE_ADDRESS: "link.update_address",
854
- DELETE_ADDRESS: "link.delete_address",
855
- SET_DEFAULT_ADDRESS: "link.set_default_address",
856
- TRACK_ADDRESS_USAGE: "link.track_address_usage",
857
- CREATE_MOBILE_MONEY: "link.create_mobile_money",
858
- DELETE_MOBILE_MONEY: "link.delete_mobile_money",
859
- SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
860
- TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
861
- VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
862
- REVOKE_SESSION: "link.revoke_session",
863
- REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
864
- };
865
- var AUTH_MUTATION = {
866
- REQUEST_OTP: "auth.request_otp",
867
- VERIFY_OTP: "auth.verify_otp"
868
- };
869
- var CHECKOUT_MUTATION = {
870
- PROCESS: "checkout.process"
871
- };
872
- var PAYMENT_MUTATION = {
873
- SUBMIT_AUTHORIZATION: "payment.submit_authorization",
874
- CHECK_STATUS: "order.poll_payment_status"
875
- };
876
- var ORDER_MUTATION = {
877
- UPDATE_CUSTOMER: "order.update_order_customer"
878
- };
879
- var DEFAULT_CURRENCY = "GHS";
880
- var DEFAULT_COUNTRY = "GHA";
881
-
882
- // src/utils/price.ts
883
- var CURRENCY_SYMBOLS = {
884
- USD: "$",
885
- EUR: "\u20AC",
886
- GBP: "\xA3",
887
- JPY: "\xA5",
888
- CNY: "\xA5",
889
- CHF: "CHF",
890
- CAD: "C$",
891
- AUD: "A$",
892
- NZD: "NZ$",
893
- HKD: "HK$",
894
- SGD: "S$",
895
- INR: "\u20B9",
896
- BRL: "R$",
897
- MXN: "MX$",
898
- KRW: "\u20A9",
899
- RUB: "\u20BD",
900
- TRY: "\u20BA",
901
- THB: "\u0E3F",
902
- PLN: "z\u0142",
903
- SEK: "kr",
904
- NOK: "kr",
905
- DKK: "kr",
906
- CZK: "K\u010D",
907
- HUF: "Ft",
908
- ILS: "\u20AA",
909
- AED: "\u062F.\u0625",
910
- SAR: "\uFDFC",
911
- MYR: "RM",
912
- PHP: "\u20B1",
913
- IDR: "Rp",
914
- VND: "\u20AB",
915
- TWD: "NT$",
916
- GHS: "GH\u20B5",
917
- NGN: "\u20A6",
918
- KES: "KSh",
919
- ZAR: "R",
920
- XOF: "CFA",
921
- XAF: "FCFA",
922
- EGP: "E\xA3",
923
- MAD: "MAD",
924
- TZS: "TSh",
925
- UGX: "USh",
926
- RWF: "FRw",
927
- ETB: "Br",
928
- ZMW: "ZK",
929
- BWP: "P",
930
- MUR: "\u20A8",
931
- SCR: "\u20A8",
932
- NAD: "N$",
933
- SZL: "E",
934
- LSL: "L",
935
- MWK: "MK",
936
- AOA: "Kz",
937
- CDF: "FC",
938
- GMD: "D",
939
- GNF: "FG",
940
- LRD: "L$",
941
- SLL: "Le",
942
- MZN: "MT",
943
- SDG: "SDG",
944
- SSP: "SSP",
945
- SOS: "Sh.So.",
946
- DJF: "Fdj",
947
- ERN: "Nfk",
948
- CVE: "$",
949
- STN: "Db",
950
- KMF: "CF",
951
- BIF: "FBu"
952
- };
953
- function getCurrencySymbol(currencyCode3) {
954
- return CURRENCY_SYMBOLS[currencyCode3.toUpperCase()] || currencyCode3;
955
- }
956
- function formatNumberCompact(value, decimals = 1) {
957
- const absValue = Math.abs(value);
958
- const sign = value < 0 ? "-" : "";
959
- if (absValue >= 1e9) {
960
- return `${sign}${(absValue / 1e9).toFixed(decimals)}B`;
961
- }
962
- if (absValue >= 1e6) {
963
- return `${sign}${(absValue / 1e6).toFixed(decimals)}M`;
964
- }
965
- if (absValue >= 1e3) {
966
- return `${sign}${(absValue / 1e3).toFixed(decimals)}K`;
967
- }
968
- return `${sign}${absValue.toFixed(decimals)}`;
969
- }
970
- function formatPrice(amount, currency = "GHS", locale = "en-US") {
971
- const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
972
- if (isNaN(numAmount)) {
973
- return `${getCurrencySymbol(currency)}0.00`;
974
- }
975
- try {
976
- return new Intl.NumberFormat(locale, {
977
- style: "currency",
978
- currency: currency.toUpperCase(),
979
- minimumFractionDigits: 2,
980
- maximumFractionDigits: 2
981
- }).format(numAmount);
982
- } catch {
983
- return `${getCurrencySymbol(currency)}${numAmount.toFixed(2)}`;
984
- }
985
- }
986
- function formatPriceAdjustment(amount, currency = "GHS", locale = "en-US") {
987
- const formatted = formatPrice(Math.abs(amount), currency, locale);
988
- if (amount > 0) {
989
- return `+${formatted}`;
990
- } else if (amount < 0) {
991
- return `-${formatted}`;
992
- }
993
- return formatted;
994
- }
995
- function formatPriceCompact(amount, currency = "GHS", decimals = 1) {
996
- const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
997
- if (isNaN(numAmount)) {
998
- return `${getCurrencySymbol(currency)}0`;
999
- }
1000
- const symbol = getCurrencySymbol(currency);
1001
- if (Math.abs(numAmount) < 1e3) {
1002
- return `${symbol}${numAmount.toFixed(2)}`;
1003
- }
1004
- return `${symbol}${formatNumberCompact(numAmount, decimals)}`;
1005
- }
1006
- function formatMoney(amount, currency = "GHS") {
1007
- const symbol = getCurrencySymbol(currency);
1008
- const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
1009
- if (isNaN(numAmount)) {
1010
- return `${symbol}0.00`;
1011
- }
1012
- return `${symbol}${numAmount.toFixed(2)}`;
1013
- }
1014
- function parsePrice(value) {
1015
- if (value === void 0 || value === null) {
1016
- return 0;
1017
- }
1018
- if (typeof value === "number") {
1019
- return isNaN(value) ? 0 : value;
1020
- }
1021
- const cleaned = value.replace(/[^\d.-]/g, "");
1022
- const parsed = parseFloat(cleaned);
1023
- return isNaN(parsed) ? 0 : parsed;
1024
- }
1025
- function hasTaxInfo(priceInfo) {
1026
- return priceInfo.tax_info !== void 0 && priceInfo.tax_info !== null;
1027
- }
1028
- function getTaxAmount(priceInfo) {
1029
- return parsePrice(priceInfo.tax_info?.tax_amount);
1030
- }
1031
- function isTaxInclusive(priceInfo) {
1032
- return priceInfo.tax_info?.is_inclusive === true;
1033
- }
1034
- function formatPriceWithTax(priceInfo, currency = "GHS") {
1035
- const finalPrice = formatPrice(priceInfo.final_price, currency);
1036
- if (!hasTaxInfo(priceInfo)) {
1037
- return finalPrice;
1038
- }
1039
- if (isTaxInclusive(priceInfo)) {
1040
- return `${finalPrice} (incl. tax)`;
1041
- }
1042
- return `${finalPrice} + ${formatPrice(getTaxAmount(priceInfo), currency)} tax`;
1043
- }
1044
- function getDisplayPrice(product) {
1045
- if (product.price_info) {
1046
- return parsePrice(product.price_info.final_price);
1047
- }
1048
- if (product.final_price !== void 0 && product.final_price !== null) {
1049
- return parsePrice(product.final_price);
1050
- }
1051
- if (product.default_price !== void 0 && product.default_price !== null) {
1052
- return parsePrice(product.default_price);
1053
- }
1054
- return 0;
1055
- }
1056
- function getBasePrice(product) {
1057
- if (product.price_info) {
1058
- return parsePrice(product.price_info.base_price);
1059
- }
1060
- if (product.base_price !== void 0 && product.base_price !== null) {
1061
- return parsePrice(product.base_price);
1062
- }
1063
- if (product.default_price !== void 0 && product.default_price !== null) {
1064
- return parsePrice(product.default_price);
1065
- }
1066
- return 0;
1067
- }
1068
- function isOnSale(product) {
1069
- const basePrice = getBasePrice(product);
1070
- const finalPrice = getDisplayPrice(product);
1071
- return basePrice > finalPrice && basePrice > 0;
1072
- }
1073
- function getDiscountPercentage(product) {
1074
- const basePrice = getBasePrice(product);
1075
- const finalPrice = getDisplayPrice(product);
1076
- if (basePrice > finalPrice && basePrice > 0) {
1077
- return Math.round((basePrice - finalPrice) / basePrice * 100);
1078
- }
1079
- return 0;
1080
- }
1081
- function getMarkupPercentage(product) {
1082
- const basePrice = getBasePrice(product);
1083
- const finalPrice = getDisplayPrice(product);
1084
- if (finalPrice > basePrice && basePrice > 0) {
1085
- return Math.round((finalPrice - basePrice) / basePrice * 100);
1086
- }
1087
- return 0;
1088
- }
1089
- function getProductCurrency(product) {
1090
- if (product.price_info?.currency) {
1091
- return product.price_info.currency;
1092
- }
1093
- if (product.currency) {
1094
- return product.currency;
1095
- }
1096
- return "GHS";
1097
- }
1098
- function formatProductPrice(product, locale = "en-US") {
1099
- const price = getDisplayPrice(product);
1100
- const currency = getProductCurrency(product);
1101
- return formatPrice(price, currency, locale);
1102
- }
1103
-
1104
- // src/utils/payment.ts
1105
- function categorizePaymentError(error, errorCode) {
1106
- let message = "An unexpected error occurred during payment processing. Please try again or contact support.";
1107
- let recoverable = true;
1108
- let code = errorCode || "PAYMENT_ERROR";
1109
- const technical = error.stack;
1110
- const errorMessage = error.message?.toLowerCase() || "";
1111
- if (errorCode === "INSUFFICIENT_FUNDS" || errorMessage.includes("insufficient") || errorMessage.includes("funds")) {
1112
- code = "INSUFFICIENT_FUNDS";
1113
- message = "Your payment method has insufficient funds. Please try another payment method.";
1114
- } else if (errorCode === "CARD_DECLINED" || errorMessage.includes("declined")) {
1115
- code = "CARD_DECLINED";
1116
- message = "Your card was declined. Please try another card or payment method.";
1117
- } else if (errorMessage.includes("cancelled") || errorMessage.includes("canceled") || errorCode === "PAYMENT_CANCELLED") {
1118
- code = "PAYMENT_CANCELLED";
1119
- message = "Payment was cancelled. You can try again when ready.";
1120
- } else if (errorMessage.includes("network") || errorMessage.includes("connection") || errorCode === "NETWORK_ERROR") {
1121
- code = "NETWORK_ERROR";
1122
- message = "Network connection issue. Please check your internet connection and try again.";
1123
- } else if (errorMessage.includes("timeout") || errorCode === "TIMEOUT") {
1124
- code = "TIMEOUT";
1125
- message = "Payment processing timed out. Please try again.";
1126
- } else if (errorCode === "PAYMENT_ACTION_NOT_COMPLETED") {
1127
- code = "PAYMENT_ACTION_NOT_COMPLETED";
1128
- message = "Payment action was not completed. Please try again.";
1129
- } else if (errorCode === "AUTHORIZATION_FAILED") {
1130
- code = "AUTHORIZATION_FAILED";
1131
- message = "Authorization failed. Please check your code and try again.";
1132
- } else if (errorCode === "INVALID_OTP") {
1133
- code = "INVALID_OTP";
1134
- message = "Invalid verification code. Please check and try again.";
1135
- }
1136
- return { code, message, recoverable, technical };
1137
- }
1138
- function isQuickPaymentResponse(response) {
1139
- return response !== null && typeof response === "object" && "payment" in response && typeof response.payment === "object";
1140
- }
1141
- function isWebPaymentResponse(response) {
1142
- return response !== null && typeof response === "object" && "transaction" in response && typeof response.transaction === "object";
1143
- }
1144
- function normalizePaymentResponse(response) {
1145
- if (!response) {
1146
- return {
1147
- method: "unknown",
1148
- provider: "unknown",
1149
- requires_action: false,
1150
- metadata: {}
1151
- };
1152
- }
1153
- if (isQuickPaymentResponse(response)) {
1154
- return {
1155
- method: response.payment.type?.toLowerCase() || "unknown",
1156
- provider: response.payment.provider?.toLowerCase() || "unknown",
1157
- requires_action: !!response.payment.redirect_url || !!response.payment.access_code,
1158
- public_key: response.payment.public_key,
1159
- client_secret: response.payment.access_code,
1160
- access_code: response.payment.access_code,
1161
- redirect_url: response.payment.redirect_url,
1162
- transaction_id: response.payment.reference,
1163
- order_id: response.order_id,
1164
- reference: response.payment.reference,
1165
- instructions: response.payment.instructions,
1166
- metadata: response.payment.metadata
1167
- };
1168
- }
1169
- if (isWebPaymentResponse(response)) {
1170
- const authType = response.authorization_type?.toLowerCase();
1171
- const validStringAuthTypes = ["otp", "pin", "phone", "birthday"];
1172
- const safeAuthType = authType && validStringAuthTypes.includes(authType) ? authType : void 0;
1173
- return {
1174
- provider: response.transaction.provider_type?.toLowerCase() || "unknown",
1175
- requires_action: response.requires_action || false,
1176
- public_key: response.public_key,
1177
- client_secret: response.client_secret,
1178
- redirect_url: response.authorization_url,
1179
- transaction_id: response.transaction.id,
1180
- order_id: response.transaction.order_id,
1181
- reference: response.transaction.provider_reference,
1182
- metadata: response.transaction.metadata,
1183
- method: response.transaction.payment_method?.toLowerCase() || "unknown",
1184
- instructions: response.display_text,
1185
- display_text: response.display_text,
1186
- requires_authorization: response.requires_authorization,
1187
- authorization_type: safeAuthType,
1188
- provider_payment_id: response.provider_payment_id || response.transaction.provider_reference
1189
- };
1190
- }
1191
- return {
1192
- method: "unknown",
1193
- provider: "unknown",
1194
- requires_action: false,
1195
- metadata: {}
1196
- };
1197
- }
1198
- var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
1199
- "success",
1200
- "succeeded",
1201
- "paid",
1202
- "captured",
1203
- "completed",
1204
- "authorized"
1205
- ]);
1206
- var PAYMENT_FAILURE_STATUSES = /* @__PURE__ */ new Set([
1207
- "failed",
1208
- "declined",
1209
- "cancelled",
1210
- "voided",
1211
- "error",
1212
- "abandoned"
1213
- ]);
1214
- var PAYMENT_REQUIRES_ACTION_STATUSES = /* @__PURE__ */ new Set([
1215
- "requires_action",
1216
- "requires_payment_method",
1217
- "requires_capture"
1218
- ]);
1219
- var PAYMENT_STATUS_ALIAS_MAP = {
1220
- ok: "success",
1221
- done: "success",
1222
- paid: "paid",
1223
- paid_in_full: "paid",
1224
- paid_successfully: "paid",
1225
- succeeded: "success",
1226
- captured: "captured",
1227
- completed: "completed",
1228
- pending_confirmation: "pending_confirmation",
1229
- requires_authorization: "requires_action",
1230
- requires_action: "requires_action",
1231
- requires_payment_method: "requires_payment_method",
1232
- requires_capture: "requires_capture",
1233
- partially_paid: "partially_paid",
1234
- partially_refunded: "partially_refunded",
1235
- card_declined: "declined",
1236
- canceled: "cancelled",
1237
- authorized: "authorized",
1238
- cancelled: "cancelled",
1239
- unresolved: "pending"
1240
- };
1241
- var KNOWN_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
1242
- "initialized",
1243
- "pending",
1244
- "processing",
1245
- "authorized",
1246
- "captured",
1247
- "failed",
1248
- "cancelled",
1249
- "refunded",
1250
- "unknown",
1251
- "voided",
1252
- "requires_action",
1253
- "abandoned",
1254
- "reversed",
1255
- "disputed",
1256
- "refund_pending",
1257
- "created",
1258
- "pending_confirmation",
1259
- "success",
1260
- "succeeded",
1261
- "declined",
1262
- "partially_refunded",
1263
- "partially_paid",
1264
- "paid",
1265
- "unpaid",
1266
- "requires_payment_method",
1267
- "requires_capture",
1268
- "completed",
1269
- "error"
1270
- ]);
1271
- function normalizeStatusToken(status) {
1272
- return status?.trim().toLowerCase().replace(/[\s-]+/g, "_") ?? "";
1273
- }
1274
- function normalizePaymentStatusValue(status) {
1275
- const normalized = normalizeStatusToken(status);
1276
- if (Object.prototype.hasOwnProperty.call(PAYMENT_STATUS_ALIAS_MAP, normalized)) {
1277
- return PAYMENT_STATUS_ALIAS_MAP[normalized];
1278
- }
1279
- return KNOWN_PAYMENT_STATUSES.has(normalized) ? normalized : "unknown";
1280
- }
1281
- function isPaymentStatusSuccess(status) {
1282
- const normalizedStatus = normalizePaymentStatusValue(status);
1283
- return PAYMENT_SUCCESS_STATUSES.has(normalizedStatus);
1284
- }
1285
- function isPaymentStatusFailure(status) {
1286
- const normalizedStatus = normalizePaymentStatusValue(status);
1287
- return PAYMENT_FAILURE_STATUSES.has(normalizedStatus);
1288
- }
1289
- function isPaymentStatusRequiresAction(status) {
1290
- const normalizedStatus = normalizePaymentStatusValue(status);
1291
- return PAYMENT_REQUIRES_ACTION_STATUSES.has(normalizedStatus);
1292
- }
1293
- function normalizeStatusResponse(response) {
1294
- if (!response || typeof response !== "object") {
1295
- return {
1296
- status: "pending",
1297
- paid: false,
1298
- amount: moneyFromNumber(0),
1299
- currency: "",
1300
- message: "No status available"
1301
- };
1302
- }
1303
- const res = response;
1304
- const normalizedStatus = normalizePaymentStatusValue(res.status ?? void 0);
1305
- const normalizedAmount = typeof res.amount === "string" ? money(res.amount) : typeof res.amount === "number" && Number.isFinite(res.amount) ? moneyFromNumber(res.amount) : moneyFromNumber(0);
1306
- const normalizedCurrency = typeof res.currency === "string" && res.currency.trim().length > 0 ? res.currency : "";
1307
- const paidValue = res.paid === true;
1308
- const derivedPaid = paidValue || [
1309
- "success",
1310
- "succeeded",
1311
- "paid",
1312
- "captured",
1313
- "authorized",
1314
- "completed"
1315
- ].includes(normalizedStatus);
1316
- return {
1317
- status: normalizedStatus,
1318
- paid: derivedPaid,
1319
- amount: normalizedAmount,
1320
- currency: normalizedCurrency,
1321
- reference: res.reference,
1322
- message: res.message || ""
1323
- };
1324
- }
1325
- var MOBILE_MONEY_PROVIDERS = {
1326
- mtn: { name: "MTN Mobile Money", prefix: ["024", "054", "055", "059"] },
1327
- vodafone: { name: "Vodafone Cash", prefix: ["020", "050"] },
1328
- airtel: { name: "AirtelTigo Money", prefix: ["027", "057", "026", "056"] }
1329
- };
1330
- function detectMobileMoneyProvider(phoneNumber) {
1331
- const cleaned = phoneNumber.replace(/\D/g, "");
1332
- const prefix = cleaned.slice(-9, -6);
1333
- for (const [provider, info] of Object.entries(MOBILE_MONEY_PROVIDERS)) {
1334
- if (info.prefix.some((p) => prefix.startsWith(p.slice(1)))) {
1335
- return provider;
1336
- }
1337
- }
1338
- return null;
1339
- }
1340
-
1341
- // src/utils/paystack.ts
1342
- async function openPaystackPopup(options, signal) {
1343
- if (typeof window === "undefined") {
1344
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
1345
- }
1346
- let PaystackPop;
1347
- try {
1348
- const imported = await import('@paystack/inline-js');
1349
- PaystackPop = imported.default;
1350
- } catch {
1351
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
1352
- }
1353
- return new Promise((resolve) => {
1354
- let settled = false;
1355
- const resolveOnce = (result) => {
1356
- if (settled) {
1357
- return;
1358
- }
1359
- settled = true;
1360
- if (signal) {
1361
- signal.removeEventListener("abort", onAbort);
1362
- }
1363
- resolve(result);
1364
- };
1365
- const onAbort = () => {
1366
- resolveOnce({ success: false, error: "CANCELLED" });
1367
- };
1368
- if (signal?.aborted) {
1369
- resolveOnce({ success: false, error: "CANCELLED" });
1370
- return;
1371
- }
1372
- if (signal) {
1373
- signal.addEventListener("abort", onAbort, { once: true });
1374
- }
1375
- try {
1376
- const popup = new PaystackPop();
1377
- popup.newTransaction({
1378
- key: options.key,
1379
- email: options.email,
1380
- amount: options.amount,
1381
- currency: options.currency,
1382
- reference: options.reference,
1383
- accessCode: options.accessCode,
1384
- onSuccess: (transaction) => {
1385
- resolveOnce({
1386
- success: true,
1387
- reference: transaction.reference ?? options.reference
1388
- });
1389
- },
1390
- onCancel: () => {
1391
- resolveOnce({ success: false, error: "PAYMENT_CANCELLED" });
1392
- },
1393
- onError: (error) => {
1394
- resolveOnce({
1395
- success: false,
1396
- error: error?.message || "PAYMENT_FAILED"
1397
- });
1398
- }
1399
- });
1400
- } catch {
1401
- resolveOnce({ success: false, error: "POPUP_BLOCKED" });
1402
- }
1403
- });
1404
- }
1405
-
1406
- // src/utils/checkout-resolver.ts
1407
- var DEFAULT_POLL_INTERVAL_MS = 3e3;
1408
- var DEFAULT_MAX_POLL_ATTEMPTS = 60;
1409
- var MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
1410
- var CARD_PROVIDER_PAYSTACK = "paystack";
1411
- var NEXT_ACTION_NONE = "none";
1412
- var NEXT_ACTION_CARD_POPUP = "card_popup";
1413
- var NEXT_ACTION_REDIRECT = "redirect";
1414
- var NEXT_ACTION_AUTHORIZATION = "authorization";
1415
- function normalizeCardPopupError(error) {
1416
- if (!error || error === "PAYMENT_CANCELLED" || error === "CANCELLED") {
1417
- return "PAYMENT_CANCELLED";
1418
- }
1419
- if (error === "PROVIDER_UNAVAILABLE") {
1420
- return "PROVIDER_UNAVAILABLE";
1421
- }
1422
- if (error === "POPUP_BLOCKED") {
1423
- return "POPUP_BLOCKED";
1424
- }
1425
- return "PAYMENT_FAILED";
1426
- }
1427
- function normalizeCardProvider(value) {
1428
- const normalized = value?.trim().toLowerCase();
1429
- return normalized && normalized.length > 0 ? normalized : CARD_PROVIDER_PAYSTACK;
1430
- }
1431
- async function openCardPopup(provider, checkoutResult, email, currency, signal) {
1432
- if (typeof window === "undefined") {
1433
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
1434
- }
1435
- if (provider === CARD_PROVIDER_PAYSTACK) {
1436
- return openPaystackPopup(
1437
- {
1438
- key: checkoutResult.public_key || "",
1439
- email,
1440
- accessCode: checkoutResult.client_secret,
1441
- reference: checkoutResult.payment_reference || checkoutResult.client_secret,
1442
- currency
1443
- },
1444
- signal
1445
- );
1446
- }
1447
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
1448
- }
1449
- var VALID_MOBILE_MONEY_PROVIDERS = new Set(Object.values(MOBILE_MONEY_PROVIDER));
1450
- function isValidMobileMoneyProvider(value) {
1451
- return VALID_MOBILE_MONEY_PROVIDERS.has(value);
1452
- }
1453
- function normalizeAuthorizationType(value) {
1454
- if (typeof value !== "string") return void 0;
1455
- const lower = value.toLowerCase();
1456
- return lower === "otp" || lower === "pin" ? lower : void 0;
1457
- }
1458
- function formatMoney2(value) {
1459
- if (typeof value === "number" && Number.isFinite(value)) {
1460
- return value.toFixed(2);
1461
- }
1462
- if (typeof value === "string" && value.trim().length > 0) {
1463
- return value;
1464
- }
1465
- return "0.00";
1466
- }
1467
- function createAbortError() {
1468
- const error = new Error("CANCELLED");
1469
- error.name = "AbortError";
1470
- return error;
1471
- }
1472
- function isAbortError(error) {
1473
- if (error instanceof DOMException && error.name === "AbortError") {
1474
- return true;
1475
- }
1476
- return error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
1477
- }
1478
- var CheckoutResolver = class {
1479
- constructor(options) {
1480
- this.client = options.client;
1481
- this.checkoutData = options.checkoutData;
1482
- this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1483
- this.maxPollAttempts = options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS;
1484
- this.onStatusChange = options.onStatusChange;
1485
- this.onAuthorizationRequired = options.onAuthorizationRequired;
1486
- this.signal = options.signal;
1487
- this.returnUrl = options.returnUrl;
1488
- this.enrollInLink = options.enrollInLink !== false;
1489
- this.businessId = options.businessId;
1490
- this.addressData = options.addressData;
1491
- this.paymentData = options.paymentData;
1492
- this.orderType = options.orderType;
1493
- this.cartTotal = options.cartTotal;
1494
- this.cartCurrency = options.cartCurrency;
1495
- this.allowPopups = options.allowPopups ?? typeof window !== "undefined";
1496
- }
1497
- async resolve(checkoutResult) {
1498
- try {
1499
- this.ensureNotAborted();
1500
- if (!checkoutResult.order_id) {
1501
- return this.fail("CHECKOUT_FAILED", "Checkout did not return an order ID.", false);
1502
- }
1503
- if (checkoutResult.next_action) {
1504
- return this.resolveNextAction(checkoutResult);
1505
- }
1506
- let latestCheckoutResult = checkoutResult;
1507
- let authorizationType = normalizeAuthorizationType(checkoutResult.authorization_type);
1508
- let paymentReference = checkoutResult.payment_reference;
1509
- if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
1510
- return this.finalizeSuccess(checkoutResult);
1511
- }
1512
- if (checkoutResult.client_secret && checkoutResult.public_key) {
1513
- const provider = normalizeCardProvider(checkoutResult.provider);
1514
- this.emit("awaiting_authorization", {
1515
- display_text: "Complete payment in the card authorization popup.",
1516
- order_id: checkoutResult.order_id,
1517
- order_number: checkoutResult.order_number
1518
- });
1519
- if (!this.allowPopups) {
1520
- return this.fail(
1521
- "PROVIDER_UNAVAILABLE",
1522
- "Card payment popup is unavailable in this environment.",
1523
- false
1524
- );
1525
- }
1526
- const popupResult = await openCardPopup(
1527
- provider,
1528
- checkoutResult,
1529
- this.checkoutData.customer.email || "customer@cimplify.io",
1530
- this.getOrderCurrency(checkoutResult),
1531
- this.signal
1532
- );
1533
- if (!popupResult.success) {
1534
- const popupError = normalizeCardPopupError(popupResult.error);
1535
- if (popupError === "POPUP_BLOCKED") {
1536
- return this.fail(
1537
- "POPUP_BLOCKED",
1538
- "Unable to open card payment popup. Please allow popups and try again.",
1539
- true
1540
- );
1541
- }
1542
- if (popupError === "PROVIDER_UNAVAILABLE") {
1543
- return this.fail(
1544
- "PROVIDER_UNAVAILABLE",
1545
- "Card payment provider is unavailable.",
1546
- false
1547
- );
1548
- }
1549
- return this.fail(
1550
- "PAYMENT_CANCELLED",
1551
- "Card payment was cancelled before completion.",
1552
- true
1553
- );
1554
- }
1555
- paymentReference = popupResult.reference || paymentReference;
1556
- }
1557
- if (checkoutResult.authorization_url) {
1558
- if (typeof window !== "undefined" && this.returnUrl) {
1559
- window.location.assign(checkoutResult.authorization_url);
1560
- return this.fail(
1561
- "REDIRECT_REQUIRED",
1562
- "Redirecting to complete payment authorization.",
1563
- true
1564
- );
1565
- }
1566
- if (typeof window !== "undefined") {
1567
- const popup = window.open(
1568
- checkoutResult.authorization_url,
1569
- "cimplify-auth",
1570
- "width=520,height=760,noopener,noreferrer"
1571
- );
1572
- if (!popup) {
1573
- return this.fail(
1574
- "POPUP_BLOCKED",
1575
- "Authorization popup was blocked. Please allow popups and retry.",
1576
- true
1577
- );
1578
- }
1579
- }
1580
- }
1581
- if (checkoutResult.requires_authorization || isPaymentStatusRequiresAction(checkoutResult.payment_status)) {
1582
- const authorization = await this.handleAuthorization({
1583
- authorizationType,
1584
- paymentReference,
1585
- displayText: checkoutResult.display_text,
1586
- provider: checkoutResult.provider
1587
- });
1588
- if (!authorization.ok) {
1589
- return authorization.result;
1590
- }
1591
- if (authorization.value) {
1592
- latestCheckoutResult = authorization.value;
1593
- paymentReference = authorization.value.payment_reference || paymentReference;
1594
- authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1595
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1596
- return this.finalizeSuccess(authorization.value);
1597
- }
1598
- if (this.isFailureStatus(authorization.value.payment_status)) {
1599
- return this.fail(
1600
- "AUTHORIZATION_FAILED",
1601
- authorization.value.display_text || "Payment authorization failed.",
1602
- false
1603
- );
1604
- }
1605
- }
1606
- }
1607
- return this.pollUntilTerminal({
1608
- orderId: checkoutResult.order_id,
1609
- latestCheckoutResult,
1610
- paymentReference,
1611
- authorizationType
1612
- });
1613
- } catch (error) {
1614
- if (isAbortError(error)) {
1615
- return this.fail("CANCELLED", "Checkout was cancelled.", true);
1616
- }
1617
- const message = error instanceof Error ? error.message : "Checkout failed unexpectedly.";
1618
- return this.fail("CHECKOUT_FAILED", message, true);
1619
- }
1620
- }
1621
- async resolveNextAction(checkoutResult) {
1622
- const action = checkoutResult.next_action;
1623
- if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
1624
- return this.finalizeSuccess(checkoutResult);
1625
- }
1626
- let latestCheckoutResult = checkoutResult;
1627
- let paymentReference = checkoutResult.payment_reference;
1628
- switch (action.type) {
1629
- case NEXT_ACTION_NONE:
1630
- return this.finalizeSuccess(checkoutResult);
1631
- case NEXT_ACTION_CARD_POPUP: {
1632
- const provider = normalizeCardProvider(action.provider);
1633
- this.emit("awaiting_authorization", {
1634
- display_text: "Complete payment in the card authorization popup.",
1635
- order_id: checkoutResult.order_id,
1636
- order_number: checkoutResult.order_number
1637
- });
1638
- if (!this.allowPopups) {
1639
- return this.fail(
1640
- "PROVIDER_UNAVAILABLE",
1641
- "Card payment popup is unavailable in this environment.",
1642
- false
1643
- );
1644
- }
1645
- const popupResult = await openCardPopup(
1646
- provider,
1647
- checkoutResult,
1648
- this.checkoutData.customer.email || "customer@cimplify.io",
1649
- this.getOrderCurrency(checkoutResult),
1650
- this.signal
1651
- );
1652
- if (!popupResult.success) {
1653
- const popupError = normalizeCardPopupError(popupResult.error);
1654
- if (popupError === "POPUP_BLOCKED") {
1655
- return this.fail(
1656
- "POPUP_BLOCKED",
1657
- "Unable to open card payment popup. Please allow popups and try again.",
1658
- true
1659
- );
1660
- }
1661
- if (popupError === "PROVIDER_UNAVAILABLE") {
1662
- return this.fail("PROVIDER_UNAVAILABLE", "Card payment provider is unavailable.", false);
1663
- }
1664
- return this.fail("PAYMENT_CANCELLED", "Card payment was cancelled before completion.", true);
1665
- }
1666
- paymentReference = popupResult.reference || paymentReference;
1667
- break;
1668
- }
1669
- case NEXT_ACTION_REDIRECT: {
1670
- if (typeof window !== "undefined" && this.returnUrl) {
1671
- window.location.assign(action.authorization_url);
1672
- return this.fail("REDIRECT_REQUIRED", "Redirecting to complete payment authorization.", true);
1673
- }
1674
- if (typeof window !== "undefined") {
1675
- const popup = window.open(
1676
- action.authorization_url,
1677
- "cimplify-auth",
1678
- "width=520,height=760,noopener,noreferrer"
1679
- );
1680
- if (!popup) {
1681
- return this.fail(
1682
- "POPUP_BLOCKED",
1683
- "Authorization popup was blocked. Please allow popups and retry.",
1684
- true
1685
- );
1686
- }
1687
- }
1688
- break;
1689
- }
1690
- case NEXT_ACTION_AUTHORIZATION: {
1691
- const authType = normalizeAuthorizationType(action.authorization_type);
1692
- const authorization = await this.handleAuthorization({
1693
- authorizationType: authType,
1694
- paymentReference,
1695
- displayText: action.display_text,
1696
- provider: checkoutResult.provider
1697
- });
1698
- if (!authorization.ok) {
1699
- return authorization.result;
1700
- }
1701
- if (authorization.value) {
1702
- latestCheckoutResult = authorization.value;
1703
- paymentReference = authorization.value.payment_reference || paymentReference;
1704
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1705
- return this.finalizeSuccess(authorization.value);
1706
- }
1707
- if (this.isFailureStatus(authorization.value.payment_status)) {
1708
- return this.fail(
1709
- "AUTHORIZATION_FAILED",
1710
- authorization.value.display_text || "Payment authorization failed.",
1711
- false
1712
- );
1713
- }
1714
- }
1715
- break;
1716
- }
1717
- }
1718
- return this.pollUntilTerminal({
1719
- orderId: checkoutResult.order_id,
1720
- latestCheckoutResult,
1721
- paymentReference,
1722
- authorizationType: normalizeAuthorizationType(checkoutResult.authorization_type)
1723
- });
1724
- }
1725
- async pollUntilTerminal(input) {
1726
- let consecutiveErrors = 0;
1727
- let latestCheckoutResult = input.latestCheckoutResult;
1728
- let paymentReference = input.paymentReference;
1729
- let authorizationType = input.authorizationType;
1730
- for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) {
1731
- this.ensureNotAborted();
1732
- this.emit("polling", {
1733
- poll_attempt: attempt,
1734
- max_poll_attempts: this.maxPollAttempts,
1735
- order_id: input.orderId,
1736
- order_number: latestCheckoutResult.order_number
1737
- });
1738
- const statusResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1739
- if (!statusResult.ok) {
1740
- consecutiveErrors += 1;
1741
- if (consecutiveErrors >= MAX_CONSECUTIVE_NETWORK_ERRORS) {
1742
- return this.fail(
1743
- "NETWORK_ERROR",
1744
- "Unable to confirm payment due to repeated network errors.",
1745
- true
1746
- );
1747
- }
1748
- await this.wait(this.pollIntervalMs);
1749
- continue;
1750
- }
1751
- consecutiveErrors = 0;
1752
- if (statusResult.value.reference) {
1753
- paymentReference = statusResult.value.reference;
1754
- }
1755
- const normalized = normalizeStatusResponse(statusResult.value);
1756
- if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1757
- return this.finalizeSuccess(latestCheckoutResult);
1758
- }
1759
- if (isPaymentStatusFailure(normalized.status)) {
1760
- return this.fail(
1761
- normalized.status ? normalized.status.toUpperCase() : "PAYMENT_FAILED",
1762
- normalized.message || "Payment failed during confirmation.",
1763
- false
1764
- );
1765
- }
1766
- if (isPaymentStatusRequiresAction(normalized.status)) {
1767
- const authorization = await this.handleAuthorization({
1768
- authorizationType,
1769
- paymentReference,
1770
- displayText: normalized.message || latestCheckoutResult.display_text,
1771
- provider: latestCheckoutResult.provider
1772
- });
1773
- if (!authorization.ok) {
1774
- return authorization.result;
1775
- }
1776
- if (authorization.value) {
1777
- latestCheckoutResult = authorization.value;
1778
- paymentReference = authorization.value.payment_reference || paymentReference;
1779
- authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1780
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1781
- return this.finalizeSuccess(authorization.value);
1782
- }
1783
- if (this.isFailureStatus(authorization.value.payment_status)) {
1784
- return this.fail(
1785
- "AUTHORIZATION_FAILED",
1786
- authorization.value.display_text || "Payment authorization failed.",
1787
- false
1788
- );
1789
- }
1790
- }
1791
- }
1792
- await this.wait(this.pollIntervalMs);
1793
- }
1794
- try {
1795
- const finalResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1796
- if (finalResult.ok) {
1797
- const normalized = normalizeStatusResponse(finalResult.value);
1798
- if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1799
- return this.finalizeSuccess(latestCheckoutResult);
1800
- }
1801
- }
1802
- } catch {
1803
- }
1804
- return this.fail(
1805
- "PAYMENT_TIMEOUT",
1806
- "Payment confirmation timed out. Please retry checkout.",
1807
- true
1808
- );
1809
- }
1810
- async handleAuthorization(input) {
1811
- const authorizationType = input.authorizationType;
1812
- const paymentReference = input.paymentReference;
1813
- if (!authorizationType || !paymentReference) {
1814
- return { ok: true };
1815
- }
1816
- this.emit("awaiting_authorization", {
1817
- authorization_type: authorizationType,
1818
- display_text: input.displayText,
1819
- provider: input.provider
1820
- });
1821
- let authorizationResult;
1822
- const submit = async (code) => {
1823
- this.ensureNotAborted();
1824
- const trimmedCode = code.trim();
1825
- if (!trimmedCode) {
1826
- throw new Error("Authorization code is required.");
1827
- }
1828
- const submitResult = await this.client.checkout.submitAuthorization({
1829
- reference: paymentReference,
1830
- auth_type: authorizationType,
1831
- value: trimmedCode
1832
- });
1833
- if (!submitResult.ok) {
1834
- throw new Error(submitResult.error.message || "Authorization failed.");
1835
- }
1836
- authorizationResult = submitResult.value;
1837
- };
1838
- try {
1839
- if (this.onAuthorizationRequired) {
1840
- await this.onAuthorizationRequired(authorizationType, submit);
1841
- } else {
1842
- return {
1843
- ok: false,
1844
- result: this.fail(
1845
- "AUTHORIZATION_REQUIRED",
1846
- "Authorization callback is required in headless checkout mode.",
1847
- false
1848
- )
1849
- };
1850
- }
1851
- } catch (error) {
1852
- if (isAbortError(error)) {
1853
- return {
1854
- ok: false,
1855
- result: this.fail("CANCELLED", "Checkout was cancelled.", true)
1856
- };
1857
- }
1858
- const message = error instanceof Error ? error.message : "Payment authorization failed.";
1859
- return {
1860
- ok: false,
1861
- result: this.fail("AUTHORIZATION_FAILED", message, true)
1862
- };
1863
- }
1864
- return {
1865
- ok: true,
1866
- value: authorizationResult
1867
- };
1868
- }
1869
- async finalizeSuccess(checkoutResult) {
1870
- this.emit("finalizing", {
1871
- order_id: checkoutResult.order_id,
1872
- order_number: checkoutResult.order_number
1873
- });
1874
- const enrolledInLink = await this.maybeEnrollInLink(checkoutResult.order_id);
1875
- this.emit("success", {
1876
- order_id: checkoutResult.order_id,
1877
- order_number: checkoutResult.order_number
1878
- });
1879
- return {
1880
- success: true,
1881
- order: {
1882
- id: checkoutResult.order_id,
1883
- order_number: checkoutResult.order_number || checkoutResult.order_id,
1884
- status: checkoutResult.payment_status || "paid",
1885
- total: this.getOrderTotal(checkoutResult),
1886
- currency: this.getOrderCurrency(checkoutResult)
1887
- },
1888
- enrolled_in_link: enrolledInLink
1889
- };
1890
- }
1891
- async maybeEnrollInLink(orderId) {
1892
- if (!this.enrollInLink || !orderId) {
1893
- return false;
1894
- }
1895
- let businessId = this.businessId;
1896
- if (!businessId) {
1897
- const businessResult = await this.client.business.getInfo();
1898
- if (!businessResult.ok || !businessResult.value?.id) {
1899
- return false;
1900
- }
1901
- businessId = businessResult.value.id;
1902
- }
1903
- const address = this.getEnrollmentAddress();
1904
- const mobileMoney = this.getEnrollmentMobileMoney();
1905
- try {
1906
- const enrollment = await this.client.link.enrollAndLinkOrder({
1907
- order_id: orderId,
1908
- business_id: businessId,
1909
- order_type: this.orderType || this.checkoutData.order_type,
1910
- address,
1911
- mobile_money: mobileMoney
1912
- });
1913
- return enrollment.ok && enrollment.value.success;
1914
- } catch {
1915
- return false;
1916
- }
1917
- }
1918
- getEnrollmentAddress() {
1919
- const source = this.addressData ?? this.checkoutData.address_info;
1920
- if (!source?.street_address) {
1921
- return void 0;
1922
- }
1923
- return {
1924
- label: "Default",
1925
- street_address: source.street_address,
1926
- apartment: source.apartment || void 0,
1927
- city: source.city || "",
1928
- region: source.region || "",
1929
- delivery_instructions: source.delivery_instructions || void 0,
1930
- phone_for_delivery: source.phone_for_delivery || void 0
1931
- };
1932
- }
1933
- getEnrollmentMobileMoney() {
1934
- if (this.paymentData?.type === "mobile_money" && this.paymentData.phone_number && this.paymentData.provider && isValidMobileMoneyProvider(this.paymentData.provider)) {
1935
- return {
1936
- phone_number: this.paymentData.phone_number,
1937
- provider: this.paymentData.provider,
1938
- label: this.paymentData.label || "Mobile Money"
1939
- };
1940
- }
1941
- if (this.checkoutData.mobile_money_details?.phone_number) {
1942
- return {
1943
- phone_number: this.checkoutData.mobile_money_details.phone_number,
1944
- provider: this.checkoutData.mobile_money_details.provider,
1945
- label: "Mobile Money"
1946
- };
1947
- }
1948
- return void 0;
1949
- }
1950
- getOrderTotal(checkoutResult) {
1951
- if (checkoutResult.fx?.pay_amount !== void 0) {
1952
- return formatMoney2(checkoutResult.fx.pay_amount);
1953
- }
1954
- if (this.cartTotal !== void 0) {
1955
- return formatMoney2(this.cartTotal);
1956
- }
1957
- return "0.00";
1958
- }
1959
- getOrderCurrency(checkoutResult) {
1960
- if (checkoutResult.fx?.pay_currency) {
1961
- return checkoutResult.fx.pay_currency;
1962
- }
1963
- if (this.cartCurrency) {
1964
- return this.cartCurrency;
1965
- }
1966
- if (this.checkoutData.pay_currency) {
1967
- return this.checkoutData.pay_currency;
1968
- }
1969
- return "GHS";
1970
- }
1971
- emit(status, context = {}) {
1972
- if (!this.onStatusChange) {
1973
- return;
1974
- }
1975
- try {
1976
- this.onStatusChange(status, context);
1977
- } catch {
1978
- }
1979
- }
1980
- fail(code, message, recoverable) {
1981
- this.emit("failed", {
1982
- display_text: message
1983
- });
1984
- return {
1985
- success: false,
1986
- error: {
1987
- code,
1988
- message,
1989
- recoverable
1990
- }
1991
- };
1992
- }
1993
- isSuccessfulStatus(status) {
1994
- const normalized = normalizeStatusResponse({ status, paid: false });
1995
- return normalized.paid || isPaymentStatusSuccess(normalized.status);
1996
- }
1997
- isFailureStatus(status) {
1998
- const normalized = normalizeStatusResponse({ status, paid: false });
1999
- return isPaymentStatusFailure(normalized.status);
2000
- }
2001
- ensureNotAborted() {
2002
- if (this.signal?.aborted) {
2003
- throw createAbortError();
2004
- }
2005
- }
2006
- wait(ms) {
2007
- this.ensureNotAborted();
2008
- return new Promise((resolve, reject) => {
2009
- const timer = setTimeout(() => {
2010
- if (this.signal) {
2011
- this.signal.removeEventListener("abort", onAbort);
2012
- }
2013
- resolve();
2014
- }, ms);
2015
- const onAbort = () => {
2016
- clearTimeout(timer);
2017
- reject(createAbortError());
2018
- };
2019
- if (this.signal) {
2020
- this.signal.addEventListener("abort", onAbort, { once: true });
2021
- }
2022
- });
2023
- }
2024
- };
2025
-
2026
- // src/checkout.ts
2027
- function toTerminalFailure(code, message, recoverable) {
2028
- return {
2029
- success: false,
2030
- error: {
2031
- code,
2032
- message,
2033
- recoverable
2034
- }
2035
- };
2036
- }
2037
- function generateIdempotencyKey() {
2038
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2039
- return `idem_${crypto.randomUUID()}`;
2040
- }
2041
- const timestamp = Date.now().toString(36);
2042
- const random = Math.random().toString(36).substring(2, 15);
2043
- return `idem_${timestamp}_${random}`;
2044
- }
2045
- var CheckoutService = class {
2046
- constructor(client) {
2047
- this.client = client;
2048
- }
2049
- orderTokenParam(orderId) {
2050
- const token = this.client.getOrderToken(orderId);
2051
- return token ? `?token=${encodeURIComponent(token)}` : "";
2052
- }
2053
- async process(data) {
2054
- const checkoutData = {
2055
- ...data,
2056
- idempotency_key: data.idempotency_key || generateIdempotencyKey()
2057
- };
2058
- const result = await safe(
2059
- this.client.post("/api/v1/checkout", {
2060
- checkout_data: checkoutData
2061
- })
2062
- );
2063
- if (result.ok && result.value.bill_token) {
2064
- this.client.setOrderToken(result.value.order_id, result.value.bill_token);
2065
- }
2066
- return result;
2067
- }
2068
- async initializePayment(_orderId, _method) {
2069
- return err(
2070
- new CimplifyError(
2071
- "NOT_IMPLEMENTED",
2072
- "initializePayment is not available in REST mode.",
2073
- false
2074
- )
2075
- );
2076
- }
2077
- async submitAuthorization(input) {
2078
- return safe(this.client.post("/api/v1/payments/authorization", input));
2079
- }
2080
- async pollPaymentStatus(orderId) {
2081
- const encodedId = encodeURIComponent(orderId);
2082
- const tokenParam = this.orderTokenParam(orderId);
2083
- return safe(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
2084
- }
2085
- async updateOrderCustomer(orderId, customer) {
2086
- const encodedId = encodeURIComponent(orderId);
2087
- const tokenParam = this.orderTokenParam(orderId);
2088
- return safe(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
2089
- }
2090
- async verifyPayment(orderId) {
2091
- const encodedId = encodeURIComponent(orderId);
2092
- const tokenParam = this.orderTokenParam(orderId);
2093
- return safe(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
2094
- }
2095
- async processAndResolve(data) {
2096
- data.on_status_change?.("preparing", {});
2097
- if (!data.cart_id) {
2098
- return ok(
2099
- toTerminalFailure(
2100
- "INVALID_CART",
2101
- "A valid cart is required before checkout can start.",
2102
- false
2103
- )
2104
- );
2105
- }
2106
- const cartResult = await this.client.cart.get();
2107
- if (!cartResult.ok || !cartResult.value?.id) {
2108
- return ok(
2109
- toTerminalFailure(
2110
- "INVALID_CART",
2111
- "Unable to load cart for checkout.",
2112
- false
2113
- )
2114
- );
2115
- }
2116
- const cart = cartResult.value;
2117
- if (cart.id !== data.cart_id || cart.items.length === 0) {
2118
- return ok(
2119
- toTerminalFailure(
2120
- "INVALID_CART",
2121
- "Cart is empty or no longer valid. Please refresh and try again.",
2122
- false
2123
- )
2124
- );
2125
- }
2126
- const checkoutData = {
2127
- cart_id: data.cart_id,
2128
- location_id: data.location_id,
2129
- customer: data.customer,
2130
- order_type: data.order_type,
2131
- address_info: data.address_info,
2132
- payment_method: data.payment_method,
2133
- mobile_money_details: data.mobile_money_details,
2134
- special_instructions: data.special_instructions,
2135
- link_address_id: data.link_address_id,
2136
- link_payment_method_id: data.link_payment_method_id,
2137
- idempotency_key: data.idempotency_key || generateIdempotencyKey(),
2138
- metadata: data.metadata,
2139
- pay_currency: data.pay_currency,
2140
- fx_quote_id: data.fx_quote_id
2141
- };
2142
- const baseCurrency = currencyCode(
2143
- (cart.pricing.currency || checkoutData.pay_currency || "GHS").toUpperCase()
2144
- );
2145
- const payCurrency = data.pay_currency?.trim().toUpperCase();
2146
- const payCurrencyCode = payCurrency ? currencyCode(payCurrency) : void 0;
2147
- const cartTotalAmount = typeof cart.pricing.total_price === "number" ? cart.pricing.total_price : Number.parseFloat(cart.pricing.total_price || "0");
2148
- if (payCurrencyCode && payCurrencyCode !== baseCurrency && !checkoutData.fx_quote_id && Number.isFinite(cartTotalAmount) && cartTotalAmount > 0) {
2149
- const fxQuoteResult = await this.client.fx.lockQuote({
2150
- from: baseCurrency,
2151
- to: payCurrencyCode,
2152
- amount: cart.pricing.total_price
2153
- });
2154
- if (!fxQuoteResult.ok) {
2155
- return ok(
2156
- toTerminalFailure(
2157
- "FX_QUOTE_FAILED",
2158
- fxQuoteResult.error.message || "Unable to lock FX quote for checkout.",
2159
- true
2160
- )
2161
- );
2162
- }
2163
- checkoutData.pay_currency = payCurrencyCode;
2164
- checkoutData.fx_quote_id = fxQuoteResult.value.id;
2165
- }
2166
- data.on_status_change?.("processing", {});
2167
- const processResult = await this.process(checkoutData);
2168
- if (!processResult.ok) {
2169
- return ok(
2170
- toTerminalFailure(
2171
- processResult.error.code || "CHECKOUT_FAILED",
2172
- processResult.error.message || "Unable to process checkout.",
2173
- processResult.error.retryable ?? true
2174
- )
2175
- );
2176
- }
2177
- const resolver = new CheckoutResolver({
2178
- client: this.client,
2179
- checkoutData,
2180
- pollIntervalMs: data.poll_interval_ms,
2181
- maxPollAttempts: data.max_poll_attempts,
2182
- onStatusChange: data.on_status_change,
2183
- onAuthorizationRequired: data.on_authorization_required,
2184
- signal: data.signal,
2185
- returnUrl: data.return_url,
2186
- enrollInLink: data.enroll_in_link,
2187
- cartTotal: cart.pricing.total_price,
2188
- cartCurrency: checkoutData.pay_currency || cart.pricing.currency || "GHS",
2189
- orderType: checkoutData.order_type,
2190
- allowPopups: data.allow_popups
2191
- });
2192
- const resolved = await resolver.resolve(processResult.value);
2193
- return ok(resolved);
2194
- }
2195
- };
2196
-
2197
- // src/orders.ts
2198
- var OrderQueries = class {
2199
- constructor(client) {
2200
- this.client = client;
2201
- }
2202
- orderTokenParam(orderId) {
2203
- const token = this.client.getOrderToken(orderId);
2204
- return token ? `?token=${encodeURIComponent(token)}` : "";
2205
- }
2206
- async list(options) {
2207
- const params = new URLSearchParams();
2208
- if (options?.status) params.set("status", options.status);
2209
- if (options?.limit) params.set("limit", String(options.limit));
2210
- if (options?.offset) params.set("offset", String(options.offset));
2211
- const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
2212
- return safe(this.client.get(path));
2213
- }
2214
- async get(orderId) {
2215
- const encodedId = encodeURIComponent(orderId);
2216
- const tokenParam = this.orderTokenParam(orderId);
2217
- return safe(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
2218
- }
2219
- async getRecent(limit = 5) {
2220
- return this.list({ limit });
2221
- }
2222
- async getByStatus(status) {
2223
- return this.list({ status });
2224
- }
2225
- async cancel(orderId, reason) {
2226
- const encodedId = encodeURIComponent(orderId);
2227
- const tokenParam = this.orderTokenParam(orderId);
2228
- return safe(
2229
- this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
2230
- reason
2231
- })
2232
- );
2233
- }
2234
- };
2235
-
2236
- // src/link.ts
2237
- function encodePathSegment(value) {
2238
- return encodeURIComponent(value);
2239
- }
2240
- function toCreateAddressPayload(input) {
2241
- return {
2242
- label: input.label,
2243
- street_address: input.address_line1,
2244
- apartment: input.address_line2,
2245
- city: input.city,
2246
- region: input.state ?? "",
2247
- postal_code: input.postal_code,
2248
- country: input.country
2249
- };
2250
- }
2251
- function toUpdateAddressPayload(input) {
2252
- return {
2253
- label: input.label,
2254
- street_address: input.address_line1,
2255
- apartment: input.address_line2,
2256
- city: input.city,
2257
- region: input.state,
2258
- postal_code: input.postal_code,
2259
- country: input.country
2260
- };
2261
- }
2262
- function toCreateMobileMoneyPayload(input) {
2263
- return {
2264
- phone_number: input.phone_number,
2265
- provider: input.provider,
2266
- label: input.account_name
2267
- };
2268
- }
2269
- var LinkService = class {
2270
- constructor(client) {
2271
- this.client = client;
2272
- }
2273
- async getProfile() {
2274
- return safe(this.client.linkGet("/v1/link/profile"));
2275
- }
2276
- async requestOtp(input) {
2277
- return safe(this.client.linkPost("/v1/link/auth/request-otp", input));
2278
- }
2279
- async verifyOtp(input) {
2280
- const result = await safe(
2281
- this.client.linkPost("/v1/link/auth/verify-otp", input)
2282
- );
2283
- if (result.ok && result.value.session_token) {
2284
- this.client.setAccessToken(result.value.session_token);
2285
- }
2286
- return result;
2287
- }
2288
- async logout() {
2289
- const result = await safe(this.client.linkPost("/v1/link/auth/logout"));
2290
- if (result.ok) {
2291
- this.client.clearSession();
2292
- }
2293
- return result;
2294
- }
2295
- async checkStatus(contact) {
2296
- return safe(this.client.linkPost("/v1/link/check-status", { contact }));
2297
- }
2298
- async getLinkData() {
2299
- return safe(this.client.linkGet("/v1/link/data"));
2300
- }
2301
- async getAddresses() {
2302
- return safe(this.client.linkGet("/v1/link/addresses"));
2303
- }
2304
- async getMobileMoney() {
2305
- return safe(this.client.linkGet("/v1/link/mobile-money"));
2306
- }
2307
- async getPreferences() {
2308
- return safe(this.client.linkGet("/v1/link/preferences"));
2309
- }
2310
- async enroll(data) {
2311
- return safe(this.client.linkPost("/v1/link/enroll", data));
2312
- }
2313
- async enrollAndLinkOrder(data) {
2314
- return safe(
2315
- this.client.linkPost("/v1/link/enroll-and-link-order", data)
2316
- );
2317
- }
2318
- async updatePreferences(preferences) {
2319
- return safe(this.client.linkPost("/v1/link/preferences", preferences));
2320
- }
2321
- async createAddress(input) {
2322
- return safe(
2323
- this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
2324
- );
2325
- }
2326
- async updateAddress(input) {
2327
- return safe(
2328
- this.client.linkPost(
2329
- `/v1/link/addresses/${encodePathSegment(input.address_id)}`,
2330
- toUpdateAddressPayload(input)
2331
- )
2332
- );
2333
- }
2334
- async deleteAddress(addressId) {
2335
- return safe(
2336
- this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
2337
- );
2338
- }
2339
- async setDefaultAddress(addressId) {
2340
- return safe(
2341
- this.client.linkPost(
2342
- `/v1/link/addresses/${encodePathSegment(addressId)}/default`
2343
- )
2344
- );
2345
- }
2346
- async trackAddressUsage(addressId) {
2347
- return safe(
2348
- this.client.linkPost(
2349
- `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
2350
- )
2351
- );
2352
- }
2353
- async createMobileMoney(input) {
2354
- return safe(
2355
- this.client.linkPost(
2356
- "/v1/link/mobile-money",
2357
- toCreateMobileMoneyPayload(input)
2358
- )
2359
- );
2360
- }
2361
- async deleteMobileMoney(mobileMoneyId) {
2362
- return safe(
2363
- this.client.linkDelete(
2364
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
2365
- )
2366
- );
2367
- }
2368
- async setDefaultMobileMoney(mobileMoneyId) {
2369
- return safe(
2370
- this.client.linkPost(
2371
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
2372
- )
2373
- );
2374
- }
2375
- async trackMobileMoneyUsage(mobileMoneyId) {
2376
- return safe(
2377
- this.client.linkPost(
2378
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
2379
- )
2380
- );
2381
- }
2382
- async verifyMobileMoney(mobileMoneyId) {
2383
- return safe(
2384
- this.client.linkPost(
2385
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
2386
- )
2387
- );
2388
- }
2389
- async getSessions() {
2390
- return safe(this.client.linkGet("/v1/link/sessions"));
2391
- }
2392
- async revokeSession(sessionId) {
2393
- return safe(this.client.linkDelete(`/v1/link/sessions/${sessionId}`));
2394
- }
2395
- async revokeAllSessions() {
2396
- return safe(this.client.linkDelete("/v1/link/sessions"));
2397
- }
2398
- };
2399
-
2400
- // src/auth.ts
2401
- var AuthService = class {
2402
- constructor(client) {
2403
- this.client = client;
2404
- }
2405
- async getStatus() {
2406
- return safe(this.client.get("/api/v1/auth/status"));
2407
- }
2408
- async getCurrentUser() {
2409
- const result = await this.getStatus();
2410
- if (!result.ok) return result;
2411
- return ok(result.value.customer || null);
2412
- }
2413
- async isAuthenticated() {
2414
- const result = await this.getStatus();
2415
- if (!result.ok) return result;
2416
- return ok(result.value.is_authenticated);
2417
- }
2418
- async requestOtp(contact, contactType) {
2419
- return safe(
2420
- this.client.post("/api/v1/auth/request-otp", {
2421
- contact,
2422
- contact_type: contactType
2423
- })
2424
- );
2425
- }
2426
- async verifyOtp(code, contact) {
2427
- return safe(
2428
- this.client.post("/api/v1/auth/verify-otp", {
2429
- otp_code: code,
2430
- contact
2431
- })
2432
- );
2433
- }
2434
- async logout() {
2435
- return safe(this.client.post("/api/v1/auth/logout"));
2436
- }
2437
- async updateProfile(input) {
2438
- return safe(this.client.post("/api/v1/auth/profile", input));
2439
- }
2440
- };
2441
-
2442
- // src/business.ts
2443
- var BusinessService = class {
2444
- constructor(client) {
2445
- this.client = client;
2446
- }
2447
- async getInfo() {
2448
- return safe(this.client.get("/api/v1/business"));
2449
- }
2450
- async getByHandle(handle) {
2451
- const encodedHandle = encodeURIComponent(handle);
2452
- return safe(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
2453
- }
2454
- async getByDomain(domain) {
2455
- const encodedDomain = encodeURIComponent(domain);
2456
- return safe(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
2457
- }
2458
- async getSettings() {
2459
- return safe(this.client.get("/api/v1/business/settings"));
2460
- }
2461
- async getLocations() {
2462
- return safe(this.client.get("/api/v1/business/locations"));
2463
- }
2464
- async getLocation(locationId) {
2465
- const result = await this.getLocations();
2466
- if (!result.ok) return err(result.error);
2467
- const location = result.value.find((item) => item.id === locationId);
2468
- if (!location) {
2469
- return err(new CimplifyError(ErrorCode.NOT_FOUND, `Location not found: ${locationId}`, false));
2470
- }
2471
- return ok(location);
2472
- }
2473
- async getHours() {
2474
- return safe(this.client.get("/api/v1/business/hours"));
2475
- }
2476
- async getLocationHours(locationId) {
2477
- const result = await this.getHours();
2478
- if (!result.ok) return result;
2479
- return ok(result.value.filter((hour) => hour.location_id === locationId));
2480
- }
2481
- async getBootstrap() {
2482
- return safe(this.client.get("/api/v1/bootstrap"));
2483
- }
2484
- };
2485
-
2486
- // src/inventory.ts
2487
- var InventoryService = class {
2488
- constructor(client) {
2489
- this.client = client;
2490
- }
2491
- withQuery(path, params) {
2492
- const searchParams = new URLSearchParams();
2493
- for (const [key, value] of Object.entries(params)) {
2494
- if (value === void 0) continue;
2495
- searchParams.set(key, String(value));
2496
- }
2497
- const query2 = searchParams.toString();
2498
- return query2 ? `${path}?${query2}` : path;
2499
- }
2500
- async getProductStock(productId, locationId) {
2501
- const encodedId = encodeURIComponent(productId);
2502
- const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
2503
- location_id: locationId
2504
- });
2505
- return safe(this.client.get(path));
2506
- }
2507
- async getVariantStock(variantId, locationId) {
2508
- const encodedId = encodeURIComponent(variantId);
2509
- const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
2510
- location_id: locationId
2511
- });
2512
- return safe(this.client.get(path));
2513
- }
2514
- async checkProductAvailability(productId, quantity, locationId) {
2515
- const encodedId = encodeURIComponent(productId);
2516
- const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
2517
- quantity,
2518
- location_id: locationId
2519
- });
2520
- return safe(this.client.get(path));
2521
- }
2522
- async checkVariantAvailability(variantId, quantity, locationId) {
2523
- const encodedId = encodeURIComponent(variantId);
2524
- const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
2525
- quantity,
2526
- location_id: locationId
2527
- });
2528
- return safe(this.client.get(path));
2529
- }
2530
- async checkMultipleAvailability(items, locationId) {
2531
- const results = await Promise.all(
2532
- items.map(
2533
- (item) => item.variant_id ? this.checkVariantAvailability(item.variant_id, item.quantity, locationId) : this.checkProductAvailability(item.product_id, item.quantity, locationId)
2534
- )
2535
- );
2536
- for (const result of results) {
2537
- if (!result.ok) return result;
2538
- }
2539
- return ok(results.map((r) => r.value));
2540
- }
2541
- async isInStock(productId, locationId) {
2542
- const result = await this.checkProductAvailability(productId, 1, locationId);
2543
- if (!result.ok) return result;
2544
- return ok(result.value.is_available);
2545
- }
2546
- async getAvailableQuantity(productId, locationId) {
2547
- const result = await this.getProductStock(productId, locationId);
2548
- if (!result.ok) return result;
2549
- return ok(result.value.available_quantity);
2550
- }
2551
- };
2552
-
2553
- // src/scheduling.ts
2554
- function withQuery2(path, params) {
2555
- const searchParams = new URLSearchParams();
2556
- for (const [key, value] of Object.entries(params)) {
2557
- if (value === void 0) continue;
2558
- searchParams.set(key, String(value));
2559
- }
2560
- const query2 = searchParams.toString();
2561
- return query2 ? `${path}?${query2}` : path;
2562
- }
2563
- function firstScheduledTime(booking) {
2564
- return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
2565
- }
2566
- var SchedulingService = class {
2567
- constructor(client) {
2568
- this.client = client;
2569
- }
2570
- async getServices() {
2571
- return safe(this.client.get("/api/v1/scheduling/services"));
2572
- }
2573
- async getService(serviceId) {
2574
- const encodedId = encodeURIComponent(serviceId);
2575
- return safe(this.client.get(`/api/v1/scheduling/services/${encodedId}`));
2576
- }
2577
- async getAvailableSlots(input) {
2578
- const path = withQuery2("/api/v1/scheduling/slots", {
2579
- service_id: input.service_id,
2580
- date: input.date,
2581
- participant_count: input.participant_count,
2582
- duration_minutes: input.duration_minutes
2583
- });
2584
- return safe(this.client.get(path));
2585
- }
2586
- async checkSlotAvailability(input) {
2587
- const path = withQuery2("/api/v1/scheduling/slots/check", {
2588
- service_id: input.service_id,
2589
- slot_time: input.slot_time,
2590
- duration_minutes: input.duration_minutes,
2591
- participant_count: input.participant_count
2592
- });
2593
- return safe(this.client.get(path));
2594
- }
2595
- async getServiceAvailability(params) {
2596
- const path = withQuery2("/api/v1/scheduling/availability", {
2597
- service_id: params.service_id,
2598
- start_date: params.start_date,
2599
- end_date: params.end_date,
2600
- location_id: params.location_id,
2601
- participant_count: params.participant_count
2602
- });
2603
- return safe(this.client.get(path));
2604
- }
2605
- async getBooking(bookingId) {
2606
- const encodedId = encodeURIComponent(bookingId);
2607
- return safe(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2608
- }
2609
- async getCustomerBookings(customerId) {
2610
- const path = withQuery2("/api/v1/scheduling/bookings", {
2611
- customer_id: customerId
2612
- });
2613
- return safe(this.client.get(path));
2614
- }
2615
- async getUpcomingBookings() {
2616
- const result = await this.getCustomerBookings();
2617
- if (!result.ok) return result;
2618
- const upcoming = result.value.filter((booking) => {
2619
- const status = String(booking.status).toLowerCase();
2620
- return status !== "completed" && status !== "cancelled";
2621
- }).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
2622
- return ok(upcoming);
2623
- }
2624
- async getPastBookings(limit = 10) {
2625
- const result = await this.getCustomerBookings();
2626
- if (!result.ok) return result;
2627
- const past = result.value.filter((booking) => String(booking.status).toLowerCase() === "completed").sort((a, b) => firstScheduledTime(b).localeCompare(firstScheduledTime(a))).slice(0, Math.max(0, limit));
2628
- return ok(past);
2629
- }
2630
- async cancelBooking(input) {
2631
- const encodedId = encodeURIComponent(input.booking_id);
2632
- return safe(
2633
- this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
2634
- reason: input.reason
2635
- })
2636
- );
2637
- }
2638
- async rescheduleBooking(input) {
2639
- return safe(
2640
- this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2641
- );
2642
- }
2643
- async getNextAvailableSlot(serviceId, fromDate) {
2644
- const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2645
- const result = await this.getAvailableSlots({
2646
- service_id: serviceId,
2647
- date
2648
- });
2649
- if (!result.ok) return result;
2650
- return ok(result.value.find((slot) => slot.is_available) || null);
2651
- }
2652
- async hasAvailabilityOn(serviceId, date) {
2653
- const result = await this.getAvailableSlots({
2654
- service_id: serviceId,
2655
- date
2656
- });
2657
- if (!result.ok) return result;
2658
- return ok(result.value.some((slot) => slot.is_available));
2659
- }
2660
- };
2661
-
2662
- // src/lite.ts
2663
- var LiteService = class {
2664
- constructor(client) {
2665
- this.client = client;
2666
- }
2667
- async getBootstrap() {
2668
- return safe(this.client.get("/api/v1/lite/bootstrap"));
2669
- }
2670
- async getTable(tableId) {
2671
- const encodedId = encodeURIComponent(tableId);
2672
- return safe(this.client.get(`/api/v1/lite/tables/${encodedId}`));
2673
- }
2674
- async getMenu() {
2675
- return safe(this.client.get("/api/v1/lite/menu"));
2676
- }
2677
- async getMenuByCategory(categoryId) {
2678
- const encodedId = encodeURIComponent(categoryId);
2679
- return safe(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
2680
- }
2681
- };
2682
-
2683
- // src/fx.ts
2684
- var FxService = class {
2685
- constructor(client) {
2686
- this.client = client;
2687
- }
2688
- async getRate(from, to) {
2689
- const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
2690
- return safe(this.client.get(path));
2691
- }
2692
- async lockQuote(request) {
2693
- return safe(this.client.post("/api/v1/fx/quotes", request));
2694
- }
2695
- };
2696
-
2697
- // src/activity.ts
2698
- var ActivityService = class {
2699
- constructor(client) {
2700
- this.client = client;
2701
- }
2702
- trackProductView(productId, options = {}) {
2703
- const event = {
2704
- type: "product_view",
2705
- product_id: productId,
2706
- product_name: options.productName,
2707
- category_id: options.categoryId,
2708
- price: options.price,
2709
- page_path: options.pagePath ?? currentPath()
2710
- };
2711
- this.sendEvents([event]);
2712
- }
2713
- trackCategoryView(categoryId, options = {}) {
2714
- const event = {
2715
- type: "category_view",
2716
- category_id: categoryId,
2717
- category_name: options.categoryName,
2718
- page_path: options.pagePath ?? currentPath()
2719
- };
2720
- this.sendEvents([event]);
2721
- }
2722
- sendEvents(events) {
2723
- try {
2724
- this.client.post("/api/v1/activity/events", { events }).catch(() => {
2725
- });
2726
- } catch {
2727
- }
2728
- }
2729
- };
2730
- function currentPath() {
2731
- if (typeof window !== "undefined") {
2732
- return window.location.pathname;
2733
- }
2734
- return void 0;
2735
- }
2736
-
2737
- // src/types/elements.ts
2738
- var ELEMENT_TYPES = {
2739
- AUTH: "auth",
2740
- ADDRESS: "address",
2741
- PAYMENT: "payment",
2742
- CHECKOUT: "checkout"
2743
- };
2744
- var MESSAGE_TYPES = {
2745
- INIT: "init",
2746
- SET_TOKEN: "set_token",
2747
- SET_CART: "set_cart",
2748
- GET_DATA: "get_data",
2749
- REFRESH_TOKEN: "refresh_token",
2750
- LOGOUT: "logout",
2751
- PROCESS_CHECKOUT: "process_checkout",
2752
- ABORT_CHECKOUT: "abort_checkout",
2753
- READY: "ready",
2754
- HEIGHT_CHANGE: "height_change",
2755
- AUTHENTICATED: "authenticated",
2756
- REQUIRES_OTP: "requires_otp",
2757
- ERROR: "error",
2758
- ADDRESS_CHANGED: "address_changed",
2759
- ADDRESS_SELECTED: "address_selected",
2760
- PAYMENT_METHOD_SELECTED: "payment_method_selected",
2761
- TOKEN_REFRESHED: "token_refreshed",
2762
- LOGOUT_COMPLETE: "logout_complete",
2763
- CONTACT_PROVIDED: "contact_provided",
2764
- CHECKOUT_STATUS: "checkout_status",
2765
- CHECKOUT_COMPLETE: "checkout_complete",
2766
- ORDER_TYPE_CHANGED: "order_type_changed",
2767
- REQUEST_SUBMIT: "request_submit"
2768
- };
2769
- var EVENT_TYPES = {
2770
- READY: "ready",
2771
- AUTHENTICATED: "authenticated",
2772
- REQUIRES_OTP: "requires_otp",
2773
- ERROR: "error",
2774
- CHANGE: "change",
2775
- BLUR: "blur",
2776
- FOCUS: "focus",
2777
- ORDER_TYPE_CHANGED: "order_type_changed",
2778
- REQUEST_SUBMIT: "request_submit"
2779
- };
2780
-
2781
- // src/elements.ts
2782
- function toCheckoutError(code, message, recoverable) {
2783
- const hint = getErrorHint(code);
2784
- return {
2785
- success: false,
2786
- error: {
2787
- code,
2788
- message,
2789
- recoverable,
2790
- docs_url: hint?.docs_url,
2791
- suggestion: hint?.suggestion
2792
- }
2793
- };
2794
- }
2795
- var DEFAULT_LINK_URL = "https://link.cimplify.io";
2796
- function generateNonce() {
2797
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2798
- return crypto.randomUUID().replace(/-/g, "").slice(0, 16);
2799
- }
2800
- return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
2801
- }
2802
- function isAllowedOrigin(origin) {
2803
- try {
2804
- const url = new URL(origin);
2805
- const hostname = url.hostname;
2806
- if (hostname === "localhost" || hostname === "127.0.0.1") {
2807
- return true;
2808
- }
2809
- if (url.protocol !== "https:") {
2810
- return false;
2811
- }
2812
- return hostname === "cimplify.io" || hostname.endsWith(".cimplify.io");
2813
- } catch {
2814
- return false;
2815
- }
2816
- }
2817
- function parseIframeMessage(data) {
2818
- if (!data || typeof data !== "object") {
2819
- return null;
2820
- }
2821
- const maybeType = data.type;
2822
- if (typeof maybeType !== "string") {
2823
- return null;
2824
- }
2825
- return data;
2826
- }
2827
- var CimplifyElements = class {
2828
- constructor(client, businessId, options = {}) {
2829
- this.elements = /* @__PURE__ */ new Map();
2830
- this.accessToken = null;
2831
- this.accountId = null;
2832
- this.customerId = null;
2833
- this.customerData = null;
2834
- this.addressData = null;
2835
- this.paymentData = null;
2836
- this.checkoutInProgress = false;
2837
- this.activeCheckoutAbort = null;
2838
- this.businessIdResolvePromise = null;
2839
- this.client = client;
2840
- this.businessId = businessId ?? null;
2841
- this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2842
- this.options = options;
2843
- this.boundHandleMessage = this.handleMessage.bind(this);
2844
- if (typeof window !== "undefined") {
2845
- window.addEventListener("message", this.boundHandleMessage);
2846
- }
2847
- }
2848
- debug(...args) {
2849
- if (this.client.isTestMode()) {
2850
- console.debug(...args);
2851
- }
2852
- }
2853
- create(type, options = {}) {
2854
- const existing = this.elements.get(type);
2855
- if (existing) return existing;
2856
- const element = new CimplifyElement(type, this.businessId, this.linkUrl, options, this);
2857
- this.elements.set(type, element);
2858
- return element;
2859
- }
2860
- getElement(type) {
2861
- return this.elements.get(type);
2862
- }
2863
- _removeElement(type, instance) {
2864
- const current = this.elements.get(type);
2865
- if (current === instance) {
2866
- this.elements.delete(type);
2867
- }
2868
- }
2869
- destroy() {
2870
- this.elements.forEach((element) => element.destroy());
2871
- this.elements.clear();
2872
- if (typeof window !== "undefined") {
2873
- window.removeEventListener("message", this.boundHandleMessage);
2874
- }
2875
- }
2876
- async submitCheckout(data) {
2877
- const result = await this.processCheckout({
2878
- cart_id: data.cart_id,
2879
- order_type: data.order_type ?? "delivery",
2880
- location_id: data.location_id,
2881
- notes: data.notes,
2882
- scheduled_time: data.scheduled_time,
2883
- tip_amount: data.tip_amount,
2884
- enroll_in_link: true
2885
- });
2886
- if (result.success) {
2887
- return {
2888
- success: true,
2889
- order: {
2890
- id: result.order?.id || "",
2891
- status: result.order?.status || "unknown",
2892
- total: result.order?.total || ""
2893
- }
2894
- };
2895
- }
2896
- return {
2897
- success: false,
2898
- error: {
2899
- code: result.error?.code || "CHECKOUT_FAILED",
2900
- message: result.error?.message || "Checkout failed"
2901
- }
2902
- };
2903
- }
2904
- processCheckout(options) {
2905
- let abortFn = null;
2906
- const task = (async () => {
2907
- this.debug("[cimplify:checkout] processCheckout called", { cart_id: options.cart_id, order_type: options.order_type, location_id: options.location_id });
2908
- if (this.checkoutInProgress) {
2909
- this.debug("[cimplify:checkout] BLOCKED: already processing");
2910
- return toCheckoutError(
2911
- "ALREADY_PROCESSING",
2912
- "Checkout is already in progress.",
2913
- false
2914
- );
2915
- }
2916
- this.checkoutInProgress = true;
2917
- if (!options.cart_id) {
2918
- this.debug("[cimplify:checkout] BLOCKED: no cart_id");
2919
- this.checkoutInProgress = false;
2920
- return toCheckoutError(
2921
- "INVALID_CART",
2922
- "A valid cart is required before checkout can start.",
2923
- false
2924
- );
2925
- }
2926
- if (!options.order_type) {
2927
- this.debug("[cimplify:checkout] BLOCKED: no order_type");
2928
- this.checkoutInProgress = false;
2929
- return toCheckoutError(
2930
- "ORDER_TYPE_REQUIRED",
2931
- "Order type is required before checkout can start.",
2932
- false
2933
- );
2934
- }
2935
- const checkoutElement = this.elements.get(ELEMENT_TYPES.CHECKOUT) || this.elements.get(ELEMENT_TYPES.PAYMENT);
2936
- if (!checkoutElement) {
2937
- this.debug("[cimplify:checkout] BLOCKED: no checkout element");
2938
- this.checkoutInProgress = false;
2939
- return toCheckoutError(
2940
- "NO_PAYMENT_ELEMENT",
2941
- "Checkout element must be mounted before checkout.",
2942
- false
2943
- );
2944
- }
2945
- if (!checkoutElement.isMounted()) {
2946
- this.debug("[cimplify:checkout] BLOCKED: checkout element not mounted");
2947
- this.checkoutInProgress = false;
2948
- return toCheckoutError(
2949
- "PAYMENT_NOT_MOUNTED",
2950
- "Checkout element must be mounted before checkout.",
2951
- false
2952
- );
2953
- }
2954
- const isUnifiedCheckout = this.elements.has(ELEMENT_TYPES.CHECKOUT);
2955
- if (!isUnifiedCheckout) {
2956
- const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
2957
- if (authElement && !this.accessToken) {
2958
- this.debug("[cimplify:checkout] BLOCKED: auth incomplete");
2959
- this.checkoutInProgress = false;
2960
- return toCheckoutError(
2961
- "AUTH_INCOMPLETE",
2962
- "Authentication must complete before checkout can start.",
2963
- true
2964
- );
2965
- }
2966
- const addressElement = this.elements.get(ELEMENT_TYPES.ADDRESS);
2967
- if (addressElement) {
2968
- this.debug("[cimplify:checkout] getting address data...");
2969
- await addressElement.getData();
2970
- this.debug("[cimplify:checkout] address data resolved", this.addressData);
2971
- }
2972
- await this.hydrateCustomerData();
2973
- }
2974
- this.debug("[cimplify:checkout] customer data hydrated", { customerData: this.customerData, accountId: this.accountId, isUnifiedCheckout });
2975
- const processMessage = {
2976
- type: MESSAGE_TYPES.PROCESS_CHECKOUT,
2977
- cart_id: options.cart_id,
2978
- order_type: options.order_type,
2979
- location_id: options.location_id,
2980
- notes: options.notes,
2981
- scheduled_time: options.scheduled_time,
2982
- tip_amount: options.tip_amount,
2983
- pay_currency: options.pay_currency,
2984
- enroll_in_link: options.enroll_in_link ?? true,
2985
- address: isUnifiedCheckout ? void 0 : this.addressData ?? void 0,
2986
- customer: isUnifiedCheckout ? void 0 : this.customerData ? {
2987
- name: this.customerData.name,
2988
- email: this.customerData.email,
2989
- phone: this.customerData.phone
2990
- } : null,
2991
- account_id: this.accountId ?? void 0,
2992
- customer_id: this.customerId ?? void 0
2993
- };
2994
- const timeoutMs = options.timeout_ms ?? 18e4;
2995
- const paymentWindow = checkoutElement.getContentWindow();
2996
- return new Promise((resolve) => {
2997
- let settled = false;
2998
- const cleanup = () => {
2999
- if (typeof window !== "undefined") {
3000
- window.removeEventListener("message", handleCheckoutMessage);
3001
- }
3002
- clearTimeout(timeout);
3003
- this.checkoutInProgress = false;
3004
- this.activeCheckoutAbort = null;
3005
- };
3006
- const settle = (result) => {
3007
- if (settled) {
3008
- return;
3009
- }
3010
- settled = true;
3011
- cleanup();
3012
- resolve(result);
3013
- };
3014
- const timeout = setTimeout(() => {
3015
- settle(
3016
- toCheckoutError(
3017
- "TIMEOUT",
3018
- "Checkout timed out before receiving a terminal response.",
3019
- true
3020
- )
3021
- );
3022
- }, timeoutMs);
3023
- const handleCheckoutMessage = (event) => {
3024
- if (!isAllowedOrigin(event.origin)) {
3025
- return;
3026
- }
3027
- const message = parseIframeMessage(event.data);
3028
- if (!message) {
3029
- return;
3030
- }
3031
- if (message.type === MESSAGE_TYPES.LOGOUT_COMPLETE) {
3032
- checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
3033
- settle(
3034
- toCheckoutError(
3035
- "AUTH_LOST",
3036
- "Authentication was cleared during checkout.",
3037
- true
3038
- )
3039
- );
3040
- return;
3041
- }
3042
- if (paymentWindow && event.source && event.source !== paymentWindow) {
3043
- return;
3044
- }
3045
- if (message.type === MESSAGE_TYPES.CHECKOUT_STATUS) {
3046
- options.on_status_change?.(message.status, message.context);
3047
- return;
3048
- }
3049
- if (message.type === MESSAGE_TYPES.CHECKOUT_COMPLETE) {
3050
- this.debug("[cimplify:checkout] received checkout_complete", { success: message.success, error: message.error });
3051
- settle({
3052
- success: message.success,
3053
- order: message.order,
3054
- error: message.error,
3055
- enrolled_in_link: message.enrolled_in_link
3056
- });
3057
- }
3058
- };
3059
- if (typeof window !== "undefined") {
3060
- window.addEventListener("message", handleCheckoutMessage);
3061
- }
3062
- abortFn = () => {
3063
- checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
3064
- settle(
3065
- toCheckoutError(
3066
- "CANCELLED",
3067
- "Checkout was cancelled.",
3068
- true
3069
- )
3070
- );
3071
- };
3072
- this.activeCheckoutAbort = abortFn;
3073
- this.debug("[cimplify:checkout] sending process_checkout to checkout iframe", { cart_id: processMessage.cart_id, order_type: processMessage.order_type, hasCustomer: !!processMessage.customer, hasAddress: !!processMessage.address, isUnifiedCheckout });
3074
- checkoutElement.sendMessage(processMessage);
3075
- this.debug("[cimplify:checkout] postMessage sent, waiting for checkout_complete...");
3076
- });
3077
- })();
3078
- const abortable = task;
3079
- abortable.abort = () => {
3080
- if (abortFn) {
3081
- abortFn();
3082
- }
3083
- };
3084
- return abortable;
3085
- }
3086
- isAuthenticated() {
3087
- return this.accessToken !== null;
3088
- }
3089
- getAccessToken() {
3090
- return this.accessToken;
3091
- }
3092
- getPublicKey() {
3093
- return this.client.getPublicKey();
3094
- }
3095
- getBusinessId() {
3096
- return this.businessId;
3097
- }
3098
- async resolveBusinessId() {
3099
- if (this.businessId) {
3100
- return this.businessId;
3101
- }
3102
- if (this.businessIdResolvePromise) {
3103
- return this.businessIdResolvePromise;
3104
- }
3105
- this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
3106
- this.businessId = resolvedBusinessId;
3107
- return resolvedBusinessId;
3108
- }).catch(() => null).finally(() => {
3109
- this.businessIdResolvePromise = null;
3110
- });
3111
- return this.businessIdResolvePromise;
3112
- }
3113
- getAppearance() {
3114
- return this.options.appearance;
3115
- }
3116
- async hydrateCustomerData() {
3117
- if (!this.accessToken || this.customerData) {
3118
- return;
3119
- }
3120
- if (!this.client.getAccessToken()) {
3121
- this.client.setAccessToken(this.accessToken);
3122
- }
3123
- const linkDataResult = await this.client.link.getLinkData();
3124
- if (!linkDataResult.ok || !linkDataResult.value?.customer) {
3125
- return;
3126
- }
3127
- const customer = linkDataResult.value.customer;
3128
- this.customerData = {
3129
- name: customer.name || "",
3130
- email: customer.email || null,
3131
- phone: customer.phone || null
3132
- };
3133
- }
3134
- handleMessage(event) {
3135
- if (!isAllowedOrigin(event.origin)) {
3136
- return;
3137
- }
3138
- const message = parseIframeMessage(event.data);
3139
- if (!message) return;
3140
- switch (message.type) {
3141
- case MESSAGE_TYPES.AUTHENTICATED:
3142
- const customer = message.customer ?? {
3143
- name: "",
3144
- email: null,
3145
- phone: null
3146
- };
3147
- this.accessToken = message.token;
3148
- this.accountId = message.accountId;
3149
- this.customerId = message.customerId;
3150
- this.customerData = customer;
3151
- this.client.setAccessToken(message.token);
3152
- this.elements.forEach((element, type) => {
3153
- if (type !== ELEMENT_TYPES.AUTH && type !== ELEMENT_TYPES.CHECKOUT) {
3154
- element.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token: message.token });
3155
- }
3156
- });
3157
- break;
3158
- case MESSAGE_TYPES.TOKEN_REFRESHED:
3159
- this.accessToken = message.token;
3160
- break;
3161
- case MESSAGE_TYPES.ADDRESS_CHANGED:
3162
- case MESSAGE_TYPES.ADDRESS_SELECTED:
3163
- this.addressData = message.address;
3164
- break;
3165
- case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
3166
- this.paymentData = message.method;
3167
- break;
3168
- case MESSAGE_TYPES.CONTACT_PROVIDED:
3169
- if (!this.customerData) {
3170
- this.customerData = { name: "", email: null, phone: null };
3171
- }
3172
- if (message.contactType === "email") {
3173
- this.customerData.email = message.contact;
3174
- } else {
3175
- this.customerData.phone = message.contact;
3176
- }
3177
- break;
3178
- case MESSAGE_TYPES.LOGOUT_COMPLETE:
3179
- if (this.checkoutInProgress && this.activeCheckoutAbort) {
3180
- this.activeCheckoutAbort();
3181
- }
3182
- this.accessToken = null;
3183
- this.accountId = null;
3184
- this.customerId = null;
3185
- this.customerData = null;
3186
- this.addressData = null;
3187
- this.paymentData = null;
3188
- this.client.clearSession();
3189
- break;
3190
- }
3191
- }
3192
- _setAddressData(data) {
3193
- this.addressData = data;
3194
- }
3195
- _setPaymentData(data) {
3196
- this.paymentData = data;
3197
- }
3198
- _setGuestContact(contact, contactType) {
3199
- if (!this.customerData) {
3200
- this.customerData = { name: "", email: null, phone: null };
3201
- }
3202
- if (contactType === "email") {
3203
- this.customerData.email = contact;
3204
- } else {
3205
- this.customerData.phone = contact;
3206
- }
3207
- }
3208
- };
3209
- var CimplifyElement = class {
3210
- constructor(type, businessId, linkUrl, options, parent) {
3211
- this.iframe = null;
3212
- this.container = null;
3213
- this.mounted = false;
3214
- this.pendingInit = null;
3215
- this.eventHandlers = /* @__PURE__ */ new Map();
3216
- this.resolvers = /* @__PURE__ */ new Map();
3217
- this.listening = false;
3218
- this.type = type;
3219
- this.businessId = businessId;
3220
- this.linkUrl = linkUrl;
3221
- this.options = options;
3222
- this.parent = parent;
3223
- this.nonce = generateNonce();
3224
- this.boundHandleMessage = this.handleMessage.bind(this);
3225
- if (typeof window !== "undefined") {
3226
- window.addEventListener("message", this.boundHandleMessage);
3227
- this.listening = true;
3228
- }
3229
- }
3230
- mount(container) {
3231
- if (this.mounted) {
3232
- console.warn(`Element ${this.type} is already mounted`);
3233
- return;
3234
- }
3235
- const target = typeof container === "string" ? document.querySelector(container) : container;
3236
- if (!target) {
3237
- console.error(`Container not found: ${container}`);
3238
- return;
3239
- }
3240
- this.container = target;
3241
- this.mounted = true;
3242
- if (!this.listening && typeof window !== "undefined") {
3243
- window.addEventListener("message", this.boundHandleMessage);
3244
- this.listening = true;
3245
- }
3246
- void this.createIframe();
3247
- }
3248
- destroy() {
3249
- if (this.iframe) {
3250
- this.iframe.remove();
3251
- this.iframe = null;
3252
- }
3253
- this.container = null;
3254
- this.mounted = false;
3255
- this.eventHandlers.clear();
3256
- this.resolvers.forEach((entry) => clearTimeout(entry.timeoutId));
3257
- this.resolvers.clear();
3258
- if (this.listening && typeof window !== "undefined") {
3259
- window.removeEventListener("message", this.boundHandleMessage);
3260
- this.listening = false;
3261
- }
3262
- this.parent._removeElement(this.type, this);
3263
- }
3264
- on(event, handler) {
3265
- if (!this.eventHandlers.has(event)) {
3266
- this.eventHandlers.set(event, /* @__PURE__ */ new Set());
3267
- }
3268
- this.eventHandlers.get(event).add(handler);
3269
- }
3270
- off(event, handler) {
3271
- this.eventHandlers.get(event)?.delete(handler);
3272
- }
3273
- async getData() {
3274
- if (!this.isMounted()) {
3275
- return null;
3276
- }
3277
- return new Promise((resolve) => {
3278
- const id = Math.random().toString(36).slice(2);
3279
- const timeoutId = setTimeout(() => {
3280
- const entry = this.resolvers.get(id);
3281
- if (!entry) {
3282
- return;
3283
- }
3284
- this.resolvers.delete(id);
3285
- entry.resolve(null);
3286
- }, 5e3);
3287
- this.resolvers.set(id, { resolve, timeoutId });
3288
- this.sendMessage({ type: MESSAGE_TYPES.GET_DATA });
3289
- });
3290
- }
3291
- setCart(cart) {
3292
- this.sendMessage({ type: MESSAGE_TYPES.SET_CART, cart });
3293
- }
3294
- sendMessage(message) {
3295
- if (this.iframe?.contentWindow) {
3296
- this.iframe.contentWindow.postMessage(message, this.linkUrl);
3297
- } else {
3298
- console.warn("[cimplify:checkout] sendMessage DROPPED \u2014 no contentWindow", { type: message.type, hasIframe: !!this.iframe, isConnected: this.iframe?.isConnected });
3299
- }
3300
- }
3301
- getContentWindow() {
3302
- return this.iframe?.contentWindow ?? null;
3303
- }
3304
- isMounted() {
3305
- return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
3306
- }
3307
- async createIframe() {
3308
- if (!this.container) return;
3309
- const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
3310
- if (!resolvedBusinessId || !this.container || !this.mounted) {
3311
- console.error("Unable to mount element without a resolved business ID");
3312
- this.emit(EVENT_TYPES.ERROR, {
3313
- code: "BUSINESS_ID_REQUIRED",
3314
- message: "Unable to initialize checkout without a business ID."
3315
- });
3316
- return;
3317
- }
3318
- this.businessId = resolvedBusinessId;
3319
- const iframe = document.createElement("iframe");
3320
- const url = new URL(`${this.linkUrl}/elements/${this.type}`);
3321
- url.searchParams.set("businessId", resolvedBusinessId);
3322
- url.searchParams.set("nonce", this.nonce);
3323
- if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
3324
- if (this.options.mode) url.searchParams.set("mode", this.options.mode);
3325
- iframe.src = url.toString();
3326
- iframe.style.border = "none";
3327
- iframe.style.width = "100%";
3328
- iframe.style.minHeight = "200px";
3329
- iframe.style.display = "block";
3330
- iframe.style.overflow = "hidden";
3331
- iframe.style.background = "transparent";
3332
- iframe.setAttribute("allowtransparency", "true");
3333
- iframe.setAttribute("frameborder", "0");
3334
- iframe.setAttribute("allow", "geolocation");
3335
- iframe.setAttribute(
3336
- "sandbox",
3337
- "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
3338
- );
3339
- this.iframe = iframe;
3340
- this.container.appendChild(iframe);
3341
- this.pendingInit = {
3342
- businessId: resolvedBusinessId,
3343
- publicKey: this.parent.getPublicKey()
3344
- };
3345
- }
3346
- handleMessage(event) {
3347
- if (!isAllowedOrigin(event.origin)) {
3348
- return;
3349
- }
3350
- const data = event.data;
3351
- if (data?.nonce) {
3352
- if (data.nonce !== this.nonce) return;
3353
- } else {
3354
- const iframeWindow = this.iframe?.contentWindow;
3355
- if (iframeWindow && event.source && event.source !== iframeWindow) {
3356
- return;
3357
- }
3358
- }
3359
- const message = parseIframeMessage(event.data);
3360
- if (!message) return;
3361
- switch (message.type) {
3362
- case MESSAGE_TYPES.READY:
3363
- if (this.iframe && message.height) this.iframe.style.height = `${message.height}px`;
3364
- if (this.pendingInit) {
3365
- const { publicKey } = this.pendingInit;
3366
- this.sendMessage({
3367
- type: MESSAGE_TYPES.INIT,
3368
- businessId: this.pendingInit.businessId,
3369
- publicKey,
3370
- demoMode: publicKey.length === 0,
3371
- prefillEmail: this.options.prefillEmail,
3372
- appearance: this.parent.getAppearance(),
3373
- orderTypes: this.options.orderTypes,
3374
- defaultOrderType: this.options.defaultOrderType,
3375
- renderSubmitButton: true,
3376
- submitLabel: this.options.submitLabel
3377
- });
3378
- const token = this.parent.getAccessToken();
3379
- if (token && this.type !== ELEMENT_TYPES.AUTH) {
3380
- this.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token });
3381
- }
3382
- this.pendingInit = null;
3383
- }
3384
- this.emit(EVENT_TYPES.READY, { height: message.height });
3385
- break;
3386
- case MESSAGE_TYPES.HEIGHT_CHANGE:
3387
- if (this.iframe) this.iframe.style.height = `${message.height}px`;
3388
- break;
3389
- case MESSAGE_TYPES.AUTHENTICATED:
3390
- const customer = message.customer ?? {
3391
- name: "",
3392
- email: null,
3393
- phone: null
3394
- };
3395
- this.emit(EVENT_TYPES.AUTHENTICATED, {
3396
- accountId: message.accountId,
3397
- customerId: message.customerId,
3398
- token: message.token,
3399
- customer
3400
- });
3401
- break;
3402
- case MESSAGE_TYPES.REQUIRES_OTP:
3403
- this.emit(EVENT_TYPES.REQUIRES_OTP, { contactMasked: message.contactMasked });
3404
- break;
3405
- case MESSAGE_TYPES.ERROR:
3406
- this.emit(EVENT_TYPES.ERROR, { code: message.code, message: message.message });
3407
- break;
3408
- case MESSAGE_TYPES.ADDRESS_CHANGED:
3409
- case MESSAGE_TYPES.ADDRESS_SELECTED:
3410
- this.parent._setAddressData(message.address);
3411
- this.emit(EVENT_TYPES.CHANGE, { address: message.address });
3412
- this.resolveData(message.address);
3413
- break;
3414
- case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
3415
- this.parent._setPaymentData(message.method);
3416
- this.emit(EVENT_TYPES.CHANGE, { paymentMethod: message.method });
3417
- this.resolveData(message.method);
3418
- break;
3419
- case MESSAGE_TYPES.CONTACT_PROVIDED:
3420
- this.parent._setGuestContact(message.contact, message.contactType);
3421
- break;
3422
- case MESSAGE_TYPES.ORDER_TYPE_CHANGED:
3423
- this.emit(EVENT_TYPES.ORDER_TYPE_CHANGED, { orderType: message.orderType });
3424
- break;
3425
- case MESSAGE_TYPES.REQUEST_SUBMIT:
3426
- this.emit(EVENT_TYPES.REQUEST_SUBMIT, {});
3427
- break;
3428
- }
3429
- }
3430
- emit(event, data) {
3431
- this.eventHandlers.get(event)?.forEach((handler) => handler(data));
3432
- }
3433
- resolveData(data) {
3434
- this.resolvers.forEach((entry) => {
3435
- clearTimeout(entry.timeoutId);
3436
- entry.resolve(data);
3437
- });
3438
- this.resolvers.clear();
3439
- }
3440
- };
3441
- function createElements(client, businessId, options) {
3442
- return new CimplifyElements(client, businessId, options);
3443
- }
3444
-
3445
- // src/client.ts
3446
- var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3447
- var SESSION_TOKEN_STORAGE_KEY = "cimplify_session_token";
3448
- var ORDER_TOKEN_PREFIX = "cimplify_ot_";
3449
- var SESSION_TOKEN_HEADER = "x-session-token";
3450
- var ORDER_TOKEN_TTL_MS = 24 * 60 * 60 * 1e3;
3451
- var DEFAULT_TIMEOUT_MS = 3e4;
3452
- var DEFAULT_MAX_RETRIES = 3;
3453
- var DEFAULT_RETRY_DELAY_MS = 1e3;
3454
- function sleep(ms) {
3455
- return new Promise((resolve) => setTimeout(resolve, ms));
3456
- }
3457
- function isRetryable(error) {
3458
- if (error instanceof TypeError && error.message.includes("fetch")) {
3459
- return true;
3460
- }
3461
- if (error instanceof DOMException && error.name === "AbortError") {
3462
- return true;
3463
- }
3464
- if (error instanceof CimplifyError) {
3465
- return error.retryable;
3466
- }
3467
- return false;
3468
- }
3469
- function toNetworkError(error, isTestMode) {
3470
- if (error instanceof DOMException && error.name === "AbortError") {
3471
- return enrichError(
3472
- new CimplifyError(
3473
- ErrorCode.TIMEOUT,
3474
- "Request timed out. Please check your connection and try again.",
3475
- true
3476
- ),
3477
- { isTestMode }
3478
- );
3479
- }
3480
- if (error instanceof TypeError && error.message.includes("fetch")) {
3481
- return enrichError(
3482
- new CimplifyError(
3483
- ErrorCode.NETWORK_ERROR,
3484
- "Network error. Please check your internet connection.",
3485
- true
3486
- ),
3487
- { isTestMode }
3488
- );
3489
- }
3490
- if (error instanceof CimplifyError) {
3491
- return enrichError(error, { isTestMode });
3492
- }
3493
- return enrichError(
3494
- new CimplifyError(
3495
- ErrorCode.UNKNOWN_ERROR,
3496
- error instanceof Error ? error.message : "An unknown error occurred",
3497
- false
3498
- ),
3499
- { isTestMode }
3500
- );
3501
- }
3502
- function deriveUrls() {
3503
- const hostname = typeof window !== "undefined" ? window.location.hostname : "";
3504
- if (hostname === "localhost" || hostname === "127.0.0.1") {
3505
- const protocol = window.location.protocol;
3506
- return {
3507
- baseUrl: `${protocol}//${hostname}:8082`,
3508
- linkApiUrl: `${protocol}//${hostname}:8080`
3509
- };
3510
- }
3511
- return {
3512
- baseUrl: "https://storefronts.cimplify.io",
3513
- linkApiUrl: "https://api.cimplify.io"
3514
- };
3515
- }
3516
- function normalizeUrl(url) {
3517
- const trimmed = url.trim();
3518
- if (!trimmed) return trimmed;
3519
- return trimmed.replace(/\/+$/, "");
3520
- }
3521
- function getEnvPublicKey() {
3522
- try {
3523
- const env = globalThis.process;
3524
- return env?.env.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || void 0;
3525
- } catch {
3526
- return void 0;
3527
- }
3528
- }
3529
- var CimplifyClient = class {
3530
- constructor(config = {}) {
3531
- this.accessToken = null;
3532
- this.sessionToken = null;
3533
- this.context = {};
3534
- this.businessId = null;
3535
- this.businessIdResolvePromise = null;
3536
- this.inflightRequests = /* @__PURE__ */ new Map();
3537
- this.publicKey = config.publicKey || getEnvPublicKey() || "";
3538
- const urls = deriveUrls();
3539
- this.baseUrl = config.baseUrl ? normalizeUrl(config.baseUrl) : urls.baseUrl;
3540
- this.linkApiUrl = config.linkApiUrl ? normalizeUrl(config.linkApiUrl) : urls.linkApiUrl;
3541
- this.credentials = config.credentials || "include";
3542
- this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
3543
- this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
3544
- this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
3545
- this.hooks = config.hooks ?? {};
3546
- this.accessToken = this.loadAccessToken();
3547
- this.sessionToken = this.loadSessionToken();
3548
- if (!this.publicKey && !config.suppressPublicKeyWarning) {
3549
- console.warn(
3550
- '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "pk_..." } to createCimplifyClient().'
3551
- );
3552
- }
3553
- }
3554
- buildUrl(base, path) {
3555
- const url = `${base}${path}`;
3556
- const locationId = this.context.location_id;
3557
- if (!locationId) return url;
3558
- const separator = url.includes("?") ? "&" : "?";
3559
- return `${url}${separator}location_id=${encodeURIComponent(locationId)}`;
3560
- }
3561
- getAccessToken() {
3562
- return this.accessToken;
3563
- }
3564
- getPublicKey() {
3565
- return this.publicKey;
3566
- }
3567
- isTestMode() {
3568
- return this.publicKey.trim().startsWith("pk_test_");
3569
- }
3570
- setAccessToken(token) {
3571
- const previous = this.accessToken;
3572
- this.accessToken = token;
3573
- this.saveAccessToken(token);
3574
- this.hooks.onSessionChange?.({
3575
- previousToken: previous,
3576
- newToken: token,
3577
- source: "manual"
3578
- });
3579
- }
3580
- clearSession() {
3581
- const previous = this.accessToken;
3582
- this.accessToken = null;
3583
- this.sessionToken = null;
3584
- this.saveAccessToken(null);
3585
- if (typeof window !== "undefined" && window.localStorage) {
3586
- localStorage.removeItem(SESSION_TOKEN_STORAGE_KEY);
3587
- }
3588
- this.hooks.onSessionChange?.({
3589
- previousToken: previous,
3590
- newToken: null,
3591
- source: "clear"
3592
- });
3593
- }
3594
- setOrderToken(orderId, token) {
3595
- if (typeof window !== "undefined" && window.localStorage) {
3596
- try {
3597
- const entry = JSON.stringify({ token, storedAt: Date.now() });
3598
- localStorage.setItem(`${ORDER_TOKEN_PREFIX}${orderId}`, entry);
3599
- } catch {
3600
- }
3601
- }
3602
- }
3603
- getOrderToken(orderId) {
3604
- if (typeof window !== "undefined" && window.localStorage) {
3605
- try {
3606
- const raw = localStorage.getItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
3607
- if (!raw) return null;
3608
- const entry = JSON.parse(raw);
3609
- if (Date.now() - entry.storedAt > ORDER_TOKEN_TTL_MS) {
3610
- localStorage.removeItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
3611
- return null;
3612
- }
3613
- return entry.token;
3614
- } catch {
3615
- return null;
3616
- }
3617
- }
3618
- return null;
3619
- }
3620
- clearOrderTokens() {
3621
- if (typeof window !== "undefined" && window.localStorage) {
3622
- const keysToRemove = [];
3623
- for (let i = 0; i < localStorage.length; i++) {
3624
- const key = localStorage.key(i);
3625
- if (key?.startsWith(ORDER_TOKEN_PREFIX)) {
3626
- keysToRemove.push(key);
3627
- }
3628
- }
3629
- keysToRemove.forEach((k) => localStorage.removeItem(k));
3630
- }
3631
- }
3632
- setLocationId(locationId) {
3633
- if (locationId) {
3634
- this.context.location_id = locationId;
3635
- } else {
3636
- delete this.context.location_id;
3637
- }
3638
- }
3639
- getLocationId() {
3640
- return this.context.location_id ?? null;
3641
- }
3642
- setBusinessId(businessId) {
3643
- const normalized = businessId.trim();
3644
- if (!normalized) {
3645
- return;
3646
- }
3647
- this.businessId = normalized;
3648
- }
3649
- getBusinessId() {
3650
- return this.businessId;
3651
- }
3652
- async resolveBusinessId() {
3653
- if (this.businessId) {
3654
- return this.businessId;
3655
- }
3656
- if (this.businessIdResolvePromise) {
3657
- return this.businessIdResolvePromise;
3658
- }
3659
- this.businessIdResolvePromise = (async () => {
3660
- const result = await this.business.getInfo();
3661
- if (!result.ok || !result.value?.id) {
3662
- throw new CimplifyError(
3663
- ErrorCode.NOT_FOUND,
3664
- "Unable to resolve business ID from the current public key.",
3665
- true
3666
- );
3667
- }
3668
- this.businessId = result.value.id;
3669
- return result.value.id;
3670
- })();
3671
- try {
3672
- return await this.businessIdResolvePromise;
3673
- } finally {
3674
- this.businessIdResolvePromise = null;
3675
- }
3676
- }
3677
- loadAccessToken() {
3678
- if (typeof window !== "undefined" && window.localStorage) {
3679
- return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
3680
- }
3681
- return null;
3682
- }
3683
- saveAccessToken(token) {
3684
- if (typeof window !== "undefined" && window.localStorage) {
3685
- try {
3686
- if (token) {
3687
- localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, token);
3688
- } else {
3689
- localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
3690
- }
3691
- } catch {
3692
- }
3693
- }
3694
- }
3695
- loadSessionToken() {
3696
- if (typeof window !== "undefined" && window.localStorage) {
3697
- return localStorage.getItem(SESSION_TOKEN_STORAGE_KEY);
3698
- }
3699
- return null;
3700
- }
3701
- saveSessionToken(token) {
3702
- if (typeof window !== "undefined" && window.localStorage) {
3703
- try {
3704
- localStorage.setItem(SESSION_TOKEN_STORAGE_KEY, token);
3705
- } catch {
3706
- }
3707
- }
3708
- }
3709
- captureSessionToken(response) {
3710
- const token = response.headers.get(SESSION_TOKEN_HEADER);
3711
- if (token && token !== this.sessionToken) {
3712
- this.sessionToken = token;
3713
- this.saveSessionToken(token);
3714
- }
3715
- }
3716
- getHeaders() {
3717
- const headers = {
3718
- "Content-Type": "application/json"
3719
- };
3720
- const trimmedPublicKey = this.publicKey.trim();
3721
- if (trimmedPublicKey) {
3722
- headers["X-API-Key"] = trimmedPublicKey;
3723
- }
3724
- if (this.accessToken) {
3725
- headers["Authorization"] = `Bearer ${this.accessToken}`;
3726
- }
3727
- if (this.sessionToken) {
3728
- headers[SESSION_TOKEN_HEADER] = this.sessionToken;
3729
- }
3730
- return headers;
3731
- }
3732
- async resilientFetch(url, options) {
3733
- const method = options.method || "GET";
3734
- const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
3735
- const startTime = Date.now();
3736
- let retryCount = 0;
3737
- const context = {
3738
- method,
3739
- path,
3740
- url,
3741
- body: options.body ? JSON.parse(options.body) : void 0,
3742
- startTime
3743
- };
3744
- this.hooks.onRequestStart?.(context);
3745
- let lastError;
3746
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
3747
- try {
3748
- const controller = new AbortController();
3749
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
3750
- const response = await fetch(url, {
3751
- ...options,
3752
- signal: controller.signal
3753
- });
3754
- clearTimeout(timeoutId);
3755
- this.captureSessionToken(response);
3756
- if (response.ok) {
3757
- this.hooks.onRequestSuccess?.({
3758
- ...context,
3759
- status: response.status,
3760
- durationMs: Date.now() - startTime
3761
- });
3762
- return response;
3763
- }
3764
- if (response.status === 429 && attempt < this.maxRetries) {
3765
- retryCount++;
3766
- const retryAfter = response.headers.get("Retry-After");
3767
- const delay = retryAfter ? Math.min(parseInt(retryAfter, 10) * 1e3, 3e4) || this.retryDelay * Math.pow(2, attempt) : this.retryDelay * Math.pow(2, attempt);
3768
- this.hooks.onRetry?.({
3769
- ...context,
3770
- attempt: retryCount,
3771
- delayMs: delay,
3772
- error: new Error(`Rate limited: ${response.status}`)
3773
- });
3774
- await sleep(delay);
3775
- continue;
3776
- }
3777
- if (response.status >= 400 && response.status < 500) {
3778
- this.hooks.onRequestError?.({
3779
- ...context,
3780
- error: new CimplifyError(
3781
- `HTTP_${response.status}`,
3782
- `Request failed with status ${response.status}`,
3783
- false
3784
- ),
3785
- status: response.status,
3786
- durationMs: Date.now() - startTime,
3787
- retryCount,
3788
- retryable: false
3789
- });
3790
- return response;
3791
- }
3792
- if (response.status >= 500 && attempt < this.maxRetries) {
3793
- retryCount++;
3794
- const delay = this.retryDelay * Math.pow(2, attempt);
3795
- this.hooks.onRetry?.({
3796
- ...context,
3797
- attempt: retryCount,
3798
- delayMs: delay,
3799
- error: new Error(`Server error: ${response.status}`)
3800
- });
3801
- await sleep(delay);
3802
- continue;
3803
- }
3804
- this.hooks.onRequestError?.({
3805
- ...context,
3806
- error: new CimplifyError(
3807
- "SERVER_ERROR",
3808
- `Server error ${response.status} after ${retryCount} retries`,
3809
- false
3810
- ),
3811
- status: response.status,
3812
- durationMs: Date.now() - startTime,
3813
- retryCount,
3814
- retryable: false
3815
- });
3816
- return response;
3817
- } catch (error) {
3818
- lastError = error;
3819
- const networkError = toNetworkError(error, this.isTestMode());
3820
- const errorRetryable = isRetryable(error);
3821
- if (!errorRetryable || attempt >= this.maxRetries) {
3822
- this.hooks.onRequestError?.({
3823
- ...context,
3824
- error: networkError,
3825
- durationMs: Date.now() - startTime,
3826
- retryCount,
3827
- retryable: errorRetryable
3828
- });
3829
- throw networkError;
3830
- }
3831
- retryCount++;
3832
- const delay = this.retryDelay * Math.pow(2, attempt);
3833
- this.hooks.onRetry?.({
3834
- ...context,
3835
- attempt: retryCount,
3836
- delayMs: delay,
3837
- error: networkError
3838
- });
3839
- await sleep(delay);
3840
- }
3841
- }
3842
- const finalError = toNetworkError(lastError, this.isTestMode());
3843
- this.hooks.onRequestError?.({
3844
- ...context,
3845
- error: finalError,
3846
- durationMs: Date.now() - startTime,
3847
- retryCount,
3848
- retryable: false
3849
- });
3850
- throw finalError;
3851
- }
3852
- getDedupeKey(type, payload) {
3853
- return `${type}:${JSON.stringify(payload)}`;
3854
- }
3855
- async deduplicatedRequest(key, requestFn) {
3856
- const existing = this.inflightRequests.get(key);
3857
- if (existing) {
3858
- return existing;
3859
- }
3860
- const request = requestFn().finally(() => {
3861
- this.inflightRequests.delete(key);
3862
- });
3863
- this.inflightRequests.set(key, request);
3864
- return request;
3865
- }
3866
- async get(path) {
3867
- const key = this.getDedupeKey("get", path);
3868
- return this.deduplicatedRequest(key, async () => {
3869
- const response = await this.resilientFetch(this.buildUrl(this.baseUrl, path), {
3870
- method: "GET",
3871
- credentials: this.credentials,
3872
- headers: this.getHeaders()
3873
- });
3874
- return this.handleRestResponse(response);
3875
- });
3876
- }
3877
- async post(path, body) {
3878
- const response = await this.resilientFetch(this.buildUrl(this.baseUrl, path), {
3879
- method: "POST",
3880
- credentials: this.credentials,
3881
- headers: this.getHeaders(),
3882
- body: body ? JSON.stringify(body) : void 0
3883
- });
3884
- return this.handleRestResponse(response);
3885
- }
3886
- async patch(path, body) {
3887
- const response = await this.resilientFetch(this.buildUrl(this.baseUrl, path), {
3888
- method: "PATCH",
3889
- credentials: this.credentials,
3890
- headers: this.getHeaders(),
3891
- body: body ? JSON.stringify(body) : void 0
3892
- });
3893
- return this.handleRestResponse(response);
3894
- }
3895
- async delete(path) {
3896
- const response = await this.resilientFetch(this.buildUrl(this.baseUrl, path), {
3897
- method: "DELETE",
3898
- credentials: this.credentials,
3899
- headers: this.getHeaders()
3900
- });
3901
- return this.handleRestResponse(response);
3902
- }
3903
- async linkGet(path) {
3904
- const key = this.getDedupeKey("linkGet", path);
3905
- return this.deduplicatedRequest(key, async () => {
3906
- const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3907
- method: "GET",
3908
- credentials: this.credentials,
3909
- headers: this.getHeaders()
3910
- });
3911
- return this.handleRestResponse(response);
3912
- });
3913
- }
3914
- async linkPost(path, body) {
3915
- const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3916
- method: "POST",
3917
- credentials: this.credentials,
3918
- headers: this.getHeaders(),
3919
- body: body ? JSON.stringify(body) : void 0
3920
- });
3921
- return this.handleRestResponse(response);
3922
- }
3923
- async linkDelete(path) {
3924
- const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3925
- method: "DELETE",
3926
- credentials: this.credentials,
3927
- headers: this.getHeaders()
3928
- });
3929
- return this.handleRestResponse(response);
3930
- }
3931
- async handleRestResponse(response) {
3932
- const json = await response.json();
3933
- if (!response.ok) {
3934
- const errorCode = typeof json.error === "object" && json.error?.error_code || typeof json.error === "object" && json.error?.code || "API_ERROR";
3935
- const errorMessage = typeof json.error === "object" && json.error?.error_message || typeof json.error === "object" && json.error?.message || typeof json.error === "string" && json.error || typeof json.message === "string" && json.message || "An error occurred";
3936
- const retryable = typeof json.error === "object" && typeof json.error?.retryable === "boolean" ? json.error.retryable : false;
3937
- const error = enrichError(
3938
- new CimplifyError(
3939
- errorCode,
3940
- errorMessage,
3941
- retryable
3942
- ),
3943
- { isTestMode: this.isTestMode() }
3944
- );
3945
- if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
3946
- console.warn(
3947
- "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
3948
- );
3949
- }
3950
- throw error;
3951
- }
3952
- if (json?.success === false || json?.error?.code || json?.error?.message) {
3953
- const error = enrichError(
3954
- new CimplifyError(
3955
- json.error?.code || "API_ERROR",
3956
- json.error?.message || "An error occurred",
3957
- json.error?.retryable || false
3958
- ),
3959
- { isTestMode: this.isTestMode() }
3960
- );
3961
- throw error;
3962
- }
3963
- if (json?.data !== void 0) {
3964
- return json.data;
3965
- }
3966
- return json;
3967
- }
3968
- get catalogue() {
3969
- if (!this._catalogue) {
3970
- this._catalogue = new CatalogueQueries(this);
3971
- }
3972
- return this._catalogue;
3973
- }
3974
- get cart() {
3975
- if (!this._cart) {
3976
- this._cart = new CartOperations(this);
3977
- }
3978
- return this._cart;
3979
- }
3980
- get checkout() {
3981
- if (!this._checkout) {
3982
- this._checkout = new CheckoutService(this);
3983
- }
3984
- return this._checkout;
3985
- }
3986
- get orders() {
3987
- if (!this._orders) {
3988
- this._orders = new OrderQueries(this);
3989
- }
3990
- return this._orders;
3991
- }
3992
- get link() {
3993
- if (!this._link) {
3994
- this._link = new LinkService(this);
3995
- }
3996
- return this._link;
3997
- }
3998
- get auth() {
3999
- if (!this._auth) {
4000
- this._auth = new AuthService(this);
4001
- }
4002
- return this._auth;
4003
- }
4004
- get business() {
4005
- if (!this._business) {
4006
- this._business = new BusinessService(this);
4007
- }
4008
- return this._business;
4009
- }
4010
- get inventory() {
4011
- if (!this._inventory) {
4012
- this._inventory = new InventoryService(this);
4013
- }
4014
- return this._inventory;
4015
- }
4016
- get scheduling() {
4017
- if (!this._scheduling) {
4018
- this._scheduling = new SchedulingService(this);
4019
- }
4020
- return this._scheduling;
4021
- }
4022
- get lite() {
4023
- if (!this._lite) {
4024
- this._lite = new LiteService(this);
4025
- }
4026
- return this._lite;
4027
- }
4028
- get fx() {
4029
- if (!this._fx) {
4030
- this._fx = new FxService(this);
4031
- }
4032
- return this._fx;
4033
- }
4034
- get activity() {
4035
- if (!this._activity) {
4036
- this._activity = new ActivityService(this);
4037
- }
4038
- return this._activity;
4039
- }
4040
- elements(businessId, options) {
4041
- if (businessId) {
4042
- this.setBusinessId(businessId);
4043
- }
4044
- return createElements(this, businessId ?? this.businessId ?? void 0, options);
4045
- }
4046
- };
4047
- function createCimplifyClient(config = {}) {
4048
- return new CimplifyClient(config);
4049
- }
4050
-
4051
- // src/query/builder.ts
4052
- function escapeQueryValue(value) {
4053
- return value.replace(/'/g, "\\'");
4054
- }
4055
- var QueryBuilder = class {
4056
- constructor(entity) {
4057
- this.filters = [];
4058
- this.modifiers = [];
4059
- this.pathSegments = [];
4060
- this.entity = entity;
4061
- }
4062
- path(segment) {
4063
- this.pathSegments.push(segment);
4064
- return this;
4065
- }
4066
- where(field, op, value) {
4067
- const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
4068
- if (op === "contains" || op === "startsWith") {
4069
- this.filters.push(`@.${field} ${op} ${v}`);
4070
- } else {
4071
- this.filters.push(`@.${field}${op}${v}`);
4072
- }
4073
- return this;
4074
- }
4075
- and(field, op, value) {
4076
- return this.where(field, op, value);
4077
- }
4078
- sort(field, order = "asc") {
4079
- this.modifiers.push(`sort(${field},${order})`);
4080
- return this;
4081
- }
4082
- limit(n) {
4083
- this.modifiers.push(`limit(${n})`);
4084
- return this;
4085
- }
4086
- offset(n) {
4087
- this.modifiers.push(`offset(${n})`);
4088
- return this;
4089
- }
4090
- count() {
4091
- this.modifiers.push("count");
4092
- return this;
4093
- }
4094
- enriched() {
4095
- this.modifiers.push("enriched");
4096
- return this;
4097
- }
4098
- build() {
4099
- let query2 = this.entity;
4100
- if (this.pathSegments.length > 0) {
4101
- query2 += "." + this.pathSegments.join(".");
4102
- }
4103
- if (this.filters.length > 0) {
4104
- query2 += `[?(${this.filters.join(" && ")})]`;
4105
- }
4106
- for (const mod of this.modifiers) {
4107
- query2 += `#${mod}`;
4108
- }
4109
- return query2;
4110
- }
4111
- toString() {
4112
- return this.build();
4113
- }
4114
- };
4115
- function query(entity) {
4116
- return new QueryBuilder(entity);
4117
- }
4118
-
4119
- // src/utils/variant.ts
4120
- function stripProductPrefix(variantName, productName) {
4121
- if (!variantName || !productName) return variantName || productName;
4122
- const lower = variantName.toLowerCase().trim();
4123
- if (lower === "default" || lower === "standard") return productName;
4124
- if (lower.endsWith("-default") || lower.endsWith("-standard")) return productName;
4125
- if (variantName.startsWith(productName)) {
4126
- const rest = variantName.slice(productName.length);
4127
- const match = rest.match(/^\s*[-–—]\s*(.*)/);
4128
- if (match && match[1].length > 0) return match[1];
4129
- }
4130
- const lowerProduct = productName.toLowerCase().trim();
4131
- if (lower.startsWith(lowerProduct)) {
4132
- const rest = variantName.slice(productName.length);
4133
- const match = rest.match(/^\s*[-–—]\s*(.*)/);
4134
- if (match && match[1].length > 0) return match[1];
4135
- }
4136
- const lastDash = variantName.lastIndexOf("-");
4137
- if (lastDash > 0 && lastDash < variantName.length - 1) {
4138
- const prefix = variantName.slice(0, lastDash).trim();
4139
- const suffix = variantName.slice(lastDash + 1).trim();
4140
- if (suffix.length > 0 && prefix.length > suffix.length * 2) {
4141
- return suffix;
4142
- }
4143
- }
4144
- return variantName;
4145
- }
4146
- function getVariantDisplayName(variant, productName) {
4147
- if (variant.display_attributes?.length) {
4148
- return variant.display_attributes.map((a) => a.value_name).join(" / ");
4149
- }
4150
- if (variant.name) {
4151
- return productName ? stripProductPrefix(variant.name, productName) : variant.name;
4152
- }
4153
- return productName || (variant.is_default ? "Default" : "Option");
4154
- }
4155
- var ISO3_TO_COUNTRY_CODE = {
4156
- AGO: "AO",
4157
- ARE: "AE",
4158
- AUS: "AU",
4159
- BDI: "BI",
4160
- BRA: "BR",
4161
- BWA: "BW",
4162
- CAN: "CA",
4163
- CHE: "CH",
4164
- CHN: "CN",
4165
- COD: "CD",
4166
- EGY: "EG",
4167
- ETH: "ET",
4168
- GHA: "GH",
4169
- GIN: "GN",
4170
- GMB: "GM",
4171
- GBR: "GB",
4172
- HKG: "HK",
4173
- IDN: "ID",
4174
- IND: "IN",
4175
- ISR: "IL",
4176
- JPN: "JP",
4177
- KEN: "KE",
4178
- KOR: "KR",
4179
- LBR: "LR",
4180
- MUS: "MU",
4181
- MEX: "MX",
4182
- MOZ: "MZ",
4183
- MWI: "MW",
4184
- MYS: "MY",
4185
- NAM: "NA",
4186
- NGA: "NG",
4187
- PHL: "PH",
4188
- RWA: "RW",
4189
- SAU: "SA",
4190
- SGP: "SG",
4191
- SLE: "SL",
4192
- THA: "TH",
4193
- TUR: "TR",
4194
- TWN: "TW",
4195
- TZA: "TZ",
4196
- UGA: "UG",
4197
- USA: "US",
4198
- VNM: "VN",
4199
- ZAF: "ZA",
4200
- ZMB: "ZM"
4201
- };
4202
- var CURRENCY_TO_COUNTRY_CODE = {
4203
- AED: "AE",
4204
- AOA: "AO",
4205
- AUD: "AU",
4206
- BIF: "BI",
4207
- BWP: "BW",
4208
- BRL: "BR",
4209
- CAD: "CA",
4210
- CDF: "CD",
4211
- CHF: "CH",
4212
- CNY: "CN",
4213
- EGP: "EG",
4214
- ETB: "ET",
4215
- GHS: "GH",
4216
- GMD: "GM",
4217
- GNF: "GN",
4218
- GBP: "GB",
4219
- HKD: "HK",
4220
- IDR: "ID",
4221
- ILS: "IL",
4222
- INR: "IN",
4223
- JPY: "JP",
4224
- KES: "KE",
4225
- KRW: "KR",
4226
- LRD: "LR",
4227
- MUR: "MU",
4228
- MWK: "MW",
4229
- MXN: "MX",
4230
- MYR: "MY",
4231
- MZN: "MZ",
4232
- NAD: "NA",
4233
- NGN: "NG",
4234
- PHP: "PH",
4235
- RWF: "RW",
4236
- SAR: "SA",
4237
- SGD: "SG",
4238
- SLL: "SL",
4239
- THB: "TH",
4240
- TRY: "TR",
4241
- TWD: "TW",
4242
- TZS: "TZ",
4243
- UGX: "UG",
4244
- USD: "US",
4245
- VND: "VN",
4246
- ZAR: "ZA",
4247
- ZMW: "ZM"
4248
- };
4249
- function normalizeCountryCode(value) {
4250
- const normalized = value?.trim().toUpperCase();
4251
- if (!normalized) {
4252
- return void 0;
4253
- }
4254
- if (normalized.length === 2) {
4255
- return normalized;
4256
- }
4257
- return ISO3_TO_COUNTRY_CODE[normalized];
4258
- }
4259
- function parsePhoneCandidate(value, country) {
4260
- try {
4261
- return country ? parsePhoneNumberFromString(value, country) : parsePhoneNumberFromString(value);
4262
- } catch {
4263
- return void 0;
4264
- }
4265
- }
4266
- function resolvePhoneCountryCode(options = {}) {
4267
- const explicitCountry = normalizeCountryCode(options.country);
4268
- if (explicitCountry) {
4269
- return explicitCountry;
4270
- }
4271
- const currency = options.currency?.trim().toUpperCase();
4272
- if (!currency) {
4273
- return void 0;
4274
- }
4275
- return CURRENCY_TO_COUNTRY_CODE[currency];
4276
- }
4277
- function normalizePhoneToE164(raw, options = {}) {
4278
- const trimmed = raw.trim();
4279
- if (!trimmed) {
4280
- return null;
4281
- }
4282
- const country = resolvePhoneCountryCode(options);
4283
- const digits = trimmed.replace(/\D/g, "");
4284
- const internationalDigits = digits.startsWith("00") ? digits.slice(2) : digits;
4285
- const attempts = [];
4286
- const seen = /* @__PURE__ */ new Set();
4287
- function addAttempt(value, nextCountry) {
4288
- const key = `${nextCountry || ""}:${value}`;
4289
- if (seen.has(key)) {
4290
- return;
4291
- }
4292
- seen.add(key);
4293
- attempts.push({ value, country: nextCountry });
4294
- }
4295
- if (country) {
4296
- addAttempt(trimmed, country);
4297
- }
4298
- addAttempt(trimmed);
4299
- if (country && digits) {
4300
- addAttempt(digits, country);
4301
- }
4302
- if (internationalDigits) {
4303
- addAttempt(`+${internationalDigits}`);
4304
- }
4305
- for (const attempt of attempts) {
4306
- const parsed = parsePhoneCandidate(attempt.value, attempt.country);
4307
- if (parsed?.isValid()) {
4308
- return parsed.format("E.164");
4309
- }
4310
- }
4311
- return null;
4312
- }
4313
- function isValidPhoneForContext(raw, options = {}) {
4314
- return normalizePhoneToE164(raw, options) !== null;
4315
- }
4316
-
4317
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, ActivityService, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyElement, CimplifyElements, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENT_TYPES, ERROR_HINTS, EVENT_TYPES, ErrorCode, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, ZERO, categorizePaymentError, combine, combineObject, createCimplifyClient, createElements, currencyCode, detectMobileMoneyProvider, enrichError, err, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatPriceWithTax, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getErrorHint, getMarkupPercentage, getOrElse, getProductCurrency, getTaxAmount, getVariantDisplayName, hasTaxInfo, isCimplifyError, isErr, isOk, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isRetryableError, isSupportedCurrency, isTaxInclusive, isValidPhoneForContext, mapError, mapResult, money, moneyFromNumber, normalizePaymentResponse, normalizePhoneToE164, normalizeStatusResponse, ok, parsePrice, query, resolvePhoneCountryCode, toNullable, tryCatch, unwrap };
1
+ export { ActivityService, CimplifyClient, createCimplifyClient, getVariantDisplayName } from './chunk-G6KNFYJD.mjs';
2
+ export { isValidPhoneForContext, normalizePhoneToE164, resolvePhoneCountryCode } from './chunk-WDIMISRC.mjs';
3
+ export { QueryBuilder, query } from './chunk-LM3CJ4L7.mjs';
4
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyElement, CimplifyElements, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENT_TYPES, EVENT_TYPES, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, SchedulingService, combine, combineObject, createElements, err, flatMap, fromPromise, generateIdempotencyKey, getOrElse, isErr, isOk, mapError, mapResult, ok, toNullable, tryCatch, unwrap } from './chunk-GFKBH7R2.mjs';
5
+ export { CURRENCY_SYMBOLS, CimplifyError, ERROR_HINTS, ErrorCode, MOBILE_MONEY_PROVIDERS, ZERO, categorizePaymentError, currencyCode, detectMobileMoneyProvider, enrichError, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatPriceWithTax, formatProductPrice, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getErrorHint, getMarkupPercentage, getProductCurrency, getTaxAmount, hasTaxInfo, isCimplifyError, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isRetryableError, isSupportedCurrency, isTaxInclusive, money, moneyFromNumber, normalizePaymentResponse, normalizeStatusResponse, parsePrice } from './chunk-OVM5YWM5.mjs';