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