@cimplify/sdk 0.16.3 → 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.
package/dist/advanced.js CHANGED
@@ -1,2915 +1,92 @@
1
1
  'use strict';
2
2
 
3
- // src/types/result.ts
4
- function ok(value) {
5
- return { ok: true, value };
6
- }
7
- function err(error) {
8
- return { ok: false, error };
9
- }
10
-
11
- // src/types/common.ts
12
- function money(value) {
13
- return typeof value === "string" ? parseFloat(value) || 0 : value;
14
- }
15
- function moneyFromNumber(value) {
16
- return value;
17
- }
18
- function currencyCode(value) {
19
- return value;
20
- }
21
- var ErrorCode = {
22
- UNKNOWN_ERROR: "UNKNOWN_ERROR",
23
- NOT_FOUND: "NOT_FOUND"};
24
- var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
25
- function docsUrlForCode(code) {
26
- return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
27
- }
28
- var ERROR_SUGGESTIONS = {
29
- UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
30
- NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
31
- TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
32
- UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
33
- FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
34
- NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
35
- VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
36
- CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
37
- CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
38
- CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
39
- ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
40
- VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
41
- VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
42
- ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
43
- ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
44
- CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
45
- DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
46
- CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
47
- QUOTE_NOT_FOUND: "Quote could not be found. Refresh pricing and create a new quote before checkout.",
48
- QUOTE_EXPIRED: "Quote has expired. Re-fetch pricing to generate a new quote with a valid expiry window.",
49
- QUOTE_CONSUMED: "Quote has already been used. Request a fresh quote to prevent duplicate checkout attempts.",
50
- QUOTE_STORAGE_UNAVAILABLE: "Quote storage is temporarily unavailable. Retry shortly and avoid charging until quote fetch succeeds.",
51
- PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
52
- PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
53
- INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
54
- CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
55
- INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
56
- OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
57
- AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
58
- PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
59
- SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
60
- BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
61
- SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
62
- OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
63
- INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
64
- BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
65
- INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
66
- ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
67
- NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
68
- PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
69
- AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
70
- AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
71
- ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
72
- CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
73
- CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
74
- REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
75
- POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
76
- FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
77
- };
78
- var ERROR_HINTS = Object.fromEntries(
79
- Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
80
- code,
81
- {
82
- docs_url: docsUrlForCode(code),
83
- suggestion
84
- }
85
- ])
86
- );
87
- var CimplifyError = class extends Error {
88
- constructor(code, message, retryable = false, docs_url, suggestion) {
89
- super(message);
90
- this.code = code;
91
- this.retryable = retryable;
92
- this.docs_url = docs_url;
93
- this.suggestion = suggestion;
94
- this.name = "CimplifyError";
95
- }
96
- get userMessage() {
97
- return this.message;
98
- }
99
- };
100
- function getErrorHint(code) {
101
- return ERROR_HINTS[code];
102
- }
103
- function enrichError(error, options = {}) {
104
- const hint = getErrorHint(error.code);
105
- if (hint) {
106
- if (!error.docs_url) {
107
- error.docs_url = hint.docs_url;
108
- }
109
- if (!error.suggestion) {
110
- error.suggestion = hint.suggestion;
111
- }
112
- } else if (!error.docs_url) {
113
- error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
114
- }
115
- if (options.isTestMode && !error.message.includes("pk_test_")) {
116
- error.message = `${error.message}
117
-
118
- \u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
119
- }
120
- return error;
121
- }
122
-
123
- // src/internal/safe.ts
124
- function toCimplifyError(error) {
125
- if (error instanceof CimplifyError) return enrichError(error);
126
- if (error instanceof Error) {
127
- return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
128
- }
129
- return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
130
- }
131
- async function safe(promise) {
132
- try {
133
- return ok(await promise);
134
- } catch (error) {
135
- return err(toCimplifyError(error));
136
- }
137
- }
138
-
139
- // src/catalogue.ts
140
- function withQuery(path, params) {
141
- const query2 = new URLSearchParams();
142
- for (const [key, value] of Object.entries(params)) {
143
- if (value === void 0) continue;
144
- query2.set(key, String(value));
145
- }
146
- const queryString = query2.toString();
147
- return queryString ? `${path}?${queryString}` : path;
148
- }
149
- function isRecord(value) {
150
- return typeof value === "object" && value !== null;
151
- }
152
- function readFinalPrice(value) {
153
- if (!isRecord(value)) return void 0;
154
- const finalPrice = value.final_price;
155
- if (typeof finalPrice === "string" || typeof finalPrice === "number") {
156
- return finalPrice;
157
- }
158
- return void 0;
159
- }
160
- function normalizeAddOnPayload(addOn) {
161
- if (!isRecord(addOn)) return addOn;
162
- const normalizedAddOn = { ...addOn };
163
- const options = normalizedAddOn["options"];
164
- if (!Array.isArray(options)) return normalizedAddOn;
165
- normalizedAddOn["options"] = options.map((option) => {
166
- if (!isRecord(option)) return option;
167
- const normalizedOption = { ...option };
168
- const optionPrice = normalizedOption["default_price"];
169
- if (optionPrice === void 0 || optionPrice === null || optionPrice === "") {
170
- normalizedOption["default_price"] = readFinalPrice(normalizedOption["default_price_info"]) || readFinalPrice(normalizedOption["price_info"]) || "0";
171
- }
172
- return normalizedOption;
173
- });
174
- return normalizedAddOn;
175
- }
176
- function normalizeCatalogueProductPayload(product) {
177
- const normalized = { ...product };
178
- const defaultPrice = normalized["default_price"];
179
- if (defaultPrice === void 0 || defaultPrice === null || defaultPrice === "") {
180
- 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);
181
- normalized["default_price"] = derivedDefaultPrice ?? "0";
182
- }
183
- const addOns = normalized["add_ons"];
184
- if (Array.isArray(addOns)) {
185
- normalized["add_ons"] = addOns.map((addOn) => normalizeAddOnPayload(addOn));
186
- }
187
- return normalized;
188
- }
189
- function toFiniteNumber(value) {
190
- if (typeof value === "number" && Number.isFinite(value)) {
191
- return value;
192
- }
193
- if (typeof value === "string" && value.trim().length > 0) {
194
- const parsed = Number(value);
195
- if (Number.isFinite(parsed)) {
196
- return parsed;
197
- }
198
- }
199
- return void 0;
200
- }
201
- function normalizePagination(value) {
202
- if (!isRecord(value)) {
203
- return void 0;
204
- }
205
- const totalCount = toFiniteNumber(value.total_count);
206
- const currentPage = toFiniteNumber(value.current_page);
207
- const pageSize = toFiniteNumber(value.page_size);
208
- const totalPages = toFiniteNumber(value.total_pages);
209
- if (totalCount === void 0 || currentPage === void 0 || pageSize === void 0 || totalPages === void 0) {
210
- return void 0;
211
- }
212
- return {
213
- total_count: totalCount,
214
- current_page: currentPage,
215
- page_size: pageSize,
216
- total_pages: totalPages,
217
- has_more: value.has_more === true,
218
- next_cursor: typeof value.next_cursor === "string" ? value.next_cursor : void 0
219
- };
220
- }
221
- function normalizeCatalogueResult(payload) {
222
- if (Array.isArray(payload)) {
223
- return {
224
- items: payload.map((product) => normalizeCatalogueProductPayload(product)),
225
- is_complete: true
226
- };
227
- }
228
- if (!isRecord(payload)) {
229
- return {
230
- items: [],
231
- is_complete: true
232
- };
233
- }
234
- const rawItems = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
235
- return {
236
- items: rawItems.map((product) => normalizeCatalogueProductPayload(product)),
237
- is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
238
- total_available: toFiniteNumber(payload.total_available),
239
- pagination: normalizePagination(payload.pagination)
240
- };
241
- }
242
- function normalizeCatalogueSnapshot(payload) {
243
- if (Array.isArray(payload)) {
244
- return {
245
- categories: [],
246
- products: payload.map((product) => normalizeCatalogueProductPayload(product)),
247
- add_ons: [],
248
- is_complete: true
249
- };
250
- }
251
- if (!isRecord(payload)) {
252
- return {
253
- categories: [],
254
- products: [],
255
- add_ons: [],
256
- is_complete: true
257
- };
258
- }
259
- const rawProducts = Array.isArray(payload.products) ? payload.products : Array.isArray(payload.items) ? payload.items : [];
260
- const rawCategories = Array.isArray(payload.categories) ? payload.categories : [];
261
- const rawAddOns = Array.isArray(payload.add_ons) ? payload.add_ons : [];
262
- return {
263
- categories: rawCategories,
264
- products: rawProducts.map((product) => normalizeCatalogueProductPayload(product)),
265
- add_ons: rawAddOns.map((addOn) => normalizeAddOnPayload(addOn)),
266
- is_complete: typeof payload.is_complete === "boolean" ? payload.is_complete : true,
267
- total_available: toFiniteNumber(payload.total_available),
268
- pagination: normalizePagination(payload.pagination)
269
- };
270
- }
271
- var CatalogueQueries = class {
272
- constructor(client) {
273
- this.client = client;
274
- }
275
- async getCatalogue() {
276
- const result = await safe(this.client.get("/api/v1/catalogue"));
277
- if (!result.ok) return result;
278
- return ok(normalizeCatalogueSnapshot(result.value));
279
- }
280
- async getProducts(options) {
281
- const path = withQuery("/api/v1/catalogue/products", {
282
- category_id: options?.category,
283
- taxonomy_id: options?.taxonomy,
284
- search: options?.search,
285
- page: options?.page,
286
- tags: options?.tags?.join(","),
287
- featured: options?.featured,
288
- in_stock: options?.in_stock,
289
- min_price: options?.min_price,
290
- max_price: options?.max_price,
291
- sort_by: options?.sort_by,
292
- sort_order: options?.sort_order,
293
- limit: options?.limit,
294
- offset: options?.offset,
295
- cursor: options?.cursor
296
- });
297
- const result = await safe(this.client.get(path));
298
- if (!result.ok) return result;
299
- return ok(normalizeCatalogueResult(result.value));
300
- }
301
- async getProduct(id) {
302
- const encodedId = encodeURIComponent(id);
303
- const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
304
- if (!result.ok) return result;
305
- return ok(normalizeCatalogueProductPayload(result.value));
306
- }
307
- async getProductBySlug(slug) {
308
- const encodedSlug = encodeURIComponent(slug);
309
- const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
310
- if (!result.ok) return result;
311
- return ok(normalizeCatalogueProductPayload(result.value));
312
- }
313
- async getVariants(productId) {
314
- const encodedId = encodeURIComponent(productId);
315
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
316
- }
317
- async getVariantAxes(productId) {
318
- const encodedId = encodeURIComponent(productId);
319
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
320
- }
321
- async getVariantByAxisSelections(productId, selections) {
322
- const encodedId = encodeURIComponent(productId);
323
- return safe(
324
- this.client.post(
325
- `/api/v1/catalogue/products/${encodedId}/variants/find`,
326
- { axis_selections: selections }
327
- )
328
- );
329
- }
330
- async getVariantById(productId, variantId) {
331
- const encodedProductId = encodeURIComponent(productId);
332
- const encodedVariantId = encodeURIComponent(variantId);
333
- return safe(
334
- this.client.get(
335
- `/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
336
- )
337
- );
338
- }
339
- async getAddOns(productId) {
340
- const encodedId = encodeURIComponent(productId);
341
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
342
- }
343
- async getCategories() {
344
- return safe(this.client.get("/api/v1/catalogue/categories"));
345
- }
346
- async getCategory(id) {
347
- const encodedId = encodeURIComponent(id);
348
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
349
- }
350
- async getCategoryBySlug(slug) {
351
- const encodedSlug = encodeURIComponent(slug);
352
- return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
353
- }
354
- async getCategoryProducts(categoryId) {
355
- const encodedId = encodeURIComponent(categoryId);
356
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
357
- }
358
- async getCollections() {
359
- return safe(this.client.get("/api/v1/catalogue/collections"));
360
- }
361
- async getCollection(id) {
362
- const encodedId = encodeURIComponent(id);
363
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
364
- }
365
- async getCollectionBySlug(slug) {
366
- const encodedSlug = encodeURIComponent(slug);
367
- return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
368
- }
369
- async getCollectionProducts(collectionId) {
370
- const encodedId = encodeURIComponent(collectionId);
371
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
372
- }
373
- async searchCollections(query2, limit = 20) {
374
- const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
375
- return safe(this.client.get(path));
376
- }
377
- async getBundles() {
378
- return safe(this.client.get("/api/v1/catalogue/bundles"));
379
- }
380
- async searchBundles(query2, limit = 20) {
381
- const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
382
- return safe(this.client.get(path));
383
- }
384
- async getComposites(options) {
385
- const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
386
- return safe(this.client.get(path));
387
- }
388
- async calculateCompositePrice(compositeId, selections, locationId) {
389
- const encodedId = encodeURIComponent(compositeId);
390
- return safe(
391
- this.client.post(
392
- `/api/v1/catalogue/composites/${encodedId}/calculate-price`,
393
- {
394
- selections,
395
- location_id: locationId
396
- }
397
- )
398
- );
399
- }
400
- async fetchQuote(input) {
401
- return safe(this.client.post("/api/v1/catalogue/quotes", input));
402
- }
403
- async getQuote(quoteId) {
404
- const encodedQuoteId = encodeURIComponent(quoteId);
405
- return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
406
- }
407
- async refreshQuote(input) {
408
- const encodedQuoteId = encodeURIComponent(input.quote_id);
409
- return safe(
410
- this.client.post(
411
- `/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
412
- input
413
- )
414
- );
415
- }
416
- async getTaxonomies(parentId) {
417
- const path = withQuery("/api/v1/catalogue/taxonomies", { parent_id: parentId });
418
- return safe(this.client.get(path));
419
- }
420
- async getTaxonomy(id) {
421
- const encodedId = encodeURIComponent(id);
422
- return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}`));
423
- }
424
- async getTaxonomyPath(id) {
425
- const encodedId = encodeURIComponent(id);
426
- return safe(this.client.get(`/api/v1/catalogue/taxonomies/${encodedId}/path`));
427
- }
428
- async searchTaxonomies(query2, limit) {
429
- const path = withQuery("/api/v1/catalogue/taxonomies/search", { q: query2, limit });
430
- return safe(this.client.get(path));
431
- }
432
- async getProductSchedules(productId) {
433
- const encodedId = encodeURIComponent(productId);
434
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/schedules`));
435
- }
436
- async checkProductAvailableNow(productId, locationId) {
437
- const encodedId = encodeURIComponent(productId);
438
- const path = withQuery(`/api/v1/catalogue/products/${encodedId}/available-now`, { location_id: locationId });
439
- return safe(this.client.get(path));
440
- }
441
- async getDeals(locationId) {
442
- const path = withQuery("/api/v1/catalogue/deals", { location_id: locationId });
443
- return safe(this.client.get(path));
444
- }
445
- async getProductsOnSale() {
446
- return safe(this.client.get("/api/v1/catalogue/deals/on-sale"));
447
- }
448
- async getProductDeals(productId) {
449
- const encodedId = encodeURIComponent(productId);
450
- return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/deals`));
451
- }
452
- async getCategoryDeals(categoryId) {
453
- const encodedId = encodeURIComponent(categoryId);
454
- return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/deals`));
455
- }
456
- async getCollectionDeals(collectionId) {
457
- const encodedId = encodeURIComponent(collectionId);
458
- return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/deals`));
459
- }
460
- async validateDiscountCode(code, orderSubtotal, locationId) {
461
- return safe(
462
- this.client.post("/api/v1/catalogue/deals/validate", {
463
- discount_code: code,
464
- order_subtotal: orderSubtotal,
465
- location_id: locationId
466
- })
467
- );
468
- }
469
- async search(query2, options) {
470
- const result = await this.getProducts({
471
- search: query2,
472
- category: options?.category,
473
- limit: options?.limit ?? 20
474
- });
475
- if (!result.ok) return result;
476
- return ok(result.value.items);
477
- }
478
- async searchProducts(query2, options) {
479
- return this.search(query2, options);
480
- }
481
- async getMenu(options) {
482
- const path = withQuery("/api/v1/catalogue/menu", {
483
- category_id: options?.category,
484
- limit: options?.limit
485
- });
486
- return safe(this.client.get(path));
487
- }
488
- async getMenuCategory(categoryId) {
489
- const encodedId = encodeURIComponent(categoryId);
490
- return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
491
- }
492
- async getMenuItem(itemId) {
493
- const encodedId = encodeURIComponent(itemId);
494
- return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
495
- }
496
- async getTags(options) {
497
- const path = withQuery("/api/v1/catalogue/tags", {
498
- tag_group: options?.tag_group,
499
- search: options?.search,
500
- min_usage: options?.min_usage,
501
- limit: options?.limit,
502
- offset: options?.offset
503
- });
504
- return safe(this.client.get(path));
505
- }
506
- };
507
-
508
- // src/cart.ts
509
- function isUICartResponse(value) {
510
- return "cart" in value;
511
- }
512
- function unwrapEnrichedCart(value) {
513
- return isUICartResponse(value) ? value.cart : value;
514
- }
515
- var CartOperations = class {
516
- constructor(client) {
517
- this.client = client;
518
- }
519
- async get() {
520
- const result = await safe(this.client.get("/api/v1/cart"));
521
- if (!result.ok) return result;
522
- return ok(unwrapEnrichedCart(result.value));
523
- }
524
- async getRaw() {
525
- return safe(this.client.get("/api/v1/cart"));
526
- }
527
- async getItems() {
528
- return safe(this.client.get("/api/v1/cart/items"));
529
- }
530
- async getCount() {
531
- return safe(this.client.get("/api/v1/cart/count"));
532
- }
533
- async getTotal() {
534
- return safe(this.client.get("/api/v1/cart/total"));
535
- }
536
- async getSummary() {
537
- const cartResult = await this.get();
538
- if (!cartResult.ok) return cartResult;
539
- const cart = cartResult.value;
540
- return ok({
541
- item_count: cart.items.length,
542
- total_items: cart.items.reduce((sum, item) => sum + item.quantity, 0),
543
- subtotal: cart.pricing.subtotal,
544
- discount_amount: cart.pricing.total_discounts,
545
- tax_amount: cart.pricing.tax_amount,
546
- total: cart.pricing.total_price,
547
- currency: cart.pricing.currency
548
- });
549
- }
550
- async addItem(input) {
551
- return safe(this.client.post("/api/v1/cart/items", input));
552
- }
553
- async updateItem(cartItemId, updates) {
554
- if (typeof updates.quantity === "number") {
555
- return this.updateQuantity(cartItemId, updates.quantity);
556
- }
557
- const encodedId = encodeURIComponent(cartItemId);
558
- return safe(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
559
- }
560
- async updateQuantity(cartItemId, quantity) {
561
- const encodedId = encodeURIComponent(cartItemId);
562
- return safe(
563
- this.client.patch(`/api/v1/cart/items/${encodedId}`, {
564
- quantity
565
- })
566
- );
567
- }
568
- async removeItem(cartItemId) {
569
- const encodedId = encodeURIComponent(cartItemId);
570
- return safe(this.client.delete(`/api/v1/cart/items/${encodedId}`));
571
- }
572
- async clear() {
573
- return safe(this.client.delete("/api/v1/cart"));
574
- }
575
- async applyCoupon(code) {
576
- return safe(
577
- this.client.post("/api/v1/cart/coupons", {
578
- coupon_code: code
579
- })
580
- );
581
- }
582
- async removeCoupon() {
583
- return safe(this.client.delete("/api/v1/cart/coupons/current"));
584
- }
585
- async isEmpty() {
586
- const countResult = await this.getCount();
587
- if (!countResult.ok) return countResult;
588
- return ok(countResult.value === 0);
589
- }
590
- async hasItem(productId, variantId) {
591
- const itemsResult = await this.getItems();
592
- if (!itemsResult.ok) return itemsResult;
593
- const found = itemsResult.value.some((item) => {
594
- const matchesProduct = item.item_id === productId;
595
- if (!variantId) return matchesProduct;
596
- const config = item.configuration;
597
- if ("variant" in config && config.variant) {
598
- return matchesProduct && config.variant.variant_id === variantId;
599
- }
600
- return matchesProduct;
601
- });
602
- return ok(found);
603
- }
604
- async findItem(productId, variantId) {
605
- const itemsResult = await this.getItems();
606
- if (!itemsResult.ok) return itemsResult;
607
- const found = itemsResult.value.find((item) => {
608
- const matchesProduct = item.item_id === productId;
609
- if (!variantId) return matchesProduct;
610
- const config = item.configuration;
611
- if ("variant" in config && config.variant) {
612
- return matchesProduct && config.variant.variant_id === variantId;
613
- }
614
- return matchesProduct;
615
- });
616
- return ok(found);
617
- }
618
- };
619
-
620
- // src/constants.ts
621
- var MOBILE_MONEY_PROVIDER = {
622
- MTN: "mtn",
623
- VODAFONE: "vodafone",
624
- AIRTEL: "airtel"
625
- };
626
-
627
- // src/utils/payment.ts
628
- var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
629
- "success",
630
- "succeeded",
631
- "paid",
632
- "captured",
633
- "completed",
634
- "authorized"
635
- ]);
636
- var PAYMENT_FAILURE_STATUSES = /* @__PURE__ */ new Set([
637
- "failed",
638
- "declined",
639
- "cancelled",
640
- "voided",
641
- "error",
642
- "abandoned"
643
- ]);
644
- var PAYMENT_REQUIRES_ACTION_STATUSES = /* @__PURE__ */ new Set([
645
- "requires_action",
646
- "requires_payment_method",
647
- "requires_capture"
648
- ]);
649
- var PAYMENT_STATUS_ALIAS_MAP = {
650
- ok: "success",
651
- done: "success",
652
- paid: "paid",
653
- paid_in_full: "paid",
654
- paid_successfully: "paid",
655
- succeeded: "success",
656
- captured: "captured",
657
- completed: "completed",
658
- pending_confirmation: "pending_confirmation",
659
- requires_authorization: "requires_action",
660
- requires_action: "requires_action",
661
- requires_payment_method: "requires_payment_method",
662
- requires_capture: "requires_capture",
663
- partially_paid: "partially_paid",
664
- partially_refunded: "partially_refunded",
665
- card_declined: "declined",
666
- canceled: "cancelled",
667
- authorized: "authorized",
668
- cancelled: "cancelled",
669
- unresolved: "pending"
670
- };
671
- var KNOWN_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
672
- "initialized",
673
- "pending",
674
- "processing",
675
- "authorized",
676
- "captured",
677
- "failed",
678
- "cancelled",
679
- "refunded",
680
- "unknown",
681
- "voided",
682
- "requires_action",
683
- "abandoned",
684
- "reversed",
685
- "disputed",
686
- "refund_pending",
687
- "created",
688
- "pending_confirmation",
689
- "success",
690
- "succeeded",
691
- "declined",
692
- "partially_refunded",
693
- "partially_paid",
694
- "paid",
695
- "unpaid",
696
- "requires_payment_method",
697
- "requires_capture",
698
- "completed",
699
- "error"
700
- ]);
701
- function normalizeStatusToken(status) {
702
- return status?.trim().toLowerCase().replace(/[\s-]+/g, "_") ?? "";
703
- }
704
- function normalizePaymentStatusValue(status) {
705
- const normalized = normalizeStatusToken(status);
706
- if (Object.prototype.hasOwnProperty.call(PAYMENT_STATUS_ALIAS_MAP, normalized)) {
707
- return PAYMENT_STATUS_ALIAS_MAP[normalized];
708
- }
709
- return KNOWN_PAYMENT_STATUSES.has(normalized) ? normalized : "unknown";
710
- }
711
- function isPaymentStatusSuccess(status) {
712
- const normalizedStatus = normalizePaymentStatusValue(status);
713
- return PAYMENT_SUCCESS_STATUSES.has(normalizedStatus);
714
- }
715
- function isPaymentStatusFailure(status) {
716
- const normalizedStatus = normalizePaymentStatusValue(status);
717
- return PAYMENT_FAILURE_STATUSES.has(normalizedStatus);
718
- }
719
- function isPaymentStatusRequiresAction(status) {
720
- const normalizedStatus = normalizePaymentStatusValue(status);
721
- return PAYMENT_REQUIRES_ACTION_STATUSES.has(normalizedStatus);
722
- }
723
- function normalizeStatusResponse(response) {
724
- if (!response || typeof response !== "object") {
725
- return {
726
- status: "pending",
727
- paid: false,
728
- amount: moneyFromNumber(0),
729
- currency: "",
730
- message: "No status available"
731
- };
732
- }
733
- const res = response;
734
- const normalizedStatus = normalizePaymentStatusValue(res.status ?? void 0);
735
- const normalizedAmount = typeof res.amount === "string" ? money(res.amount) : typeof res.amount === "number" && Number.isFinite(res.amount) ? moneyFromNumber(res.amount) : moneyFromNumber(0);
736
- const normalizedCurrency = typeof res.currency === "string" && res.currency.trim().length > 0 ? res.currency : "";
737
- const paidValue = res.paid === true;
738
- const derivedPaid = paidValue || [
739
- "success",
740
- "succeeded",
741
- "paid",
742
- "captured",
743
- "authorized",
744
- "completed"
745
- ].includes(normalizedStatus);
746
- return {
747
- status: normalizedStatus,
748
- paid: derivedPaid,
749
- amount: normalizedAmount,
750
- currency: normalizedCurrency,
751
- reference: res.reference,
752
- message: res.message || ""
753
- };
754
- }
755
-
756
- // src/utils/paystack.ts
757
- async function openPaystackPopup(options, signal) {
758
- if (typeof window === "undefined") {
759
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
760
- }
761
- let PaystackPop;
762
- try {
763
- const imported = await import('@paystack/inline-js');
764
- PaystackPop = imported.default;
765
- } catch {
766
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
767
- }
768
- return new Promise((resolve) => {
769
- let settled = false;
770
- const resolveOnce = (result) => {
771
- if (settled) {
772
- return;
773
- }
774
- settled = true;
775
- if (signal) {
776
- signal.removeEventListener("abort", onAbort);
777
- }
778
- resolve(result);
779
- };
780
- const onAbort = () => {
781
- resolveOnce({ success: false, error: "CANCELLED" });
782
- };
783
- if (signal?.aborted) {
784
- resolveOnce({ success: false, error: "CANCELLED" });
785
- return;
786
- }
787
- if (signal) {
788
- signal.addEventListener("abort", onAbort, { once: true });
789
- }
790
- try {
791
- const popup = new PaystackPop();
792
- popup.newTransaction({
793
- key: options.key,
794
- email: options.email,
795
- amount: options.amount,
796
- currency: options.currency,
797
- reference: options.reference,
798
- accessCode: options.accessCode,
799
- onSuccess: (transaction) => {
800
- resolveOnce({
801
- success: true,
802
- reference: transaction.reference ?? options.reference
803
- });
804
- },
805
- onCancel: () => {
806
- resolveOnce({ success: false, error: "PAYMENT_CANCELLED" });
807
- },
808
- onError: (error) => {
809
- resolveOnce({
810
- success: false,
811
- error: error?.message || "PAYMENT_FAILED"
812
- });
813
- }
814
- });
815
- } catch {
816
- resolveOnce({ success: false, error: "POPUP_BLOCKED" });
817
- }
818
- });
819
- }
820
-
821
- // src/utils/checkout-resolver.ts
822
- var DEFAULT_POLL_INTERVAL_MS = 3e3;
823
- var DEFAULT_MAX_POLL_ATTEMPTS = 60;
824
- var MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
825
- var CARD_PROVIDER_PAYSTACK = "paystack";
826
- var NEXT_ACTION_NONE = "none";
827
- var NEXT_ACTION_CARD_POPUP = "card_popup";
828
- var NEXT_ACTION_REDIRECT = "redirect";
829
- var NEXT_ACTION_AUTHORIZATION = "authorization";
830
- function normalizeCardPopupError(error) {
831
- if (!error || error === "PAYMENT_CANCELLED" || error === "CANCELLED") {
832
- return "PAYMENT_CANCELLED";
833
- }
834
- if (error === "PROVIDER_UNAVAILABLE") {
835
- return "PROVIDER_UNAVAILABLE";
836
- }
837
- if (error === "POPUP_BLOCKED") {
838
- return "POPUP_BLOCKED";
839
- }
840
- return "PAYMENT_FAILED";
841
- }
842
- function normalizeCardProvider(value) {
843
- const normalized = value?.trim().toLowerCase();
844
- return normalized && normalized.length > 0 ? normalized : CARD_PROVIDER_PAYSTACK;
845
- }
846
- async function openCardPopup(provider, checkoutResult, email, currency, signal) {
847
- if (typeof window === "undefined") {
848
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
849
- }
850
- if (provider === CARD_PROVIDER_PAYSTACK) {
851
- return openPaystackPopup(
852
- {
853
- key: checkoutResult.public_key || "",
854
- email,
855
- accessCode: checkoutResult.client_secret,
856
- reference: checkoutResult.payment_reference || checkoutResult.client_secret,
857
- currency
858
- },
859
- signal
860
- );
861
- }
862
- return { success: false, error: "PROVIDER_UNAVAILABLE" };
863
- }
864
- var VALID_MOBILE_MONEY_PROVIDERS = new Set(Object.values(MOBILE_MONEY_PROVIDER));
865
- function isValidMobileMoneyProvider(value) {
866
- return VALID_MOBILE_MONEY_PROVIDERS.has(value);
867
- }
868
- function normalizeAuthorizationType(value) {
869
- if (value && typeof value === "object" && "address" in value) {
870
- return "address";
871
- }
872
- if (typeof value !== "string") return void 0;
873
- const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
874
- if (normalized === "otp" || normalized === "pin") return normalized;
875
- if (normalized === "phone" || normalized === "birthday" || normalized === "address") {
876
- return normalized;
877
- }
878
- return void 0;
879
- }
880
- function formatMoney2(value) {
881
- if (typeof value === "number" && Number.isFinite(value)) {
882
- return value.toFixed(2);
883
- }
884
- if (typeof value === "string" && value.trim().length > 0) {
885
- return value;
886
- }
887
- return "0.00";
888
- }
889
- function createAbortError() {
890
- const error = new Error("CANCELLED");
891
- error.name = "AbortError";
892
- return error;
893
- }
894
- function isAbortError(error) {
895
- if (error instanceof DOMException && error.name === "AbortError") {
896
- return true;
897
- }
898
- return error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
899
- }
900
- var CheckoutResolver = class {
901
- constructor(options) {
902
- this.client = options.client;
903
- this.checkoutData = options.checkoutData;
904
- this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
905
- this.maxPollAttempts = options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS;
906
- this.onStatusChange = options.onStatusChange;
907
- this.onAuthorizationRequired = options.onAuthorizationRequired;
908
- this.signal = options.signal;
909
- this.returnUrl = options.returnUrl;
910
- this.enrollInLink = options.enrollInLink !== false;
911
- this.businessId = options.businessId;
912
- this.addressData = options.addressData;
913
- this.paymentData = options.paymentData;
914
- this.orderType = options.orderType;
915
- this.cartTotal = options.cartTotal;
916
- this.cartCurrency = options.cartCurrency;
917
- this.allowPopups = options.allowPopups ?? typeof window !== "undefined";
918
- }
919
- async resolve(checkoutResult) {
920
- try {
921
- this.ensureNotAborted();
922
- if (!checkoutResult.order_id) {
923
- return this.fail("CHECKOUT_FAILED", "Checkout did not return an order ID.", false);
924
- }
925
- if (checkoutResult.next_action) {
926
- return this.resolveNextAction(checkoutResult);
927
- }
928
- let latestCheckoutResult = checkoutResult;
929
- let authorizationType = normalizeAuthorizationType(checkoutResult.authorization_type);
930
- let paymentReference = checkoutResult.payment_reference;
931
- if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
932
- return this.finalizeSuccess(checkoutResult);
933
- }
934
- if (checkoutResult.client_secret && checkoutResult.public_key) {
935
- const provider = normalizeCardProvider(checkoutResult.provider);
936
- this.emit("awaiting_authorization", {
937
- display_text: "Complete payment in the card authorization popup.",
938
- order_id: checkoutResult.order_id,
939
- order_number: checkoutResult.order_number
940
- });
941
- if (!this.allowPopups) {
942
- return this.fail(
943
- "PROVIDER_UNAVAILABLE",
944
- "Card payment popup is unavailable in this environment.",
945
- false
946
- );
947
- }
948
- const popupResult = await openCardPopup(
949
- provider,
950
- checkoutResult,
951
- this.checkoutData.customer.email || "customer@cimplify.io",
952
- this.getOrderCurrency(checkoutResult),
953
- this.signal
954
- );
955
- if (!popupResult.success) {
956
- const popupError = normalizeCardPopupError(popupResult.error);
957
- if (popupError === "POPUP_BLOCKED") {
958
- return this.fail(
959
- "POPUP_BLOCKED",
960
- "Unable to open card payment popup. Please allow popups and try again.",
961
- true
962
- );
963
- }
964
- if (popupError === "PROVIDER_UNAVAILABLE") {
965
- return this.fail(
966
- "PROVIDER_UNAVAILABLE",
967
- "Card payment provider is unavailable.",
968
- false
969
- );
970
- }
971
- return this.fail(
972
- "PAYMENT_CANCELLED",
973
- "Card payment was cancelled before completion.",
974
- true
975
- );
976
- }
977
- paymentReference = popupResult.reference || paymentReference;
978
- }
979
- if (checkoutResult.authorization_url) {
980
- if (typeof window !== "undefined" && this.returnUrl) {
981
- window.location.assign(checkoutResult.authorization_url);
982
- return this.fail(
983
- "REDIRECT_REQUIRED",
984
- "Redirecting to complete payment authorization.",
985
- true
986
- );
987
- }
988
- if (typeof window !== "undefined") {
989
- const popup = window.open(
990
- checkoutResult.authorization_url,
991
- "cimplify-auth",
992
- "width=520,height=760,noopener,noreferrer"
993
- );
994
- if (!popup) {
995
- return this.fail(
996
- "POPUP_BLOCKED",
997
- "Authorization popup was blocked. Please allow popups and retry.",
998
- true
999
- );
1000
- }
1001
- }
1002
- }
1003
- if (checkoutResult.requires_authorization || isPaymentStatusRequiresAction(checkoutResult.payment_status)) {
1004
- const authorization = await this.handleAuthorization({
1005
- authorizationType,
1006
- paymentReference,
1007
- displayText: checkoutResult.display_text,
1008
- provider: checkoutResult.provider
1009
- });
1010
- if (!authorization.ok) {
1011
- return authorization.result;
1012
- }
1013
- if (authorization.value) {
1014
- latestCheckoutResult = authorization.value;
1015
- paymentReference = authorization.value.payment_reference || paymentReference;
1016
- authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1017
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1018
- return this.finalizeSuccess(authorization.value);
1019
- }
1020
- if (this.isFailureStatus(authorization.value.payment_status)) {
1021
- return this.fail(
1022
- "AUTHORIZATION_FAILED",
1023
- authorization.value.display_text || "Payment authorization failed.",
1024
- false
1025
- );
1026
- }
1027
- }
1028
- }
1029
- return this.pollUntilTerminal({
1030
- orderId: checkoutResult.order_id,
1031
- latestCheckoutResult,
1032
- paymentReference,
1033
- authorizationType
1034
- });
1035
- } catch (error) {
1036
- if (isAbortError(error)) {
1037
- return this.fail("CANCELLED", "Checkout was cancelled.", true);
1038
- }
1039
- const message = error instanceof Error ? error.message : "Checkout failed unexpectedly.";
1040
- return this.fail("CHECKOUT_FAILED", message, true);
1041
- }
1042
- }
1043
- async resolveNextAction(checkoutResult) {
1044
- const action = checkoutResult.next_action;
1045
- if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
1046
- return this.finalizeSuccess(checkoutResult);
1047
- }
1048
- let latestCheckoutResult = checkoutResult;
1049
- let paymentReference = checkoutResult.payment_reference;
1050
- switch (action.type) {
1051
- case NEXT_ACTION_NONE:
1052
- return this.finalizeSuccess(checkoutResult);
1053
- case NEXT_ACTION_CARD_POPUP: {
1054
- const provider = normalizeCardProvider(action.provider);
1055
- this.emit("awaiting_authorization", {
1056
- display_text: "Complete payment in the card authorization popup.",
1057
- order_id: checkoutResult.order_id,
1058
- order_number: checkoutResult.order_number
1059
- });
1060
- if (!this.allowPopups) {
1061
- return this.fail(
1062
- "PROVIDER_UNAVAILABLE",
1063
- "Card payment popup is unavailable in this environment.",
1064
- false
1065
- );
1066
- }
1067
- const popupResult = await openCardPopup(
1068
- provider,
1069
- checkoutResult,
1070
- this.checkoutData.customer.email || "customer@cimplify.io",
1071
- this.getOrderCurrency(checkoutResult),
1072
- this.signal
1073
- );
1074
- if (!popupResult.success) {
1075
- const popupError = normalizeCardPopupError(popupResult.error);
1076
- if (popupError === "POPUP_BLOCKED") {
1077
- return this.fail(
1078
- "POPUP_BLOCKED",
1079
- "Unable to open card payment popup. Please allow popups and try again.",
1080
- true
1081
- );
1082
- }
1083
- if (popupError === "PROVIDER_UNAVAILABLE") {
1084
- return this.fail("PROVIDER_UNAVAILABLE", "Card payment provider is unavailable.", false);
1085
- }
1086
- return this.fail("PAYMENT_CANCELLED", "Card payment was cancelled before completion.", true);
1087
- }
1088
- paymentReference = popupResult.reference || paymentReference;
1089
- break;
1090
- }
1091
- case NEXT_ACTION_REDIRECT: {
1092
- if (typeof window !== "undefined" && this.returnUrl) {
1093
- window.location.assign(action.authorization_url);
1094
- return this.fail("REDIRECT_REQUIRED", "Redirecting to complete payment authorization.", true);
1095
- }
1096
- if (typeof window !== "undefined") {
1097
- const popup = window.open(
1098
- action.authorization_url,
1099
- "cimplify-auth",
1100
- "width=520,height=760,noopener,noreferrer"
1101
- );
1102
- if (!popup) {
1103
- return this.fail(
1104
- "POPUP_BLOCKED",
1105
- "Authorization popup was blocked. Please allow popups and retry.",
1106
- true
1107
- );
1108
- }
1109
- }
1110
- break;
1111
- }
1112
- case NEXT_ACTION_AUTHORIZATION: {
1113
- const authType = normalizeAuthorizationType(action.authorization_type);
1114
- const authorization = await this.handleAuthorization({
1115
- authorizationType: authType,
1116
- paymentReference,
1117
- displayText: action.display_text,
1118
- provider: checkoutResult.provider
1119
- });
1120
- if (!authorization.ok) {
1121
- return authorization.result;
1122
- }
1123
- if (authorization.value) {
1124
- latestCheckoutResult = authorization.value;
1125
- paymentReference = authorization.value.payment_reference || paymentReference;
1126
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1127
- return this.finalizeSuccess(authorization.value);
1128
- }
1129
- if (this.isFailureStatus(authorization.value.payment_status)) {
1130
- return this.fail(
1131
- "AUTHORIZATION_FAILED",
1132
- authorization.value.display_text || "Payment authorization failed.",
1133
- false
1134
- );
1135
- }
1136
- }
1137
- break;
1138
- }
1139
- }
1140
- return this.pollUntilTerminal({
1141
- orderId: checkoutResult.order_id,
1142
- latestCheckoutResult,
1143
- paymentReference,
1144
- authorizationType: normalizeAuthorizationType(checkoutResult.authorization_type)
1145
- });
1146
- }
1147
- async pollUntilTerminal(input) {
1148
- let consecutiveErrors = 0;
1149
- let latestCheckoutResult = input.latestCheckoutResult;
1150
- let paymentReference = input.paymentReference;
1151
- let authorizationType = input.authorizationType;
1152
- for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) {
1153
- this.ensureNotAborted();
1154
- this.emit("polling", {
1155
- poll_attempt: attempt,
1156
- max_poll_attempts: this.maxPollAttempts,
1157
- order_id: input.orderId,
1158
- order_number: latestCheckoutResult.order_number
1159
- });
1160
- const statusResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1161
- if (!statusResult.ok) {
1162
- consecutiveErrors += 1;
1163
- if (consecutiveErrors >= MAX_CONSECUTIVE_NETWORK_ERRORS) {
1164
- return this.fail(
1165
- "NETWORK_ERROR",
1166
- "Unable to confirm payment due to repeated network errors.",
1167
- true
1168
- );
1169
- }
1170
- await this.wait(this.pollIntervalMs);
1171
- continue;
1172
- }
1173
- consecutiveErrors = 0;
1174
- if (statusResult.value.reference) {
1175
- paymentReference = statusResult.value.reference;
1176
- }
1177
- const normalized = normalizeStatusResponse(statusResult.value);
1178
- if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1179
- return this.finalizeSuccess(latestCheckoutResult);
1180
- }
1181
- if (isPaymentStatusFailure(normalized.status)) {
1182
- return this.fail(
1183
- normalized.status ? normalized.status.toUpperCase() : "PAYMENT_FAILED",
1184
- normalized.message || "Payment failed during confirmation.",
1185
- false
1186
- );
1187
- }
1188
- if (isPaymentStatusRequiresAction(normalized.status)) {
1189
- const authorization = await this.handleAuthorization({
1190
- authorizationType,
1191
- paymentReference,
1192
- displayText: normalized.message || latestCheckoutResult.display_text,
1193
- provider: latestCheckoutResult.provider
1194
- });
1195
- if (!authorization.ok) {
1196
- return authorization.result;
1197
- }
1198
- if (authorization.value) {
1199
- latestCheckoutResult = authorization.value;
1200
- paymentReference = authorization.value.payment_reference || paymentReference;
1201
- authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1202
- if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1203
- return this.finalizeSuccess(authorization.value);
1204
- }
1205
- if (this.isFailureStatus(authorization.value.payment_status)) {
1206
- return this.fail(
1207
- "AUTHORIZATION_FAILED",
1208
- authorization.value.display_text || "Payment authorization failed.",
1209
- false
1210
- );
1211
- }
1212
- }
1213
- }
1214
- await this.wait(this.pollIntervalMs);
1215
- }
1216
- try {
1217
- const finalResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1218
- if (finalResult.ok) {
1219
- const normalized = normalizeStatusResponse(finalResult.value);
1220
- if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1221
- return this.finalizeSuccess(latestCheckoutResult);
1222
- }
1223
- }
1224
- } catch {
1225
- }
1226
- return this.fail(
1227
- "PAYMENT_TIMEOUT",
1228
- "Payment confirmation timed out. Please retry checkout.",
1229
- true
1230
- );
1231
- }
1232
- async handleAuthorization(input) {
1233
- const authorizationType = input.authorizationType;
1234
- const paymentReference = input.paymentReference;
1235
- if (!authorizationType || !paymentReference) {
1236
- return { ok: true };
1237
- }
1238
- this.emit("awaiting_authorization", {
1239
- authorization_type: authorizationType,
1240
- display_text: input.displayText,
1241
- provider: input.provider
1242
- });
1243
- let authorizationResult;
1244
- const submit = async (code) => {
1245
- this.ensureNotAborted();
1246
- const trimmedCode = code.trim();
1247
- if (!trimmedCode) {
1248
- throw new Error("Authorization code is required.");
1249
- }
1250
- const submitResult = await this.client.checkout.submitAuthorization({
1251
- reference: paymentReference,
1252
- auth_type: authorizationType,
1253
- value: trimmedCode
1254
- });
1255
- if (!submitResult.ok) {
1256
- throw new Error(submitResult.error.message || "Authorization failed.");
1257
- }
1258
- authorizationResult = submitResult.value;
1259
- };
1260
- try {
1261
- if (this.onAuthorizationRequired) {
1262
- await this.onAuthorizationRequired(authorizationType, submit);
1263
- } else {
1264
- return {
1265
- ok: false,
1266
- result: this.fail(
1267
- "AUTHORIZATION_REQUIRED",
1268
- "Authorization callback is required in headless checkout mode.",
1269
- false
1270
- )
1271
- };
1272
- }
1273
- } catch (error) {
1274
- if (isAbortError(error)) {
1275
- return {
1276
- ok: false,
1277
- result: this.fail("CANCELLED", "Checkout was cancelled.", true)
1278
- };
1279
- }
1280
- const message = error instanceof Error ? error.message : "Payment authorization failed.";
1281
- return {
1282
- ok: false,
1283
- result: this.fail("AUTHORIZATION_FAILED", message, true)
1284
- };
1285
- }
1286
- return {
1287
- ok: true,
1288
- value: authorizationResult
1289
- };
1290
- }
1291
- async finalizeSuccess(checkoutResult) {
1292
- this.emit("finalizing", {
1293
- order_id: checkoutResult.order_id,
1294
- order_number: checkoutResult.order_number
1295
- });
1296
- const enrolledInLink = await this.maybeEnrollInLink(checkoutResult.order_id);
1297
- this.emit("success", {
1298
- order_id: checkoutResult.order_id,
1299
- order_number: checkoutResult.order_number
1300
- });
1301
- return {
1302
- success: true,
1303
- order: {
1304
- id: checkoutResult.order_id,
1305
- order_number: checkoutResult.order_number || checkoutResult.order_id,
1306
- status: checkoutResult.payment_status || "paid",
1307
- total: this.getOrderTotal(checkoutResult),
1308
- currency: this.getOrderCurrency(checkoutResult)
1309
- },
1310
- enrolled_in_link: enrolledInLink
1311
- };
1312
- }
1313
- async maybeEnrollInLink(orderId) {
1314
- if (!this.enrollInLink || !orderId) {
1315
- return false;
1316
- }
1317
- let businessId = this.businessId;
1318
- if (!businessId) {
1319
- const businessResult = await this.client.business.getInfo();
1320
- if (!businessResult.ok || !businessResult.value?.id) {
1321
- return false;
1322
- }
1323
- businessId = businessResult.value.id;
1324
- }
1325
- const address = this.getEnrollmentAddress();
1326
- const mobileMoney = this.getEnrollmentMobileMoney();
1327
- try {
1328
- const enrollment = await this.client.link.enrollAndLinkOrder({
1329
- order_id: orderId,
1330
- business_id: businessId,
1331
- order_type: this.orderType || this.checkoutData.order_type,
1332
- address,
1333
- mobile_money: mobileMoney
1334
- });
1335
- return enrollment.ok && enrollment.value.success;
1336
- } catch {
1337
- return false;
1338
- }
1339
- }
1340
- getEnrollmentAddress() {
1341
- const source = this.addressData ?? this.checkoutData.address_info;
1342
- if (!source?.street_address) {
1343
- return void 0;
1344
- }
1345
- return {
1346
- label: "Default",
1347
- street_address: source.street_address,
1348
- apartment: source.apartment || void 0,
1349
- city: source.city || "",
1350
- region: source.region || "",
1351
- delivery_instructions: source.delivery_instructions || void 0,
1352
- phone_for_delivery: source.phone_for_delivery || void 0
1353
- };
1354
- }
1355
- getEnrollmentMobileMoney() {
1356
- if (this.paymentData?.type === "mobile_money" && this.paymentData.phone_number && this.paymentData.provider && isValidMobileMoneyProvider(this.paymentData.provider)) {
1357
- return {
1358
- phone_number: this.paymentData.phone_number,
1359
- provider: this.paymentData.provider,
1360
- label: this.paymentData.label || "Mobile Money"
1361
- };
1362
- }
1363
- if (this.checkoutData.mobile_money_details?.phone_number) {
1364
- return {
1365
- phone_number: this.checkoutData.mobile_money_details.phone_number,
1366
- provider: this.checkoutData.mobile_money_details.provider,
1367
- label: "Mobile Money"
1368
- };
1369
- }
1370
- return void 0;
1371
- }
1372
- getOrderTotal(checkoutResult) {
1373
- if (checkoutResult.fx?.pay_amount !== void 0) {
1374
- return formatMoney2(checkoutResult.fx.pay_amount);
1375
- }
1376
- if (this.cartTotal !== void 0) {
1377
- return formatMoney2(this.cartTotal);
1378
- }
1379
- return "0.00";
1380
- }
1381
- getOrderCurrency(checkoutResult) {
1382
- if (checkoutResult.fx?.pay_currency) {
1383
- return checkoutResult.fx.pay_currency;
1384
- }
1385
- if (this.cartCurrency) {
1386
- return this.cartCurrency;
1387
- }
1388
- if (this.checkoutData.pay_currency) {
1389
- return this.checkoutData.pay_currency;
1390
- }
1391
- return "GHS";
1392
- }
1393
- emit(status, context = {}) {
1394
- if (!this.onStatusChange) {
1395
- return;
1396
- }
1397
- try {
1398
- this.onStatusChange(status, context);
1399
- } catch {
1400
- }
1401
- }
1402
- fail(code, message, recoverable) {
1403
- this.emit("failed", {
1404
- display_text: message
1405
- });
1406
- return {
1407
- success: false,
1408
- error: {
1409
- code,
1410
- message,
1411
- recoverable
1412
- }
1413
- };
1414
- }
1415
- isSuccessfulStatus(status) {
1416
- const normalized = normalizeStatusResponse({ status, paid: false });
1417
- return normalized.paid || isPaymentStatusSuccess(normalized.status);
1418
- }
1419
- isFailureStatus(status) {
1420
- const normalized = normalizeStatusResponse({ status, paid: false });
1421
- return isPaymentStatusFailure(normalized.status);
1422
- }
1423
- ensureNotAborted() {
1424
- if (this.signal?.aborted) {
1425
- throw createAbortError();
1426
- }
1427
- }
1428
- wait(ms) {
1429
- this.ensureNotAborted();
1430
- return new Promise((resolve, reject) => {
1431
- const timer = setTimeout(() => {
1432
- if (this.signal) {
1433
- this.signal.removeEventListener("abort", onAbort);
1434
- }
1435
- resolve();
1436
- }, ms);
1437
- const onAbort = () => {
1438
- clearTimeout(timer);
1439
- reject(createAbortError());
1440
- };
1441
- if (this.signal) {
1442
- this.signal.addEventListener("abort", onAbort, { once: true });
1443
- }
1444
- });
1445
- }
1446
- };
1447
-
1448
- // src/checkout.ts
1449
- function toTerminalFailure(code, message, recoverable) {
1450
- return {
1451
- success: false,
1452
- error: {
1453
- code,
1454
- message,
1455
- recoverable
1456
- }
1457
- };
1458
- }
1459
- function generateIdempotencyKey() {
1460
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
1461
- return `idem_${crypto.randomUUID()}`;
1462
- }
1463
- const timestamp = Date.now().toString(36);
1464
- const random = Math.random().toString(36).substring(2, 15);
1465
- return `idem_${timestamp}_${random}`;
1466
- }
1467
- var CheckoutService = class {
1468
- constructor(client) {
1469
- this.client = client;
1470
- }
1471
- orderTokenParam(orderId) {
1472
- const token = this.client.getOrderToken(orderId);
1473
- return token ? `?token=${encodeURIComponent(token)}` : "";
1474
- }
1475
- async process(data) {
1476
- const checkoutData = {
1477
- ...data,
1478
- idempotency_key: data.idempotency_key || generateIdempotencyKey()
1479
- };
1480
- const result = await safe(
1481
- this.client.post("/api/v1/checkout", {
1482
- checkout_data: checkoutData
1483
- })
1484
- );
1485
- if (result.ok && result.value.bill_token) {
1486
- this.client.setOrderToken(result.value.order_id, result.value.bill_token);
1487
- }
1488
- return result;
1489
- }
1490
- async initializePayment(_orderId, _method) {
1491
- return err(
1492
- new CimplifyError(
1493
- "NOT_IMPLEMENTED",
1494
- "initializePayment is not available in REST mode.",
1495
- false
1496
- )
1497
- );
1498
- }
1499
- async submitAuthorization(input) {
1500
- return safe(this.client.post("/api/v1/payments/authorization", input));
1501
- }
1502
- async pollPaymentStatus(orderId) {
1503
- const encodedId = encodeURIComponent(orderId);
1504
- const tokenParam = this.orderTokenParam(orderId);
1505
- return safe(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
1506
- }
1507
- async updateOrderCustomer(orderId, customer) {
1508
- const encodedId = encodeURIComponent(orderId);
1509
- const tokenParam = this.orderTokenParam(orderId);
1510
- return safe(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
1511
- }
1512
- async verifyPayment(orderId) {
1513
- const encodedId = encodeURIComponent(orderId);
1514
- const tokenParam = this.orderTokenParam(orderId);
1515
- return safe(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
1516
- }
1517
- async processAndResolve(data) {
1518
- data.on_status_change?.("preparing", {});
1519
- if (!data.cart_id) {
1520
- return ok(
1521
- toTerminalFailure(
1522
- "INVALID_CART",
1523
- "A valid cart is required before checkout can start.",
1524
- false
1525
- )
1526
- );
1527
- }
1528
- const cartResult = await this.client.cart.get();
1529
- if (!cartResult.ok || !cartResult.value?.id) {
1530
- return ok(
1531
- toTerminalFailure(
1532
- "INVALID_CART",
1533
- "Unable to load cart for checkout.",
1534
- false
1535
- )
1536
- );
1537
- }
1538
- const cart = cartResult.value;
1539
- if (cart.id !== data.cart_id || cart.items.length === 0) {
1540
- return ok(
1541
- toTerminalFailure(
1542
- "INVALID_CART",
1543
- "Cart is empty or no longer valid. Please refresh and try again.",
1544
- false
1545
- )
1546
- );
1547
- }
1548
- const checkoutData = {
1549
- cart_id: data.cart_id,
1550
- location_id: data.location_id,
1551
- customer: data.customer,
1552
- order_type: data.order_type,
1553
- address_info: data.address_info,
1554
- payment_method: data.payment_method,
1555
- mobile_money_details: data.mobile_money_details,
1556
- special_instructions: data.special_instructions,
1557
- link_address_id: data.link_address_id,
1558
- link_payment_method_id: data.link_payment_method_id,
1559
- idempotency_key: data.idempotency_key || generateIdempotencyKey(),
1560
- metadata: data.metadata,
1561
- pay_currency: data.pay_currency,
1562
- fx_quote_id: data.fx_quote_id
1563
- };
1564
- const baseCurrency = currencyCode(
1565
- (cart.pricing.currency || checkoutData.pay_currency || "GHS").toUpperCase()
1566
- );
1567
- const payCurrency = data.pay_currency?.trim().toUpperCase();
1568
- const payCurrencyCode = payCurrency ? currencyCode(payCurrency) : void 0;
1569
- const cartTotalAmount = typeof cart.pricing.total_price === "number" ? cart.pricing.total_price : Number.parseFloat(cart.pricing.total_price || "0");
1570
- if (payCurrencyCode && payCurrencyCode !== baseCurrency && !checkoutData.fx_quote_id && Number.isFinite(cartTotalAmount) && cartTotalAmount > 0) {
1571
- const fxQuoteResult = await this.client.fx.lockQuote({
1572
- from: baseCurrency,
1573
- to: payCurrencyCode,
1574
- amount: cart.pricing.total_price
1575
- });
1576
- if (!fxQuoteResult.ok) {
1577
- return ok(
1578
- toTerminalFailure(
1579
- "FX_QUOTE_FAILED",
1580
- fxQuoteResult.error.message || "Unable to lock FX quote for checkout.",
1581
- true
1582
- )
1583
- );
1584
- }
1585
- checkoutData.pay_currency = payCurrencyCode;
1586
- checkoutData.fx_quote_id = fxQuoteResult.value.id;
1587
- }
1588
- data.on_status_change?.("processing", {});
1589
- const processResult = await this.process(checkoutData);
1590
- if (!processResult.ok) {
1591
- return ok(
1592
- toTerminalFailure(
1593
- processResult.error.code || "CHECKOUT_FAILED",
1594
- processResult.error.message || "Unable to process checkout.",
1595
- processResult.error.retryable ?? true
1596
- )
1597
- );
1598
- }
1599
- const resolver = new CheckoutResolver({
1600
- client: this.client,
1601
- checkoutData,
1602
- pollIntervalMs: data.poll_interval_ms,
1603
- maxPollAttempts: data.max_poll_attempts,
1604
- onStatusChange: data.on_status_change,
1605
- onAuthorizationRequired: data.on_authorization_required,
1606
- signal: data.signal,
1607
- returnUrl: data.return_url,
1608
- enrollInLink: data.enroll_in_link,
1609
- cartTotal: cart.pricing.total_price,
1610
- cartCurrency: checkoutData.pay_currency || cart.pricing.currency || "GHS",
1611
- orderType: checkoutData.order_type,
1612
- allowPopups: data.allow_popups
1613
- });
1614
- const resolved = await resolver.resolve(processResult.value);
1615
- return ok(resolved);
1616
- }
1617
- };
1618
-
1619
- // src/orders.ts
1620
- var OrderQueries = class {
1621
- constructor(client) {
1622
- this.client = client;
1623
- }
1624
- orderTokenParam(orderId) {
1625
- const token = this.client.getOrderToken(orderId);
1626
- return token ? `?token=${encodeURIComponent(token)}` : "";
1627
- }
1628
- async list(options) {
1629
- const params = new URLSearchParams();
1630
- if (options?.status) params.set("status", options.status);
1631
- if (options?.limit) params.set("limit", String(options.limit));
1632
- if (options?.offset) params.set("offset", String(options.offset));
1633
- const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
1634
- return safe(this.client.get(path));
1635
- }
1636
- async get(orderId) {
1637
- const encodedId = encodeURIComponent(orderId);
1638
- const tokenParam = this.orderTokenParam(orderId);
1639
- return safe(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
1640
- }
1641
- async getRecent(limit = 5) {
1642
- return this.list({ limit });
1643
- }
1644
- async getByStatus(status) {
1645
- return this.list({ status });
1646
- }
1647
- async cancel(orderId, reason) {
1648
- const encodedId = encodeURIComponent(orderId);
1649
- const tokenParam = this.orderTokenParam(orderId);
1650
- return safe(
1651
- this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
1652
- reason
1653
- })
1654
- );
1655
- }
1656
- };
1657
-
1658
- // src/link.ts
1659
- function encodePathSegment(value) {
1660
- return encodeURIComponent(value);
1661
- }
1662
- function toCreateAddressPayload(input) {
1663
- return {
1664
- label: input.label,
1665
- street_address: input.address_line1,
1666
- apartment: input.address_line2,
1667
- city: input.city,
1668
- region: input.state ?? "",
1669
- postal_code: input.postal_code,
1670
- country: input.country
1671
- };
1672
- }
1673
- function toUpdateAddressPayload(input) {
1674
- return {
1675
- label: input.label,
1676
- street_address: input.address_line1,
1677
- apartment: input.address_line2,
1678
- city: input.city,
1679
- region: input.state,
1680
- postal_code: input.postal_code,
1681
- country: input.country
1682
- };
1683
- }
1684
- function toCreateMobileMoneyPayload(input) {
1685
- return {
1686
- phone_number: input.phone_number,
1687
- provider: input.provider,
1688
- label: input.account_name
1689
- };
1690
- }
1691
- var LinkService = class {
1692
- constructor(client) {
1693
- this.client = client;
1694
- }
1695
- async getProfile() {
1696
- return safe(this.client.linkGet("/v1/link/profile"));
1697
- }
1698
- async requestOtp(input) {
1699
- return safe(this.client.linkPost("/v1/link/auth/request-otp", input));
1700
- }
1701
- async verifyOtp(input) {
1702
- const result = await safe(
1703
- this.client.linkPost("/v1/link/auth/verify-otp", input)
1704
- );
1705
- if (result.ok && result.value.session_token) {
1706
- this.client.setAccessToken(result.value.session_token);
1707
- }
1708
- return result;
1709
- }
1710
- async logout() {
1711
- const result = await safe(this.client.linkPost("/v1/link/auth/logout"));
1712
- if (result.ok) {
1713
- this.client.clearSession();
1714
- }
1715
- return result;
1716
- }
1717
- async checkStatus(contact) {
1718
- return safe(this.client.linkPost("/v1/link/check-status", { contact }));
1719
- }
1720
- async getLinkData() {
1721
- return safe(this.client.linkGet("/v1/link/data"));
1722
- }
1723
- async getAddresses() {
1724
- return safe(this.client.linkGet("/v1/link/addresses"));
1725
- }
1726
- async getMobileMoney() {
1727
- return safe(this.client.linkGet("/v1/link/mobile-money"));
1728
- }
1729
- async getPreferences() {
1730
- return safe(this.client.linkGet("/v1/link/preferences"));
1731
- }
1732
- async enroll(data) {
1733
- return safe(this.client.linkPost("/v1/link/enroll", data));
1734
- }
1735
- async enrollAndLinkOrder(data) {
1736
- return safe(
1737
- this.client.linkPost("/v1/link/enroll-and-link-order", data)
1738
- );
1739
- }
1740
- async updatePreferences(preferences) {
1741
- return safe(this.client.linkPost("/v1/link/preferences", preferences));
1742
- }
1743
- async createAddress(input) {
1744
- return safe(
1745
- this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
1746
- );
1747
- }
1748
- async updateAddress(input) {
1749
- return safe(
1750
- this.client.linkPost(
1751
- `/v1/link/addresses/${encodePathSegment(input.address_id)}`,
1752
- toUpdateAddressPayload(input)
1753
- )
1754
- );
1755
- }
1756
- async deleteAddress(addressId) {
1757
- return safe(
1758
- this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
1759
- );
1760
- }
1761
- async setDefaultAddress(addressId) {
1762
- return safe(
1763
- this.client.linkPost(
1764
- `/v1/link/addresses/${encodePathSegment(addressId)}/default`
1765
- )
1766
- );
1767
- }
1768
- async trackAddressUsage(addressId) {
1769
- return safe(
1770
- this.client.linkPost(
1771
- `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
1772
- )
1773
- );
1774
- }
1775
- async createMobileMoney(input) {
1776
- return safe(
1777
- this.client.linkPost(
1778
- "/v1/link/mobile-money",
1779
- toCreateMobileMoneyPayload(input)
1780
- )
1781
- );
1782
- }
1783
- async deleteMobileMoney(mobileMoneyId) {
1784
- return safe(
1785
- this.client.linkDelete(
1786
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
1787
- )
1788
- );
1789
- }
1790
- async setDefaultMobileMoney(mobileMoneyId) {
1791
- return safe(
1792
- this.client.linkPost(
1793
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
1794
- )
1795
- );
1796
- }
1797
- async trackMobileMoneyUsage(mobileMoneyId) {
1798
- return safe(
1799
- this.client.linkPost(
1800
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
1801
- )
1802
- );
1803
- }
1804
- async verifyMobileMoney(mobileMoneyId) {
1805
- return safe(
1806
- this.client.linkPost(
1807
- `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
1808
- )
1809
- );
1810
- }
1811
- async getSessions() {
1812
- return safe(this.client.linkGet("/v1/link/sessions"));
1813
- }
1814
- async revokeSession(sessionId) {
1815
- return safe(this.client.linkDelete(`/v1/link/sessions/${sessionId}`));
1816
- }
1817
- async revokeAllSessions() {
1818
- return safe(this.client.linkDelete("/v1/link/sessions"));
1819
- }
1820
- };
1821
-
1822
- // src/auth.ts
1823
- var AuthService = class {
1824
- constructor(client) {
1825
- this.client = client;
1826
- }
1827
- async getStatus() {
1828
- return safe(this.client.get("/api/v1/auth/status"));
1829
- }
1830
- async getCurrentUser() {
1831
- const result = await this.getStatus();
1832
- if (!result.ok) return result;
1833
- return ok(result.value.customer || null);
1834
- }
1835
- async isAuthenticated() {
1836
- const result = await this.getStatus();
1837
- if (!result.ok) return result;
1838
- return ok(result.value.is_authenticated);
1839
- }
1840
- async requestOtp(contact, contactType) {
1841
- return safe(
1842
- this.client.post("/api/v1/auth/request-otp", {
1843
- contact,
1844
- contact_type: contactType
1845
- })
1846
- );
1847
- }
1848
- async verifyOtp(code, contact) {
1849
- return safe(
1850
- this.client.post("/api/v1/auth/verify-otp", {
1851
- otp_code: code,
1852
- contact
1853
- })
1854
- );
1855
- }
1856
- async logout() {
1857
- return safe(this.client.post("/api/v1/auth/logout"));
1858
- }
1859
- async updateProfile(input) {
1860
- return safe(this.client.post("/api/v1/auth/profile", input));
1861
- }
1862
- };
1863
-
1864
- // src/business.ts
1865
- var BusinessService = class {
1866
- constructor(client) {
1867
- this.client = client;
1868
- }
1869
- async getInfo() {
1870
- return safe(this.client.get("/api/v1/business"));
1871
- }
1872
- async getByHandle(handle) {
1873
- const encodedHandle = encodeURIComponent(handle);
1874
- return safe(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
1875
- }
1876
- async getByDomain(domain) {
1877
- const encodedDomain = encodeURIComponent(domain);
1878
- return safe(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
1879
- }
1880
- async getSettings() {
1881
- return safe(this.client.get("/api/v1/business/settings"));
1882
- }
1883
- async getLocations() {
1884
- return safe(this.client.get("/api/v1/business/locations"));
1885
- }
1886
- async getLocation(locationId) {
1887
- const result = await this.getLocations();
1888
- if (!result.ok) return err(result.error);
1889
- const location = result.value.find((item) => item.id === locationId);
1890
- if (!location) {
1891
- return err(new CimplifyError(ErrorCode.NOT_FOUND, `Location not found: ${locationId}`, false));
1892
- }
1893
- return ok(location);
1894
- }
1895
- async getHours() {
1896
- return safe(this.client.get("/api/v1/business/hours"));
1897
- }
1898
- async getLocationHours(locationId) {
1899
- const result = await this.getHours();
1900
- if (!result.ok) return result;
1901
- return ok(result.value.filter((hour) => hour.location_id === locationId));
1902
- }
1903
- async getBootstrap() {
1904
- return safe(this.client.get("/api/v1/bootstrap"));
1905
- }
1906
- };
1907
-
1908
- // src/inventory.ts
1909
- var InventoryService = class {
1910
- constructor(client) {
1911
- this.client = client;
1912
- }
1913
- withQuery(path, params) {
1914
- const searchParams = new URLSearchParams();
1915
- for (const [key, value] of Object.entries(params)) {
1916
- if (value === void 0) continue;
1917
- searchParams.set(key, String(value));
1918
- }
1919
- const query2 = searchParams.toString();
1920
- return query2 ? `${path}?${query2}` : path;
1921
- }
1922
- async getProductStock(productId, locationId) {
1923
- const encodedId = encodeURIComponent(productId);
1924
- const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
1925
- location_id: locationId
1926
- });
1927
- return safe(this.client.get(path));
1928
- }
1929
- async getVariantStock(variantId, locationId) {
1930
- const encodedId = encodeURIComponent(variantId);
1931
- const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
1932
- location_id: locationId
1933
- });
1934
- return safe(this.client.get(path));
1935
- }
1936
- async checkProductAvailability(productId, quantity, locationId) {
1937
- const encodedId = encodeURIComponent(productId);
1938
- const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
1939
- quantity,
1940
- location_id: locationId
1941
- });
1942
- return safe(this.client.get(path));
1943
- }
1944
- async checkVariantAvailability(variantId, quantity, locationId) {
1945
- const encodedId = encodeURIComponent(variantId);
1946
- const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
1947
- quantity,
1948
- location_id: locationId
1949
- });
1950
- return safe(this.client.get(path));
1951
- }
1952
- async checkMultipleAvailability(items, locationId) {
1953
- const results = await Promise.all(
1954
- items.map(
1955
- (item) => item.variant_id ? this.checkVariantAvailability(item.variant_id, item.quantity, locationId) : this.checkProductAvailability(item.product_id, item.quantity, locationId)
1956
- )
1957
- );
1958
- for (const result of results) {
1959
- if (!result.ok) return result;
1960
- }
1961
- return ok(results.map((r) => r.value));
1962
- }
1963
- async isInStock(productId, locationId) {
1964
- const result = await this.checkProductAvailability(productId, 1, locationId);
1965
- if (!result.ok) return result;
1966
- return ok(result.value.is_available);
1967
- }
1968
- async getAvailableQuantity(productId, locationId) {
1969
- const result = await this.getProductStock(productId, locationId);
1970
- if (!result.ok) return result;
1971
- return ok(result.value.available_quantity);
1972
- }
1973
- };
1974
-
1975
- // src/scheduling.ts
1976
- function withQuery2(path, params) {
1977
- const searchParams = new URLSearchParams();
1978
- for (const [key, value] of Object.entries(params)) {
1979
- if (value === void 0) continue;
1980
- searchParams.set(key, String(value));
1981
- }
1982
- const query2 = searchParams.toString();
1983
- return query2 ? `${path}?${query2}` : path;
1984
- }
1985
- function firstScheduledTime(booking) {
1986
- return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
1987
- }
1988
- var SchedulingService = class {
1989
- constructor(client) {
1990
- this.client = client;
1991
- }
1992
- async getServices() {
1993
- return safe(this.client.get("/api/v1/scheduling/services"));
1994
- }
1995
- async getService(serviceId) {
1996
- const encodedId = encodeURIComponent(serviceId);
1997
- return safe(this.client.get(`/api/v1/scheduling/services/${encodedId}`));
1998
- }
1999
- async getAvailableSlots(input) {
2000
- const path = withQuery2("/api/v1/scheduling/slots", {
2001
- service_id: input.service_id,
2002
- date: input.date,
2003
- participant_count: input.participant_count,
2004
- duration_minutes: input.duration_minutes
2005
- });
2006
- return safe(this.client.get(path));
2007
- }
2008
- async checkSlotAvailability(input) {
2009
- const path = withQuery2("/api/v1/scheduling/slots/check", {
2010
- service_id: input.service_id,
2011
- slot_time: input.slot_time,
2012
- duration_minutes: input.duration_minutes,
2013
- participant_count: input.participant_count
2014
- });
2015
- return safe(this.client.get(path));
2016
- }
2017
- async getServiceAvailability(params) {
2018
- const path = withQuery2("/api/v1/scheduling/availability", {
2019
- service_id: params.service_id,
2020
- start_date: params.start_date,
2021
- end_date: params.end_date,
2022
- location_id: params.location_id,
2023
- participant_count: params.participant_count
2024
- });
2025
- return safe(this.client.get(path));
2026
- }
2027
- async getBooking(bookingId) {
2028
- const encodedId = encodeURIComponent(bookingId);
2029
- return safe(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2030
- }
2031
- async getCustomerBookings(customerId) {
2032
- const path = withQuery2("/api/v1/scheduling/bookings", {
2033
- customer_id: customerId
2034
- });
2035
- return safe(this.client.get(path));
2036
- }
2037
- async getUpcomingBookings() {
2038
- const result = await this.getCustomerBookings();
2039
- if (!result.ok) return result;
2040
- const upcoming = result.value.filter((booking) => {
2041
- const status = String(booking.status).toLowerCase();
2042
- return status !== "completed" && status !== "cancelled";
2043
- }).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
2044
- return ok(upcoming);
2045
- }
2046
- async getPastBookings(limit = 10) {
2047
- const result = await this.getCustomerBookings();
2048
- if (!result.ok) return result;
2049
- 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));
2050
- return ok(past);
2051
- }
2052
- async cancelBooking(input) {
2053
- const encodedId = encodeURIComponent(input.booking_id);
2054
- return safe(
2055
- this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
2056
- reason: input.reason
2057
- })
2058
- );
2059
- }
2060
- async rescheduleBooking(input) {
2061
- return safe(
2062
- this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2063
- );
2064
- }
2065
- async getNextAvailableSlot(serviceId, fromDate) {
2066
- const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2067
- const result = await this.getAvailableSlots({
2068
- service_id: serviceId,
2069
- date
2070
- });
2071
- if (!result.ok) return result;
2072
- return ok(result.value.find((slot) => slot.is_available) || null);
2073
- }
2074
- async hasAvailabilityOn(serviceId, date) {
2075
- const result = await this.getAvailableSlots({
2076
- service_id: serviceId,
2077
- date
2078
- });
2079
- if (!result.ok) return result;
2080
- return ok(result.value.some((slot) => slot.is_available));
2081
- }
2082
- };
2083
-
2084
- // src/lite.ts
2085
- var LiteService = class {
2086
- constructor(client) {
2087
- this.client = client;
2088
- }
2089
- async getBootstrap() {
2090
- return safe(this.client.get("/api/v1/lite/bootstrap"));
2091
- }
2092
- async getTable(tableId) {
2093
- const encodedId = encodeURIComponent(tableId);
2094
- return safe(this.client.get(`/api/v1/lite/tables/${encodedId}`));
2095
- }
2096
- async getMenu() {
2097
- return safe(this.client.get("/api/v1/lite/menu"));
2098
- }
2099
- async getMenuByCategory(categoryId) {
2100
- const encodedId = encodeURIComponent(categoryId);
2101
- return safe(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
2102
- }
2103
- };
2104
-
2105
- // src/fx.ts
2106
- var FxService = class {
2107
- constructor(client) {
2108
- this.client = client;
2109
- }
2110
- async getRate(from, to) {
2111
- const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
2112
- return safe(this.client.get(path));
2113
- }
2114
- async lockQuote(request) {
2115
- return safe(this.client.post("/api/v1/fx/quotes", request));
2116
- }
2117
- };
2118
-
2119
- // src/types/elements.ts
2120
- var ELEMENT_TYPES = {
2121
- AUTH: "auth",
2122
- ADDRESS: "address",
2123
- PAYMENT: "payment",
2124
- CHECKOUT: "checkout"
2125
- };
2126
- var MESSAGE_TYPES = {
2127
- INIT: "init",
2128
- SET_TOKEN: "set_token",
2129
- SET_CART: "set_cart",
2130
- GET_DATA: "get_data",
2131
- REFRESH_TOKEN: "refresh_token",
2132
- LOGOUT: "logout",
2133
- PROCESS_CHECKOUT: "process_checkout",
2134
- ABORT_CHECKOUT: "abort_checkout",
2135
- READY: "ready",
2136
- HEIGHT_CHANGE: "height_change",
2137
- AUTHENTICATED: "authenticated",
2138
- REQUIRES_OTP: "requires_otp",
2139
- ERROR: "error",
2140
- ADDRESS_CHANGED: "address_changed",
2141
- ADDRESS_SELECTED: "address_selected",
2142
- PAYMENT_METHOD_SELECTED: "payment_method_selected",
2143
- TOKEN_REFRESHED: "token_refreshed",
2144
- LOGOUT_COMPLETE: "logout_complete",
2145
- CONTACT_PROVIDED: "contact_provided",
2146
- CHECKOUT_STATUS: "checkout_status",
2147
- CHECKOUT_COMPLETE: "checkout_complete",
2148
- ORDER_TYPE_CHANGED: "order_type_changed",
2149
- REQUEST_SUBMIT: "request_submit"
2150
- };
2151
- var EVENT_TYPES = {
2152
- READY: "ready",
2153
- AUTHENTICATED: "authenticated",
2154
- REQUIRES_OTP: "requires_otp",
2155
- ERROR: "error",
2156
- CHANGE: "change",
2157
- BLUR: "blur",
2158
- FOCUS: "focus",
2159
- ORDER_TYPE_CHANGED: "order_type_changed",
2160
- REQUEST_SUBMIT: "request_submit"
2161
- };
2162
-
2163
- // src/elements.ts
2164
- function toCheckoutError(code, message, recoverable) {
2165
- const hint = getErrorHint(code);
2166
- return {
2167
- success: false,
2168
- error: {
2169
- code,
2170
- message,
2171
- recoverable,
2172
- docs_url: hint?.docs_url,
2173
- suggestion: hint?.suggestion
2174
- }
2175
- };
2176
- }
2177
- var DEFAULT_LINK_URL = "https://link.cimplify.io";
2178
- function generateNonce() {
2179
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2180
- return crypto.randomUUID().replace(/-/g, "").slice(0, 16);
2181
- }
2182
- return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
2183
- }
2184
- function isAllowedOrigin(origin) {
2185
- try {
2186
- const url = new URL(origin);
2187
- const hostname = url.hostname;
2188
- if (hostname === "localhost" || hostname === "127.0.0.1") {
2189
- return true;
2190
- }
2191
- if (url.protocol !== "https:") {
2192
- return false;
2193
- }
2194
- return hostname === "cimplify.io" || hostname.endsWith(".cimplify.io");
2195
- } catch {
2196
- return false;
2197
- }
2198
- }
2199
- function parseIframeMessage(data) {
2200
- if (!data || typeof data !== "object") {
2201
- return null;
2202
- }
2203
- const maybeType = data.type;
2204
- if (typeof maybeType !== "string") {
2205
- return null;
2206
- }
2207
- return data;
2208
- }
2209
- var CimplifyElements = class {
2210
- constructor(client, businessId, options = {}) {
2211
- this.elements = /* @__PURE__ */ new Map();
2212
- this.accessToken = null;
2213
- this.accountId = null;
2214
- this.customerId = null;
2215
- this.customerData = null;
2216
- this.addressData = null;
2217
- this.paymentData = null;
2218
- this.checkoutInProgress = false;
2219
- this.activeCheckoutAbort = null;
2220
- this.businessIdResolvePromise = null;
2221
- this.client = client;
2222
- this.businessId = businessId ?? null;
2223
- this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2224
- this.options = options;
2225
- this.boundHandleMessage = this.handleMessage.bind(this);
2226
- if (typeof window !== "undefined") {
2227
- window.addEventListener("message", this.boundHandleMessage);
2228
- }
2229
- }
2230
- debug(...args) {
2231
- if (this.client.isTestMode()) {
2232
- console.debug(...args);
2233
- }
2234
- }
2235
- create(type, options = {}) {
2236
- const existing = this.elements.get(type);
2237
- if (existing) return existing;
2238
- const element = new CimplifyElement(type, this.businessId, this.linkUrl, options, this);
2239
- this.elements.set(type, element);
2240
- return element;
2241
- }
2242
- getElement(type) {
2243
- return this.elements.get(type);
2244
- }
2245
- _removeElement(type, instance) {
2246
- const current = this.elements.get(type);
2247
- if (current === instance) {
2248
- this.elements.delete(type);
2249
- }
2250
- }
2251
- destroy() {
2252
- this.elements.forEach((element) => element.destroy());
2253
- this.elements.clear();
2254
- if (typeof window !== "undefined") {
2255
- window.removeEventListener("message", this.boundHandleMessage);
2256
- }
2257
- }
2258
- async submitCheckout(data) {
2259
- const result = await this.processCheckout({
2260
- cart_id: data.cart_id,
2261
- order_type: data.order_type ?? "delivery",
2262
- location_id: data.location_id,
2263
- notes: data.notes,
2264
- scheduled_time: data.scheduled_time,
2265
- tip_amount: data.tip_amount,
2266
- enroll_in_link: true
2267
- });
2268
- if (result.success) {
2269
- return {
2270
- success: true,
2271
- order: {
2272
- id: result.order?.id || "",
2273
- status: result.order?.status || "unknown",
2274
- total: result.order?.total || ""
2275
- }
2276
- };
2277
- }
2278
- return {
2279
- success: false,
2280
- error: {
2281
- code: result.error?.code || "CHECKOUT_FAILED",
2282
- message: result.error?.message || "Checkout failed"
2283
- }
2284
- };
2285
- }
2286
- processCheckout(options) {
2287
- let abortFn = null;
2288
- const task = (async () => {
2289
- this.debug("[cimplify:checkout] processCheckout called", { cart_id: options.cart_id, order_type: options.order_type, location_id: options.location_id });
2290
- if (this.checkoutInProgress) {
2291
- this.debug("[cimplify:checkout] BLOCKED: already processing");
2292
- return toCheckoutError(
2293
- "ALREADY_PROCESSING",
2294
- "Checkout is already in progress.",
2295
- false
2296
- );
2297
- }
2298
- this.checkoutInProgress = true;
2299
- if (!options.cart_id) {
2300
- this.debug("[cimplify:checkout] BLOCKED: no cart_id");
2301
- this.checkoutInProgress = false;
2302
- return toCheckoutError(
2303
- "INVALID_CART",
2304
- "A valid cart is required before checkout can start.",
2305
- false
2306
- );
2307
- }
2308
- if (!options.order_type) {
2309
- this.debug("[cimplify:checkout] BLOCKED: no order_type");
2310
- this.checkoutInProgress = false;
2311
- return toCheckoutError(
2312
- "ORDER_TYPE_REQUIRED",
2313
- "Order type is required before checkout can start.",
2314
- false
2315
- );
2316
- }
2317
- const checkoutElement = this.elements.get(ELEMENT_TYPES.CHECKOUT) || this.elements.get(ELEMENT_TYPES.PAYMENT);
2318
- if (!checkoutElement) {
2319
- this.debug("[cimplify:checkout] BLOCKED: no checkout element");
2320
- this.checkoutInProgress = false;
2321
- return toCheckoutError(
2322
- "NO_PAYMENT_ELEMENT",
2323
- "Checkout element must be mounted before checkout.",
2324
- false
2325
- );
2326
- }
2327
- if (!checkoutElement.isMounted()) {
2328
- this.debug("[cimplify:checkout] BLOCKED: checkout element not mounted");
2329
- this.checkoutInProgress = false;
2330
- return toCheckoutError(
2331
- "PAYMENT_NOT_MOUNTED",
2332
- "Checkout element must be mounted before checkout.",
2333
- false
2334
- );
2335
- }
2336
- const isUnifiedCheckout = this.elements.has(ELEMENT_TYPES.CHECKOUT);
2337
- if (!isUnifiedCheckout) {
2338
- const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
2339
- if (authElement && !this.accessToken) {
2340
- this.debug("[cimplify:checkout] BLOCKED: auth incomplete");
2341
- this.checkoutInProgress = false;
2342
- return toCheckoutError(
2343
- "AUTH_INCOMPLETE",
2344
- "Authentication must complete before checkout can start.",
2345
- true
2346
- );
2347
- }
2348
- const addressElement = this.elements.get(ELEMENT_TYPES.ADDRESS);
2349
- if (addressElement) {
2350
- this.debug("[cimplify:checkout] getting address data...");
2351
- await addressElement.getData();
2352
- this.debug("[cimplify:checkout] address data resolved", this.addressData);
2353
- }
2354
- await this.hydrateCustomerData();
2355
- }
2356
- this.debug("[cimplify:checkout] customer data hydrated", { customerData: this.customerData, accountId: this.accountId, isUnifiedCheckout });
2357
- const processMessage = {
2358
- type: MESSAGE_TYPES.PROCESS_CHECKOUT,
2359
- cart_id: options.cart_id,
2360
- order_type: options.order_type,
2361
- location_id: options.location_id,
2362
- notes: options.notes,
2363
- scheduled_time: options.scheduled_time,
2364
- tip_amount: options.tip_amount,
2365
- pay_currency: options.pay_currency,
2366
- enroll_in_link: options.enroll_in_link ?? true,
2367
- address: isUnifiedCheckout ? void 0 : this.addressData ?? void 0,
2368
- customer: isUnifiedCheckout ? void 0 : this.customerData ? {
2369
- name: this.customerData.name,
2370
- email: this.customerData.email,
2371
- phone: this.customerData.phone
2372
- } : null,
2373
- account_id: this.accountId ?? void 0,
2374
- customer_id: this.customerId ?? void 0
2375
- };
2376
- const timeoutMs = options.timeout_ms ?? 18e4;
2377
- const paymentWindow = checkoutElement.getContentWindow();
2378
- return new Promise((resolve) => {
2379
- let settled = false;
2380
- const cleanup = () => {
2381
- if (typeof window !== "undefined") {
2382
- window.removeEventListener("message", handleCheckoutMessage);
2383
- }
2384
- clearTimeout(timeout);
2385
- this.checkoutInProgress = false;
2386
- this.activeCheckoutAbort = null;
2387
- };
2388
- const settle = (result) => {
2389
- if (settled) {
2390
- return;
2391
- }
2392
- settled = true;
2393
- cleanup();
2394
- resolve(result);
2395
- };
2396
- const timeout = setTimeout(() => {
2397
- settle(
2398
- toCheckoutError(
2399
- "TIMEOUT",
2400
- "Checkout timed out before receiving a terminal response.",
2401
- true
2402
- )
2403
- );
2404
- }, timeoutMs);
2405
- const handleCheckoutMessage = (event) => {
2406
- if (!isAllowedOrigin(event.origin)) {
2407
- return;
2408
- }
2409
- const message = parseIframeMessage(event.data);
2410
- if (!message) {
2411
- return;
2412
- }
2413
- if (message.type === MESSAGE_TYPES.LOGOUT_COMPLETE) {
2414
- checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
2415
- settle(
2416
- toCheckoutError(
2417
- "AUTH_LOST",
2418
- "Authentication was cleared during checkout.",
2419
- true
2420
- )
2421
- );
2422
- return;
2423
- }
2424
- if (paymentWindow && event.source && event.source !== paymentWindow) {
2425
- return;
2426
- }
2427
- if (message.type === MESSAGE_TYPES.CHECKOUT_STATUS) {
2428
- options.on_status_change?.(message.status, message.context);
2429
- return;
2430
- }
2431
- if (message.type === MESSAGE_TYPES.CHECKOUT_COMPLETE) {
2432
- this.debug("[cimplify:checkout] received checkout_complete", { success: message.success, error: message.error });
2433
- settle({
2434
- success: message.success,
2435
- order: message.order,
2436
- error: message.error,
2437
- enrolled_in_link: message.enrolled_in_link
2438
- });
2439
- }
2440
- };
2441
- if (typeof window !== "undefined") {
2442
- window.addEventListener("message", handleCheckoutMessage);
2443
- }
2444
- abortFn = () => {
2445
- checkoutElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
2446
- settle(
2447
- toCheckoutError(
2448
- "CANCELLED",
2449
- "Checkout was cancelled.",
2450
- true
2451
- )
2452
- );
2453
- };
2454
- this.activeCheckoutAbort = abortFn;
2455
- 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 });
2456
- checkoutElement.sendMessage(processMessage);
2457
- this.debug("[cimplify:checkout] postMessage sent, waiting for checkout_complete...");
2458
- });
2459
- })();
2460
- const abortable = task;
2461
- abortable.abort = () => {
2462
- if (abortFn) {
2463
- abortFn();
2464
- }
2465
- };
2466
- return abortable;
2467
- }
2468
- isAuthenticated() {
2469
- return this.accessToken !== null;
2470
- }
2471
- getAccessToken() {
2472
- return this.accessToken;
2473
- }
2474
- getPublicKey() {
2475
- return this.client.getPublicKey();
2476
- }
2477
- getBusinessId() {
2478
- return this.businessId;
2479
- }
2480
- async resolveBusinessId() {
2481
- if (this.businessId) {
2482
- return this.businessId;
2483
- }
2484
- if (this.businessIdResolvePromise) {
2485
- return this.businessIdResolvePromise;
2486
- }
2487
- this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
2488
- this.businessId = resolvedBusinessId;
2489
- return resolvedBusinessId;
2490
- }).catch(() => null).finally(() => {
2491
- this.businessIdResolvePromise = null;
2492
- });
2493
- return this.businessIdResolvePromise;
2494
- }
2495
- getAppearance() {
2496
- return this.options.appearance;
2497
- }
2498
- async hydrateCustomerData() {
2499
- if (!this.accessToken || this.customerData) {
2500
- return;
2501
- }
2502
- if (!this.client.getAccessToken()) {
2503
- this.client.setAccessToken(this.accessToken);
2504
- }
2505
- const linkDataResult = await this.client.link.getLinkData();
2506
- if (!linkDataResult.ok || !linkDataResult.value?.customer) {
2507
- return;
2508
- }
2509
- const customer = linkDataResult.value.customer;
2510
- this.customerData = {
2511
- name: customer.name || "",
2512
- email: customer.email || null,
2513
- phone: customer.phone || null
2514
- };
2515
- }
2516
- handleMessage(event) {
2517
- if (!isAllowedOrigin(event.origin)) {
2518
- return;
2519
- }
2520
- const message = parseIframeMessage(event.data);
2521
- if (!message) return;
2522
- switch (message.type) {
2523
- case MESSAGE_TYPES.AUTHENTICATED:
2524
- const customer = message.customer ?? {
2525
- name: "",
2526
- email: null,
2527
- phone: null
2528
- };
2529
- this.accessToken = message.token;
2530
- this.accountId = message.accountId;
2531
- this.customerId = message.customerId;
2532
- this.customerData = customer;
2533
- this.client.setAccessToken(message.token);
2534
- this.elements.forEach((element, type) => {
2535
- if (type !== ELEMENT_TYPES.AUTH && type !== ELEMENT_TYPES.CHECKOUT) {
2536
- element.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token: message.token });
2537
- }
2538
- });
2539
- break;
2540
- case MESSAGE_TYPES.TOKEN_REFRESHED:
2541
- this.accessToken = message.token;
2542
- break;
2543
- case MESSAGE_TYPES.ADDRESS_CHANGED:
2544
- case MESSAGE_TYPES.ADDRESS_SELECTED:
2545
- this.addressData = message.address;
2546
- break;
2547
- case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
2548
- this.paymentData = message.method;
2549
- break;
2550
- case MESSAGE_TYPES.CONTACT_PROVIDED:
2551
- if (!this.customerData) {
2552
- this.customerData = { name: "", email: null, phone: null };
2553
- }
2554
- if (message.contactType === "email") {
2555
- this.customerData.email = message.contact;
2556
- } else {
2557
- this.customerData.phone = message.contact;
2558
- }
2559
- break;
2560
- case MESSAGE_TYPES.LOGOUT_COMPLETE:
2561
- if (this.checkoutInProgress && this.activeCheckoutAbort) {
2562
- this.activeCheckoutAbort();
2563
- }
2564
- this.accessToken = null;
2565
- this.accountId = null;
2566
- this.customerId = null;
2567
- this.customerData = null;
2568
- this.addressData = null;
2569
- this.paymentData = null;
2570
- this.client.clearSession();
2571
- break;
2572
- }
2573
- }
2574
- _setAddressData(data) {
2575
- this.addressData = data;
2576
- }
2577
- _setPaymentData(data) {
2578
- this.paymentData = data;
2579
- }
2580
- _setGuestContact(contact, contactType) {
2581
- if (!this.customerData) {
2582
- this.customerData = { name: "", email: null, phone: null };
2583
- }
2584
- if (contactType === "email") {
2585
- this.customerData.email = contact;
2586
- } else {
2587
- this.customerData.phone = contact;
2588
- }
2589
- }
2590
- };
2591
- var CimplifyElement = class {
2592
- constructor(type, businessId, linkUrl, options, parent) {
2593
- this.iframe = null;
2594
- this.container = null;
2595
- this.mounted = false;
2596
- this.pendingInit = null;
2597
- this.eventHandlers = /* @__PURE__ */ new Map();
2598
- this.resolvers = /* @__PURE__ */ new Map();
2599
- this.listening = false;
2600
- this.type = type;
2601
- this.businessId = businessId;
2602
- this.linkUrl = linkUrl;
2603
- this.options = options;
2604
- this.parent = parent;
2605
- this.nonce = generateNonce();
2606
- this.boundHandleMessage = this.handleMessage.bind(this);
2607
- if (typeof window !== "undefined") {
2608
- window.addEventListener("message", this.boundHandleMessage);
2609
- this.listening = true;
2610
- }
2611
- }
2612
- mount(container) {
2613
- if (this.mounted) {
2614
- console.warn(`Element ${this.type} is already mounted`);
2615
- return;
2616
- }
2617
- const target = typeof container === "string" ? document.querySelector(container) : container;
2618
- if (!target) {
2619
- console.error(`Container not found: ${container}`);
2620
- return;
2621
- }
2622
- this.container = target;
2623
- this.mounted = true;
2624
- if (!this.listening && typeof window !== "undefined") {
2625
- window.addEventListener("message", this.boundHandleMessage);
2626
- this.listening = true;
2627
- }
2628
- void this.createIframe();
2629
- }
2630
- destroy() {
2631
- if (this.iframe) {
2632
- this.iframe.remove();
2633
- this.iframe = null;
2634
- }
2635
- this.container = null;
2636
- this.mounted = false;
2637
- this.eventHandlers.clear();
2638
- this.resolvers.forEach((entry) => clearTimeout(entry.timeoutId));
2639
- this.resolvers.clear();
2640
- if (this.listening && typeof window !== "undefined") {
2641
- window.removeEventListener("message", this.boundHandleMessage);
2642
- this.listening = false;
2643
- }
2644
- this.parent._removeElement(this.type, this);
2645
- }
2646
- on(event, handler) {
2647
- if (!this.eventHandlers.has(event)) {
2648
- this.eventHandlers.set(event, /* @__PURE__ */ new Set());
2649
- }
2650
- this.eventHandlers.get(event).add(handler);
2651
- }
2652
- off(event, handler) {
2653
- this.eventHandlers.get(event)?.delete(handler);
2654
- }
2655
- async getData() {
2656
- if (!this.isMounted()) {
2657
- return null;
2658
- }
2659
- return new Promise((resolve) => {
2660
- const id = Math.random().toString(36).slice(2);
2661
- const timeoutId = setTimeout(() => {
2662
- const entry = this.resolvers.get(id);
2663
- if (!entry) {
2664
- return;
2665
- }
2666
- this.resolvers.delete(id);
2667
- entry.resolve(null);
2668
- }, 5e3);
2669
- this.resolvers.set(id, { resolve, timeoutId });
2670
- this.sendMessage({ type: MESSAGE_TYPES.GET_DATA });
2671
- });
2672
- }
2673
- setCart(cart) {
2674
- this.sendMessage({ type: MESSAGE_TYPES.SET_CART, cart });
2675
- }
2676
- sendMessage(message) {
2677
- if (this.iframe?.contentWindow) {
2678
- this.iframe.contentWindow.postMessage(message, this.linkUrl);
2679
- } else {
2680
- console.warn("[cimplify:checkout] sendMessage DROPPED \u2014 no contentWindow", { type: message.type, hasIframe: !!this.iframe, isConnected: this.iframe?.isConnected });
2681
- }
2682
- }
2683
- getContentWindow() {
2684
- return this.iframe?.contentWindow ?? null;
2685
- }
2686
- isMounted() {
2687
- return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
2688
- }
2689
- async createIframe() {
2690
- if (!this.container) return;
2691
- const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
2692
- if (!resolvedBusinessId || !this.container || !this.mounted) {
2693
- console.error("Unable to mount element without a resolved business ID");
2694
- this.emit(EVENT_TYPES.ERROR, {
2695
- code: "BUSINESS_ID_REQUIRED",
2696
- message: "Unable to initialize checkout without a business ID."
2697
- });
2698
- return;
2699
- }
2700
- this.businessId = resolvedBusinessId;
2701
- const iframe = document.createElement("iframe");
2702
- const url = new URL(`${this.linkUrl}/elements/${this.type}`);
2703
- url.searchParams.set("businessId", resolvedBusinessId);
2704
- url.searchParams.set("nonce", this.nonce);
2705
- if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
2706
- if (this.options.mode) url.searchParams.set("mode", this.options.mode);
2707
- iframe.src = url.toString();
2708
- iframe.style.border = "none";
2709
- iframe.style.width = "100%";
2710
- iframe.style.minHeight = "200px";
2711
- iframe.style.display = "block";
2712
- iframe.style.overflow = "hidden";
2713
- iframe.style.background = "transparent";
2714
- iframe.setAttribute("allowtransparency", "true");
2715
- iframe.setAttribute("frameborder", "0");
2716
- iframe.setAttribute("allow", "geolocation");
2717
- iframe.setAttribute(
2718
- "sandbox",
2719
- "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
2720
- );
2721
- this.iframe = iframe;
2722
- this.container.appendChild(iframe);
2723
- this.pendingInit = {
2724
- businessId: resolvedBusinessId,
2725
- publicKey: this.parent.getPublicKey()
2726
- };
2727
- }
2728
- handleMessage(event) {
2729
- if (!isAllowedOrigin(event.origin)) {
2730
- return;
2731
- }
2732
- const data = event.data;
2733
- if (data?.nonce) {
2734
- if (data.nonce !== this.nonce) return;
2735
- } else {
2736
- const iframeWindow = this.iframe?.contentWindow;
2737
- if (iframeWindow && event.source && event.source !== iframeWindow) {
2738
- return;
2739
- }
2740
- }
2741
- const message = parseIframeMessage(event.data);
2742
- if (!message) return;
2743
- switch (message.type) {
2744
- case MESSAGE_TYPES.READY:
2745
- if (this.iframe && message.height) this.iframe.style.height = `${message.height}px`;
2746
- if (this.pendingInit) {
2747
- const { publicKey } = this.pendingInit;
2748
- this.sendMessage({
2749
- type: MESSAGE_TYPES.INIT,
2750
- businessId: this.pendingInit.businessId,
2751
- publicKey,
2752
- demoMode: publicKey.length === 0,
2753
- prefillEmail: this.options.prefillEmail,
2754
- appearance: this.parent.getAppearance(),
2755
- orderTypes: this.options.orderTypes,
2756
- defaultOrderType: this.options.defaultOrderType,
2757
- renderSubmitButton: true,
2758
- submitLabel: this.options.submitLabel
2759
- });
2760
- const token = this.parent.getAccessToken();
2761
- if (token && this.type !== ELEMENT_TYPES.AUTH) {
2762
- this.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token });
2763
- }
2764
- this.pendingInit = null;
2765
- }
2766
- this.emit(EVENT_TYPES.READY, { height: message.height });
2767
- break;
2768
- case MESSAGE_TYPES.HEIGHT_CHANGE:
2769
- if (this.iframe) this.iframe.style.height = `${message.height}px`;
2770
- break;
2771
- case MESSAGE_TYPES.AUTHENTICATED:
2772
- const customer = message.customer ?? {
2773
- name: "",
2774
- email: null,
2775
- phone: null
2776
- };
2777
- this.emit(EVENT_TYPES.AUTHENTICATED, {
2778
- accountId: message.accountId,
2779
- customerId: message.customerId,
2780
- token: message.token,
2781
- customer
2782
- });
2783
- break;
2784
- case MESSAGE_TYPES.REQUIRES_OTP:
2785
- this.emit(EVENT_TYPES.REQUIRES_OTP, { contactMasked: message.contactMasked });
2786
- break;
2787
- case MESSAGE_TYPES.ERROR:
2788
- this.emit(EVENT_TYPES.ERROR, { code: message.code, message: message.message });
2789
- break;
2790
- case MESSAGE_TYPES.ADDRESS_CHANGED:
2791
- case MESSAGE_TYPES.ADDRESS_SELECTED:
2792
- this.parent._setAddressData(message.address);
2793
- this.emit(EVENT_TYPES.CHANGE, { address: message.address });
2794
- this.resolveData(message.address);
2795
- break;
2796
- case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
2797
- this.parent._setPaymentData(message.method);
2798
- this.emit(EVENT_TYPES.CHANGE, { paymentMethod: message.method });
2799
- this.resolveData(message.method);
2800
- break;
2801
- case MESSAGE_TYPES.CONTACT_PROVIDED:
2802
- this.parent._setGuestContact(message.contact, message.contactType);
2803
- break;
2804
- case MESSAGE_TYPES.ORDER_TYPE_CHANGED:
2805
- this.emit(EVENT_TYPES.ORDER_TYPE_CHANGED, { orderType: message.orderType });
2806
- break;
2807
- case MESSAGE_TYPES.REQUEST_SUBMIT:
2808
- this.emit(EVENT_TYPES.REQUEST_SUBMIT, {});
2809
- break;
2810
- }
2811
- }
2812
- emit(event, data) {
2813
- this.eventHandlers.get(event)?.forEach((handler) => handler(data));
2814
- }
2815
- resolveData(data) {
2816
- this.resolvers.forEach((entry) => {
2817
- clearTimeout(entry.timeoutId);
2818
- entry.resolve(data);
2819
- });
2820
- this.resolvers.clear();
2821
- }
2822
- };
2823
- function createElements(client, businessId, options) {
2824
- return new CimplifyElements(client, businessId, options);
2825
- }
2826
-
2827
- // src/query/builder.ts
2828
- function escapeQueryValue(value) {
2829
- return value.replace(/'/g, "\\'");
2830
- }
2831
- var QueryBuilder = class {
2832
- constructor(entity) {
2833
- this.filters = [];
2834
- this.modifiers = [];
2835
- this.pathSegments = [];
2836
- this.entity = entity;
2837
- }
2838
- path(segment) {
2839
- this.pathSegments.push(segment);
2840
- return this;
2841
- }
2842
- where(field, op, value) {
2843
- const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
2844
- if (op === "contains" || op === "startsWith") {
2845
- this.filters.push(`@.${field} ${op} ${v}`);
2846
- } else {
2847
- this.filters.push(`@.${field}${op}${v}`);
2848
- }
2849
- return this;
2850
- }
2851
- and(field, op, value) {
2852
- return this.where(field, op, value);
2853
- }
2854
- sort(field, order = "asc") {
2855
- this.modifiers.push(`sort(${field},${order})`);
2856
- return this;
2857
- }
2858
- limit(n) {
2859
- this.modifiers.push(`limit(${n})`);
2860
- return this;
2861
- }
2862
- offset(n) {
2863
- this.modifiers.push(`offset(${n})`);
2864
- return this;
2865
- }
2866
- count() {
2867
- this.modifiers.push("count");
2868
- return this;
2869
- }
2870
- enriched() {
2871
- this.modifiers.push("enriched");
2872
- return this;
2873
- }
2874
- build() {
2875
- let query2 = this.entity;
2876
- if (this.pathSegments.length > 0) {
2877
- query2 += "." + this.pathSegments.join(".");
2878
- }
2879
- if (this.filters.length > 0) {
2880
- query2 += `[?(${this.filters.join(" && ")})]`;
2881
- }
2882
- for (const mod of this.modifiers) {
2883
- query2 += `#${mod}`;
2884
- }
2885
- return query2;
2886
- }
2887
- toString() {
2888
- return this.build();
2889
- }
2890
- };
2891
- function query(entity) {
2892
- return new QueryBuilder(entity);
2893
- }
2894
-
2895
- exports.AuthService = AuthService;
2896
- exports.BusinessService = BusinessService;
2897
- exports.CartOperations = CartOperations;
2898
- exports.CatalogueQueries = CatalogueQueries;
2899
- exports.CheckoutOperations = CheckoutService;
2900
- exports.CheckoutService = CheckoutService;
2901
- exports.CimplifyElement = CimplifyElement;
2902
- exports.CimplifyElements = CimplifyElements;
2903
- exports.ELEMENT_TYPES = ELEMENT_TYPES;
2904
- exports.EVENT_TYPES = EVENT_TYPES;
2905
- exports.FxService = FxService;
2906
- exports.InventoryService = InventoryService;
2907
- exports.LinkService = LinkService;
2908
- exports.LiteService = LiteService;
2909
- exports.MESSAGE_TYPES = MESSAGE_TYPES;
2910
- exports.OrderQueries = OrderQueries;
2911
- exports.QueryBuilder = QueryBuilder;
2912
- exports.SchedulingService = SchedulingService;
2913
- exports.createElements = createElements;
2914
- exports.generateIdempotencyKey = generateIdempotencyKey;
2915
- exports.query = query;
3
+ var chunkFLPI2VVJ_js = require('./chunk-FLPI2VVJ.js');
4
+ var chunkREPTMTQ4_js = require('./chunk-REPTMTQ4.js');
5
+ require('./chunk-J65U5SED.js');
6
+
7
+
8
+
9
+ Object.defineProperty(exports, "QueryBuilder", {
10
+ enumerable: true,
11
+ get: function () { return chunkFLPI2VVJ_js.QueryBuilder; }
12
+ });
13
+ Object.defineProperty(exports, "query", {
14
+ enumerable: true,
15
+ get: function () { return chunkFLPI2VVJ_js.query; }
16
+ });
17
+ Object.defineProperty(exports, "AuthService", {
18
+ enumerable: true,
19
+ get: function () { return chunkREPTMTQ4_js.AuthService; }
20
+ });
21
+ Object.defineProperty(exports, "BusinessService", {
22
+ enumerable: true,
23
+ get: function () { return chunkREPTMTQ4_js.BusinessService; }
24
+ });
25
+ Object.defineProperty(exports, "CartOperations", {
26
+ enumerable: true,
27
+ get: function () { return chunkREPTMTQ4_js.CartOperations; }
28
+ });
29
+ Object.defineProperty(exports, "CatalogueQueries", {
30
+ enumerable: true,
31
+ get: function () { return chunkREPTMTQ4_js.CatalogueQueries; }
32
+ });
33
+ Object.defineProperty(exports, "CheckoutOperations", {
34
+ enumerable: true,
35
+ get: function () { return chunkREPTMTQ4_js.CheckoutService; }
36
+ });
37
+ Object.defineProperty(exports, "CheckoutService", {
38
+ enumerable: true,
39
+ get: function () { return chunkREPTMTQ4_js.CheckoutService; }
40
+ });
41
+ Object.defineProperty(exports, "CimplifyElement", {
42
+ enumerable: true,
43
+ get: function () { return chunkREPTMTQ4_js.CimplifyElement; }
44
+ });
45
+ Object.defineProperty(exports, "CimplifyElements", {
46
+ enumerable: true,
47
+ get: function () { return chunkREPTMTQ4_js.CimplifyElements; }
48
+ });
49
+ Object.defineProperty(exports, "ELEMENT_TYPES", {
50
+ enumerable: true,
51
+ get: function () { return chunkREPTMTQ4_js.ELEMENT_TYPES; }
52
+ });
53
+ Object.defineProperty(exports, "EVENT_TYPES", {
54
+ enumerable: true,
55
+ get: function () { return chunkREPTMTQ4_js.EVENT_TYPES; }
56
+ });
57
+ Object.defineProperty(exports, "FxService", {
58
+ enumerable: true,
59
+ get: function () { return chunkREPTMTQ4_js.FxService; }
60
+ });
61
+ Object.defineProperty(exports, "InventoryService", {
62
+ enumerable: true,
63
+ get: function () { return chunkREPTMTQ4_js.InventoryService; }
64
+ });
65
+ Object.defineProperty(exports, "LinkService", {
66
+ enumerable: true,
67
+ get: function () { return chunkREPTMTQ4_js.LinkService; }
68
+ });
69
+ Object.defineProperty(exports, "LiteService", {
70
+ enumerable: true,
71
+ get: function () { return chunkREPTMTQ4_js.LiteService; }
72
+ });
73
+ Object.defineProperty(exports, "MESSAGE_TYPES", {
74
+ enumerable: true,
75
+ get: function () { return chunkREPTMTQ4_js.MESSAGE_TYPES; }
76
+ });
77
+ Object.defineProperty(exports, "OrderQueries", {
78
+ enumerable: true,
79
+ get: function () { return chunkREPTMTQ4_js.OrderQueries; }
80
+ });
81
+ Object.defineProperty(exports, "SchedulingService", {
82
+ enumerable: true,
83
+ get: function () { return chunkREPTMTQ4_js.SchedulingService; }
84
+ });
85
+ Object.defineProperty(exports, "createElements", {
86
+ enumerable: true,
87
+ get: function () { return chunkREPTMTQ4_js.createElements; }
88
+ });
89
+ Object.defineProperty(exports, "generateIdempotencyKey", {
90
+ enumerable: true,
91
+ get: function () { return chunkREPTMTQ4_js.generateIdempotencyKey; }
92
+ });