@yassirbenmoussa/aicommerce-sdk 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -33,6 +33,68 @@ var init_client = __esm({
33
33
  exports.AICommerce = class _AICommerce {
34
34
  constructor(config) {
35
35
  this.sessionToken = null;
36
+ // ============================================
37
+ // Products API
38
+ // ============================================
39
+ /**
40
+ * Products API namespace
41
+ */
42
+ this.products = {
43
+ /**
44
+ * Create a new product
45
+ */
46
+ create: async (product) => {
47
+ return this.request("/api/v1/products", {
48
+ method: "POST",
49
+ body: JSON.stringify(product)
50
+ });
51
+ },
52
+ /**
53
+ * Batch upsert products (create or update)
54
+ */
55
+ batchUpsert: async (products) => {
56
+ return this.request("/api/v1/products", {
57
+ method: "POST",
58
+ body: JSON.stringify({ products })
59
+ });
60
+ },
61
+ /**
62
+ * List products with pagination
63
+ */
64
+ list: async (options) => {
65
+ const params = new URLSearchParams();
66
+ if (options?.page) params.set("page", String(options.page));
67
+ if (options?.perPage) params.set("perPage", String(options.perPage));
68
+ if (options?.search) params.set("search", options.search);
69
+ if (options?.categoryId) params.set("categoryId", options.categoryId);
70
+ if (options?.isActive !== void 0) params.set("isActive", String(options.isActive));
71
+ const query = params.toString();
72
+ return this.request(`/api/v1/products${query ? `?${query}` : ""}`);
73
+ },
74
+ /**
75
+ * Get a single product by ID
76
+ */
77
+ get: async (productId) => {
78
+ return this.request(`/api/v1/products/${productId}`);
79
+ },
80
+ /**
81
+ * Update a product
82
+ */
83
+ update: async (productId, data) => {
84
+ return this.request(`/api/v1/products/${productId}`, {
85
+ method: "PUT",
86
+ body: JSON.stringify(data)
87
+ });
88
+ },
89
+ /**
90
+ * Delete a product
91
+ */
92
+ delete: async (productId) => {
93
+ return this.request(`/api/v1/products/${productId}`, {
94
+ method: "DELETE"
95
+ });
96
+ }
97
+ };
36
98
  if (!config.apiKey) {
37
99
  throw new Error("AICommerce: apiKey is required");
38
100
  }
@@ -159,6 +221,47 @@ var init_client = __esm({
159
221
  setSessionToken(token) {
160
222
  this.sessionToken = token;
161
223
  }
224
+ // ============================================
225
+ // Upload API
226
+ // ============================================
227
+ /**
228
+ * Upload an image file
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * // Upload from File input
233
+ * const file = document.querySelector('input[type="file"]').files[0];
234
+ * const result = await client.upload(file);
235
+ * console.log(result.url);
236
+ *
237
+ * // Upload and associate with product
238
+ * const result = await client.upload(file, { productId: 'prod_123', isPrimary: true });
239
+ * ```
240
+ */
241
+ async upload(file, options) {
242
+ const formData = new FormData();
243
+ formData.append("file", file);
244
+ if (options?.folder) formData.append("folder", options.folder);
245
+ if (options?.productId) formData.append("productId", options.productId);
246
+ if (options?.isPrimary) formData.append("isPrimary", "true");
247
+ const url = `${this.baseUrl}/api/v1/upload`;
248
+ const response = await fetch(url, {
249
+ method: "POST",
250
+ headers: {
251
+ "X-API-Key": this.apiKey
252
+ },
253
+ body: formData
254
+ });
255
+ if (!response.ok) {
256
+ const errorData = await response.json().catch(() => ({}));
257
+ throw new exports.AICommerceError(
258
+ errorData.message || errorData.error || `HTTP ${response.status}`,
259
+ errorData.code || "UPLOAD_ERROR",
260
+ response.status
261
+ );
262
+ }
263
+ return response.json();
264
+ }
162
265
  /**
163
266
  * Static method for one-off chat requests
164
267
  *
@@ -190,14 +293,749 @@ var init_client = __esm({
190
293
  }
191
294
  });
192
295
 
296
+ // src/widget-styles.ts
297
+ function hexToRgb(hex) {
298
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
299
+ return result ? {
300
+ r: parseInt(result[1], 16),
301
+ g: parseInt(result[2], 16),
302
+ b: parseInt(result[3], 16)
303
+ } : { r: 99, g: 102, b: 241 };
304
+ }
305
+ function createWidgetStyles(config) {
306
+ const primary = config.primaryColor;
307
+ const rgb = hexToRgb(primary);
308
+ const isLeft = config.position === "bottom-left";
309
+ return `
310
+ /* AI Commerce Widget Styles */
311
+ #aicommerce-widget {
312
+ --aic-primary: ${primary};
313
+ --aic-primary-rgb: ${rgb.r}, ${rgb.g}, ${rgb.b};
314
+ --aic-primary-light: rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1);
315
+ --aic-primary-dark: rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.9);
316
+ --aic-bg: #ffffff;
317
+ --aic-bg-secondary: #f8fafc;
318
+ --aic-text: #1e293b;
319
+ --aic-text-secondary: #64748b;
320
+ --aic-border: #e2e8f0;
321
+ --aic-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
322
+ --aic-radius: 16px;
323
+ --aic-z-index: ${config.zIndex};
324
+
325
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
326
+ font-size: 14px;
327
+ line-height: 1.5;
328
+ position: fixed;
329
+ bottom: 20px;
330
+ ${isLeft ? "left: 20px;" : "right: 20px;"}
331
+ z-index: var(--aic-z-index);
332
+ }
333
+
334
+ /* Dark theme */
335
+ #aicommerce-widget.aicommerce-theme-dark,
336
+ @media (prefers-color-scheme: dark) {
337
+ #aicommerce-widget.aicommerce-theme-auto {
338
+ --aic-bg: #1e293b;
339
+ --aic-bg-secondary: #0f172a;
340
+ --aic-text: #f1f5f9;
341
+ --aic-text-secondary: #94a3b8;
342
+ --aic-border: #334155;
343
+ }
344
+ }
345
+
346
+ /* Launcher Button */
347
+ .aicommerce-launcher {
348
+ width: 60px;
349
+ height: 60px;
350
+ border-radius: 50%;
351
+ background: linear-gradient(135deg, var(--aic-primary), var(--aic-primary-dark));
352
+ border: none;
353
+ cursor: pointer;
354
+ box-shadow: 0 4px 20px rgba(var(--aic-primary-rgb), 0.4);
355
+ display: flex;
356
+ align-items: center;
357
+ justify-content: center;
358
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
359
+ animation: aic-pulse 2s infinite;
360
+ }
361
+
362
+ .aicommerce-launcher:hover {
363
+ transform: scale(1.1);
364
+ box-shadow: 0 6px 30px rgba(var(--aic-primary-rgb), 0.5);
365
+ }
366
+
367
+ .aicommerce-launcher-icon {
368
+ font-size: 24px;
369
+ }
370
+
371
+ .aicommerce-hidden {
372
+ display: none !important;
373
+ }
374
+
375
+ @keyframes aic-pulse {
376
+ 0%, 100% { box-shadow: 0 4px 20px rgba(var(--aic-primary-rgb), 0.4); }
377
+ 50% { box-shadow: 0 4px 30px rgba(var(--aic-primary-rgb), 0.6); }
378
+ }
379
+
380
+ /* Chat Window */
381
+ .aicommerce-chat {
382
+ position: absolute;
383
+ bottom: 0;
384
+ ${isLeft ? "left: 0;" : "right: 0;"}
385
+ width: 380px;
386
+ max-width: calc(100vw - 40px);
387
+ height: 600px;
388
+ max-height: calc(100vh - 100px);
389
+ background: var(--aic-bg);
390
+ border-radius: var(--aic-radius);
391
+ box-shadow: var(--aic-shadow);
392
+ display: flex;
393
+ flex-direction: column;
394
+ overflow: hidden;
395
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
396
+ transform-origin: bottom ${isLeft ? "left" : "right"};
397
+ }
398
+
399
+ .aicommerce-chat.aicommerce-closed {
400
+ opacity: 0;
401
+ transform: scale(0.9) translateY(20px);
402
+ pointer-events: none;
403
+ }
404
+
405
+ .aicommerce-chat.aicommerce-open {
406
+ opacity: 1;
407
+ transform: scale(1) translateY(0);
408
+ }
409
+
410
+ /* Header */
411
+ .aicommerce-header {
412
+ background: linear-gradient(135deg, var(--aic-primary), var(--aic-primary-dark));
413
+ color: white;
414
+ padding: 16px 20px;
415
+ display: flex;
416
+ align-items: center;
417
+ justify-content: space-between;
418
+ }
419
+
420
+ .aicommerce-header-info {
421
+ display: flex;
422
+ align-items: center;
423
+ gap: 12px;
424
+ }
425
+
426
+ .aicommerce-avatar {
427
+ width: 40px;
428
+ height: 40px;
429
+ border-radius: 50%;
430
+ background: rgba(255, 255, 255, 0.2);
431
+ display: flex;
432
+ align-items: center;
433
+ justify-content: center;
434
+ font-size: 20px;
435
+ overflow: hidden;
436
+ }
437
+
438
+ .aicommerce-avatar img {
439
+ width: 100%;
440
+ height: 100%;
441
+ object-fit: cover;
442
+ }
443
+
444
+ .aicommerce-header-text {
445
+ display: flex;
446
+ flex-direction: column;
447
+ }
448
+
449
+ .aicommerce-bot-name {
450
+ font-weight: 600;
451
+ font-size: 16px;
452
+ }
453
+
454
+ .aicommerce-status {
455
+ font-size: 12px;
456
+ opacity: 0.9;
457
+ }
458
+
459
+ .aicommerce-close {
460
+ width: 32px;
461
+ height: 32px;
462
+ border-radius: 50%;
463
+ background: rgba(255, 255, 255, 0.2);
464
+ border: none;
465
+ color: white;
466
+ cursor: pointer;
467
+ display: flex;
468
+ align-items: center;
469
+ justify-content: center;
470
+ font-size: 16px;
471
+ transition: background 0.2s;
472
+ }
473
+
474
+ .aicommerce-close:hover {
475
+ background: rgba(255, 255, 255, 0.3);
476
+ }
477
+
478
+ /* Messages */
479
+ .aicommerce-messages {
480
+ flex: 1;
481
+ overflow-y: auto;
482
+ padding: 20px;
483
+ display: flex;
484
+ flex-direction: column;
485
+ gap: 16px;
486
+ background: var(--aic-bg-secondary);
487
+ }
488
+
489
+ .aicommerce-message {
490
+ max-width: 85%;
491
+ animation: aic-slide-in 0.3s ease-out;
492
+ }
493
+
494
+ .aicommerce-message.aicommerce-user {
495
+ align-self: flex-end;
496
+ }
497
+
498
+ .aicommerce-message.aicommerce-assistant {
499
+ align-self: flex-start;
500
+ }
501
+
502
+ .aicommerce-message-content {
503
+ padding: 12px 16px;
504
+ border-radius: 16px;
505
+ line-height: 1.5;
506
+ }
507
+
508
+ .aicommerce-user .aicommerce-message-content {
509
+ background: var(--aic-primary);
510
+ color: white;
511
+ border-bottom-right-radius: 4px;
512
+ }
513
+
514
+ .aicommerce-assistant .aicommerce-message-content {
515
+ background: var(--aic-bg);
516
+ color: var(--aic-text);
517
+ border-bottom-left-radius: 4px;
518
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
519
+ }
520
+
521
+ @keyframes aic-slide-in {
522
+ from { opacity: 0; transform: translateY(10px); }
523
+ to { opacity: 1; transform: translateY(0); }
524
+ }
525
+
526
+ /* Typing Indicator */
527
+ .aicommerce-typing {
528
+ display: flex;
529
+ gap: 4px;
530
+ padding: 12px 16px;
531
+ background: var(--aic-bg);
532
+ border-radius: 16px;
533
+ width: fit-content;
534
+ }
535
+
536
+ .aicommerce-typing span {
537
+ width: 8px;
538
+ height: 8px;
539
+ background: var(--aic-text-secondary);
540
+ border-radius: 50%;
541
+ animation: aic-bounce 1.4s infinite ease-in-out;
542
+ }
543
+
544
+ .aicommerce-typing span:nth-child(1) { animation-delay: -0.32s; }
545
+ .aicommerce-typing span:nth-child(2) { animation-delay: -0.16s; }
546
+
547
+ @keyframes aic-bounce {
548
+ 0%, 80%, 100% { transform: scale(0); }
549
+ 40% { transform: scale(1); }
550
+ }
551
+
552
+ /* Product Cards */
553
+ .aicommerce-products {
554
+ display: flex;
555
+ gap: 8px;
556
+ margin-top: 12px;
557
+ overflow-x: auto;
558
+ padding-bottom: 4px;
559
+ }
560
+
561
+ .aicommerce-product-card {
562
+ flex-shrink: 0;
563
+ width: 140px;
564
+ background: var(--aic-bg);
565
+ border-radius: 12px;
566
+ overflow: hidden;
567
+ cursor: pointer;
568
+ transition: all 0.2s;
569
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
570
+ }
571
+
572
+ .aicommerce-product-card:hover {
573
+ transform: translateY(-2px);
574
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
575
+ }
576
+
577
+ .aicommerce-product-image {
578
+ width: 100%;
579
+ height: 100px;
580
+ object-fit: cover;
581
+ }
582
+
583
+ .aicommerce-product-placeholder {
584
+ width: 100%;
585
+ height: 100px;
586
+ background: var(--aic-bg-secondary);
587
+ display: flex;
588
+ align-items: center;
589
+ justify-content: center;
590
+ font-size: 32px;
591
+ }
592
+
593
+ .aicommerce-product-info {
594
+ padding: 10px;
595
+ display: flex;
596
+ flex-direction: column;
597
+ gap: 4px;
598
+ }
599
+
600
+ .aicommerce-product-name {
601
+ font-weight: 500;
602
+ font-size: 13px;
603
+ color: var(--aic-text);
604
+ white-space: nowrap;
605
+ overflow: hidden;
606
+ text-overflow: ellipsis;
607
+ }
608
+
609
+ .aicommerce-product-price {
610
+ font-weight: 600;
611
+ font-size: 14px;
612
+ color: var(--aic-primary);
613
+ }
614
+
615
+ /* Input Area */
616
+ .aicommerce-input-container {
617
+ padding: 16px 20px;
618
+ background: var(--aic-bg);
619
+ border-top: 1px solid var(--aic-border);
620
+ display: flex;
621
+ gap: 12px;
622
+ }
623
+
624
+ .aicommerce-input {
625
+ flex: 1;
626
+ padding: 12px 16px;
627
+ border: 1px solid var(--aic-border);
628
+ border-radius: 24px;
629
+ background: var(--aic-bg-secondary);
630
+ color: var(--aic-text);
631
+ font-size: 14px;
632
+ outline: none;
633
+ transition: all 0.2s;
634
+ }
635
+
636
+ .aicommerce-input:focus {
637
+ border-color: var(--aic-primary);
638
+ box-shadow: 0 0 0 3px var(--aic-primary-light);
639
+ }
640
+
641
+ .aicommerce-input::placeholder {
642
+ color: var(--aic-text-secondary);
643
+ }
644
+
645
+ .aicommerce-send {
646
+ width: 44px;
647
+ height: 44px;
648
+ border-radius: 50%;
649
+ background: var(--aic-primary);
650
+ border: none;
651
+ color: white;
652
+ cursor: pointer;
653
+ display: flex;
654
+ align-items: center;
655
+ justify-content: center;
656
+ transition: all 0.2s;
657
+ }
658
+
659
+ .aicommerce-send:hover:not(:disabled) {
660
+ background: var(--aic-primary-dark);
661
+ transform: scale(1.05);
662
+ }
663
+
664
+ .aicommerce-send:disabled {
665
+ opacity: 0.6;
666
+ cursor: not-allowed;
667
+ }
668
+
669
+ /* Mobile Responsive */
670
+ @media (max-width: 420px) {
671
+ #aicommerce-widget {
672
+ bottom: 16px;
673
+ ${isLeft ? "left: 16px;" : "right: 16px;"}
674
+ }
675
+
676
+ .aicommerce-chat {
677
+ width: calc(100vw - 32px);
678
+ height: calc(100vh - 100px);
679
+ border-radius: 12px;
680
+ }
681
+
682
+ .aicommerce-launcher {
683
+ width: 56px;
684
+ height: 56px;
685
+ }
686
+ }
687
+
688
+ /* Scrollbar */
689
+ .aicommerce-messages::-webkit-scrollbar {
690
+ width: 6px;
691
+ }
692
+
693
+ .aicommerce-messages::-webkit-scrollbar-track {
694
+ background: transparent;
695
+ }
696
+
697
+ .aicommerce-messages::-webkit-scrollbar-thumb {
698
+ background: var(--aic-border);
699
+ border-radius: 3px;
700
+ }
701
+
702
+ .aicommerce-messages::-webkit-scrollbar-thumb:hover {
703
+ background: var(--aic-text-secondary);
704
+ }
705
+ `;
706
+ }
707
+ function injectStyles(css) {
708
+ const style = document.createElement("style");
709
+ style.id = "aicommerce-widget-styles";
710
+ style.textContent = css;
711
+ const existing = document.getElementById("aicommerce-widget-styles");
712
+ if (existing) {
713
+ existing.remove();
714
+ }
715
+ document.head.appendChild(style);
716
+ return style;
717
+ }
718
+ var init_widget_styles = __esm({
719
+ "src/widget-styles.ts"() {
720
+ }
721
+ });
722
+
723
+ // src/widget.ts
724
+ var widget_exports = {};
725
+ __export(widget_exports, {
726
+ AICommerceWidget: () => exports.AICommerceWidget,
727
+ createWidget: () => createWidget
728
+ });
729
+ function createWidget(config) {
730
+ if (!config.apiKey) {
731
+ throw new Error("AICommerceWidget: apiKey is required");
732
+ }
733
+ const client = new exports.AICommerce({
734
+ apiKey: config.apiKey,
735
+ baseUrl: config.baseUrl
736
+ });
737
+ const state = {
738
+ isOpen: false,
739
+ isLoading: true,
740
+ messages: [],
741
+ storeConfig: null
742
+ };
743
+ let container = null;
744
+ let styleElement = null;
745
+ let resolvedConfig;
746
+ async function fetchStoreConfig() {
747
+ try {
748
+ const baseUrl = config.baseUrl || detectBaseUrl();
749
+ const response = await fetch(`${baseUrl}/api/v1/store`, {
750
+ headers: { "x-api-key": config.apiKey }
751
+ });
752
+ if (!response.ok) return null;
753
+ const data = await response.json();
754
+ return data.store;
755
+ } catch (error) {
756
+ console.error("Failed to fetch store config:", error);
757
+ return null;
758
+ }
759
+ }
760
+ function detectBaseUrl() {
761
+ if (typeof window !== "undefined") {
762
+ const script = document.querySelector("script[data-aicommerce-url]");
763
+ if (script) {
764
+ return script.getAttribute("data-aicommerce-url") || "";
765
+ }
766
+ }
767
+ return "https://api.aicommerce.dev";
768
+ }
769
+ async function initialize() {
770
+ state.storeConfig = await fetchStoreConfig();
771
+ resolvedConfig = {
772
+ apiKey: config.apiKey,
773
+ baseUrl: config.baseUrl || detectBaseUrl(),
774
+ position: config.position || "bottom-right",
775
+ theme: config.theme || "auto",
776
+ primaryColor: config.primaryColor || state.storeConfig?.primaryColor || "#6366f1",
777
+ welcomeMessage: config.welcomeMessage || state.storeConfig?.welcomeMessage || "Hi! How can I help you find the perfect product today?",
778
+ botName: config.botName || state.storeConfig?.chatBotName || "Shopping Assistant",
779
+ zIndex: config.zIndex || 9999,
780
+ buttonText: config.buttonText || "\u{1F4AC}",
781
+ hideLauncher: config.hideLauncher || false,
782
+ onOpen: config.onOpen,
783
+ onClose: config.onClose,
784
+ onProductClick: config.onProductClick,
785
+ onMessage: config.onMessage
786
+ };
787
+ const styles = createWidgetStyles(resolvedConfig);
788
+ styleElement = injectStyles(styles);
789
+ container = document.createElement("div");
790
+ container.id = "aicommerce-widget";
791
+ container.className = `aicommerce-widget aicommerce-${resolvedConfig.position} aicommerce-theme-${resolvedConfig.theme}`;
792
+ document.body.appendChild(container);
793
+ render();
794
+ state.messages.push({
795
+ role: "assistant",
796
+ content: resolvedConfig.welcomeMessage
797
+ });
798
+ state.isLoading = false;
799
+ render();
800
+ }
801
+ function render() {
802
+ if (!container) return;
803
+ const html = `
804
+ ${!resolvedConfig.hideLauncher ? `
805
+ <button class="aicommerce-launcher ${state.isOpen ? "aicommerce-hidden" : ""}" aria-label="Open chat">
806
+ <span class="aicommerce-launcher-icon">${resolvedConfig.buttonText}</span>
807
+ </button>
808
+ ` : ""}
809
+
810
+ <div class="aicommerce-chat ${state.isOpen ? "aicommerce-open" : "aicommerce-closed"}">
811
+ <div class="aicommerce-header">
812
+ <div class="aicommerce-header-info">
813
+ <div class="aicommerce-avatar">
814
+ ${state.storeConfig?.logo ? `<img src="${state.storeConfig.logo}" alt="${resolvedConfig.botName}" />` : `<span>\u{1F916}</span>`}
815
+ </div>
816
+ <div class="aicommerce-header-text">
817
+ <span class="aicommerce-bot-name">${resolvedConfig.botName}</span>
818
+ <span class="aicommerce-status">Online</span>
819
+ </div>
820
+ </div>
821
+ <button class="aicommerce-close" aria-label="Close chat">\u2715</button>
822
+ </div>
823
+
824
+ <div class="aicommerce-messages">
825
+ ${state.messages.map((msg) => `
826
+ <div class="aicommerce-message aicommerce-${msg.role}">
827
+ <div class="aicommerce-message-content">${escapeHtml(msg.content)}</div>
828
+ ${msg.products && msg.products.length > 0 ? `
829
+ <div class="aicommerce-products">
830
+ ${msg.products.map((product) => `
831
+ <div class="aicommerce-product-card" data-product-id="${product.id}">
832
+ ${product.imageUrl ? `
833
+ <img src="${product.imageUrl}" alt="${escapeHtml(product.name)}" class="aicommerce-product-image" />
834
+ ` : `
835
+ <div class="aicommerce-product-placeholder">\u{1F4E6}</div>
836
+ `}
837
+ <div class="aicommerce-product-info">
838
+ <span class="aicommerce-product-name">${escapeHtml(product.name)}</span>
839
+ <span class="aicommerce-product-price">${formatPrice(product.price, product.currency)}</span>
840
+ </div>
841
+ </div>
842
+ `).join("")}
843
+ </div>
844
+ ` : ""}
845
+ </div>
846
+ `).join("")}
847
+ ${state.isLoading ? `
848
+ <div class="aicommerce-message aicommerce-assistant">
849
+ <div class="aicommerce-typing">
850
+ <span></span><span></span><span></span>
851
+ </div>
852
+ </div>
853
+ ` : ""}
854
+ </div>
855
+
856
+ <div class="aicommerce-input-container">
857
+ <input
858
+ type="text"
859
+ class="aicommerce-input"
860
+ placeholder="Type your message..."
861
+ ${state.isLoading ? "disabled" : ""}
862
+ />
863
+ <button class="aicommerce-send" ${state.isLoading ? "disabled" : ""} aria-label="Send message">
864
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
865
+ <path d="M22 2L11 13M22 2L15 22L11 13M22 2L2 9L11 13"/>
866
+ </svg>
867
+ </button>
868
+ </div>
869
+ </div>
870
+ `;
871
+ container.innerHTML = html;
872
+ attachEventListeners();
873
+ const messagesEl = container.querySelector(".aicommerce-messages");
874
+ if (messagesEl) {
875
+ messagesEl.scrollTop = messagesEl.scrollHeight;
876
+ }
877
+ }
878
+ function attachEventListeners() {
879
+ if (!container) return;
880
+ const launcherEl = container.querySelector(".aicommerce-launcher");
881
+ if (launcherEl) {
882
+ launcherEl.addEventListener("click", () => open());
883
+ }
884
+ const closeEl = container.querySelector(".aicommerce-close");
885
+ if (closeEl) {
886
+ closeEl.addEventListener("click", () => close());
887
+ }
888
+ const inputEl = container.querySelector(".aicommerce-input");
889
+ const sendEl = container.querySelector(".aicommerce-send");
890
+ if (inputEl) {
891
+ inputEl.addEventListener("keypress", (e) => {
892
+ if (e.key === "Enter" && inputEl.value.trim()) {
893
+ handleSend(inputEl.value.trim());
894
+ inputEl.value = "";
895
+ }
896
+ });
897
+ }
898
+ if (sendEl && inputEl) {
899
+ sendEl.addEventListener("click", () => {
900
+ if (inputEl.value.trim()) {
901
+ handleSend(inputEl.value.trim());
902
+ inputEl.value = "";
903
+ }
904
+ });
905
+ }
906
+ const productCards = container.querySelectorAll(".aicommerce-product-card");
907
+ productCards.forEach((card) => {
908
+ card.addEventListener("click", () => {
909
+ const productId = card.getAttribute("data-product-id");
910
+ const product = state.messages.flatMap((m) => m.products || []).find((p) => p.id === productId);
911
+ if (product && resolvedConfig.onProductClick) {
912
+ resolvedConfig.onProductClick(product);
913
+ }
914
+ });
915
+ });
916
+ }
917
+ async function handleSend(message) {
918
+ state.messages.push({ role: "user", content: message });
919
+ state.isLoading = true;
920
+ render();
921
+ try {
922
+ const response = await client.chat(message);
923
+ state.messages.push({
924
+ role: "assistant",
925
+ content: response.reply,
926
+ products: response.products
927
+ });
928
+ if (resolvedConfig.onMessage) {
929
+ resolvedConfig.onMessage(message, response);
930
+ }
931
+ return response;
932
+ } catch (error) {
933
+ state.messages.push({
934
+ role: "assistant",
935
+ content: "Sorry, I encountered an error. Please try again."
936
+ });
937
+ throw error;
938
+ } finally {
939
+ state.isLoading = false;
940
+ render();
941
+ }
942
+ }
943
+ function open() {
944
+ state.isOpen = true;
945
+ render();
946
+ resolvedConfig.onOpen?.();
947
+ setTimeout(() => {
948
+ const input = container?.querySelector(".aicommerce-input");
949
+ input?.focus();
950
+ }, 100);
951
+ }
952
+ function close() {
953
+ state.isOpen = false;
954
+ render();
955
+ resolvedConfig.onClose?.();
956
+ }
957
+ function toggle() {
958
+ if (state.isOpen) {
959
+ close();
960
+ } else {
961
+ open();
962
+ }
963
+ }
964
+ function destroy() {
965
+ if (container) {
966
+ container.remove();
967
+ container = null;
968
+ }
969
+ if (styleElement) {
970
+ styleElement.remove();
971
+ styleElement = null;
972
+ }
973
+ }
974
+ function updateConfig(newConfig) {
975
+ Object.assign(resolvedConfig, newConfig);
976
+ if (newConfig.primaryColor) {
977
+ const styles = createWidgetStyles(resolvedConfig);
978
+ if (styleElement) {
979
+ styleElement.textContent = styles;
980
+ }
981
+ }
982
+ render();
983
+ }
984
+ function escapeHtml(text) {
985
+ const div = document.createElement("div");
986
+ div.textContent = text;
987
+ return div.innerHTML;
988
+ }
989
+ function formatPrice(price, currency) {
990
+ const symbols = {
991
+ USD: "$",
992
+ EUR: "\u20AC",
993
+ GBP: "\xA3",
994
+ MAD: "DH",
995
+ SAR: "SAR",
996
+ AED: "AED",
997
+ JPY: "\xA5",
998
+ CNY: "\xA5"
999
+ };
1000
+ const symbol = symbols[currency || "USD"] || currency || "$";
1001
+ return `${price.toFixed(2)} ${symbol}`;
1002
+ }
1003
+ initialize();
1004
+ return {
1005
+ open,
1006
+ close,
1007
+ toggle,
1008
+ destroy,
1009
+ sendMessage: handleSend,
1010
+ updateConfig
1011
+ };
1012
+ }
1013
+ exports.AICommerceWidget = void 0;
1014
+ var init_widget = __esm({
1015
+ "src/widget.ts"() {
1016
+ init_client();
1017
+ init_widget_styles();
1018
+ exports.AICommerceWidget = {
1019
+ init: createWidget,
1020
+ VERSION: "1.0.0"
1021
+ };
1022
+ if (typeof window !== "undefined") {
1023
+ window.AICommerceWidget = exports.AICommerceWidget;
1024
+ }
1025
+ }
1026
+ });
1027
+
193
1028
  // src/index.ts
194
1029
  init_client();
1030
+ init_widget();
195
1031
  var VERSION = "1.0.0";
196
1032
  if (typeof window !== "undefined") {
197
1033
  window.AICommerce = (init_client(), __toCommonJS(client_exports)).AICommerce;
198
1034
  window.AICommerceError = (init_client(), __toCommonJS(client_exports)).AICommerceError;
1035
+ window.AICommerceWidget = (init_widget(), __toCommonJS(widget_exports)).AICommerceWidget;
199
1036
  }
200
1037
 
201
1038
  exports.VERSION = VERSION;
1039
+ exports.createWidget = createWidget;
202
1040
  //# sourceMappingURL=index.cjs.map
203
1041
  //# sourceMappingURL=index.cjs.map