@cimplify/sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/advanced.mjs CHANGED
@@ -120,74 +120,6 @@ function enrichError(error, options = {}) {
120
120
  return error;
121
121
  }
122
122
 
123
- // src/query/builder.ts
124
- function escapeQueryValue(value) {
125
- return value.replace(/'/g, "\\'");
126
- }
127
- var QueryBuilder = class {
128
- constructor(entity) {
129
- this.filters = [];
130
- this.modifiers = [];
131
- this.pathSegments = [];
132
- this.entity = entity;
133
- }
134
- path(segment) {
135
- this.pathSegments.push(segment);
136
- return this;
137
- }
138
- where(field, op, value) {
139
- const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
140
- if (op === "contains" || op === "startsWith") {
141
- this.filters.push(`@.${field} ${op} ${v}`);
142
- } else {
143
- this.filters.push(`@.${field}${op}${v}`);
144
- }
145
- return this;
146
- }
147
- and(field, op, value) {
148
- return this.where(field, op, value);
149
- }
150
- sort(field, order = "asc") {
151
- this.modifiers.push(`sort(${field},${order})`);
152
- return this;
153
- }
154
- limit(n) {
155
- this.modifiers.push(`limit(${n})`);
156
- return this;
157
- }
158
- offset(n) {
159
- this.modifiers.push(`offset(${n})`);
160
- return this;
161
- }
162
- count() {
163
- this.modifiers.push("count");
164
- return this;
165
- }
166
- enriched() {
167
- this.modifiers.push("enriched");
168
- return this;
169
- }
170
- build() {
171
- let query2 = this.entity;
172
- if (this.pathSegments.length > 0) {
173
- query2 += "." + this.pathSegments.join(".");
174
- }
175
- if (this.filters.length > 0) {
176
- query2 += `[?(${this.filters.join(" && ")})]`;
177
- }
178
- for (const mod of this.modifiers) {
179
- query2 += `#${mod}`;
180
- }
181
- return query2;
182
- }
183
- toString() {
184
- return this.build();
185
- }
186
- };
187
- function query(entity) {
188
- return new QueryBuilder(entity);
189
- }
190
-
191
123
  // src/catalogue.ts
192
124
  function toCimplifyError(error) {
193
125
  if (error instanceof CimplifyError) return enrichError(error);
@@ -203,14 +135,6 @@ async function safe(promise) {
203
135
  return err(toCimplifyError(error));
204
136
  }
205
137
  }
206
- async function safeWithFallback(primary, fallback) {
207
- const primaryResult = await safe(primary());
208
- if (primaryResult.ok) return primaryResult;
209
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
210
- return primaryResult;
211
- }
212
- return safe(fallback());
213
- }
214
138
  function withQuery(path, params) {
215
139
  const query2 = new URLSearchParams();
216
140
  for (const [key, value] of Object.entries(params)) {
@@ -272,22 +196,6 @@ function normalizeCatalogueProductPayload(product) {
272
196
  }
273
197
  return normalized;
274
198
  }
275
- function findProductBySlug(products, slug) {
276
- return products.find((product) => {
277
- const value = product["slug"];
278
- return typeof value === "string" && value === slug;
279
- });
280
- }
281
- function findCategoryBySlug(categories, slug) {
282
- return categories.find((category) => {
283
- const value = category["slug"];
284
- return typeof value === "string" && value === slug;
285
- });
286
- }
287
- function hasCategorySlug(category) {
288
- const value = category["slug"];
289
- return typeof value === "string" && value.trim().length > 0;
290
- }
291
199
  function toFiniteNumber(value) {
292
200
  if (typeof value === "number" && Number.isFinite(value)) {
293
201
  return value;
@@ -375,53 +283,11 @@ var CatalogueQueries = class {
375
283
  this.client = client;
376
284
  }
377
285
  async getCatalogue() {
378
- const result = await safeWithFallback(
379
- () => this.client.get("/api/v1/catalogue"),
380
- () => this.client.query("catalogue")
381
- );
286
+ const result = await safe(this.client.get("/api/v1/catalogue"));
382
287
  if (!result.ok) return result;
383
288
  return ok(normalizeCatalogueSnapshot(result.value));
384
289
  }
385
290
  async getProducts(options) {
386
- let query2 = "products";
387
- const filters = [];
388
- if (options?.category) {
389
- filters.push(`@.category_id=='${escapeQueryValue(options.category)}'`);
390
- }
391
- if (options?.featured !== void 0) {
392
- filters.push(`@.featured==${options.featured}`);
393
- }
394
- if (options?.in_stock !== void 0) {
395
- filters.push(`@.in_stock==${options.in_stock}`);
396
- }
397
- if (options?.search) {
398
- filters.push(`@.name contains '${escapeQueryValue(options.search)}'`);
399
- }
400
- if (options?.tags?.length) {
401
- for (const tag of options.tags) {
402
- if (tag.trim().length > 0) {
403
- filters.push(`@.tags contains '${escapeQueryValue(tag)}'`);
404
- }
405
- }
406
- }
407
- if (options?.min_price !== void 0) {
408
- filters.push(`@.price>=${options.min_price}`);
409
- }
410
- if (options?.max_price !== void 0) {
411
- filters.push(`@.price<=${options.max_price}`);
412
- }
413
- if (filters.length > 0) {
414
- query2 += `[?(${filters.join(" && ")})]`;
415
- }
416
- if (options?.sort_by) {
417
- query2 += `#sort(${options.sort_by},${options.sort_order || "asc"})`;
418
- }
419
- if (options?.limit !== void 0) {
420
- query2 += `#limit(${options.limit})`;
421
- }
422
- if (options?.offset !== void 0) {
423
- query2 += `#offset(${options.offset})`;
424
- }
425
291
  const path = withQuery("/api/v1/catalogue/products", {
426
292
  category_id: options?.category,
427
293
  search: options?.search,
@@ -437,325 +303,145 @@ var CatalogueQueries = class {
437
303
  offset: options?.offset,
438
304
  cursor: options?.cursor
439
305
  });
440
- const result = await safeWithFallback(
441
- () => this.client.get(path),
442
- () => this.client.query(query2)
443
- );
306
+ const result = await safe(this.client.get(path));
444
307
  if (!result.ok) return result;
445
308
  return ok(normalizeCatalogueResult(result.value));
446
309
  }
447
310
  async getProduct(id) {
448
311
  const encodedId = encodeURIComponent(id);
449
- const result = await safeWithFallback(
450
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}`),
451
- () => this.client.query(`products.${id}`)
452
- );
312
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
453
313
  if (!result.ok) return result;
454
314
  return ok(normalizeCatalogueProductPayload(result.value));
455
315
  }
456
316
  async getProductBySlug(slug) {
457
317
  const encodedSlug = encodeURIComponent(slug);
458
- const restResult = await safe(
459
- this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`)
460
- );
461
- if (restResult.ok) {
462
- return ok(normalizeCatalogueProductPayload(restResult.value));
463
- }
464
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
465
- return restResult;
466
- }
467
- const filteredResult = await safe(
468
- this.client.query(
469
- `products[?(@.slug=='${escapeQueryValue(slug)}')]#limit(50)`
470
- )
471
- );
472
- if (!filteredResult.ok) return filteredResult;
473
- const exactMatch = findProductBySlug(filteredResult.value, slug);
474
- if (exactMatch) {
475
- return ok(normalizeCatalogueProductPayload(exactMatch));
476
- }
477
- if (filteredResult.value.length === 1) {
478
- return ok(normalizeCatalogueProductPayload(filteredResult.value[0]));
479
- }
480
- const unfilteredResult = await safe(
481
- this.client.query("products#limit(200)")
482
- );
483
- if (!unfilteredResult.ok) return unfilteredResult;
484
- const fallbackMatch = findProductBySlug(unfilteredResult.value, slug);
485
- if (!fallbackMatch) {
486
- return err(new CimplifyError("NOT_FOUND", `Product not found: ${slug}`, false));
487
- }
488
- return ok(normalizeCatalogueProductPayload(fallbackMatch));
318
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
319
+ if (!result.ok) return result;
320
+ return ok(normalizeCatalogueProductPayload(result.value));
489
321
  }
490
322
  async getVariants(productId) {
491
323
  const encodedId = encodeURIComponent(productId);
492
- return safeWithFallback(
493
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`),
494
- () => this.client.query(`products.${productId}.variants`)
495
- );
324
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
496
325
  }
497
326
  async getVariantAxes(productId) {
498
327
  const encodedId = encodeURIComponent(productId);
499
- return safeWithFallback(
500
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`),
501
- () => this.client.query(`products.${productId}.variant_axes`)
502
- );
328
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
503
329
  }
504
- /**
505
- * Find a variant by axis selections (e.g., { "Size": "Large", "Color": "Red" })
506
- * Returns the matching variant or null if no match found.
507
- */
508
330
  async getVariantByAxisSelections(productId, selections) {
509
331
  const encodedId = encodeURIComponent(productId);
510
- return safeWithFallback(
511
- () => this.client.post(
332
+ return safe(
333
+ this.client.post(
512
334
  `/api/v1/catalogue/products/${encodedId}/variants/find`,
513
335
  {
514
336
  axis_selections: selections
515
337
  }
516
- ),
517
- () => this.client.query(`products.${productId}.variant`, {
518
- axis_selections: selections
519
- })
338
+ )
520
339
  );
521
340
  }
522
- /**
523
- * Get a specific variant by its ID
524
- */
525
341
  async getVariantById(productId, variantId) {
526
342
  const encodedProductId = encodeURIComponent(productId);
527
343
  const encodedVariantId = encodeURIComponent(variantId);
528
- return safeWithFallback(
529
- () => this.client.get(
344
+ return safe(
345
+ this.client.get(
530
346
  `/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
531
- ),
532
- () => this.client.query(`products.${productId}.variant.${variantId}`)
347
+ )
533
348
  );
534
349
  }
535
350
  async getAddOns(productId) {
536
351
  const encodedId = encodeURIComponent(productId);
537
- return safeWithFallback(
538
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`),
539
- () => this.client.query(`products.${productId}.add_ons`)
540
- );
352
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
541
353
  }
542
354
  async getCategories() {
543
- const result = await safeWithFallback(
544
- () => this.client.get("/api/v1/catalogue/categories"),
545
- () => this.client.query("categories")
546
- );
547
- if (!result.ok) return result;
548
- if (result.value.some(hasCategorySlug)) {
549
- return result;
550
- }
551
- const catalogueResult = await safe(
552
- this.client.query("catalogue#limit(1)")
553
- );
554
- if (!catalogueResult.ok) {
555
- return result;
556
- }
557
- const fallbackCategories = Array.isArray(catalogueResult.value.categories) ? catalogueResult.value.categories : [];
558
- return fallbackCategories.length > 0 ? ok(fallbackCategories) : result;
355
+ return safe(this.client.get("/api/v1/catalogue/categories"));
559
356
  }
560
357
  async getCategory(id) {
561
358
  const encodedId = encodeURIComponent(id);
562
- return safeWithFallback(
563
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}`),
564
- () => this.client.query(`categories.${id}`)
565
- );
359
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
566
360
  }
567
361
  async getCategoryBySlug(slug) {
568
362
  const encodedSlug = encodeURIComponent(slug);
569
- const restResult = await safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
570
- if (restResult.ok) {
571
- return restResult;
572
- }
573
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
574
- return restResult;
575
- }
576
- const result = await safe(
577
- this.client.query(`categories[?(@.slug=='${escapeQueryValue(slug)}')]`)
578
- );
579
- if (!result.ok) return result;
580
- const exactMatch = findCategoryBySlug(result.value, slug);
581
- if (exactMatch) {
582
- return ok(exactMatch);
583
- }
584
- const categoriesResult = await this.getCategories();
585
- if (!categoriesResult.ok) {
586
- return categoriesResult;
587
- }
588
- const fallbackMatch = findCategoryBySlug(categoriesResult.value, slug);
589
- if (!fallbackMatch) {
590
- return err(new CimplifyError("NOT_FOUND", `Category not found: ${slug}`, false));
591
- }
592
- return ok(fallbackMatch);
363
+ return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
593
364
  }
594
365
  async getCategoryProducts(categoryId) {
595
366
  const encodedId = encodeURIComponent(categoryId);
596
- return safeWithFallback(
597
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`),
598
- () => this.client.query(
599
- `products[?(@.category_id=='${escapeQueryValue(categoryId)}')]`
600
- )
601
- );
367
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
602
368
  }
603
369
  async getCollections() {
604
- return safeWithFallback(
605
- () => this.client.get("/api/v1/catalogue/collections"),
606
- () => this.client.query("collections")
607
- );
370
+ return safe(this.client.get("/api/v1/catalogue/collections"));
608
371
  }
609
372
  async getCollection(id) {
610
373
  const encodedId = encodeURIComponent(id);
611
- return safeWithFallback(
612
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}`),
613
- () => this.client.query(`collections.${id}`)
614
- );
374
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
615
375
  }
616
376
  async getCollectionBySlug(slug) {
617
377
  const encodedSlug = encodeURIComponent(slug);
618
- const restResult = await safe(
619
- this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`)
620
- );
621
- if (restResult.ok) return restResult;
622
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
623
- return restResult;
624
- }
625
- const result = await safe(
626
- this.client.query(`collections[?(@.slug=='${escapeQueryValue(slug)}')]`)
627
- );
628
- if (!result.ok) return result;
629
- if (!result.value.length) {
630
- return err(new CimplifyError("NOT_FOUND", `Collection not found: ${slug}`, false));
631
- }
632
- return ok(result.value[0]);
378
+ return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
633
379
  }
634
380
  async getCollectionProducts(collectionId) {
635
381
  const encodedId = encodeURIComponent(collectionId);
636
- return safeWithFallback(
637
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`),
638
- () => this.client.query(`collections.${collectionId}.products`)
639
- );
382
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
640
383
  }
641
384
  async searchCollections(query2, limit = 20) {
642
385
  const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
643
- return safeWithFallback(
644
- () => this.client.get(path),
645
- () => this.client.query(
646
- `collections[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
647
- )
648
- );
386
+ return safe(this.client.get(path));
649
387
  }
650
388
  async getBundles() {
651
- return safeWithFallback(
652
- () => this.client.get("/api/v1/catalogue/bundles"),
653
- () => this.client.query("bundles")
654
- );
389
+ return safe(this.client.get("/api/v1/catalogue/bundles"));
655
390
  }
656
391
  async getBundle(id) {
657
392
  const encodedId = encodeURIComponent(id);
658
- return safeWithFallback(
659
- () => this.client.get(`/api/v1/catalogue/bundles/${encodedId}`),
660
- () => this.client.query(`bundles.${id}`)
661
- );
393
+ return safe(this.client.get(`/api/v1/catalogue/bundles/${encodedId}`));
662
394
  }
663
395
  async getBundleBySlug(slug) {
664
396
  const encodedSlug = encodeURIComponent(slug);
665
- const restResult = await safe(
666
- this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`)
667
- );
668
- if (restResult.ok) return restResult;
669
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
670
- return restResult;
671
- }
672
- const result = await safe(
673
- this.client.query(
674
- `bundles[?(@.slug=='${escapeQueryValue(slug)}')]`
675
- )
676
- );
677
- if (!result.ok) return result;
678
- if (!result.value.length) {
679
- return err(new CimplifyError("NOT_FOUND", `Bundle not found: ${slug}`, false));
680
- }
681
- return ok(result.value[0]);
397
+ return safe(this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`));
682
398
  }
683
399
  async searchBundles(query2, limit = 20) {
684
400
  const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
685
- return safeWithFallback(
686
- () => this.client.get(path),
687
- () => this.client.query(
688
- `bundles[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
689
- )
690
- );
401
+ return safe(this.client.get(path));
691
402
  }
692
403
  async getComposites(options) {
693
- let query2 = "composites";
694
- if (options?.limit) {
695
- query2 += `#limit(${options.limit})`;
696
- }
697
404
  const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
698
- return safeWithFallback(
699
- () => this.client.get(path),
700
- () => this.client.query(query2)
701
- );
405
+ return safe(this.client.get(path));
702
406
  }
703
407
  async getComposite(id) {
704
408
  const encodedId = encodeURIComponent(id);
705
- return safeWithFallback(
706
- () => this.client.get(`/api/v1/catalogue/composites/${encodedId}`),
707
- () => this.client.query(`composites.${id}`)
708
- );
409
+ return safe(this.client.get(`/api/v1/catalogue/composites/${encodedId}`));
709
410
  }
710
411
  async getCompositeByProductId(productId) {
711
412
  const encodedId = encodeURIComponent(productId);
712
- return safeWithFallback(
713
- () => this.client.get(
413
+ return safe(
414
+ this.client.get(
714
415
  `/api/v1/catalogue/composites/by-product/${encodedId}`
715
- ),
716
- () => this.client.query(`composites.by_product.${productId}`)
416
+ )
717
417
  );
718
418
  }
719
419
  async calculateCompositePrice(compositeId, selections, locationId) {
720
420
  const encodedId = encodeURIComponent(compositeId);
721
- return safeWithFallback(
722
- () => this.client.post(
421
+ return safe(
422
+ this.client.post(
723
423
  `/api/v1/catalogue/composites/${encodedId}/calculate-price`,
724
424
  {
725
425
  selections,
726
426
  location_id: locationId
727
427
  }
728
- ),
729
- () => this.client.call("composite.calculatePrice", {
730
- composite_id: compositeId,
731
- selections,
732
- location_id: locationId
733
- })
428
+ )
734
429
  );
735
430
  }
736
431
  async fetchQuote(input) {
737
- return safeWithFallback(
738
- () => this.client.post("/api/v1/catalogue/quotes", input),
739
- () => this.client.call("catalogue.createQuote", input)
740
- );
432
+ return safe(this.client.post("/api/v1/catalogue/quotes", input));
741
433
  }
742
434
  async getQuote(quoteId) {
743
435
  const encodedQuoteId = encodeURIComponent(quoteId);
744
- return safeWithFallback(
745
- () => this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`),
746
- () => this.client.call("catalogue.getQuote", {
747
- quote_id: quoteId
748
- })
749
- );
436
+ return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
750
437
  }
751
438
  async refreshQuote(input) {
752
439
  const encodedQuoteId = encodeURIComponent(input.quote_id);
753
- return safeWithFallback(
754
- () => this.client.post(
440
+ return safe(
441
+ this.client.post(
755
442
  `/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
756
443
  input
757
- ),
758
- () => this.client.call("catalogue.refreshQuote", input)
444
+ )
759
445
  );
760
446
  }
761
447
  async search(query2, options) {
@@ -771,35 +457,19 @@ var CatalogueQueries = class {
771
457
  return this.search(query2, options);
772
458
  }
773
459
  async getMenu(options) {
774
- let query2 = "menu";
775
- if (options?.category) {
776
- query2 = `menu[?(@.category=='${escapeQueryValue(options.category)}')]`;
777
- }
778
- if (options?.limit) {
779
- query2 += `#limit(${options.limit})`;
780
- }
781
460
  const path = withQuery("/api/v1/catalogue/menu", {
782
461
  category_id: options?.category,
783
462
  limit: options?.limit
784
463
  });
785
- return safeWithFallback(
786
- () => this.client.get(path),
787
- () => this.client.query(query2)
788
- );
464
+ return safe(this.client.get(path));
789
465
  }
790
466
  async getMenuCategory(categoryId) {
791
467
  const encodedId = encodeURIComponent(categoryId);
792
- return safeWithFallback(
793
- () => this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`),
794
- () => this.client.query(`menu.category.${categoryId}`)
795
- );
468
+ return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
796
469
  }
797
470
  async getMenuItem(itemId) {
798
471
  const encodedId = encodeURIComponent(itemId);
799
- return safeWithFallback(
800
- () => this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`),
801
- () => this.client.query(`menu.${itemId}`)
802
- );
472
+ return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
803
473
  }
804
474
  };
805
475
 
@@ -818,14 +488,6 @@ async function safe2(promise) {
818
488
  return err(toCimplifyError2(error));
819
489
  }
820
490
  }
821
- async function safeWithFallback2(primary, fallback) {
822
- const primaryResult = await safe2(primary());
823
- if (primaryResult.ok) return primaryResult;
824
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
825
- return primaryResult;
826
- }
827
- return safe2(fallback());
828
- }
829
491
  function isUICartResponse(value) {
830
492
  return "cart" in value;
831
493
  }
@@ -837,36 +499,21 @@ var CartOperations = class {
837
499
  this.client = client;
838
500
  }
839
501
  async get() {
840
- const result = await safeWithFallback2(
841
- () => this.client.get("/api/v1/cart"),
842
- () => this.client.query("cart#enriched")
843
- );
502
+ const result = await safe2(this.client.get("/api/v1/cart"));
844
503
  if (!result.ok) return result;
845
504
  return ok(unwrapEnrichedCart(result.value));
846
505
  }
847
506
  async getRaw() {
848
- return safeWithFallback2(
849
- () => this.client.get("/api/v1/cart"),
850
- () => this.client.query("cart")
851
- );
507
+ return safe2(this.client.get("/api/v1/cart"));
852
508
  }
853
509
  async getItems() {
854
- return safeWithFallback2(
855
- () => this.client.get("/api/v1/cart/items"),
856
- () => this.client.query("cart_items")
857
- );
510
+ return safe2(this.client.get("/api/v1/cart/items"));
858
511
  }
859
512
  async getCount() {
860
- return safeWithFallback2(
861
- () => this.client.get("/api/v1/cart/count"),
862
- () => this.client.query("cart#count")
863
- );
513
+ return safe2(this.client.get("/api/v1/cart/count"));
864
514
  }
865
515
  async getTotal() {
866
- return safeWithFallback2(
867
- () => this.client.get("/api/v1/cart/total"),
868
- () => this.client.query("cart#total")
869
- );
516
+ return safe2(this.client.get("/api/v1/cart/total"));
870
517
  }
871
518
  async getSummary() {
872
519
  const cartResult = await this.get();
@@ -883,66 +530,39 @@ var CartOperations = class {
883
530
  });
884
531
  }
885
532
  async addItem(input) {
886
- return safeWithFallback2(
887
- () => this.client.post("/api/v1/cart/items", input),
888
- () => this.client.call("cart.addItem", input)
889
- );
533
+ return safe2(this.client.post("/api/v1/cart/items", input));
890
534
  }
891
535
  async updateItem(cartItemId, updates) {
892
536
  if (typeof updates.quantity === "number") {
893
537
  return this.updateQuantity(cartItemId, updates.quantity);
894
538
  }
895
539
  const encodedId = encodeURIComponent(cartItemId);
896
- return safeWithFallback2(
897
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, updates),
898
- () => this.client.call("cart.updateItem", {
899
- cart_item_id: cartItemId,
900
- ...updates
901
- })
902
- );
540
+ return safe2(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
903
541
  }
904
542
  async updateQuantity(cartItemId, quantity) {
905
543
  const encodedId = encodeURIComponent(cartItemId);
906
- return safeWithFallback2(
907
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, {
908
- quantity
909
- }),
910
- () => this.client.call("cart.updateItemQuantity", {
911
- cart_item_id: cartItemId,
544
+ return safe2(
545
+ this.client.patch(`/api/v1/cart/items/${encodedId}`, {
912
546
  quantity
913
547
  })
914
548
  );
915
549
  }
916
550
  async removeItem(cartItemId) {
917
551
  const encodedId = encodeURIComponent(cartItemId);
918
- return safeWithFallback2(
919
- () => this.client.delete(`/api/v1/cart/items/${encodedId}`),
920
- () => this.client.call("cart.removeItem", {
921
- cart_item_id: cartItemId
922
- })
923
- );
552
+ return safe2(this.client.delete(`/api/v1/cart/items/${encodedId}`));
924
553
  }
925
554
  async clear() {
926
- return safeWithFallback2(
927
- () => this.client.delete("/api/v1/cart"),
928
- () => this.client.call("cart.clearCart")
929
- );
555
+ return safe2(this.client.delete("/api/v1/cart"));
930
556
  }
931
557
  async applyCoupon(code) {
932
- return safeWithFallback2(
933
- () => this.client.post("/api/v1/cart/coupons", {
934
- coupon_code: code
935
- }),
936
- () => this.client.call("cart.applyCoupon", {
558
+ return safe2(
559
+ this.client.post("/api/v1/cart/coupons", {
937
560
  coupon_code: code
938
561
  })
939
562
  );
940
563
  }
941
564
  async removeCoupon() {
942
- return safeWithFallback2(
943
- () => this.client.delete("/api/v1/cart/coupons/current"),
944
- () => this.client.call("cart.removeCoupon")
945
- );
565
+ return safe2(this.client.delete("/api/v1/cart/coupons/current"));
946
566
  }
947
567
  async isEmpty() {
948
568
  const countResult = await this.getCount();
@@ -979,35 +599,6 @@ var CartOperations = class {
979
599
  }
980
600
  };
981
601
 
982
- // src/constants.ts
983
- var LINK_QUERY = {
984
- PREFERENCES: "link.preferences"};
985
- var LINK_MUTATION = {
986
- CHECK_STATUS: "link.check_status",
987
- ENROLL: "link.enroll",
988
- ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
989
- UPDATE_PREFERENCES: "link.update_preferences",
990
- CREATE_ADDRESS: "link.create_address",
991
- UPDATE_ADDRESS: "link.update_address",
992
- TRACK_ADDRESS_USAGE: "link.track_address_usage",
993
- CREATE_MOBILE_MONEY: "link.create_mobile_money",
994
- TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
995
- VERIFY_MOBILE_MONEY: "link.verify_mobile_money"};
996
- var AUTH_MUTATION = {
997
- REQUEST_OTP: "auth.request_otp",
998
- VERIFY_OTP: "auth.verify_otp"
999
- };
1000
- var CHECKOUT_MUTATION = {
1001
- PROCESS: "checkout.process"
1002
- };
1003
- var PAYMENT_MUTATION = {
1004
- SUBMIT_AUTHORIZATION: "payment.submit_authorization",
1005
- CHECK_STATUS: "order.poll_payment_status"
1006
- };
1007
- var ORDER_MUTATION = {
1008
- UPDATE_CUSTOMER: "order.update_order_customer"
1009
- };
1010
-
1011
602
  // src/utils/payment.ts
1012
603
  var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
1013
604
  "success",
@@ -1702,14 +1293,6 @@ async function safe3(promise) {
1702
1293
  return err(toCimplifyError3(error));
1703
1294
  }
1704
1295
  }
1705
- async function safeWithFallback3(primary, fallback) {
1706
- const primaryResult = await safe3(primary());
1707
- if (primaryResult.ok) return primaryResult;
1708
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
1709
- return primaryResult;
1710
- }
1711
- return safe3(fallback());
1712
- }
1713
1296
  function toTerminalFailure(code, message, recoverable) {
1714
1297
  return {
1715
1298
  success: false,
@@ -1732,57 +1315,51 @@ var CheckoutService = class {
1732
1315
  constructor(client) {
1733
1316
  this.client = client;
1734
1317
  }
1318
+ orderTokenParam(orderId) {
1319
+ const token = this.client.getOrderToken(orderId);
1320
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1321
+ }
1735
1322
  async process(data) {
1736
1323
  const checkoutData = {
1737
1324
  ...data,
1738
1325
  idempotency_key: data.idempotency_key || generateIdempotencyKey()
1739
1326
  };
1740
- return safeWithFallback3(
1741
- () => this.client.post("/api/v1/checkout", {
1742
- checkout_data: checkoutData
1743
- }),
1744
- () => this.client.call(CHECKOUT_MUTATION.PROCESS, {
1327
+ const result = await safe3(
1328
+ this.client.post("/api/v1/checkout", {
1745
1329
  checkout_data: checkoutData
1746
1330
  })
1747
1331
  );
1332
+ if (result.ok && result.value.bill_token) {
1333
+ this.client.setOrderToken(result.value.order_id, result.value.bill_token);
1334
+ }
1335
+ return result;
1748
1336
  }
1749
- async initializePayment(orderId, method) {
1750
- return safe3(
1751
- this.client.call("order.initializePayment", {
1752
- order_id: orderId,
1753
- payment_method: method
1754
- })
1337
+ async initializePayment(_orderId, _method) {
1338
+ return err(
1339
+ new CimplifyError(
1340
+ "NOT_IMPLEMENTED",
1341
+ "initializePayment is not available in REST mode.",
1342
+ false
1343
+ )
1755
1344
  );
1756
1345
  }
1757
1346
  async submitAuthorization(input) {
1758
- return safeWithFallback3(
1759
- () => this.client.post("/api/v1/payments/authorization", input),
1760
- () => this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
1761
- );
1347
+ return safe3(this.client.post("/api/v1/payments/authorization", input));
1762
1348
  }
1763
1349
  async pollPaymentStatus(orderId) {
1764
1350
  const encodedId = encodeURIComponent(orderId);
1765
- return safeWithFallback3(
1766
- () => this.client.get(`/api/v1/orders/${encodedId}/payment-status`),
1767
- () => this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
1768
- );
1351
+ const tokenParam = this.orderTokenParam(orderId);
1352
+ return safe3(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
1769
1353
  }
1770
1354
  async updateOrderCustomer(orderId, customer) {
1771
1355
  const encodedId = encodeURIComponent(orderId);
1772
- return safeWithFallback3(
1773
- () => this.client.post(`/api/v1/orders/${encodedId}/customer`, customer),
1774
- () => this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
1775
- order_id: orderId,
1776
- ...customer
1777
- })
1778
- );
1356
+ const tokenParam = this.orderTokenParam(orderId);
1357
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
1779
1358
  }
1780
1359
  async verifyPayment(orderId) {
1781
- return safe3(
1782
- this.client.call("order.verifyPayment", {
1783
- order_id: orderId
1784
- })
1785
- );
1360
+ const encodedId = encodeURIComponent(orderId);
1361
+ const tokenParam = this.orderTokenParam(orderId);
1362
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
1786
1363
  }
1787
1364
  async processAndResolve(data) {
1788
1365
  data.on_status_change?.("preparing", {});
@@ -1901,61 +1478,38 @@ async function safe4(promise) {
1901
1478
  return err(toCimplifyError4(error));
1902
1479
  }
1903
1480
  }
1904
- async function safeWithFallback4(primary, fallback) {
1905
- const primaryResult = await safe4(primary());
1906
- if (primaryResult.ok) return primaryResult;
1907
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
1908
- return primaryResult;
1909
- }
1910
- return safe4(fallback());
1911
- }
1912
1481
  var OrderQueries = class {
1913
1482
  constructor(client) {
1914
1483
  this.client = client;
1915
1484
  }
1485
+ orderTokenParam(orderId) {
1486
+ const token = this.client.getOrderToken(orderId);
1487
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1488
+ }
1916
1489
  async list(options) {
1917
- let query2 = "orders";
1918
- if (options?.status) {
1919
- query2 += `[?(@.status=='${options.status}')]`;
1920
- }
1921
- query2 += "#sort(created_at,desc)";
1922
- if (options?.limit) {
1923
- query2 += `#limit(${options.limit})`;
1924
- }
1925
- if (options?.offset) {
1926
- query2 += `#offset(${options.offset})`;
1927
- }
1928
1490
  const params = new URLSearchParams();
1929
1491
  if (options?.status) params.set("status", options.status);
1930
1492
  if (options?.limit) params.set("limit", String(options.limit));
1931
1493
  if (options?.offset) params.set("offset", String(options.offset));
1932
1494
  const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
1933
- return safeWithFallback4(
1934
- () => this.client.get(path),
1935
- () => this.client.query(query2)
1936
- );
1495
+ return safe4(this.client.get(path));
1937
1496
  }
1938
1497
  async get(orderId) {
1939
1498
  const encodedId = encodeURIComponent(orderId);
1940
- return safeWithFallback4(
1941
- () => this.client.get(`/api/v1/orders/${encodedId}`),
1942
- () => this.client.query(`orders.${orderId}`)
1943
- );
1499
+ const tokenParam = this.orderTokenParam(orderId);
1500
+ return safe4(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
1944
1501
  }
1945
1502
  async getRecent(limit = 5) {
1946
- return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
1503
+ return this.list({ limit });
1947
1504
  }
1948
1505
  async getByStatus(status) {
1949
1506
  return this.list({ status });
1950
1507
  }
1951
1508
  async cancel(orderId, reason) {
1952
1509
  const encodedId = encodeURIComponent(orderId);
1953
- return safeWithFallback4(
1954
- () => this.client.post(`/api/v1/orders/${encodedId}/cancel`, {
1955
- reason
1956
- }),
1957
- () => this.client.call("order.cancelOrder", {
1958
- order_id: orderId,
1510
+ const tokenParam = this.orderTokenParam(orderId);
1511
+ return safe4(
1512
+ this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
1959
1513
  reason
1960
1514
  })
1961
1515
  );
@@ -1977,6 +1531,38 @@ async function safe5(promise) {
1977
1531
  return err(toCimplifyError5(error));
1978
1532
  }
1979
1533
  }
1534
+ function encodePathSegment(value) {
1535
+ return encodeURIComponent(value);
1536
+ }
1537
+ function toCreateAddressPayload(input) {
1538
+ return {
1539
+ label: input.label,
1540
+ street_address: input.address_line1,
1541
+ apartment: input.address_line2,
1542
+ city: input.city,
1543
+ region: input.state ?? "",
1544
+ postal_code: input.postal_code,
1545
+ country: input.country
1546
+ };
1547
+ }
1548
+ function toUpdateAddressPayload(input) {
1549
+ return {
1550
+ label: input.label,
1551
+ street_address: input.address_line1,
1552
+ apartment: input.address_line2,
1553
+ city: input.city,
1554
+ region: input.state,
1555
+ postal_code: input.postal_code,
1556
+ country: input.country
1557
+ };
1558
+ }
1559
+ function toCreateMobileMoneyPayload(input) {
1560
+ return {
1561
+ phone_number: input.phone_number,
1562
+ provider: input.provider,
1563
+ label: input.account_name
1564
+ };
1565
+ }
1980
1566
  var LinkService = class {
1981
1567
  constructor(client) {
1982
1568
  this.client = client;
@@ -2004,11 +1590,7 @@ var LinkService = class {
2004
1590
  return result;
2005
1591
  }
2006
1592
  async checkStatus(contact) {
2007
- return safe5(
2008
- this.client.call(LINK_MUTATION.CHECK_STATUS, {
2009
- contact
2010
- })
2011
- );
1593
+ return safe5(this.client.linkPost("/v1/link/check-status", { contact }));
2012
1594
  }
2013
1595
  async getLinkData() {
2014
1596
  return safe5(this.client.linkGet("/v1/link/data"));
@@ -2020,61 +1602,85 @@ var LinkService = class {
2020
1602
  return safe5(this.client.linkGet("/v1/link/mobile-money"));
2021
1603
  }
2022
1604
  async getPreferences() {
2023
- return safe5(this.client.query(LINK_QUERY.PREFERENCES));
1605
+ return safe5(this.client.linkGet("/v1/link/preferences"));
2024
1606
  }
2025
1607
  async enroll(data) {
2026
- return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
1608
+ return safe5(this.client.linkPost("/v1/link/enroll", data));
2027
1609
  }
2028
1610
  async enrollAndLinkOrder(data) {
2029
1611
  return safe5(
2030
- this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
1612
+ this.client.linkPost("/v1/link/enroll-and-link-order", data)
2031
1613
  );
2032
1614
  }
2033
1615
  async updatePreferences(preferences) {
2034
- return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
1616
+ return safe5(this.client.linkPost("/v1/link/preferences", preferences));
2035
1617
  }
2036
1618
  async createAddress(input) {
2037
- return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
1619
+ return safe5(
1620
+ this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
1621
+ );
2038
1622
  }
2039
1623
  async updateAddress(input) {
2040
- return safe5(this.client.call(LINK_MUTATION.UPDATE_ADDRESS, input));
1624
+ return safe5(
1625
+ this.client.linkPost(
1626
+ `/v1/link/addresses/${encodePathSegment(input.address_id)}`,
1627
+ toUpdateAddressPayload(input)
1628
+ )
1629
+ );
2041
1630
  }
2042
1631
  async deleteAddress(addressId) {
2043
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
1632
+ return safe5(
1633
+ this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
1634
+ );
2044
1635
  }
2045
1636
  async setDefaultAddress(addressId) {
2046
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
1637
+ return safe5(
1638
+ this.client.linkPost(
1639
+ `/v1/link/addresses/${encodePathSegment(addressId)}/default`
1640
+ )
1641
+ );
2047
1642
  }
2048
1643
  async trackAddressUsage(addressId) {
2049
1644
  return safe5(
2050
- this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2051
- address_id: addressId
2052
- })
1645
+ this.client.linkPost(
1646
+ `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
1647
+ )
2053
1648
  );
2054
1649
  }
2055
1650
  async createMobileMoney(input) {
2056
- return safe5(this.client.call(LINK_MUTATION.CREATE_MOBILE_MONEY, input));
1651
+ return safe5(
1652
+ this.client.linkPost(
1653
+ "/v1/link/mobile-money",
1654
+ toCreateMobileMoneyPayload(input)
1655
+ )
1656
+ );
2057
1657
  }
2058
1658
  async deleteMobileMoney(mobileMoneyId) {
2059
1659
  return safe5(
2060
- this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`)
1660
+ this.client.linkDelete(
1661
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
1662
+ )
2061
1663
  );
2062
1664
  }
2063
1665
  async setDefaultMobileMoney(mobileMoneyId) {
2064
1666
  return safe5(
2065
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
1667
+ this.client.linkPost(
1668
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
1669
+ )
2066
1670
  );
2067
1671
  }
2068
1672
  async trackMobileMoneyUsage(mobileMoneyId) {
2069
1673
  return safe5(
2070
- this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2071
- mobile_money_id: mobileMoneyId
2072
- })
1674
+ this.client.linkPost(
1675
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
1676
+ )
2073
1677
  );
2074
1678
  }
2075
1679
  async verifyMobileMoney(mobileMoneyId) {
2076
1680
  return safe5(
2077
- this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
1681
+ this.client.linkPost(
1682
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
1683
+ )
2078
1684
  );
2079
1685
  }
2080
1686
  async getSessions() {
@@ -2087,30 +1693,28 @@ var LinkService = class {
2087
1693
  return safe5(this.client.linkDelete("/v1/link/sessions"));
2088
1694
  }
2089
1695
  async getAddressesRest() {
2090
- return safe5(this.client.linkGet("/v1/link/addresses"));
1696
+ return this.getAddresses();
2091
1697
  }
2092
1698
  async createAddressRest(input) {
2093
- return safe5(this.client.linkPost("/v1/link/addresses", input));
1699
+ return this.createAddress(input);
2094
1700
  }
2095
1701
  async deleteAddressRest(addressId) {
2096
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
1702
+ return this.deleteAddress(addressId);
2097
1703
  }
2098
1704
  async setDefaultAddressRest(addressId) {
2099
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
1705
+ return this.setDefaultAddress(addressId);
2100
1706
  }
2101
1707
  async getMobileMoneyRest() {
2102
- return safe5(this.client.linkGet("/v1/link/mobile-money"));
1708
+ return this.getMobileMoney();
2103
1709
  }
2104
1710
  async createMobileMoneyRest(input) {
2105
- return safe5(this.client.linkPost("/v1/link/mobile-money", input));
1711
+ return this.createMobileMoney(input);
2106
1712
  }
2107
1713
  async deleteMobileMoneyRest(mobileMoneyId) {
2108
- return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
1714
+ return this.deleteMobileMoney(mobileMoneyId);
2109
1715
  }
2110
1716
  async setDefaultMobileMoneyRest(mobileMoneyId) {
2111
- return safe5(
2112
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2113
- );
1717
+ return this.setDefaultMobileMoney(mobileMoneyId);
2114
1718
  }
2115
1719
  };
2116
1720
 
@@ -2129,23 +1733,12 @@ async function safe6(promise) {
2129
1733
  return err(toCimplifyError6(error));
2130
1734
  }
2131
1735
  }
2132
- async function safeWithFallback5(primary, fallback) {
2133
- const primaryResult = await safe6(primary());
2134
- if (primaryResult.ok) return primaryResult;
2135
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2136
- return primaryResult;
2137
- }
2138
- return safe6(fallback());
2139
- }
2140
1736
  var AuthService = class {
2141
1737
  constructor(client) {
2142
1738
  this.client = client;
2143
1739
  }
2144
1740
  async getStatus() {
2145
- return safeWithFallback5(
2146
- () => this.client.get("/api/v1/auth/status"),
2147
- () => this.client.query("auth")
2148
- );
1741
+ return safe6(this.client.get("/api/v1/auth/status"));
2149
1742
  }
2150
1743
  async getCurrentUser() {
2151
1744
  const result = await this.getStatus();
@@ -2158,43 +1751,26 @@ var AuthService = class {
2158
1751
  return ok(result.value.is_authenticated);
2159
1752
  }
2160
1753
  async requestOtp(contact, contactType) {
2161
- return safeWithFallback5(
2162
- () => this.client.post("/api/v1/auth/request-otp", {
2163
- contact,
2164
- contact_type: contactType
2165
- }),
2166
- () => this.client.call(AUTH_MUTATION.REQUEST_OTP, {
1754
+ return safe6(
1755
+ this.client.post("/api/v1/auth/request-otp", {
2167
1756
  contact,
2168
1757
  contact_type: contactType
2169
1758
  })
2170
1759
  );
2171
1760
  }
2172
1761
  async verifyOtp(code, contact) {
2173
- return safeWithFallback5(
2174
- () => this.client.post("/api/v1/auth/verify-otp", {
2175
- otp_code: code,
2176
- contact
2177
- }),
2178
- () => this.client.call(AUTH_MUTATION.VERIFY_OTP, {
1762
+ return safe6(
1763
+ this.client.post("/api/v1/auth/verify-otp", {
2179
1764
  otp_code: code,
2180
1765
  contact
2181
1766
  })
2182
1767
  );
2183
1768
  }
2184
1769
  async logout() {
2185
- return safeWithFallback5(
2186
- () => this.client.post("/api/v1/auth/logout"),
2187
- () => this.client.call("auth.logout")
2188
- );
1770
+ return safe6(this.client.post("/api/v1/auth/logout"));
2189
1771
  }
2190
1772
  async updateProfile(input) {
2191
- return safe6(this.client.call("auth.update_profile", input));
2192
- }
2193
- async changePassword(input) {
2194
- return safe6(this.client.call("auth.change_password", input));
2195
- }
2196
- async resetPassword(email) {
2197
- return safe6(this.client.call("auth.reset_password", { email }));
1773
+ return safe6(this.client.post("/api/v1/auth/profile", input));
2198
1774
  }
2199
1775
  };
2200
1776
 
@@ -2213,47 +1789,29 @@ async function safe7(promise) {
2213
1789
  return err(toCimplifyError7(error));
2214
1790
  }
2215
1791
  }
2216
- async function safeWithFallback6(primary, fallback) {
2217
- const primaryResult = await safe7(primary());
2218
- if (primaryResult.ok) return primaryResult;
2219
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2220
- return primaryResult;
2221
- }
2222
- return safe7(fallback());
2223
- }
2224
1792
  var BusinessService = class {
2225
1793
  constructor(client) {
2226
1794
  this.client = client;
2227
1795
  }
2228
1796
  async getInfo() {
2229
- return safeWithFallback6(
2230
- () => this.client.get("/api/v1/business"),
2231
- () => this.client.query("business.info")
2232
- );
1797
+ return safe7(this.client.get("/api/v1/business"));
2233
1798
  }
2234
1799
  async getByHandle(handle) {
2235
- return safe7(this.client.query(`business.handle.${handle}`));
1800
+ const encodedHandle = encodeURIComponent(handle);
1801
+ return safe7(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
2236
1802
  }
2237
1803
  async getByDomain(domain) {
2238
- return safe7(this.client.query("business.domain", { domain }));
1804
+ const encodedDomain = encodeURIComponent(domain);
1805
+ return safe7(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
2239
1806
  }
2240
1807
  async getSettings() {
2241
- return safeWithFallback6(
2242
- () => this.client.get("/api/v1/business/settings"),
2243
- () => this.client.query("business.settings")
2244
- );
1808
+ return safe7(this.client.get("/api/v1/business/settings"));
2245
1809
  }
2246
1810
  async getTheme() {
2247
- return safeWithFallback6(
2248
- () => this.client.get("/api/v1/business/theme"),
2249
- () => this.client.query("business.theme")
2250
- );
1811
+ return safe7(this.client.get("/api/v1/business/theme"));
2251
1812
  }
2252
1813
  async getLocations() {
2253
- return safeWithFallback6(
2254
- () => this.client.get("/api/v1/business/locations"),
2255
- () => this.client.query("business.locations")
2256
- );
1814
+ return safe7(this.client.get("/api/v1/business/locations"));
2257
1815
  }
2258
1816
  async getLocation(locationId) {
2259
1817
  const result = await this.getLocations();
@@ -2265,10 +1823,7 @@ var BusinessService = class {
2265
1823
  return ok(location);
2266
1824
  }
2267
1825
  async getHours() {
2268
- return safeWithFallback6(
2269
- () => this.client.get("/api/v1/business/hours"),
2270
- () => this.client.query("business.hours")
2271
- );
1826
+ return safe7(this.client.get("/api/v1/business/hours"));
2272
1827
  }
2273
1828
  async getLocationHours(locationId) {
2274
1829
  const result = await this.getHours();
@@ -2276,31 +1831,7 @@ var BusinessService = class {
2276
1831
  return ok(result.value.filter((hour) => hour.location_id === locationId));
2277
1832
  }
2278
1833
  async getBootstrap() {
2279
- const restBootstrap = await safe7(this.client.get("/api/v1/bootstrap"));
2280
- if (restBootstrap.ok) {
2281
- return restBootstrap;
2282
- }
2283
- const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2284
- this.getInfo(),
2285
- this.getLocations(),
2286
- safe7(this.client.query("categories#select(id,name,slug)"))
2287
- ]);
2288
- if (!businessResult.ok) return businessResult;
2289
- if (!locationsResult.ok) return locationsResult;
2290
- if (!categoriesResult.ok) return categoriesResult;
2291
- const business = businessResult.value;
2292
- const locations = locationsResult.value;
2293
- const categories = categoriesResult.value;
2294
- const defaultLocation = locations[0];
2295
- return ok({
2296
- business,
2297
- location: defaultLocation,
2298
- locations,
2299
- categories,
2300
- currency: business.default_currency,
2301
- is_open: defaultLocation?.accepts_online_orders ?? false,
2302
- accepts_orders: defaultLocation?.accepts_online_orders ?? false
2303
- });
1834
+ return safe7(this.client.get("/api/v1/bootstrap"));
2304
1835
  }
2305
1836
  };
2306
1837
 
@@ -2323,49 +1854,47 @@ var InventoryService = class {
2323
1854
  constructor(client) {
2324
1855
  this.client = client;
2325
1856
  }
1857
+ withQuery(path, params) {
1858
+ const searchParams = new URLSearchParams();
1859
+ for (const [key, value] of Object.entries(params)) {
1860
+ if (value === void 0) continue;
1861
+ searchParams.set(key, String(value));
1862
+ }
1863
+ const query2 = searchParams.toString();
1864
+ return query2 ? `${path}?${query2}` : path;
1865
+ }
2326
1866
  async getStockLevels() {
2327
- return safe8(this.client.query("inventory.stock_levels"));
1867
+ return safe8(this.client.get("/api/v1/inventory/stock-levels"));
2328
1868
  }
2329
1869
  async getProductStock(productId, locationId) {
2330
- if (locationId) {
2331
- return safe8(
2332
- this.client.query("inventory.product", {
2333
- product_id: productId,
2334
- location_id: locationId
2335
- })
2336
- );
2337
- }
2338
- return safe8(
2339
- this.client.query("inventory.product", {
2340
- product_id: productId
2341
- })
2342
- );
1870
+ const encodedId = encodeURIComponent(productId);
1871
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
1872
+ location_id: locationId
1873
+ });
1874
+ return safe8(this.client.get(path));
2343
1875
  }
2344
1876
  async getVariantStock(variantId, locationId) {
2345
- return safe8(
2346
- this.client.query("inventory.variant", {
2347
- variant_id: variantId,
2348
- location_id: locationId
2349
- })
2350
- );
1877
+ const encodedId = encodeURIComponent(variantId);
1878
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
1879
+ location_id: locationId
1880
+ });
1881
+ return safe8(this.client.get(path));
2351
1882
  }
2352
1883
  async checkProductAvailability(productId, quantity, locationId) {
2353
- return safe8(
2354
- this.client.query("inventory.check_availability", {
2355
- product_id: productId,
2356
- quantity,
2357
- location_id: locationId
2358
- })
2359
- );
1884
+ const encodedId = encodeURIComponent(productId);
1885
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
1886
+ quantity,
1887
+ location_id: locationId
1888
+ });
1889
+ return safe8(this.client.get(path));
2360
1890
  }
2361
1891
  async checkVariantAvailability(variantId, quantity, locationId) {
2362
- return safe8(
2363
- this.client.query("inventory.check_availability", {
2364
- variant_id: variantId,
2365
- quantity,
2366
- location_id: locationId
2367
- })
2368
- );
1892
+ const encodedId = encodeURIComponent(variantId);
1893
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
1894
+ quantity,
1895
+ location_id: locationId
1896
+ });
1897
+ return safe8(this.client.get(path));
2369
1898
  }
2370
1899
  async checkMultipleAvailability(items, locationId) {
2371
1900
  const results = await Promise.all(
@@ -2379,7 +1908,7 @@ var InventoryService = class {
2379
1908
  return ok(results.map((r) => r.value));
2380
1909
  }
2381
1910
  async getSummary() {
2382
- return safe8(this.client.query("inventory.summary"));
1911
+ return safe8(this.client.get("/api/v1/inventory/summary"));
2383
1912
  }
2384
1913
  async isInStock(productId, locationId) {
2385
1914
  const result = await this.checkProductAvailability(productId, 1, locationId);
@@ -2394,9 +1923,6 @@ var InventoryService = class {
2394
1923
  };
2395
1924
 
2396
1925
  // src/scheduling.ts
2397
- function toVariables(input) {
2398
- return Object.fromEntries(Object.entries(input));
2399
- }
2400
1926
  function toCimplifyError9(error) {
2401
1927
  if (error instanceof CimplifyError) return error;
2402
1928
  if (error instanceof Error) {
@@ -2411,68 +1937,110 @@ async function safe9(promise) {
2411
1937
  return err(toCimplifyError9(error));
2412
1938
  }
2413
1939
  }
1940
+ function withQuery2(path, params) {
1941
+ const searchParams = new URLSearchParams();
1942
+ for (const [key, value] of Object.entries(params)) {
1943
+ if (value === void 0) continue;
1944
+ searchParams.set(key, String(value));
1945
+ }
1946
+ const query2 = searchParams.toString();
1947
+ return query2 ? `${path}?${query2}` : path;
1948
+ }
1949
+ function normalizeServiceAvailability(result) {
1950
+ if (Array.isArray(result.days) && result.days.length > 0) {
1951
+ return result;
1952
+ }
1953
+ const days = Array.isArray(result.availability) ? result.availability.map((day) => ({
1954
+ ...day,
1955
+ is_fully_booked: day.is_fully_booked ?? (typeof day.has_availability === "boolean" ? !day.has_availability : void 0)
1956
+ })) : [];
1957
+ return { ...result, days };
1958
+ }
1959
+ function firstScheduledTime(booking) {
1960
+ return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
1961
+ }
2414
1962
  var SchedulingService = class {
2415
1963
  constructor(client) {
2416
1964
  this.client = client;
2417
1965
  }
2418
1966
  async getServices() {
2419
- return safe9(this.client.query("scheduling.services"));
1967
+ return safe9(this.client.get("/api/v1/scheduling/services"));
2420
1968
  }
2421
1969
  /**
2422
- * Get a specific service by ID
2423
- * Note: Filters from all services client-side (no single-service endpoint)
1970
+ * Get a specific service by ID.
2424
1971
  */
2425
1972
  async getService(serviceId) {
2426
1973
  const result = await this.getServices();
2427
1974
  if (!result.ok) return result;
2428
- return ok(result.value.find((s) => s.id === serviceId) || null);
1975
+ return ok(result.value.find((service) => service.id === serviceId) || null);
2429
1976
  }
2430
1977
  async getAvailableSlots(input) {
2431
- return safe9(
2432
- this.client.query("scheduling.slots", toVariables(input))
2433
- );
1978
+ const path = withQuery2("/api/v1/scheduling/slots", {
1979
+ service_id: input.service_id,
1980
+ date: input.date,
1981
+ participant_count: input.participant_count,
1982
+ duration_minutes: input.duration_minutes
1983
+ });
1984
+ return safe9(this.client.get(path));
2434
1985
  }
2435
1986
  async checkSlotAvailability(input) {
2436
- return safe9(
2437
- this.client.query(
2438
- "scheduling.check_availability",
2439
- toVariables(input)
2440
- )
2441
- );
1987
+ const path = withQuery2("/api/v1/scheduling/slots/check", {
1988
+ service_id: input.service_id,
1989
+ slot_time: input.slot_time,
1990
+ duration_minutes: input.duration_minutes,
1991
+ participant_count: input.participant_count
1992
+ });
1993
+ return safe9(this.client.get(path));
2442
1994
  }
2443
1995
  async getServiceAvailability(params) {
1996
+ const path = withQuery2("/api/v1/scheduling/availability", {
1997
+ service_id: params.service_id,
1998
+ start_date: params.start_date,
1999
+ end_date: params.end_date,
2000
+ location_id: params.location_id,
2001
+ participant_count: params.participant_count
2002
+ });
2444
2003
  return safe9(
2445
- this.client.query(
2446
- "scheduling.availability",
2447
- toVariables(params)
2448
- )
2004
+ this.client.get(path).then((result) => normalizeServiceAvailability(result))
2449
2005
  );
2450
2006
  }
2451
2007
  async getBooking(bookingId) {
2452
- return safe9(this.client.query(`scheduling.${bookingId}`));
2008
+ const encodedId = encodeURIComponent(bookingId);
2009
+ return safe9(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2453
2010
  }
2454
- async getCustomerBookings() {
2455
- return safe9(this.client.query("scheduling"));
2011
+ async getCustomerBookings(customerId) {
2012
+ const path = withQuery2("/api/v1/scheduling/bookings", {
2013
+ customer_id: customerId
2014
+ });
2015
+ return safe9(this.client.get(path));
2456
2016
  }
2457
2017
  async getUpcomingBookings() {
2458
- return safe9(
2459
- this.client.query(
2460
- "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2461
- )
2462
- );
2018
+ const result = await this.getCustomerBookings();
2019
+ if (!result.ok) return result;
2020
+ const upcoming = result.value.filter((booking) => {
2021
+ const status = String(booking.status).toLowerCase();
2022
+ return status !== "completed" && status !== "cancelled";
2023
+ }).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
2024
+ return ok(upcoming);
2463
2025
  }
2464
2026
  async getPastBookings(limit = 10) {
2465
- return safe9(
2466
- this.client.query(
2467
- `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
2468
- )
2469
- );
2027
+ const result = await this.getCustomerBookings();
2028
+ if (!result.ok) return result;
2029
+ const past = result.value.filter((booking) => String(booking.status).toLowerCase() === "completed").sort((a, b) => firstScheduledTime(b).localeCompare(firstScheduledTime(a))).slice(0, Math.max(0, limit));
2030
+ return ok(past);
2470
2031
  }
2471
2032
  async cancelBooking(input) {
2472
- return safe9(this.client.call("scheduling.cancel_booking", input));
2033
+ const encodedId = encodeURIComponent(input.booking_id);
2034
+ return safe9(
2035
+ this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
2036
+ reason: input.reason
2037
+ })
2038
+ );
2473
2039
  }
2474
2040
  async rescheduleBooking(input) {
2475
- return safe9(this.client.call("scheduling.reschedule_booking", input));
2041
+ return safe9(
2042
+ this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2043
+ );
2476
2044
  }
2477
2045
  async getNextAvailableSlot(serviceId, fromDate) {
2478
2046
  const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -2491,6 +2059,12 @@ var SchedulingService = class {
2491
2059
  if (!result.ok) return result;
2492
2060
  return ok(result.value.some((slot) => slot.is_available));
2493
2061
  }
2062
+ // Compatibility alias for callers typed against the older Booking shape.
2063
+ async getBookingLegacy(bookingId) {
2064
+ const result = await this.getBooking(bookingId);
2065
+ if (!result.ok) return result;
2066
+ return ok(result.value);
2067
+ }
2494
2068
  };
2495
2069
 
2496
2070
  // src/lite.ts
@@ -2513,47 +2087,18 @@ var LiteService = class {
2513
2087
  this.client = client;
2514
2088
  }
2515
2089
  async getBootstrap() {
2516
- return safe10(this.client.query("lite.bootstrap"));
2090
+ return safe10(this.client.get("/api/v1/lite/bootstrap"));
2517
2091
  }
2518
2092
  async getTable(tableId) {
2519
- return safe10(this.client.query(`lite.table.${tableId}`));
2520
- }
2521
- async getTableByNumber(tableNumber, locationId) {
2522
- return safe10(
2523
- this.client.query("lite.table_by_number", {
2524
- table_number: tableNumber,
2525
- location_id: locationId
2526
- })
2527
- );
2528
- }
2529
- async sendToKitchen(tableId, items) {
2530
- return safe10(
2531
- this.client.call("lite.send_to_kitchen", {
2532
- table_id: tableId,
2533
- items
2534
- })
2535
- );
2536
- }
2537
- async callWaiter(tableId, reason) {
2538
- return safe10(
2539
- this.client.call("lite.call_waiter", {
2540
- table_id: tableId,
2541
- reason
2542
- })
2543
- );
2544
- }
2545
- async requestBill(tableId) {
2546
- return safe10(
2547
- this.client.call("lite.request_bill", {
2548
- table_id: tableId
2549
- })
2550
- );
2093
+ const encodedId = encodeURIComponent(tableId);
2094
+ return safe10(this.client.get(`/api/v1/lite/tables/${encodedId}`));
2551
2095
  }
2552
2096
  async getMenu() {
2553
- return safe10(this.client.query("lite.menu"));
2097
+ return safe10(this.client.get("/api/v1/lite/menu"));
2554
2098
  }
2555
2099
  async getMenuByCategory(categoryId) {
2556
- return safe10(this.client.query(`lite.menu.category.${categoryId}`));
2100
+ const encodedId = encodeURIComponent(categoryId);
2101
+ return safe10(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
2557
2102
  }
2558
2103
  };
2559
2104
 
@@ -2572,30 +2117,16 @@ async function safe11(promise) {
2572
2117
  return err(toCimplifyError11(error));
2573
2118
  }
2574
2119
  }
2575
- async function safeWithFallback7(primary, fallback) {
2576
- const primaryResult = await safe11(primary());
2577
- if (primaryResult.ok) return primaryResult;
2578
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2579
- return primaryResult;
2580
- }
2581
- return safe11(fallback());
2582
- }
2583
2120
  var FxService = class {
2584
2121
  constructor(client) {
2585
2122
  this.client = client;
2586
2123
  }
2587
2124
  async getRate(from, to) {
2588
2125
  const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
2589
- return safeWithFallback7(
2590
- () => this.client.get(path),
2591
- () => this.client.call("fx.getRate", { from, to })
2592
- );
2126
+ return safe11(this.client.get(path));
2593
2127
  }
2594
2128
  async lockQuote(request) {
2595
- return safeWithFallback7(
2596
- () => this.client.post("/api/v1/fx/quotes", request),
2597
- () => this.client.call("fx.lockQuote", request)
2598
- );
2129
+ return safe11(this.client.post("/api/v1/fx/quotes", request));
2599
2130
  }
2600
2131
  };
2601
2132
 
@@ -3204,4 +2735,72 @@ function createElements(client, businessId, options) {
3204
2735
  return new CimplifyElements(client, businessId, options);
3205
2736
  }
3206
2737
 
2738
+ // src/query/builder.ts
2739
+ function escapeQueryValue(value) {
2740
+ return value.replace(/'/g, "\\'");
2741
+ }
2742
+ var QueryBuilder = class {
2743
+ constructor(entity) {
2744
+ this.filters = [];
2745
+ this.modifiers = [];
2746
+ this.pathSegments = [];
2747
+ this.entity = entity;
2748
+ }
2749
+ path(segment) {
2750
+ this.pathSegments.push(segment);
2751
+ return this;
2752
+ }
2753
+ where(field, op, value) {
2754
+ const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
2755
+ if (op === "contains" || op === "startsWith") {
2756
+ this.filters.push(`@.${field} ${op} ${v}`);
2757
+ } else {
2758
+ this.filters.push(`@.${field}${op}${v}`);
2759
+ }
2760
+ return this;
2761
+ }
2762
+ and(field, op, value) {
2763
+ return this.where(field, op, value);
2764
+ }
2765
+ sort(field, order = "asc") {
2766
+ this.modifiers.push(`sort(${field},${order})`);
2767
+ return this;
2768
+ }
2769
+ limit(n) {
2770
+ this.modifiers.push(`limit(${n})`);
2771
+ return this;
2772
+ }
2773
+ offset(n) {
2774
+ this.modifiers.push(`offset(${n})`);
2775
+ return this;
2776
+ }
2777
+ count() {
2778
+ this.modifiers.push("count");
2779
+ return this;
2780
+ }
2781
+ enriched() {
2782
+ this.modifiers.push("enriched");
2783
+ return this;
2784
+ }
2785
+ build() {
2786
+ let query2 = this.entity;
2787
+ if (this.pathSegments.length > 0) {
2788
+ query2 += "." + this.pathSegments.join(".");
2789
+ }
2790
+ if (this.filters.length > 0) {
2791
+ query2 += `[?(${this.filters.join(" && ")})]`;
2792
+ }
2793
+ for (const mod of this.modifiers) {
2794
+ query2 += `#${mod}`;
2795
+ }
2796
+ return query2;
2797
+ }
2798
+ toString() {
2799
+ return this.build();
2800
+ }
2801
+ };
2802
+ function query(entity) {
2803
+ return new QueryBuilder(entity);
2804
+ }
2805
+
3207
2806
  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 };