admesh-ui-sdk 1.0.16 โ 1.0.19
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/CHANGELOG.md +10 -0
- package/dist/components/AdMeshBridgeFormat.d.ts.map +1 -1
- package/dist/components/AdMeshEcommerceCards.d.ts.map +1 -1
- package/dist/components/AdMeshInlineCard.d.ts.map +1 -1
- package/dist/components/AdMeshLayout.d.ts.map +1 -1
- package/dist/components/AdMeshLinkTracker.d.ts.map +1 -1
- package/dist/components/AdMeshProductCard.d.ts.map +1 -1
- package/dist/components/AdMeshRecommendations.d.ts +11 -5
- package/dist/components/AdMeshRecommendations.d.ts.map +1 -1
- package/dist/components/AdMeshSummaryLayout.d.ts.map +1 -1
- package/dist/components/AdMeshTailAd.d.ts.map +1 -1
- package/dist/components/AdMeshViewabilityTracker.d.ts +1 -1
- package/dist/components/AdMeshViewabilityTracker.d.ts.map +1 -1
- package/dist/components/WeaveAdFormatContainer.d.ts +4 -0
- package/dist/components/WeaveAdFormatContainer.d.ts.map +1 -1
- package/dist/components/WeaveFallbackRecommendations.d.ts.map +1 -1
- package/dist/context/AdMeshProvider.d.ts.map +1 -1
- package/dist/hooks/useAdMeshStyles.d.ts.map +1 -1
- package/dist/hooks/useAdMeshTracker.d.ts.map +1 -1
- package/dist/hooks/useViewabilityTracker.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1393 -1227
- package/dist/index.mjs.map +1 -1
- package/dist/sdk/AdMeshRenderer.d.ts.map +1 -1
- package/dist/sdk/AdMeshSDK.d.ts +3 -2
- package/dist/sdk/AdMeshSDK.d.ts.map +1 -1
- package/dist/sdk/AdMeshTracker.d.ts.map +1 -1
- package/dist/sdk/WeaveResponseProcessor.d.ts +2 -1
- package/dist/sdk/WeaveResponseProcessor.d.ts.map +1 -1
- package/dist/types/index.d.ts +22 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/inlineExposureTracker.d.ts.map +1 -1
- package/dist/utils/logger.d.ts +12 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/streamingEvents.d.ts.map +1 -1
- package/dist/utils/viewabilityTracker.d.ts.map +1 -1
- package/package.json +1 -5
- package/dist/test-setup.d.ts +0 -1
- package/dist/test-setup.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Te=Object.defineProperty;var Ee=(t,e,o)=>e in t?Te(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var L=(t,e,o)=>Ee(t,typeof e!="symbol"?e+"":e,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),je=require("react-dom/client"),h=require("react");function Ie(t,e,o){const d=t*e>242500;return{...{visibilityThreshold:d?.3:.5,minimumDuration:1e3,isLargeAd:d},...o}}function Le(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function Re(t){const e=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight,n=window.innerWidth||document.documentElement.clientWidth,d=e.height,r=e.width;if(d===0||r===0)return 0;const a=Math.max(0,e.top),i=Math.min(o,e.bottom),l=Math.max(0,e.left),g=Math.min(n,e.right),c=Math.max(0,i-a),u=Math.max(0,g-l),p=c*u,b=d*r;return b>0?p/b:0}function de(){const t=window.innerHeight,e=document.documentElement.scrollHeight,o=window.pageYOffset||document.documentElement.scrollTop,n=e-t;return n<=0?100:Math.min(100,o/n*100)}function Ne(t){const e=t.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,n=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+o,left:e.left+n}}function Pe(t){const e=t.getBoundingClientRect(),o=Ne(t),n=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight,r=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Le(n),viewportWidth:n,viewportHeight:d,adWidth:e.width,adHeight:e.height,adPositionTop:o.top,adPositionLeft:o.left,isDarkMode:r,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function De(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function Fe(t,e,o){return t>=o.visibilityThreshold&&e>=o.minimumDuration}function ce(t=new Date){return t.toISOString()}function ze(t){return t.length===0?0:t.reduce((o,n)=>o+n,0)/t.length}function le(t,e){let o;return function(...d){o||(t(...d),o=!0,setTimeout(()=>o=!1,e))}}const Be={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let Ve=Be;function pe({adId:t,productId:e,offerId:o,agentId:n,recommendationId:d,elementRef:r,config:a}){const i={...Ve,...a},l=h.useRef(De()),[g,c]=h.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:ce(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:i.enabled}),u=h.useRef(null),p=h.useRef(null),b=h.useRef(null),f=h.useRef(null),x=h.useRef(null),y=h.useRef([]),m=h.useRef([]),_=h.useRef(null),M=h.useCallback(v=>{i.debug&&console.log(`[AdMesh Viewability] ${v}`)},[i.debug]),w=h.useCallback(async(v,A)=>{if(!(!i.enabled||!r.current||!u.current)&&(M(`Analytics disabled - skipping event: ${v}`),i.onEvent)){const T=Pe(r.current),C={eventType:v,timestamp:ce(),sessionId:l.current,adId:t,productId:e,offerId:o,agentId:n,recommendationId:d,timeMetrics:g.timeMetrics,engagementMetrics:g.engagementMetrics,contextMetrics:T,mrcStandards:u.current,isViewable:g.isViewable,metadata:A};i.onEvent(C)}},[i,t,e,o,n,r,g,M]),k=h.useCallback(async()=>{m.current.length!==0&&(M("Analytics disabled - clearing batch without sending"),m.current=[],_.current&&(clearTimeout(_.current),_.current=null))},[M]),E=h.useCallback(le(()=>{if(!r.current)return;const v=Re(r.current),A=Date.now(),T=new Date(g.timeMetrics.loadedAt).getTime();c(C=>{const S={...C};v>0&&y.current.push(v);const I=C.isVisible,R=v>0;if(R&&!I)p.current=A,S.engagementMetrics.viewportEnterCount++,S.timeMetrics.timeToFirstVisible||(S.timeMetrics.timeToFirstVisible=A-T,S.engagementMetrics.scrollDepthAtFirstVisible=de(),w("ad_visible"));else if(!R&&I){if(p.current){const N=A-p.current;S.timeMetrics.totalVisibleDuration+=N,p.current=null}S.engagementMetrics.viewportExitCount++,w("ad_hidden")}else if(R&&I&&p.current){const N=A-p.current;S.timeMetrics.totalVisibleDuration+=N,p.current=A}if(S.isVisible=R,S.visibilityPercentage=v,v>S.engagementMetrics.maxVisibilityPercentage&&(S.engagementMetrics.maxVisibilityPercentage=v),y.current.length>0&&(S.engagementMetrics.averageVisibilityPercentage=ze(y.current)),u.current){const N=C.isViewable,D=Fe(v,S.timeMetrics.totalVisibleDuration,u.current);if(D&&!N)S.isViewable=!0,S.timeMetrics.timeToViewable=A-T,b.current=A,w("ad_viewable");else if(D&&N&&b.current){const F=A-b.current;S.timeMetrics.totalViewableDuration+=F,b.current=A}}return S.engagementMetrics.currentScrollDepth=de(),S})},100),[r,g.timeMetrics.loadedAt,w]);return h.useEffect(()=>{if(!r.current)return;const v=r.current.getBoundingClientRect();u.current=Ie(v.width,v.height,i.mrcStandards),M("Initialized MRC standards"),w("ad_loaded")},[r,i.mrcStandards,M,w]),h.useEffect(()=>{if(!i.enabled||!r.current)return;const v=new IntersectionObserver(A=>{A.forEach(()=>{E()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return v.observe(r.current),()=>{v.disconnect()}},[i.enabled,r,E]),h.useEffect(()=>{if(!i.enabled)return;const v=le(()=>{E()},100);return window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[i.enabled,E]),h.useEffect(()=>{if(!i.enabled||!r.current)return;const v=r.current,A=()=>{f.current=Date.now(),c(C=>({...C,engagementMetrics:{...C.engagementMetrics,hoverCount:C.engagementMetrics.hoverCount+1}})),w("ad_hover_start")},T=()=>{if(f.current){const C=Date.now()-f.current;c(S=>({...S,timeMetrics:{...S.timeMetrics,totalHoverDuration:S.timeMetrics.totalHoverDuration+C}})),f.current=null,w("ad_hover_end",{hoverDuration:C})}};return v.addEventListener("mouseenter",A),v.addEventListener("mouseleave",T),()=>{v.removeEventListener("mouseenter",A),v.removeEventListener("mouseleave",T)}},[i.enabled,r,w]),h.useEffect(()=>{if(!i.enabled||!r.current)return;const v=r.current,A=()=>{x.current=Date.now(),w("ad_focus")},T=()=>{if(x.current){const C=Date.now()-x.current;c(S=>({...S,timeMetrics:{...S.timeMetrics,totalFocusDuration:S.timeMetrics.totalFocusDuration+C}})),x.current=null,w("ad_blur",{focusDuration:C})}};return v.addEventListener("focus",A),v.addEventListener("blur",T),()=>{v.removeEventListener("focus",A),v.removeEventListener("blur",T)}},[i.enabled,r,w]),h.useEffect(()=>{if(!i.enabled||!r.current)return;const v=r.current,A=()=>{c(T=>({...T,engagementMetrics:{...T.engagementMetrics,wasClicked:!0}})),w("ad_click")};return v.addEventListener("click",A),()=>{v.removeEventListener("click",A)}},[i.enabled,r,w]),h.useEffect(()=>()=>{const v=Date.now(),A=new Date(g.timeMetrics.loadedAt).getTime(),T=v-A;c(C=>({...C,timeMetrics:{...C.timeMetrics,sessionDuration:T}})),w("ad_unloaded",{sessionDuration:T}),k()},[]),g}const B=({adId:t,productId:e,offerId:o,agentId:n,recommendationId:d,exposureUrl:r,sessionId:a,children:i,config:l,className:g,style:c,onViewabilityChange:u,onVisible:p,onViewable:b,onClick:f})=>{const x=h.useRef(null),y=h.useRef(!1),m=pe({adId:t,productId:e,offerId:o,agentId:n,recommendationId:d,elementRef:x,config:l}),_=h.useRef(m.isViewable);h.useEffect(()=>{m.isViewable!==_.current&&(_.current=m.isViewable,u&&u(m.isViewable),m.isViewable&&b&&b(),m.isViewable&&!y.current&&(console.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:r?"present":"MISSING",sessionId:a?"present":"MISSING",adId:t,recommendationId:d}),r&&a?(y.current=!0,console.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",r),fetch(r,{method:"GET",keepalive:!0}).then(()=>{console.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(k=>{console.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",k),y.current=!1})):console.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!r,hasSessionId:!!a})))},[m.isViewable,u,b,r,a,t,d]);const M=h.useRef(m.isVisible);h.useEffect(()=>{m.isVisible!==M.current&&(M.current=m.isVisible,m.isVisible&&p&&p())},[m.isVisible,p]);const w=()=>{f&&f()};return s.jsx("div",{ref:x,className:g,style:c,onClick:w,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":m.isViewable,"data-is-visible":m.isVisible,"data-visibility-percentage":m.visibilityPercentage.toFixed(2),children:i})};B.displayName="AdMeshViewabilityTracker";const We=t=>t&&t.trim()?t.trim():"",ne=({recommendations:t,theme:e,className:o="",style:n={},sessionId:d})=>{if(!t||t.length===0)return console.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const r=t[0],a=(r==null?void 0:r.ad_id)||"",i=r==null?void 0:r.product_id,l=r==null?void 0:r.exposure_url,g=r==null?void 0:r.recommendation_id,c=(r==null?void 0:r.creative_input)||{},u=c.short_description||"",p=c.brand_name||(r==null?void 0:r.title)||"",b=c.product_name||"",f=(r==null?void 0:r.click_url)||(r==null?void 0:r.admesh_link)||c.cta_url||(r==null?void 0:r.url),x=We(c.cta_label);if(!p&&!b)return console.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering"),null;const y=b?`${p} โ ${b}`:p;console.log("[AdMeshTailAd] ๐ Rendering with tracking data:",{adId:a,productId:i,recommendationId:g,exposureUrl:l?"present":"MISSING",sessionId:d?"present":"MISSING",recommendationsCount:t.length,clickUrl:f||"MISSING",clickUrlSource:r!=null&&r.click_url?"click_url":r!=null&&r.admesh_link?"admesh_link":c.cta_url?"cta_url":r!=null&&r.url?"url":"none",shortDescription:u?"present":"MISSING",brandName:p});const m=(w,k)=>{console.log(`AdMesh tail ad ${w} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:r.ad_id,productId:r.product_id,clickUrl:f,source:w}).catch(()=>{console.error(`[AdMesh] Failed to track ${w} click`)})},_=w=>{w.stopPropagation(),m("tail_ad_brand_name")},M=w=>{w.stopPropagation(),m("tail_ad_cta")};return s.jsx(B,{adId:a,productId:i,recommendationId:g,exposureUrl:l,sessionId:d,className:`admesh-tail-ad ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...n},children:s.jsxs("div",{className:"tail-ad-container",children:[y&&s.jsx("div",{className:"mb-2",children:s.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",children:f&&p?s.jsxs(s.Fragment,{children:[s.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-semibold",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:_,children:p}),b&&` โ ${b}`]}):y})}),u&&s.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",children:u}),s.jsxs("div",{className:"flex items-center justify-between mt-2",children:[x&&f&&s.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium text-sm",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:M,children:x}),s.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})})};function $e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var te={exports:{}};/*!
|
|
1
|
+
"use strict";var Le=Object.defineProperty;var Ie=(t,e,n)=>e in t?Le(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var P=(t,e,n)=>Ie(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),Ne=require("react-dom/client"),g=require("react");let W=!1;var be;try{typeof globalThis.importMeta<"u"&&((be=globalThis.importMeta.env)!=null&&be.PROD)&&(W=!0)}catch{}W||(W=typeof process<"u"&&process.env.NODE_ENV==="production"||typeof process<"u"&&process.env.ADMESH_ENV==="production");const d={log:(...t)=>{W||console.log(...t)},warn:(...t)=>{W||console.warn(...t)},error:(...t)=>{console.error(...t)},info:(...t)=>{W||console.info(...t)},debug:(...t)=>{W||console.debug(...t)}};function Pe(t,e,n){const a=t*e>242500;return{...{visibilityThreshold:a?.3:.5,minimumDuration:1e3,isLargeAd:a},...n}}function Fe(t){return t<768?"mobile":t<1024?"tablet":"desktop"}function De(t){const e=t.getBoundingClientRect(),n=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth,a=e.height,r=e.width;if(a===0||r===0)return 0;const c=Math.max(0,e.top),s=Math.min(n,e.bottom),m=Math.max(0,e.left),h=Math.min(o,e.right),l=Math.max(0,s-c),u=Math.max(0,h-m),b=l*u,x=a*r;return x>0?b/x:0}function me(){const t=window.innerHeight,e=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,o=e-t;return o<=0?100:Math.min(100,n/o*100)}function ze(t){const e=t.getBoundingClientRect(),n=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft;return{top:e.top+n,left:e.left+o}}function Be(t){const e=t.getBoundingClientRect(),n=ze(t),o=window.innerWidth||document.documentElement.clientWidth,a=window.innerHeight||document.documentElement.clientHeight,r=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches;return{pageUrl:window.location.href,pageTitle:document.title,referrer:document.referrer,deviceType:Fe(o),viewportWidth:o,viewportHeight:a,adWidth:e.width,adHeight:e.height,adPositionTop:n.top,adPositionLeft:n.left,isDarkMode:r,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}}function We(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function $e(t,e,n){return t>=n.visibilityThreshold&&e>=n.minimumDuration}function ue(t=new Date){return t.toISOString()}function Ve(t){return t.length===0?0:t.reduce((n,o)=>n+o,0)/t.length}function pe(t,e){let n;return function(...a){n||(t(...a),n=!0,setTimeout(()=>n=!1,e))}}const Ue={enabled:!0,apiEndpoint:"",enableBatching:!1,batchSize:10,batchTimeout:5e3,debug:!1,enableRetry:!1,maxRetries:3,retryDelay:1e3};let He=Ue;function xe({adId:t,productId:e,offerId:n,agentId:o,recommendationId:a,elementRef:r,config:c}){const s={...He,...c},m=g.useRef(We()),[h,l]=g.useState({isVisible:!1,isViewable:!1,visibilityPercentage:0,timeMetrics:{loadedAt:ue(),totalVisibleDuration:0,totalViewableDuration:0,totalHoverDuration:0,totalFocusDuration:0},engagementMetrics:{currentScrollDepth:0,viewportEnterCount:0,viewportExitCount:0,hoverCount:0,wasClicked:!1,maxVisibilityPercentage:0,averageVisibilityPercentage:0},isTracking:s.enabled}),u=g.useRef(null),b=g.useRef(null),x=g.useRef(null),f=g.useRef(null),v=g.useRef(null),T=g.useRef([]),p=g.useRef([]),y=g.useRef(null),k=g.useCallback(_=>{s.debug&&d.log(`[AdMesh Viewability] ${_}`)},[s.debug]),S=g.useCallback(async(_,R)=>{if(!(!s.enabled||!r.current||!u.current)&&(k(`Analytics disabled - skipping event: ${_}`),s.onEvent)){const E=Be(r.current),A={eventType:_,timestamp:ue(),sessionId:m.current,adId:t,productId:e,offerId:n,agentId:o,recommendationId:a,timeMetrics:h.timeMetrics,engagementMetrics:h.engagementMetrics,contextMetrics:E,mrcStandards:u.current,isViewable:h.isViewable,metadata:R};s.onEvent(A)}},[s,t,e,n,o,r,h,k]),M=g.useCallback(async()=>{p.current.length!==0&&(k("Analytics disabled - clearing batch without sending"),p.current=[],y.current&&(clearTimeout(y.current),y.current=null))},[k]),C=g.useCallback(pe(()=>{if(!r.current)return;const _=De(r.current),R=Date.now(),E=new Date(h.timeMetrics.loadedAt).getTime();l(A=>{const w={...A};_>0&&T.current.push(_);const L=A.isVisible,j=_>0;if(j&&!L)b.current=R,w.engagementMetrics.viewportEnterCount++,w.timeMetrics.timeToFirstVisible||(w.timeMetrics.timeToFirstVisible=R-E,w.engagementMetrics.scrollDepthAtFirstVisible=me(),S("ad_visible"));else if(!j&&L){if(b.current){const I=R-b.current;w.timeMetrics.totalVisibleDuration+=I,b.current=null}w.engagementMetrics.viewportExitCount++,S("ad_hidden")}else if(j&&L&&b.current){const I=R-b.current;w.timeMetrics.totalVisibleDuration+=I,b.current=R}if(w.isVisible=j,w.visibilityPercentage=_,_>w.engagementMetrics.maxVisibilityPercentage&&(w.engagementMetrics.maxVisibilityPercentage=_),T.current.length>0&&(w.engagementMetrics.averageVisibilityPercentage=Ve(T.current)),u.current){const I=A.isViewable,F=$e(_,w.timeMetrics.totalVisibleDuration,u.current);if(F&&!I)w.isViewable=!0,w.timeMetrics.timeToViewable=R-E,x.current=R,S("ad_viewable");else if(F&&I&&x.current){const z=R-x.current;w.timeMetrics.totalViewableDuration+=z,x.current=R}}return w.engagementMetrics.currentScrollDepth=me(),w})},100),[r,h.timeMetrics.loadedAt,S]);return g.useEffect(()=>{if(!r.current)return;const _=r.current.getBoundingClientRect();u.current=Pe(_.width,_.height,s.mrcStandards),k("Initialized MRC standards"),S("ad_loaded")},[r,s.mrcStandards,k,S]),g.useEffect(()=>{if(!s.enabled||!r.current)return;const _=new IntersectionObserver(R=>{R.forEach(()=>{C()})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});return _.observe(r.current),()=>{_.disconnect()}},[s.enabled,r,C]),g.useEffect(()=>{if(!s.enabled)return;const _=pe(()=>{C()},100);return window.addEventListener("scroll",_,{passive:!0}),()=>window.removeEventListener("scroll",_)},[s.enabled,C]),g.useEffect(()=>{if(!s.enabled||!r.current)return;const _=r.current,R=()=>{f.current=Date.now(),l(A=>({...A,engagementMetrics:{...A.engagementMetrics,hoverCount:A.engagementMetrics.hoverCount+1}})),S("ad_hover_start")},E=()=>{if(f.current){const A=Date.now()-f.current;l(w=>({...w,timeMetrics:{...w.timeMetrics,totalHoverDuration:w.timeMetrics.totalHoverDuration+A}})),f.current=null,S("ad_hover_end",{hoverDuration:A})}};return _.addEventListener("mouseenter",R),_.addEventListener("mouseleave",E),()=>{_.removeEventListener("mouseenter",R),_.removeEventListener("mouseleave",E)}},[s.enabled,r,S]),g.useEffect(()=>{if(!s.enabled||!r.current)return;const _=r.current,R=()=>{v.current=Date.now(),S("ad_focus")},E=()=>{if(v.current){const A=Date.now()-v.current;l(w=>({...w,timeMetrics:{...w.timeMetrics,totalFocusDuration:w.timeMetrics.totalFocusDuration+A}})),v.current=null,S("ad_blur",{focusDuration:A})}};return _.addEventListener("focus",R),_.addEventListener("blur",E),()=>{_.removeEventListener("focus",R),_.removeEventListener("blur",E)}},[s.enabled,r,S]),g.useEffect(()=>{if(!s.enabled||!r.current)return;const _=r.current,R=()=>{l(E=>({...E,engagementMetrics:{...E.engagementMetrics,wasClicked:!0}})),S("ad_click")};return _.addEventListener("click",R),()=>{_.removeEventListener("click",R)}},[s.enabled,r,S]),g.useEffect(()=>()=>{const _=Date.now(),R=new Date(h.timeMetrics.loadedAt).getTime(),E=_-R;l(A=>({...A,timeMetrics:{...A.timeMetrics,sessionDuration:E}})),S("ad_unloaded",{sessionDuration:E}),M()},[]),h}const $=({adId:t,productId:e,offerId:n,agentId:o,recommendationId:a,exposureUrl:r,sessionId:c,children:s,config:m,className:h,style:l,onViewabilityChange:u,onVisible:b,onViewable:x,onClick:f})=>{const v=g.useRef(null),T=g.useRef(!1),p=xe({adId:t,productId:e,offerId:n,agentId:o,recommendationId:a,elementRef:v,config:m}),y=g.useRef(p.isViewable);g.useEffect(()=>{p.isViewable!==y.current&&(y.current=p.isViewable,u&&u(p.isViewable),p.isViewable&&x&&x(),p.isViewable&&!T.current&&(d.log("[AdMeshViewabilityTracker] ๐ฏ Ad is viewable, checking exposure pixel requirements:",{exposureUrl:r?"present":"MISSING",sessionId:c?"present":"MISSING",adId:t,recommendationId:a}),r&&c?(T.current=!0,d.log("[AdMeshViewabilityTracker] ๐ฅ Firing exposure pixel:",r),fetch(r,{method:"GET",keepalive:!0}).then(()=>{d.log("[AdMesh] โ
Exposure pixel fired successfully")}).catch(M=>{d.warn("[AdMesh] โ ๏ธ Failed to fire exposure pixel:",M),T.current=!1})):d.warn("[AdMeshViewabilityTracker] โ ๏ธ Cannot fire exposure pixel - missing required data:",{hasExposureUrl:!!r,hasSessionId:!!c})))},[p.isViewable,u,x,r,c,t,a]);const k=g.useRef(p.isVisible);g.useEffect(()=>{p.isVisible!==k.current&&(k.current=p.isVisible,p.isVisible&&b&&b())},[p.isVisible,b]);const S=()=>{f&&f()};return i.jsx("div",{ref:v,className:h,style:l,onClick:S,"data-admesh-viewability-tracker":!0,"data-ad-id":t,"data-is-viewable":p.isViewable,"data-is-visible":p.isVisible,"data-visibility-percentage":p.visibilityPercentage.toFixed(2),children:s})};$.displayName="AdMeshViewabilityTracker";const Oe=t=>t&&t.trim()?t.trim():"",ie=({recommendations:t,theme:e,className:n="",style:o={},sessionId:a})=>{if(!t||t.length===0)return d.log("[AdMesh Tail Ad] No recommendations provided - not rendering"),null;const r=t[0],c=(r==null?void 0:r.ad_id)||"",s=r==null?void 0:r.product_id,m=r==null?void 0:r.exposure_url,h=r==null?void 0:r.recommendation_id,l=(r==null?void 0:r.creative_input)||{},u=l.short_description||"",b=l.offer_summary||"",x=l.brand_name||(r==null?void 0:r.title)||"",f=l.product_name||"",v=(r==null?void 0:r.click_url)||(r==null?void 0:r.admesh_link)||l.cta_url||(r==null?void 0:r.url),T=Oe(l.cta_label);if(!x)return d.log("[AdMesh Tail Ad] No valid recommendation data provided - not rendering"),null;let p=x,y="";b?y=b:f&&(y=f),y&&(p=`${x} โ ${y}`),d.log("[AdMeshTailAd] ๐ Rendering with tracking data:",{adId:c,productId:s,recommendationId:h,exposureUrl:m?"present":"MISSING",sessionId:a?"present":"MISSING",recommendationsCount:t.length,clickUrl:v||"MISSING",clickUrlSource:r!=null&&r.click_url?"click_url":r!=null&&r.admesh_link?"admesh_link":l.cta_url?"cta_url":r!=null&&r.url?"url":"none",shortDescription:u?"present":"MISSING",offerSummary:b||"MISSING",brandName:x,productName:f,headlineText:p});const k=(C,_)=>{d.log(`AdMesh tail ad ${C} clicked`),typeof window<"u"&&window.admeshTracker&&window.admeshTracker.trackClick({adId:r.ad_id,productId:r.product_id,clickUrl:v,source:C}).catch(()=>{d.error(`[AdMesh] Failed to track ${C} click`)})},S=C=>{C.stopPropagation(),k("tail_ad_brand_name")},M=C=>{C.stopPropagation(),k("tail_ad_cta")};return i.jsx($,{adId:c,productId:s,recommendationId:h,exposureUrl:m,sessionId:a,className:`admesh-tail-ad ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...o},children:i.jsxs("div",{className:"tail-ad-container",children:[p&&i.jsx("div",{className:"mb-2",children:i.jsx("h3",{className:"text-black dark:text-white font-semibold text-base",children:v&&x?i.jsxs(i.Fragment,{children:[i.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-semibold",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:S,children:x}),y&&` โ ${y}`]}):p})}),u&&i.jsx("p",{className:"text-gray-700 dark:text-gray-300 text-sm mb-3 leading-relaxed",children:u}),i.jsxs("div",{className:"flex items-center justify-between mt-2",children:[T&&v&&i.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 underline decoration-blue-600 dark:decoration-blue-400 hover:decoration-blue-800 dark:hover:decoration-blue-300 transition-colors duration-200 font-medium text-sm",style:{color:"#2563eb",textDecoration:"underline",textDecorationColor:"#2563eb",textUnderlineOffset:"2px"},onClick:M,children:T}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"})]})]})})};function Ke(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}};/*!
|
|
2
2
|
Copyright (c) 2018 Jed Watson.
|
|
3
3
|
Licensed under the MIT License (MIT), see
|
|
4
4
|
http://jedwatson.github.io/classnames
|
|
5
|
-
*/var
|
|
5
|
+
*/var he;function qe(){return he||(he=1,(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var r="",c=0;c<arguments.length;c++){var s=arguments[c];s&&(r=a(r,o(s)))}return r}function o(r){if(typeof r=="string"||typeof r=="number")return r;if(typeof r!="object")return"";if(Array.isArray(r))return n.apply(null,r);if(r.toString!==Object.prototype.toString&&!r.toString.toString().includes("[native code]"))return r.toString();var c="";for(var s in r)e.call(r,s)&&r[s]&&(c=a(c,s));return c}function a(r,c){return c?r?r+" "+c:r+c:r}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(oe)),oe.exports}var Ge=qe();const V=Ke(Ge),Ye="https://api.useadmesh.com/track";let Ze={enabled:!0,retryAttempts:3,retryDelay:1e3};const ve=t=>{const[e,n]=g.useState(!1),[o,a]=g.useState(null),r=g.useMemo(()=>({...Ze,...t}),[t]),c=g.useCallback(async(l,u)=>{if(!r.enabled)return;if(!u.adId||!u.admeshLink){a("Missing required tracking data: adId and admeshLink are required");return}n(!0),a(null);const b={event_type:l,ad_id:u.adId,admesh_link:u.admeshLink,product_id:u.productId,user_id:u.userId,session_id:u.sessionId,revenue:u.revenue,conversion_type:u.conversionType,metadata:u.metadata,timestamp:new Date().toISOString(),user_agent:navigator.userAgent,referrer:document.referrer,page_url:window.location.href};let x=null;for(let v=1;v<=(r.retryAttempts||3);v++)try{const T=await fetch(`${Ye}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!T.ok)throw new Error(`HTTP ${T.status}: ${T.statusText}`);await T.json(),n(!1);return}catch(T){x=T,v<(r.retryAttempts||3)&&await new Promise(p=>setTimeout(p,(r.retryDelay||1e3)*v))}const f=`Failed to track ${l} event after ${r.retryAttempts} attempts: ${x==null?void 0:x.message}`;a(f),n(!1)},[r]),s=g.useCallback(async l=>c("click",l),[c]),m=g.useCallback(async l=>c("view",l),[c]),h=g.useCallback(async l=>c("conversion",l),[c]);return{trackClick:s,trackView:m,trackConversion:h,isTracking:e,error:o}},X=({adId:t,admeshLink:e,productId:n,children:o,trackingData:a,className:r,style:c})=>{const{trackClick:s,trackView:m}=ve(),h=g.useRef(null),l=g.useRef(!1);g.useEffect(()=>{if(!h.current)return;h.current.querySelectorAll("a").forEach(x=>{(!x.hasAttribute("target")||x.getAttribute("target")!=="_blank")&&(x.setAttribute("target","_blank"),x.setAttribute("rel","noopener noreferrer"))})},[o]),g.useEffect(()=>{if(!h.current||l.current)return;const b=new IntersectionObserver(x=>{x.forEach(f=>{f.isIntersecting&&!l.current&&(l.current=!0,m({adId:t,admeshLink:e,productId:n,...a}).catch(d.error))})},{threshold:.5,rootMargin:"0px"});return b.observe(h.current),()=>{b.disconnect()}},[t,e,n,a,m]);const u=g.useCallback(b=>{s({adId:t,admeshLink:e,productId:n,...a}).catch(()=>{d.error("[AdMesh] Failed to track click")});const f=b.target.closest("a");f?(!f.hasAttribute("target")||f.getAttribute("target")!=="_blank")&&(f.setAttribute("target","_blank"),f.setAttribute("rel","noopener noreferrer")):window.open(e,"_blank","noopener,noreferrer")},[t,e,n,a,s]);return i.jsx("div",{ref:h,className:r,onClick:u,style:{cursor:"pointer",...c},children:o})};X.displayName="AdMeshLinkTracker";const ae="admesh-ui-sdk-styles",se="admesh-ui-sdk-reset",Xe=`
|
|
6
6
|
/* AdMesh UI SDK - CSS Reset & Normalization */
|
|
7
7
|
.admesh-component,
|
|
8
8
|
.admesh-component * {
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
.admesh-component[data-admesh-theme="light"] {
|
|
92
92
|
color-scheme: light;
|
|
93
93
|
}
|
|
94
|
-
`,
|
|
94
|
+
`,Je=`
|
|
95
95
|
/* AdMesh Core Component Styles */
|
|
96
96
|
|
|
97
97
|
.admesh-component {
|
|
@@ -302,7 +302,7 @@
|
|
|
302
302
|
font-size: 0.875rem;
|
|
303
303
|
}
|
|
304
304
|
}
|
|
305
|
-
`,
|
|
305
|
+
`,Qe=()=>{if(!(typeof document>"u")&&!(document.getElementById(se)&&document.getElementById(ae))){if(!document.getElementById(se)){const t=document.createElement("style");t.id=se,t.textContent=Xe,document.head.appendChild(t)}if(!document.getElementById(ae)){const t=document.createElement("style");t.id=ae,t.textContent=Je,document.head.appendChild(t)}}},et=`
|
|
306
306
|
/* AdMesh UI SDK - Complete Self-Contained Styles */
|
|
307
307
|
|
|
308
308
|
/* CSS Reset for AdMesh components */
|
|
@@ -970,7 +970,7 @@
|
|
|
970
970
|
.admesh-component .lg\\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
971
971
|
.admesh-component .lg\\:col-span-1 { grid-column: span 1 / span 1; }
|
|
972
972
|
}
|
|
973
|
-
`;let ue=!1;const fe=()=>{h.useEffect(()=>{if(!ue){try{Ye();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=Ze,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),ue=!0}catch{console.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},Y=(t,e={})=>{const o=t.intent_match_score||0,n=e.customLabels||{};return o>=.8?n.partnerRecommendation||"Smart Pick":o>=.6?n.partnerMatch||"Partner Recommendation":o>=.3?n.promotedOption||"Promoted Match":n.relatedOption||"Related"},he=(t,e)=>{const o=t.intent_match_score||0;return o>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":o>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":o>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},ae=({recommendation:t,theme:e,variation:o="default",className:n,style:d,sessionId:r})=>{var p,b,f,x,y,m,_,M,w,k,E,v,A,T,C,S,I,R,N,D,F,$,O,U,H;if(!t||typeof t!="object")return console.log("[AdMesh Product Card] No recommendation provided - not rendering"),null;if(!t.ad_id&&!t.recommendation_id&&!t.title)return console.log("[AdMesh Product Card] Invalid recommendation object (missing required fields) - not rendering"),null;fe();const i=(()=>{const j=t.creative_input||{},P=j.product_name||t.title||t.product_title||"";let z="";o==="simple"?z=j.short_description||j.context_snippet||t.product_summary||t.weave_summary||t.reason||"":z=j.long_description||j.short_description||t.product_summary||t.weave_summary||t.reason||"";const K=j.cta_label||P;return o==="simple"?{title:P,description:z,ctaText:K,isSimple:!0}:{title:P,description:z,ctaText:K}})(),l=V("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",n),g=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(p=e.shadows)==null?void 0:p.small,"--admesh-shadow-md":(b=e.shadows)==null?void 0:b.medium,"--admesh-shadow-lg":(f=e.shadows)==null?void 0:f.large,"--admesh-spacing-sm":(x=e.spacing)==null?void 0:x.small,"--admesh-spacing-md":(y=e.spacing)==null?void 0:y.medium,"--admesh-spacing-lg":(m=e.spacing)==null?void 0:m.large,"--admesh-font-size-sm":(_=e.fontSize)==null?void 0:_.small,"--admesh-font-size-base":(M=e.fontSize)==null?void 0:M.base,"--admesh-font-size-lg":(w=e.fontSize)==null?void 0:w.large,"--admesh-font-size-title":(k=e.fontSize)==null?void 0:k.title,fontFamily:e.fontFamily,width:((v=(E=e.components)==null?void 0:E.productCard)==null?void 0:v.width)||"100%"}:{width:"100%"};if(o==="simple"){const j=t.ad_id||"",P=t.product_id||"";return s.jsx(B,{adId:j,productId:P,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:r,className:V("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",n),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...d},children:s.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:he(t,Y(t)),children:Y(t)}),s.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[i.description," "]}),s.jsx(G,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((T=t.creative_input)==null?void 0:T.cta_url)||t.url,productId:t.product_id,trackingData:{title:i.title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:s.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:i.ctaText})})]})})}const c=t.ad_id||"",u=t.product_id||"";return console.log("[AdMeshProductCard] ๐ Rendering with tracking data:",{adId:c,productId:u,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url?"present":"MISSING",sessionId:r?"present":"MISSING"}),s.jsx(B,{adId:c,productId:u,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:r,className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(C=e==null?void 0:e.components)==null?void 0:C.productCard,...d},children:s.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(S=e==null?void 0:e.components)==null?void 0:S.productCard,...d},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",style:g,children:[s.jsx("div",{className:"mb-1.5",children:s.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:he(t,Y(t)),children:Y(t)})}),s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(((R=(I=t.creative_input)==null?void 0:I.assets)==null?void 0:R.logo_url)||((N=t.product_logo)==null?void 0:N.url))&&s.jsx("img",{src:((F=(D=t.creative_input)==null?void 0:D.assets)==null?void 0:F.logo_url)||(($=t.product_logo)==null?void 0:$.url),alt:`${i.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:j=>{j.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:i.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(G,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((O=t.creative_input)==null?void 0:O.cta_url)||t.url,productId:t.product_id,trackingData:{title:i.title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:[((U=t.creative_input)==null?void 0:U.cta_label)||"Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),s.jsx("div",{className:"mb-3",children:s.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:i.description})}),((H=t.creative_input)==null?void 0:H.value_props)&&t.creative_input.value_props.length>0&&s.jsx("div",{className:"mb-3",children:s.jsx("ul",{className:"space-y-1.5",children:t.creative_input.value_props.slice(0,3).map((j,P)=>s.jsxs("li",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[s.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),s.jsx("span",{children:j})]},P))})}),s.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};ae.displayName="AdMeshProductCard";const se=h.createContext(void 0);function be(){const t=h.useContext(se);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function W(){const t=be();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const Xe=(t,e)=>{if(!t)return"Get Started";let o="";const n=[/(?:set up|setup|integrate|add|install|use)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,| by)/i,/(?:by|from)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,)/];for(const a of n){const i=t.match(a);if(i&&i[1]){o=i[1].trim();break}}const d=e||o;if(d)return`Integrate ${d.split(/\s+/).slice(0,2).join(" ")}`;const r=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return r&&r[1]?`Integrate ${r[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},xe=({recommendation:t,theme:e,className:o="",style:n={},sessionId:d,onLinkClick:r,onPasteToInput:a})=>{var E,v,A,T;const i=t.creative_input||{},l=i.bridge_headline||"",g=i.bridge_description||"",c=i.bridge_prompt||i.bridge_content||"",u=i.product_name||"",p=i.cta_label||"";if(!g&&!c)return null;const b=t.ad_id||"",f=t.product_id||"",x=t.recommendation_id||"",{sdk:y,sessionId:m}=W(),_=d||m,M=async C=>{if(C.preventDefault(),!!c){if(x&&b&&_)try{const S=(y==null?void 0:y.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",I=await fetch(`${S}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:x,ad_id:b,session_id:_,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});I.ok?console.log("[AdMesh Bridge] โ
Engagement tracked successfully"):console.warn("[AdMesh Bridge] โ ๏ธ Failed to track engagement:",I.statusText)}catch(S){console.error("[AdMesh Bridge] โ Error tracking engagement:",S)}r&&r(t),a?a(c):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(c)}},w=p||Xe(c,u),k=!!w;return s.jsx(B,{adId:b,productId:f,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:d,className:`admesh-bridge-format ${o}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',padding:"1rem",border:"none",borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",backgroundColor:"transparent",color:(e==null?void 0:e.textColor)||"inherit",...n},children:s.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[l&&s.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:g?"0.75rem":k?"1rem":"0",fontSize:((E=e==null?void 0:e.fontSize)==null?void 0:E.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:l}),g&&s.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:k?"1rem":"0",lineHeight:"1.6",fontSize:((v=e==null?void 0:e.fontSize)==null?void 0:v.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:g}),k&&s.jsx("div",{style:{marginBottom:"0.75rem"},children:s.jsx("button",{onClick:M,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((A=e==null?void 0:e.fontSize)==null?void 0:A.small)||"0.875rem",fontWeight:500,borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",border:"none",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s"},onMouseEnter:C=>{C.currentTarget.style.backgroundColor="#1a1a1a",C.currentTarget.style.opacity="0.9"},onMouseLeave:C=>{C.currentTarget.style.backgroundColor="#000000",C.currentTarget.style.opacity="1"},children:w})}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:s.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((T=e==null?void 0:e.fontSize)==null?void 0:T.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})},ve=({recommendations:t,summaryText:e,theme:o,className:n="",style:d={},onLinkClick:r,onPasteToInput:a,sessionId:i,response:l})=>{var b;const c=(t||(l==null?void 0:l.recommendations)||[]).filter(f=>f&&typeof f=="object"&&(f.ad_id||f.recommendation_id));if(!c||c.length===0)return console.log("[AdMesh Summary Layout] Empty or invalid recommendations array - not rendering anything"),null;let u=e||(l==null?void 0:l.tail_summary);if(!u&&c.length>0&&((b=c[0])!=null&&b.creative_input)){const f=c[0].creative_input;u=f.long_description||f.context_snippet||f.short_description||void 0}console.log(`[AdMesh Summary Layout] Rendering with ${c.length} valid recommendations`);const p=()=>{if(c.length>0){const f=c[0],x=(f==null?void 0:f.creative_input)||{},y=!!x.bridge_prompt||!!x.bridge_content,m=(f==null?void 0:f.format)||(x==null?void 0:x.format),_=f==null?void 0:f.preferred_format,M=m==="bridge"||_==="bridge";if(console.log("[AdMesh Summary Layout] ๐ Checking format:",{hasBridgePrompt:y,bridgePrompt:x.bridge_prompt||x.bridge_content?(x.bridge_prompt||x.bridge_content||"").substring(0,50)+"...":void 0,format:m,preferredFormat:_,creativeInputKeys:Object.keys(x),recommendationKeys:Object.keys(f||{})}),y||M)return console.log("[AdMesh Summary Layout] ๐ฏ โ
Rendering bridge format"),s.jsx(xe,{recommendation:f,theme:o,sessionId:i,onLinkClick:r,onPasteToInput:a});console.log("[AdMesh Summary Layout] โ ๏ธ Bridge format NOT detected, falling back to other formats")}return u?s.jsx(ne,{summaryText:u,recommendations:c,theme:o,onLinkClick:r,sessionId:i}):c.length>0&&c[0]?s.jsx("div",{className:"fallback-citation",children:s.jsx(ae,{recommendation:c[0],theme:o,sessionId:i})}):null};return s.jsx("div",{className:`admesh-summary-layout ${n}`,style:{fontFamily:(o==null?void 0:o.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...d},children:p()})},ye=({recommendations:t,summaryText:e,theme:o,className:n,style:d,onLinkClick:r,onPasteToInput:a,sessionId:i,response:l})=>{const g=t||(l==null?void 0:l.recommendations)||[],c=e||(l==null?void 0:l.tail_summary),u=g.filter(p=>p&&typeof p=="object"&&(p.ad_id||p.recommendation_id));return!u||u.length===0?(console.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null):s.jsx(ve,{recommendations:u,summaryText:c,theme:o,className:n,style:d,onLinkClick:r,onPasteToInput:a,sessionId:i})};class we{constructor(e){L(this,"firedExposures",new Set);L(this,"debug",!1);L(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,o,n){const d=`${n}_${o}`;if(this.firedExposures.has(d)){this.debug&&console.log("[Tracker] Exposure already fired");return}this.firedExposures.add(d);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&console.warn("[Tracker] Failed to fire exposure")}),this.debug&&console.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&console.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,o,n,d){const r=`${n}_${o}`;if(this.firedExposures.has(r)){this.debug&&console.log("[Tracker] MRC exposure already fired");return}return new Promise(a=>{let i=null,l=null;const g=new IntersectionObserver(p=>{p.forEach(b=>{b.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?i===null&&(i=Date.now(),this.debug&&console.log("[Tracker] Ad reached MRC visibility threshold"),l=setTimeout(()=>{this.fireExposure(e,o,n),g.disconnect(),a()},this.mrcThreshold.minimumDurationMs)):i!==null&&(l&&(clearTimeout(l),l=null),i=null,this.debug&&console.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});g.observe(d);const u=setTimeout(()=>{g.disconnect(),l&&clearTimeout(l),a()},3e4);d.__admeshTrackerCleanup=()=>{g.disconnect(),l&&clearTimeout(l),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class ke{constructor(){L(this,"roots",new Map)}async render(e){var o,n;try{console.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const d=document.getElementById(e.containerId);if(!d)throw console.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);console.log("[AdMeshRenderer] โ
Container ready");const r=this.roots.get(e.containerId);r&&(console.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),r.unmount(),this.roots.delete(e.containerId)),d.innerHTML="";const a=je.createRoot(d),i=((n=(o=e.response.recommendations)==null?void 0:o[0])==null?void 0:n.tail_summary)||"";console.log("[AdMeshRenderer] ๐ Rendering recommendations");const l=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);a.render(s.jsx(ye,{recommendations:e.response.recommendations||[],summaryText:i,theme:e.theme,sessionId:e.sessionId,onPasteToInput:l})),console.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,a)}catch(d){throw console.error("[AdMeshRenderer] โ Error rendering recommendations"),d}}unmount(e){const o=this.roots.get(e);o&&(o.unmount(),this.roots.delete(e))}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class J{constructor(e){L(this,"config");L(this,"apiBaseUrl");L(this,"renderer",null);L(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),o=Math.random().toString(36).substring(2,15);return`session_${e}_${o}`}static createMessageId(e){const o=Date.now(),n=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${o}_${n}`:`msg_${o}_${n}`}getRenderer(){return this.renderer||(this.renderer=new ke),this.renderer}getTracker(){return this.tracker||(this.tracker=new we({apiKey:this.config.apiKey})),this.tracker}async showRecommendations(e){try{if(!e.session_id)throw new Error("session_id is required");const o=await this.fetchRecommendationFromAIPContext({query:e.query,sessionId:e.session_id,platformSurface:e.platformSurface,model:e.model,messages:e.messages,locale:e.locale,geo:e.geo,userId:e.userId,latencyBudgetMs:e.latencyBudgetMs,allowed_formats:e.allowed_formats}),n=this.convertAIPResponseToRecommendation(o),d={session_id:o.session_id,message_id:`msg_${o.recommendation_id}`,recommendations:[n]},r=this.getRenderer(),a=this.getTracker();await r.render({containerId:e.containerId,response:d,theme:e.theme||this.config.theme,tracker:a,sessionId:e.session_id,onPasteToInput:e.onPasteToInput})}catch(o){throw console.error("[AdMeshSDK] Error showing recommendations"),o}}async fetchRecommendationFromAIPContext(e){var g,c,u;const o=`${this.apiBaseUrl}/aip/context`;console.log("[AdMeshSDK] ๐ฅ fetchRecommendationFromAIPContext called");const n=`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;let d=e.messageId;if(!d){if(e.messages&&e.messages.length>0){const p=e.messages[e.messages.length-1];p.id&&(d=p.id)}d||(d=J.createMessageId(e.sessionId))}const r={request_id:n,session_id:e.sessionId,message_id:d,platform_id:"placeholder",platform_surface:e.platformSurface||"web",model:e.model,query_text:e.query,messages:e.messages||[],locale:e.locale||"en-US",geo:e.geo,user_id:e.userId,timestamp:new Date().toISOString(),latency_budget_ms:e.latencyBudgetMs,allowed_formats:e.allowed_formats,cpx_floor:0};(!r.query_text||!r.query_text.trim())&&console.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const a=JSON.stringify(r);console.log("[AdMeshSDK] ๐ค Sending request to /aip/context");const i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:a});if(!i.ok){const b=(await i.json().catch(()=>({}))).detail||`HTTP ${i.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${b}`)}const l=await i.json();return console.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{hasCreative:!!l.creative,creativeFormat:(g=l.creative)==null?void 0:g.format,creativeBridgeContent:(c=l.creative)!=null&&c.bridge_content?l.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!l.winning_bid,winningBidPreferredFormat:(u=l.winning_bid)==null?void 0:u.preferred_format,topLevelKeys:Object.keys(l)}),l}convertAIPResponseToRecommendation(e){var y,m,_,M,w,k,E;const o=e;let n=e.creative_input||{};const d=o.creative||{},r=d.format||o.format||((y=o.winning_bid)==null?void 0:y.preferred_format),a=d.headline,i=d.bridge_headline,l=d.bridge_description,g=d.bridge_prompt||d.bridge_content,c=g||n.bridge_prompt||n.bridge_content,u=d.cta_label,p=u||n.cta_label,b=i||n.bridge_headline,f=l||n.bridge_description;console.log("[AdMeshSDK] ๐ Extracting from response:",{creativeObject:d,creativeFormat:d.format,creativeBridgeHeadline:i,creativeBridgeDescription:l?String(l).substring(0,50)+"...":void 0,creativeBridgePrompt:g?String(g).substring(0,50)+"...":void 0,creativeCtaLabel:u,extractedFormat:r,extractedBridgeHeadline:b,extractedBridgeDescription:f?String(f).substring(0,50)+"...":void 0,extractedBridgePrompt:c?String(c).substring(0,50)+"...":void 0,extractedCtaLabel:p,creativeInputHasBridgeHeadline:!!n.bridge_headline,creativeInputHasBridgeDescription:!!n.bridge_description,creativeInputHasBridgePrompt:!!n.bridge_prompt,creativeInputHasBridgeContent:!!n.bridge_content,creativeInputHasCtaLabel:!!n.cta_label}),n={...n,...a&&{headline:a},...b&&{bridge_headline:b},...f&&{bridge_description:f},...c&&{bridge_prompt:c},...c&&{bridge_content:c},...p&&{cta_label:p},...r&&{format:r}};const x={...e,creative_input:n,product_title:e.title,tail_summary:n.long_description||"",product_summary:n.short_description||"",weave_summary:n.context_snippet||"",product_logo:(m=n.assets)!=null&&m.logo_url?{url:n.assets.logo_url}:void 0,categories:n.categories||[]};return r&&(x.format=r),console.log("[AdMeshSDK] ๐ Converted recommendation:",{hasFormat:!!r,format:r,hasBridgeHeadline:!!b,bridgeHeadline:b,hasBridgeDescription:!!f,bridgeDescriptionPreview:f?String(f).substring(0,50)+"...":void 0,hasBridgePrompt:!!c,hasCtaLabel:!!p,ctaLabel:p,bridgeHeadlineInCreativeInput:!!((_=x.creative_input)!=null&&_.bridge_headline),bridgeDescriptionInCreativeInput:!!((M=x.creative_input)!=null&&M.bridge_description),bridgePromptInCreativeInput:!!((w=x.creative_input)!=null&&w.bridge_prompt),bridgeContentInCreativeInput:!!((k=x.creative_input)!=null&&k.bridge_content),ctaLabelInCreativeInput:!!((E=x.creative_input)!=null&&E.cta_label),bridgePromptPreview:c?String(c).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(x.creative_input||{}),recommendationFormat:x.format}),x}}class ie{constructor(e={}){L(this,"autoAddLabels");L(this,"fireExposurePixels");L(this,"labelStyle");L(this,"processedLinks",new Set);L(this,"mutationObserver",null);var o,n,d,r;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((o=e.labelStyle)==null?void 0:o.fontSize)||"0.75em",fontWeight:((n=e.labelStyle)==null?void 0:n.fontWeight)||"bold",color:((d=e.labelStyle)==null?void 0:d.color)||"#666",marginLeft:((r=e.labelStyle)==null?void 0:r.marginLeft)||"2px"}}getLinksToProcess(e){const n=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return n.length>0?Array.from(n):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,o,n){if(!e)return[];const d=[];if(o.length>0){const r=this.getLinksToProcess(e),a=new Map(o.filter(i=>i.click_url).map(i=>[i.click_url,i]));r.forEach(i=>{var u;const l=i.getAttribute("href")||"",g=`${l}`;if(this.processedLinks.has(g))return;const c=a.get(l);if(c){this.processedLinks.add(g);const p={element:i,href:l,text:i.textContent||"",hasAdLabel:this.hasAdLabel(i),matchedRecommendation:{ad_id:c.ad_id||((u=c.meta)==null?void 0:u.ad_id)||"",click_url:c.click_url,exposure_url:c.exposure_url}};this.autoAddLabels&&!p.hasAdLabel&&(this.addAdLabel(i),p.hasAdLabel=!0),this.fireExposurePixels&&c.exposure_url&&n&&p.matchedRecommendation&&n({exposureUrl:c.exposure_url,adId:p.matchedRecommendation.ad_id,linkElement:i}),d.push(p)}})}else Array.from(e.querySelectorAll("a")).forEach(a=>{const i=a.getAttribute("href")||"",l=`${i}`;if(this.processedLinks.has(l))return;if(this.isAdMeshLink(i)){this.processedLinks.add(l);const c={element:a,href:i,text:a.textContent||"",hasAdLabel:this.hasAdLabel(a),matchedRecommendation:void 0};if(a.setAttribute("target","_blank"),a.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!c.hasAdLabel&&(this.addAdLabel(a),c.hasAdLabel=!0),this.fireExposurePixels&&n){const u=this.convertClickUrlToExposureUrl(i);n({exposureUrl:u,adId:this.extractAdIdFromUrl(i),linkElement:a})}d.push(c)}});return d}hasAdLabel(e){var d,r;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const a=o.textContent||"";if(a.trim()===""){o=o.previousSibling;continue}if(a.includes("[Ad]"))return!0;break}if(o&&o.nodeType===Node.ELEMENT_NODE){const a=o;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((d=a.textContent)!=null&&d.includes("[Ad]")))return!0}let n=e.nextSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const a=n.textContent||"";if(a.trim()===""){n=n.nextSibling;continue}if(a.includes("[Ad]"))return!0;break}if(n&&n.nodeType===Node.ELEMENT_NODE){const a=n;if((a.tagName==="SUB"||a.tagName==="SPAN")&&((r=a.textContent)!=null&&r.includes("[Ad]")))return!0}return!1}addAdLabel(e){var r;if(this.hasAdLabel(e))return;this.removeLeftAdLabel(e);const o=document.createElement("sub");o.textContent="[Ad]",o.style.fontSize=this.labelStyle.fontSize,o.style.fontWeight=this.labelStyle.fontWeight,o.style.color=this.labelStyle.color,o.style.marginLeft=this.labelStyle.marginLeft,o.style.cursor="pointer",o.style.borderBottom=`1px dotted ${this.labelStyle.color}`,o.style.whiteSpace="nowrap",o.title="Why this ad? This is a sponsored recommendation based on your search query.";let n=!1;o.addEventListener("mouseenter",()=>{o.style.opacity="0.7"}),o.addEventListener("mouseleave",()=>{o.style.opacity="1",n&&(n=!1)}),o.addEventListener("click",a=>{a.stopPropagation(),n=!n,n?(o.style.textDecoration="underline",o.style.opacity="0.7"):(o.style.textDecoration="none",o.style.opacity="1")});const d=a=>{n&&a.target!==o&&(n=!1,o.style.textDecoration="none",o.style.opacity="1")};document.addEventListener("click",d),(r=e.parentNode)==null||r.insertBefore(o,e.nextSibling)}removeLeftAdLabel(e){var n,d,r;let o=e.previousSibling;for(;o&&o.nodeType===Node.TEXT_NODE;){const a=o.textContent||"";if(a.trim()===""){o=o.previousSibling;continue}if(a.includes("[Ad]")){(n=o.parentNode)==null||n.removeChild(o);return}break}if(o&&o.nodeType===Node.ELEMENT_NODE){const a=o;(a.tagName==="SUB"||a.tagName==="SPAN")&&((d=a.textContent)!=null&&d.includes("[Ad]"))&&((r=a.parentNode)==null||r.removeChild(a))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(d=>e.includes(d)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractAdIdFromUrl(e){try{const o=e.match(/\/click\/([^/?]+)/);return o&&o[1]?o[1]:e}catch{return e}}convertClickUrlToExposureUrl(e){try{const o=new URL(e),d=`${`${o.protocol}//${o.host}`}/exposure`,r=new URLSearchParams(o.search);return r.has("cpx")||r.set("cpx","0"),`${d}?${r.toString()}`}catch{return console.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,o,n){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,o,n)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const Je=({apiKey:t,sessionId:e,theme:o,apiBaseUrl:n,children:d})=>{const r=h.useRef(null),[a,i]=h.useState(new Set);h.useEffect(()=>{if(!t){console.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}try{r.current=new J({apiKey:t,theme:o,apiBaseUrl:n}),console.log("[AdMeshProvider] โ
AdMesh SDK initialized"),n&&console.log("[AdMeshProvider] ๐ Using custom API base URL")}catch{console.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK")}return()=>{console.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,o,n]);const l={sdk:r.current,apiKey:t,sessionId:e,theme:o,processedMessageIds:a,markMessageAsProcessed:g=>{i(c=>{const u=new Set(c);return u.add(g),u})},isMessageProcessed:g=>a.has(g)};return s.jsx(se.Provider,{value:l,children:d})},Qe=({format:t="tail",onRecommendationsShown:e,onError:o,messageId:n,query:d,latencyBudgetMs:r,onPasteToInput:a})=>{const{sdk:i,sessionId:l}=W(),g=h.useRef(null),[c,u]=h.useState("");return h.useEffect(()=>{n&&u(`admesh-recommendations-${n}`)},[n]),h.useEffect(()=>(a&&typeof window<"u"&&(window.__admesh_onPasteToInput=a),()=>{typeof window<"u"&&delete window.__admesh_onPasteToInput}),[a]),h.useEffect(()=>{if(console.log("[AdMeshRecommendations] ๐ Checking SDK readiness"),!n||!d||d.trim()===""){console.log("[AdMeshRecommendations] โ Validation failed - missing required parameters");return}if(console.log("[AdMeshRecommendations] โ
Validation passed"),!i||!c){console.log("[AdMeshRecommendations] SDK or containerId not ready");return}(async()=>{try{if(!(i!=null&&i.showRecommendations)){console.log("[AdMeshRecommendations] SDK showRecommendations not available");return}console.log("[AdMeshRecommendations] ๐ค Requesting recommendations from SDK"),await i.showRecommendations({query:d.trim(),containerId:c,session_id:l,latencyBudgetMs:r,...t==="bridge"&&{allowed_formats:["bridge"]},onPasteToInput:a}),e==null||e(n)}catch(b){const f=b instanceof Error?b:new Error(String(b));console.log(`[AdMeshRecommendations] โ Error: ${f.message}`),o==null||o(f)}})()},[i,l,c,t,n,d,r,e,o]),s.jsx("div",{ref:g,id:c,className:"admesh-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},_e=({format:t="tail",onError:e,messageId:o,query:n,fallback:d})=>{const{sdk:r,sessionId:a}=W(),i=h.useRef(null),[l,g]=h.useState("");return h.useEffect(()=>{o&&g(`admesh-weave-fallback-${o}`)},[o]),console.log("[WeaveFallbackRecommendations] ๐จ Component render"),h.useEffect(()=>{if(console.log("[WeaveFallbackRecommendations] ๐ useEffect triggered"),!d){console.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(console.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!o||!n||n.trim()===""){console.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(console.log("[WeaveFallbackRecommendations] โ
Validation passed"),!r||!l){console.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}(async()=>{try{if(!(r!=null&&r.showRecommendations)){console.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}console.log("[WeaveFallbackRecommendations] ๐ค Calling sdk.showRecommendations"),await r.showRecommendations({query:n.trim(),containerId:l,session_id:a}),console.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(u){const p=u instanceof Error?u:new Error(String(u));console.log(`[WeaveFallbackRecommendations] โ Error: ${p.message}`),e==null||e(p)}})()},[r,a,l,t,o,n,d,e]),s.jsx("div",{ref:i,id:l,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",minHeight:"100px",display:"block"}})},Se=h.createContext(void 0),et=({children:t,shouldRenderFallback:e,messageId:o,sessionId:n,query:d})=>s.jsx(Se.Provider,{value:{shouldRenderFallback:e,messageId:o,sessionId:n,query:d},children:t}),tt=()=>h.useContext(Se),rt=({recommendations:t,title:e="Product Recommendations",showTitle:o=!0,className:n="",cardClassName:d="",onProductClick:r,maxCards:a=10,cardWidth:i="md",theme:l="auto",borderRadius:g="md",shadow:c="sm"})=>{if(!t||t.length===0)return console.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const u=t.slice(0,a),p=()=>{switch(i){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},b=()=>{switch(g){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},f=()=>{switch(c){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},x=()=>l==="dark"?"bg-gray-900 text-white":l==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",y=m=>{var _;if(r)r(m);else{const M=m.click_url||m.admesh_link||m.url||((_=m.creative_input)==null?void 0:_.cta_url);M&&window.open(M,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:s.jsxs("div",{className:V("w-full",n),children:[o&&s.jsxs("div",{className:"mb-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),s.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),s.jsxs("div",{className:"relative",children:[u.length===0?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):s.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:u.map(m=>{var k,E,v,A,T,C,S,I,R,N,D,F,$,O,U,H,j,P,z,K;const _=m.product_id||m.id||m.ad_id,M=m.ad_id||m.product_id||"",w=m.product_id||"";return s.jsx(B,{adId:M,productId:w,className:V(p(),b(),f(),x(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",d),onClick:()=>y(m),children:s.jsxs("div",{children:[s.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(E=(k=m.creative_input)==null?void 0:k.assets)!=null&&E.logo_url||(T=(A=(v=m.creative_input)==null?void 0:v.assets)==null?void 0:A.image_urls)!=null&&T[0]||(C=m.product_logo)!=null&&C.url?s.jsx("img",{src:((R=(I=(S=m.creative_input)==null?void 0:S.assets)==null?void 0:I.image_urls)==null?void 0:R[0])||((D=(N=m.creative_input)==null?void 0:N.assets)==null?void 0:D.logo_url)||((F=m.product_logo)==null?void 0:F.url),alt:(($=m.creative_input)==null?void 0:$.product_name)||m.title||m.product_title||"Product",className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy",onError:q=>{q.target.style.display="none"}}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:s.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),s.jsxs("div",{className:"p-3",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:((O=m.creative_input)==null?void 0:O.product_name)||m.title||m.product_title||""}),(((U=m.creative_input)==null?void 0:U.short_description)||((H=m.creative_input)==null?void 0:H.context_snippet)||m.weave_summary)&&s.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:((j=m.creative_input)==null?void 0:j.short_description)||((P=m.creative_input)==null?void 0:P.context_snippet)||m.weave_summary}),((z=m.creative_input)==null?void 0:z.value_props)&&m.creative_input.value_props.length>0&&s.jsx("div",{className:"mb-2",children:s.jsx("ul",{className:"space-y-1",children:m.creative_input.value_props.slice(0,2).map((q,ee)=>s.jsxs("li",{className:"flex items-start gap-1.5 text-xs text-gray-600 dark:text-gray-400",children:[s.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),s.jsx("span",{className:"line-clamp-1",children:q})]},ee))})}),(!((K=m.creative_input)!=null&&K.value_props)||m.creative_input.value_props.length===0)&&m.categories&&m.categories.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:m.categories.slice(0,2).map((q,ee)=>s.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:q},ee))}),m.trust_score!==void 0&&s.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(m.trust_score*100).toFixed(0),"%"]})]})]})},_)})}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),s.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[s.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),s.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
973
|
+
`;let ge=!1;const ye=()=>{g.useEffect(()=>{if(!ge){try{Qe();const t=document.createElement("style");t.id="admesh-ui-sdk-styles-legacy",t.textContent=et,document.getElementById("admesh-ui-sdk-styles-legacy")||document.head.appendChild(t),ge=!0}catch{d.error("[AdMesh] Failed to inject styles")}return()=>{}}},[])},J=(t,e={})=>{const n=t.intent_match_score||0,o=e.customLabels||{};return n>=.8?o.partnerRecommendation||"Smart Pick":n>=.6?o.partnerMatch||"Partner Recommendation":n>=.3?o.promotedOption||"Promoted Match":o.relatedOption||"Related"},fe=(t,e)=>{const n=t.intent_match_score||0;return n>=.8?"This recommendation is from a partner who compensates us when you engage. We've matched it to your needs based on your query.":n>=.6?"Top-rated partner solution matched to your specific requirements. Partner compensates us for qualified referrals.":n>=.3?"This partner solution may be relevant to your needs. The partner compensates us when you take qualifying actions.":"This solution is somewhat related to your query. While not a perfect match, it might still be helpful. This partner compensates us for qualified referrals."},de=({recommendation:t,theme:e,variation:n="default",className:o,style:a,sessionId:r})=>{var b,x,f,v,T,p,y,k,S,M,C,_,R,E,A,w,L,j,I,F,z,H,O,K,q,G;if(!t||typeof t!="object")return d.log("[AdMesh Product Card] No recommendation provided - not rendering"),null;if(!t.ad_id&&!t.recommendation_id&&!t.title)return d.log("[AdMesh Product Card] Invalid recommendation object (missing required fields) - not rendering"),null;ye();const s=(()=>{const N=t.creative_input||{},D=N.product_name||t.title||t.product_title||"";let B="";n==="simple"?B=N.short_description||N.context_snippet||t.product_summary||t.weave_summary||t.reason||"":B=N.long_description||N.short_description||t.product_summary||t.weave_summary||t.reason||"";const Y=N.cta_label||D;return n==="simple"?{title:D,description:B,ctaText:Y,isSimple:!0}:{title:D,description:B,ctaText:Y}})(),m=V("admesh-component","admesh-card","relative p-3 sm:p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-slate-800 dark:to-slate-900 border border-gray-200/50 dark:border-slate-700/50 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1",o),h=e?{"--admesh-primary":e.primaryColor||e.accentColor||"#3b82f6","--admesh-secondary":e.secondaryColor||"#10b981","--admesh-accent":e.accentColor||"#3b82f6","--admesh-background":e.backgroundColor,"--admesh-surface":e.surfaceColor,"--admesh-border":e.borderColor,"--admesh-text":e.textColor,"--admesh-text-secondary":e.textSecondaryColor,"--admesh-radius":e.borderRadius||"12px","--admesh-shadow-sm":(b=e.shadows)==null?void 0:b.small,"--admesh-shadow-md":(x=e.shadows)==null?void 0:x.medium,"--admesh-shadow-lg":(f=e.shadows)==null?void 0:f.large,"--admesh-spacing-sm":(v=e.spacing)==null?void 0:v.small,"--admesh-spacing-md":(T=e.spacing)==null?void 0:T.medium,"--admesh-spacing-lg":(p=e.spacing)==null?void 0:p.large,"--admesh-font-size-sm":(y=e.fontSize)==null?void 0:y.small,"--admesh-font-size-base":(k=e.fontSize)==null?void 0:k.base,"--admesh-font-size-lg":(S=e.fontSize)==null?void 0:S.large,"--admesh-font-size-title":(M=e.fontSize)==null?void 0:M.title,fontFamily:e.fontFamily,width:((_=(C=e.components)==null?void 0:C.productCard)==null?void 0:_.width)||"100%"}:{width:"100%"};if(n==="simple"){const N=t.ad_id||"",D=t.product_id||"";return i.jsx($,{adId:N,productId:D,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:r,className:V("admesh-component admesh-simple-ad","inline-block text-sm leading-relaxed",o),style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(R=e==null?void 0:e.components)==null?void 0:R.productCard,...a},children:i.jsxs("div",{"data-admesh-theme":e==null?void 0:e.mode,children:[i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px",marginRight:"8px"},title:fe(t,J(t)),children:J(t)}),i.jsxs("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#f3f4f6":"#374151",marginRight:"4px"},children:[s.description," "]}),i.jsx(X,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((E=t.creative_input)==null?void 0:E.cta_url)||t.url,productId:t.product_id,trackingData:{title:s.title,matchScore:t.contextual_relevance_score,component:"simple_ad_cta"},children:i.jsx("span",{style:{color:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",textDecoration:"underline",cursor:"pointer",fontSize:"inherit",fontFamily:"inherit"},children:s.ctaText})})]})})}const l=t.ad_id||"",u=t.product_id||"";return d.log("[AdMeshProductCard] ๐ Rendering with tracking data:",{adId:l,productId:u,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url?"present":"MISSING",sessionId:r?"present":"MISSING"}),i.jsx($,{adId:l,productId:u,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:r,className:m,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(A=e==null?void 0:e.components)==null?void 0:A.productCard,...a},children:i.jsx("div",{style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...(w=e==null?void 0:e.components)==null?void 0:w.productCard,...a},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",style:h,children:[i.jsx("div",{className:"mb-1.5",children:i.jsx("span",{style:{fontSize:"11px",fontWeight:"600",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff",backgroundColor:(e==null?void 0:e.mode)==="dark"?"#ffffff":"#000000",padding:"2px 6px",borderRadius:"4px"},title:fe(t,J(t)),children:J(t)})}),i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(((j=(L=t.creative_input)==null?void 0:L.assets)==null?void 0:j.logo_url)||((I=t.product_logo)==null?void 0:I.url))&&i.jsx("img",{src:((z=(F=t.creative_input)==null?void 0:F.assets)==null?void 0:z.logo_url)||((H=t.product_logo)==null?void 0:H.url),alt:`${s.title} logo`,className:"w-6 h-6 rounded flex-shrink-0",onError:N=>{N.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm sm:text-base truncate",children:s.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(X,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((O=t.creative_input)==null?void 0:O.cta_url)||t.url,productId:t.product_id,trackingData:{title:s.title,matchScore:t.contextual_relevance_score,component:"product_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 sm:px-3 sm:py-2 rounded-full flex items-center transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg whitespace-nowrap",style:{backgroundColor:(e==null?void 0:e.accentColor)||"#000000",color:(e==null?void 0:e.mode)==="dark"?"#000000":"#ffffff"},children:[((K=t.creative_input)==null?void 0:K.cta_label)||"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 leading-snug",children:s.description})}),((q=t.creative_input)==null?void 0:q.offer_summary)&&i.jsx("div",{className:"mb-3",children:i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 leading-relaxed italic",children:t.creative_input.offer_summary})}),((G=t.creative_input)==null?void 0:G.value_props)&&t.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-3",children:i.jsx("ul",{className:"space-y-1.5",children:t.creative_input.value_props.slice(0,3).map((N,D)=>i.jsxs("li",{className:"flex items-start gap-2 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{children:N})]},D))})}),i.jsx("div",{className:"mt-auto pt-3 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-xs text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})})};de.displayName="AdMeshProductCard";const ce=g.createContext(void 0);function we(){const t=g.useContext(ce);if(!t)throw new Error("useAdMeshContext must be used within an <AdMeshProvider>. Make sure your component is wrapped with <AdMeshProvider>.");return t}function U(){const t=we();return{sdk:t.sdk,apiKey:t.apiKey,sessionId:t.sessionId,theme:t.theme,processedMessageIds:t.processedMessageIds,markMessageAsProcessed:t.markMessageAsProcessed,isMessageProcessed:t.isMessageProcessed}}const tt=(t,e)=>{if(!t)return"Get Started";let n="";const o=[/(?:set up|setup|integrate|add|install|use)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,| by)/i,/(?:by|from)\s+([A-Z][a-zA-Z0-9\s]+?)(?:\.|$|,)/];for(const c of o){const s=t.match(c);if(s&&s[1]){n=s[1].trim();break}}const a=e||n;if(a)return`Integrate ${a.split(/\s+/).slice(0,2).join(" ")}`;const r=t.match(/to\s+set\s+up\s+([a-zA-Z0-9\s]+?)(?:\s+by|\s*[.,]|$)/i);return r&&r[1]?`Integrate ${r[1].trim().split(/\s+/).slice(0,2).join(" ")}`:"Integrate"},_e=({recommendation:t,theme:e,className:n="",style:o={},sessionId:a,onLinkClick:r,onPasteToInput:c})=>{var C,_,R,E,A,w,L;const s=t.creative_input||{},m=s.bridge_headline||"",h=s.bridge_description||"",l=s.bridge_prompt||s.bridge_content||"",u=s.product_name||"",b=s.cta_label||"";if(!h&&!l)return null;const x=t.ad_id||"",f=t.product_id||"",v=t.recommendation_id||"",{sdk:T,sessionId:p}=U(),y=a||p,k=async j=>{if(j.preventDefault(),!!l){if(v&&x&&y)try{const I=(T==null?void 0:T.apiBaseUrl)||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com",F=await fetch(`${I}/click/bridge-engagement`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recommendation_id:v,ad_id:x,session_id:y,agent_id:t.agent_id,user_id:t.user_id||void 0,is_test:!1})});F.ok?d.log("[AdMesh Bridge] โ
Engagement tracked successfully"):d.warn("[AdMesh Bridge] โ ๏ธ Failed to track engagement:",F.statusText)}catch(I){d.error("[AdMesh Bridge] โ Error tracking engagement:",I)}r&&r(t),c?c(l):typeof window<"u"&&window.__admesh_setMessage&&window.__admesh_setMessage(l)}},S=b||tt(l,u),M=!!S;return i.jsx($,{adId:x,productId:f,recommendationId:t.recommendation_id,exposureUrl:t.exposure_url,sessionId:a,className:`admesh-bridge-format ${n}`,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',padding:"1rem",border:"none",borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",backgroundColor:"transparent",color:(e==null?void 0:e.textColor)||"inherit",...o},children:i.jsxs("div",{"data-admesh-theme":(e==null?void 0:e.mode)||"light",children:[m&&i.jsx("div",{className:"admesh-bridge-headline",style:{marginBottom:h?"0.75rem":M?"1rem":"0",fontSize:((C=e==null?void 0:e.fontSize)==null?void 0:C.large)||"1rem",fontWeight:600,color:(e==null?void 0:e.textColor)||"inherit",lineHeight:"1.4"},children:m}),h&&i.jsx("div",{className:"admesh-bridge-description",style:{marginBottom:M||(_=t.creative_input)!=null&&_.offer_summary?"1rem":"0",lineHeight:"1.6",fontSize:((R=e==null?void 0:e.fontSize)==null?void 0:R.base)||"0.875rem",color:(e==null?void 0:e.textColor)||"inherit"},children:h}),((E=t.creative_input)==null?void 0:E.offer_summary)&&i.jsx("div",{className:"admesh-bridge-offer-summary",style:{marginBottom:M?"1rem":"0",lineHeight:"1.5",fontSize:((A=e==null?void 0:e.fontSize)==null?void 0:A.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:t.creative_input.offer_summary}),M&&i.jsx("div",{style:{marginBottom:"0.75rem"},children:i.jsx("button",{onClick:k,className:"admesh-bridge-cta-button",style:{padding:"0.5rem 1rem",backgroundColor:"#000000",color:"#ffffff",fontSize:((w=e==null?void 0:e.fontSize)==null?void 0:w.small)||"0.875rem",fontWeight:500,borderRadius:(e==null?void 0:e.borderRadius)||"0.5rem",border:"none",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="#1a1a1a",j.currentTarget.style.opacity="0.9"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="#000000",j.currentTarget.style.opacity="1"},children:S})}),i.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"0.5rem"},children:i.jsx("div",{className:"admesh-bridge-label",style:{fontSize:((L=e==null?void 0:e.fontSize)==null?void 0:L.small)||"0.75rem",color:e!=null&&e.textSecondaryColor||(e==null?void 0:e.mode)==="dark"?"#9ca3af":"#6b7280",fontStyle:"italic"},children:"Sponsored"})})]})})},ke=({recommendations:t,summaryText:e,theme:n,className:o="",style:a={},onLinkClick:r,onPasteToInput:c,sessionId:s,response:m})=>{var x;const l=(t||(m==null?void 0:m.recommendations)||[]).filter(f=>f&&typeof f=="object"&&(f.ad_id||f.recommendation_id));if(!l||l.length===0)return d.log("[AdMesh Summary Layout] Empty or invalid recommendations array - not rendering anything"),null;let u=e||(m==null?void 0:m.tail_summary);if(!u&&l.length>0&&((x=l[0])!=null&&x.creative_input)){const f=l[0].creative_input;u=f.long_description||f.context_snippet||f.short_description||void 0}d.log(`[AdMesh Summary Layout] Rendering with ${l.length} valid recommendations`);const b=()=>{if(l.length>0){const f=l[0],v=(f==null?void 0:f.creative_input)||{},T=!!v.bridge_prompt||!!v.bridge_content,p=(f==null?void 0:f.format)||(v==null?void 0:v.format),y=f==null?void 0:f.preferred_format,k=p==="bridge"||y==="bridge";if(d.log("[AdMesh Summary Layout] ๐ Checking format:",{hasBridgePrompt:T,bridgePrompt:v.bridge_prompt||v.bridge_content?(v.bridge_prompt||v.bridge_content||"").substring(0,50)+"...":void 0,format:p,preferredFormat:y,creativeInputKeys:Object.keys(v),recommendationKeys:Object.keys(f||{})}),T||k)return d.log("[AdMesh Summary Layout] ๐ฏ โ
Rendering bridge format"),i.jsx(_e,{recommendation:f,theme:n,sessionId:s,onLinkClick:r,onPasteToInput:c});d.log("[AdMesh Summary Layout] โ ๏ธ Bridge format NOT detected, falling back to other formats")}return u?i.jsx(ie,{summaryText:u,recommendations:l,theme:n,onLinkClick:r,sessionId:s}):l.length>0&&l[0]?i.jsx("div",{className:"fallback-citation",children:i.jsx(de,{recommendation:l[0],theme:n,sessionId:s})}):null};return i.jsx("div",{className:`admesh-summary-layout ${o}`,style:{fontFamily:(n==null?void 0:n.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',...a},children:b()})},Se=({recommendations:t,summaryText:e,theme:n,className:o,style:a,onLinkClick:r,onPasteToInput:c,sessionId:s,response:m})=>{const h=t||(m==null?void 0:m.recommendations)||[],l=e||(m==null?void 0:m.tail_summary),u=h.filter(b=>b&&typeof b=="object"&&(b.ad_id||b.recommendation_id));return!u||u.length===0?(d.log("[AdMeshLayout] Empty or invalid recommendations array - not rendering anything"),null):i.jsx(ke,{recommendations:u,summaryText:l,theme:n,className:o,style:a,onLinkClick:r,onPasteToInput:c,sessionId:s})};class Ae{constructor(e){P(this,"firedExposures",new Set);P(this,"debug",!1);P(this,"mrcThreshold",{visibilityPercentage:50,minimumDurationMs:1e3});this.debug=e.debug||!1}fireExposure(e,n,o){const a=`${o}_${n}`;if(this.firedExposures.has(a)){this.debug&&d.log("[Tracker] Exposure already fired");return}this.firedExposures.add(a);try{fetch(e,{method:"GET",keepalive:!0}).catch(()=>{this.debug&&d.warn("[Tracker] Failed to fire exposure")}),this.debug&&d.log("[Tracker] Fired MRC-compliant exposure")}catch{this.debug&&d.error("[Tracker] Error firing exposure")}}async fireExposureWithMRCCompliance(e,n,o,a){const r=`${o}_${n}`;if(this.firedExposures.has(r)){this.debug&&d.log("[Tracker] MRC exposure already fired");return}return new Promise(c=>{let s=null,m=null;const h=new IntersectionObserver(b=>{b.forEach(x=>{x.intersectionRatio*100>=this.mrcThreshold.visibilityPercentage?s===null&&(s=Date.now(),this.debug&&d.log("[Tracker] Ad reached MRC visibility threshold"),m=setTimeout(()=>{this.fireExposure(e,n,o),h.disconnect(),c()},this.mrcThreshold.minimumDurationMs)):s!==null&&(m&&(clearTimeout(m),m=null),s=null,this.debug&&d.log("[Tracker] Ad visibility dropped below MRC threshold"))})},{threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1],rootMargin:"0px"});h.observe(a);const u=setTimeout(()=>{h.disconnect(),m&&clearTimeout(m),c()},3e4);a.__admeshTrackerCleanup=()=>{h.disconnect(),m&&clearTimeout(m),clearTimeout(u)}})}clearFiredExposures(){this.firedExposures.clear()}getMRCThreshold(){return{...this.mrcThreshold}}setMRCThreshold(e){this.mrcThreshold={...this.mrcThreshold,...e}}}class Me{constructor(){P(this,"roots",new Map)}async render(e){var n;try{d.log("[AdMeshRenderer] ๐จ Attempting to render recommendations");const o=e.response.recommendations||[];if(o.length===0){d.log("[AdMeshRenderer] โ ๏ธ No recommendations to render - skipping render to avoid occupying space");return}const a=document.getElementById(e.containerId);if(!a)throw d.error("[AdMeshRenderer] โ Container not found"),new Error(`Container with ID "${e.containerId}" not found`);d.log("[AdMeshRenderer] โ
Container ready");const r=this.roots.get(e.containerId);r&&(d.log("[AdMeshRenderer] ๐งน Cleaning up existing root"),r.unmount(),this.roots.delete(e.containerId)),a.innerHTML="";const c=Ne.createRoot(a),s=((n=o[0])==null?void 0:n.tail_summary)||"";d.log("[AdMeshRenderer] ๐ Rendering recommendations");const m=e.onPasteToInput||(typeof window<"u"?window.__admesh_onPasteToInput:void 0);c.render(i.jsx(Se,{recommendations:o,summaryText:s,theme:e.theme,sessionId:e.sessionId,onPasteToInput:m})),a.style.display="block",d.log("[AdMeshRenderer] โ
Recommendations rendered successfully"),this.roots.set(e.containerId,c)}catch(o){throw d.error("[AdMeshRenderer] โ Error rendering recommendations"),o}}unmount(e){const n=this.roots.get(e);if(n){n.unmount(),this.roots.delete(e);const o=document.getElementById(e);o&&(o.style.display="none")}}unmountAll(){for(const[,e]of this.roots.entries())e.unmount();this.roots.clear()}}class te{constructor(e){P(this,"config");P(this,"apiBaseUrl");P(this,"renderer",null);P(this,"tracker",null);if(!e.apiKey)throw new Error("AdMeshSDK: apiKey is required");this.config={apiKey:e.apiKey,theme:e.theme,apiBaseUrl:e.apiBaseUrl},this.apiBaseUrl=e.apiBaseUrl||typeof window<"u"&&window.__ADMESH_API_BASE_URL__||"https://api.useadmesh.com"}static createSession(){const e=Date.now(),n=Math.random().toString(36).substring(2,15);return`session_${e}_${n}`}static createMessageId(e){const n=Date.now(),o=Math.random().toString(36).substring(2,9);return e?`msg_${e}_${n}_${o}`:`msg_${n}_${o}`}getRenderer(){return this.renderer||(this.renderer=new Me),this.renderer}getTracker(){return this.tracker||(this.tracker=new Ae({apiKey:this.config.apiKey})),this.tracker}async showRecommendations(e){try{if(!e.session_id)throw new Error("session_id is required");const n=await this.fetchRecommendationFromAIPContext({query:e.query,sessionId:e.session_id,platformSurface:e.platformSurface,model:e.model,messages:e.messages,locale:e.locale,geo:e.geo,userId:e.userId,latencyBudgetMs:e.latencyBudgetMs}),o=this.convertAIPResponseToRecommendation(n),a={session_id:n.session_id,message_id:`msg_${n.recommendation_id}`,recommendations:[o]},r=this.getRenderer(),c=this.getTracker();await r.render({containerId:e.containerId,response:a,theme:e.theme||this.config.theme,tracker:c,sessionId:e.session_id,onPasteToInput:e.onPasteToInput})}catch(n){throw d.error("[AdMeshSDK] Error showing recommendations"),n}}async fetchRecommendationFromAIPContext(e){var h,l,u;const n=`${this.apiBaseUrl}/aip/context`;d.log("[AdMeshSDK] ๐ฅ fetchRecommendationFromAIPContext called");const o=`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;let a=e.messageId;if(!a){if(e.messages&&e.messages.length>0){const b=e.messages[e.messages.length-1];b.id&&(a=b.id)}a||(a=te.createMessageId(e.sessionId))}const r={request_id:o,session_id:e.sessionId,message_id:a,platform_id:"placeholder",platform_surface:e.platformSurface||"web",model:e.model,query_text:e.query,messages:e.messages||[],locale:e.locale||"en-US",geo:e.geo,user_id:e.userId,timestamp:new Date().toISOString(),latency_budget_ms:e.latencyBudgetMs,cpx_floor:0};(!r.query_text||!r.query_text.trim())&&d.warn("[AdMeshSDK] โ ๏ธ Warning: Sending request with empty query_text");const c=JSON.stringify(r);d.log("[AdMeshSDK] ๐ค Sending request to /aip/context");const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:c});if(!s.ok){const x=(await s.json().catch(()=>({}))).detail||`HTTP ${s.status}`;throw new Error(`Failed to fetch recommendation from /aip/context: ${x}`)}const m=await s.json();return d.log("[AdMeshSDK] ๐ฅ Raw response from /aip/context:",{hasCreative:!!m.creative,creativeFormat:(h=m.creative)==null?void 0:h.format,creativeBridgeContent:(l=m.creative)!=null&&l.bridge_content?m.creative.bridge_content.substring(0,50)+"...":void 0,hasWinningBid:!!m.winning_bid,winningBidPreferredFormat:(u=m.winning_bid)==null?void 0:u.preferred_format,topLevelKeys:Object.keys(m)}),m}convertAIPResponseToRecommendation(e){var T,p,y,k,S,M,C;const n=e;let o=e.creative_input||{};const a=n.creative||{},r=a.format||n.format||((T=n.winning_bid)==null?void 0:T.preferred_format),c=a.headline,s=a.bridge_headline,m=a.bridge_description,h=a.bridge_prompt||a.bridge_content,l=h||o.bridge_prompt||o.bridge_content,u=a.cta_label,b=u||o.cta_label,x=s||o.bridge_headline,f=m||o.bridge_description;d.log("[AdMeshSDK] ๐ Extracting from response:",{creativeObject:a,creativeFormat:a.format,creativeBridgeHeadline:s,creativeBridgeDescription:m?String(m).substring(0,50)+"...":void 0,creativeBridgePrompt:h?String(h).substring(0,50)+"...":void 0,creativeCtaLabel:u,extractedFormat:r,extractedBridgeHeadline:x,extractedBridgeDescription:f?String(f).substring(0,50)+"...":void 0,extractedBridgePrompt:l?String(l).substring(0,50)+"...":void 0,extractedCtaLabel:b,creativeInputHasBridgeHeadline:!!o.bridge_headline,creativeInputHasBridgeDescription:!!o.bridge_description,creativeInputHasBridgePrompt:!!o.bridge_prompt,creativeInputHasBridgeContent:!!o.bridge_content,creativeInputHasCtaLabel:!!o.cta_label}),o={...o,...c&&{headline:c},...x&&{bridge_headline:x},...f&&{bridge_description:f},...l&&{bridge_prompt:l},...l&&{bridge_content:l},...b&&{cta_label:b},...r&&{format:r}};const v={...e,creative_input:o,product_title:e.title,tail_summary:o.long_description||"",product_summary:o.short_description||"",weave_summary:o.context_snippet||"",product_logo:(p=o.assets)!=null&&p.logo_url?{url:o.assets.logo_url}:void 0,categories:o.categories||[]};return r&&(v.format=r),d.log("[AdMeshSDK] ๐ Converted recommendation:",{hasFormat:!!r,format:r,hasBridgeHeadline:!!x,bridgeHeadline:x,hasBridgeDescription:!!f,bridgeDescriptionPreview:f?String(f).substring(0,50)+"...":void 0,hasBridgePrompt:!!l,hasCtaLabel:!!b,ctaLabel:b,bridgeHeadlineInCreativeInput:!!((y=v.creative_input)!=null&&y.bridge_headline),bridgeDescriptionInCreativeInput:!!((k=v.creative_input)!=null&&k.bridge_description),bridgePromptInCreativeInput:!!((S=v.creative_input)!=null&&S.bridge_prompt),bridgeContentInCreativeInput:!!((M=v.creative_input)!=null&&M.bridge_content),ctaLabelInCreativeInput:!!((C=v.creative_input)!=null&&C.cta_label),bridgePromptPreview:l?String(l).substring(0,50)+"...":void 0,creativeInputKeys:Object.keys(v.creative_input||{}),recommendationFormat:v.format}),v}}class le{constructor(e={}){P(this,"autoAddLabels");P(this,"fireExposurePixels");P(this,"labelStyle");P(this,"processedLinks",new Set);P(this,"mutationObserver",null);var n,o,a,r;this.autoAddLabels=e.autoAddLabels!==!1,this.fireExposurePixels=e.fireExposurePixels!==!1,this.labelStyle={fontSize:((n=e.labelStyle)==null?void 0:n.fontSize)||"0.75em",fontWeight:((o=e.labelStyle)==null?void 0:o.fontWeight)||"bold",color:((a=e.labelStyle)==null?void 0:a.color)||"#666",marginLeft:((r=e.labelStyle)==null?void 0:r.marginLeft)||"2px"}}getLinksToProcess(e){const o=e.querySelectorAll('a[href*="/click/"][href*="admesh.com"], a[href*="/click/"][href*="useadmesh.com"]');return o.length>0?Array.from(o):Array.from(e.querySelectorAll("a"))}scanAndProcessLinks(e,n,o){if(!e)return[];const a=[];if(n.length>0){const r=this.getLinksToProcess(e),c=new Map(n.filter(m=>m.click_url).map(m=>[m.click_url,m])),s=new Map;n.forEach(m=>{var l;const h=m.redirect_url||m.url||((l=m.creative_input)==null?void 0:l.cta_url);if(h&&typeof h=="string"){const u=h.trim().replace(/\/$/,"");s.set(u,m),s.set(`${u}/`,m)}}),r.forEach(m=>{var x;const h=m.getAttribute("href")||"",l=`${h}`;if(this.processedLinks.has(l))return;let u=c.get(h),b=h;if(!u){const f=h.trim().replace(/\/$/,"");u=s.get(f)||s.get(`${f}/`),u&&u.click_url&&(d.log("[WeaveResponseProcessor] ๐ Found brand URL match, replacing with click_url:",h),m.setAttribute("href",u.click_url),b=u.click_url)}if(u){this.processedLinks.add(l),m.setAttribute("target","_blank"),m.setAttribute("rel","noopener noreferrer");const f={element:m,href:b,text:m.textContent||"",hasAdLabel:this.hasAdLabel(m),matchedRecommendation:{ad_id:u.ad_id||((x=u.meta)==null?void 0:x.ad_id)||"",click_url:u.click_url,exposure_url:u.exposure_url}};this.autoAddLabels&&!f.hasAdLabel?(d.log("[WeaveResponseProcessor] ๐ท๏ธ Adding [Ad] label to matched recommendation link:",b),this.addAdLabel(m),f.hasAdLabel=!0):this.autoAddLabels?f.hasAdLabel&&d.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):d.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&u.exposure_url&&o&&f.matchedRecommendation&&o({exposureUrl:u.exposure_url,adId:f.matchedRecommendation.ad_id,linkElement:m}),a.push(f)}})}else Array.from(e.querySelectorAll("a")).forEach(c=>{const s=c.getAttribute("href")||"",m=`${s}`;if(this.processedLinks.has(m))return;if(this.isAdMeshLink(s)){this.processedLinks.add(m);const l={element:c,href:s,text:c.textContent||"",hasAdLabel:this.hasAdLabel(c),matchedRecommendation:void 0};if(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer"),this.autoAddLabels&&!l.hasAdLabel?(d.log("[WeaveResponseProcessor] ๐ท๏ธ Adding [Ad] label to pattern-matched AdMesh link:",s),this.addAdLabel(c),l.hasAdLabel=!0):this.autoAddLabels?l.hasAdLabel&&d.log("[WeaveResponseProcessor] โน๏ธ Link already has label, skipping"):d.log("[WeaveResponseProcessor] โน๏ธ autoAddLabels is disabled, skipping label"),this.fireExposurePixels&&o){const u=this.convertClickUrlToExposureUrl(s);o({exposureUrl:u,adId:this.extractAdIdFromUrl(s),linkElement:c})}a.push(l)}});return a}hasAdLabel(e){var c,s,m;if((e.textContent||"").includes("[Ad]"))return d.log("[WeaveResponseProcessor] โน๏ธ Link text contains [Ad] label"),!0;const o=e.querySelectorAll("sub, span");for(const h of Array.from(o))if((c=h.textContent)!=null&&c.includes("[Ad]"))return d.log("[WeaveResponseProcessor] โน๏ธ Link has [Ad] label as child element"),!0;let a=e.previousSibling;for(;a&&a.nodeType===Node.TEXT_NODE;){const h=a.textContent||"";if(h.trim()===""){a=a.previousSibling;continue}if(h.includes("[Ad]"))return d.log("[WeaveResponseProcessor] โน๏ธ Found [Ad] label in previous text sibling"),!0;break}if(a&&a.nodeType===Node.ELEMENT_NODE){const h=a,l=h.tagName.toUpperCase();if((l==="SUB"||l==="SPAN")&&((s=h.textContent)!=null&&s.includes("[Ad]")))return d.log("[WeaveResponseProcessor] โน๏ธ Found [Ad] label in previous element sibling:",l),!0}let r=e.nextSibling;for(;r&&r.nodeType===Node.TEXT_NODE;){const h=r.textContent||"";if(h.trim()===""){r=r.nextSibling;continue}if(h.includes("[Ad]"))return d.log("[WeaveResponseProcessor] โน๏ธ Found [Ad] label in next text sibling"),!0;break}if(r&&r.nodeType===Node.ELEMENT_NODE){const h=r,l=h.tagName.toUpperCase();if((l==="SUB"||l==="SPAN")&&((m=h.textContent)!=null&&m.includes("[Ad]")))return d.log("[WeaveResponseProcessor] โน๏ธ Found [Ad] label in next element sibling:",l),!0}return d.log("[WeaveResponseProcessor] โน๏ธ No existing [Ad] label found"),!1}addAdLabel(e){if(d.log("[WeaveResponseProcessor] ๐ท๏ธ Attempting to add [Ad] label to link:",e.href),!e.isConnected){d.warn("[WeaveResponseProcessor] โ ๏ธ Link is not in DOM, cannot add label");return}if(this.hasAdLabel(e)){d.log("[WeaveResponseProcessor] โน๏ธ Link already has [Ad] label, skipping");return}const n=e.parentNode;if(!n){d.error("[WeaveResponseProcessor] โ Link has no parent node, cannot add label");return}this.removeLeftAdLabel(e);const o=document.createElement("sub");o.textContent="[Ad]",o.style.fontSize=this.labelStyle.fontSize,o.style.fontWeight=this.labelStyle.fontWeight,o.style.color=this.labelStyle.color,o.style.marginLeft=this.labelStyle.marginLeft,o.style.cursor="pointer",o.style.borderBottom=`1px dotted ${this.labelStyle.color}`,o.style.whiteSpace="nowrap",o.title="Why this ad? This is a sponsored recommendation based on your search query.";let a=!1;o.addEventListener("mouseenter",()=>{o.style.opacity="0.7"}),o.addEventListener("mouseleave",()=>{o.style.opacity="1",a&&(a=!1)}),o.addEventListener("click",c=>{c.stopPropagation(),a=!a,a?(o.style.textDecoration="underline",o.style.opacity="0.7"):(o.style.textDecoration="none",o.style.opacity="1")});const r=c=>{a&&c.target!==o&&(a=!1,o.style.textDecoration="none",o.style.opacity="1")};document.addEventListener("click",r);try{const c=e.nextSibling;c?(n.insertBefore(o,c),d.log("[WeaveResponseProcessor] โ
[Ad] label inserted before next sibling")):(n.appendChild(o),d.log("[WeaveResponseProcessor] โ
[Ad] label appended to parent (no next sibling)")),o.isConnected&&o.parentNode===n?d.log("[WeaveResponseProcessor] โ
[Ad] label successfully added to link:",e.href):d.error("[WeaveResponseProcessor] โ [Ad] label insertion failed - label not in DOM")}catch(c){d.error("[WeaveResponseProcessor] โ Error inserting [Ad] label:",c)}}removeLeftAdLabel(e){var o,a,r;let n=e.previousSibling;for(;n&&n.nodeType===Node.TEXT_NODE;){const c=n.textContent||"";if(c.trim()===""){n=n.previousSibling;continue}if(c.includes("[Ad]")){(o=n.parentNode)==null||o.removeChild(n);return}break}if(n&&n.nodeType===Node.ELEMENT_NODE){const c=n;(c.tagName==="SUB"||c.tagName==="SPAN")&&((a=c.textContent)!=null&&a.includes("[Ad]"))&&((r=c.parentNode)==null||r.removeChild(c))}}isAdMeshLink(e){if(!e||!e.includes("/click/"))return!1;if(["useadmesh.com","admesh.com","api.useadmesh.com","api.admesh.com","localhost:8000","localhost:3000"].some(a=>e.includes(a)))return!0;try{if(new URL(e).pathname.startsWith("/click/"))return!0}catch{if(e.match(/\/click\/[a-zA-Z0-9\-_]+/))return!0}return!1}extractAdIdFromUrl(e){try{const n=e.match(/\/click\/([^/?]+)/);return n&&n[1]?n[1]:e}catch{return e}}convertClickUrlToExposureUrl(e){try{const n=new URL(e),a=`${`${n.protocol}//${n.host}`}/exposure`,r=new URLSearchParams(n.search);return r.has("cpx")||r.set("cpx","0"),`${a}?${r.toString()}`}catch{return d.warn("[WeaveResponseProcessor] Failed to convert click URL to exposure URL"),e}}watchForNewLinks(e,n,o){e&&(this.mutationObserver&&this.mutationObserver.disconnect(),this.mutationObserver=new MutationObserver(()=>{this.scanAndProcessLinks(e,n,o)}),this.mutationObserver.observe(e,{childList:!0,subtree:!0,characterData:!1}))}stopWatching(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}clearCache(){this.processedLinks.clear()}}const rt=({apiKey:t,sessionId:e,theme:n,apiBaseUrl:o,children:a})=>{const r=g.useRef(null),[c,s]=g.useState(new Set);g.useEffect(()=>{if(!t){d.warn("[AdMeshProvider] โ ๏ธ AdMesh API key not configured");return}try{r.current=new te({apiKey:t,theme:n,apiBaseUrl:o}),d.log("[AdMeshProvider] โ
AdMesh SDK initialized"),o&&d.log("[AdMeshProvider] ๐ Using custom API base URL")}catch{d.error("[AdMeshProvider] โ Failed to initialize AdMesh SDK")}return()=>{d.log("[AdMeshProvider] ๐งน Provider unmounted")}},[t,n,o]);const m={sdk:r.current,apiKey:t,sessionId:e,theme:n,processedMessageIds:c,markMessageAsProcessed:h=>{s(l=>{const u=new Set(l);return u.add(h),u})},isMessageProcessed:h=>c.has(h)};return i.jsx(ce.Provider,{value:m,children:a})},nt=({format:t,onRecommendationsShown:e,onError:n,messageId:o,query:a,latencyBudgetMs:r,onPasteToInput:c})=>{const{sdk:s,sessionId:m}=U(),h=g.useRef(null),[l,u]=g.useState("");return g.useEffect(()=>{o&&u(`admesh-recommendations-${o}`)},[o]),g.useEffect(()=>(c&&typeof window<"u"&&(window.__admesh_onPasteToInput=c),()=>{typeof window<"u"&&delete window.__admesh_onPasteToInput}),[c]),g.useEffect(()=>{if(d.log("[AdMeshRecommendations] ๐ Checking SDK readiness"),!o||!a||a.trim()===""){d.log("[AdMeshRecommendations] โ Validation failed - missing required parameters");return}if(d.log("[AdMeshRecommendations] โ
Validation passed"),!s||!l){d.log("[AdMeshRecommendations] SDK or containerId not ready");return}(async()=>{var x,f,v,T,p;try{if(!(s!=null&&s.fetchRecommendationFromAIPContext)){d.log("[AdMeshRecommendations] SDK fetchRecommendationFromAIPContext not available");return}d.log("[AdMeshRecommendations] ๐ค Fetching recommendation from /aip/context");const y=await s.fetchRecommendationFromAIPContext({query:a.trim(),sessionId:m,messageId:o,latencyBudgetMs:r}),k=y,S=((x=k.creative)==null?void 0:x.preferred_format)||((f=k.winning_bid)==null?void 0:f.preferred_format)||k.preferred_format||((v=y.creative_input)==null?void 0:v.preferred_format),M=((T=k.creative)==null?void 0:T.fallback_formats)||k.fallback_formats||((p=y.creative_input)==null?void 0:p.fallback_formats)||[];let C;if(t?C=t:S?C=S==="weave"?"tail":S:C="tail",d.log("[AdMeshRecommendations] ๐ Format selection:",{preferredFormat:S,selectedFormat:C,fallbackFormats:M}),!(s!=null&&s.showRecommendations)){d.log("[AdMeshRecommendations] SDK showRecommendations not available");return}d.log("[AdMeshRecommendations] ๐จ Rendering recommendations with format:",C),await s.showRecommendations({query:a.trim(),containerId:l,session_id:m,latencyBudgetMs:r,onPasteToInput:c}),e==null||e(o)}catch(y){const k=y instanceof Error?y:new Error(String(y));d.log(`[AdMeshRecommendations] โ Error: ${k.message}`),n==null||n(k)}})()},[s,m,l,t,o,a,r,e,n]),!o||!a||a.trim()===""?null:i.jsx("div",{ref:h,id:l,className:"admesh-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Ce=({format:t="tail",onError:e,messageId:n,query:o,fallback:a})=>{const{sdk:r,sessionId:c}=U(),s=g.useRef(null),[m,h]=g.useState("");return g.useEffect(()=>{n&&h(`admesh-weave-fallback-${n}`)},[n]),d.log("[WeaveFallbackRecommendations] ๐จ Component render"),g.useEffect(()=>{if(d.log("[WeaveFallbackRecommendations] ๐ useEffect triggered"),!a){d.log("[WeaveFallbackRecommendations] โญ๏ธ Skipping - fallback is FALSE, not rendering recommendations");return}if(d.log("[WeaveFallbackRecommendations] โ
fallback is TRUE, proceeding with recommendations"),!n||!o||o.trim()===""){d.log("[WeaveFallbackRecommendations] โ Validation failed - returning early");return}if(d.log("[WeaveFallbackRecommendations] โ
Validation passed"),!r||!m){d.log("[WeaveFallbackRecommendations] SDK or containerId not ready");return}(async()=>{try{if(!(r!=null&&r.showRecommendations)){d.log("[WeaveFallbackRecommendations] SDK showRecommendations not available");return}d.log("[WeaveFallbackRecommendations] ๐ค Calling sdk.showRecommendations"),await r.showRecommendations({query:o.trim(),containerId:m,session_id:c}),d.log("[WeaveFallbackRecommendations] โ
Recommendations displayed successfully")}catch(u){const b=u instanceof Error?u:new Error(String(u));d.log(`[WeaveFallbackRecommendations] โ Error: ${b.message}`),e==null||e(b)}})()},[r,c,m,t,n,o,a,e]),!a||!n||!o||o.trim()===""?null:i.jsx("div",{ref:s,id:m,className:"admesh-weave-fallback-recommendations-container",style:{marginTop:"1rem",display:"none"}})},Te=g.createContext(void 0),ot=({children:t,shouldRenderFallback:e,messageId:n,sessionId:o,query:a})=>i.jsx(Te.Provider,{value:{shouldRenderFallback:e,messageId:n,sessionId:o,query:a},children:t}),at=()=>g.useContext(Te),st=({recommendations:t,title:e="Product Recommendations",showTitle:n=!0,className:o="",cardClassName:a="",onProductClick:r,maxCards:c=10,cardWidth:s="md",theme:m="auto",borderRadius:h="md",shadow:l="sm"})=>{if(!t||t.length===0)return d.log("[AdMesh Ecommerce Cards] Empty recommendations - not rendering anything"),null;const u=t.slice(0,c),b=()=>{switch(s){case"sm":return"w-48 min-w-48";case"md":return"w-64 min-w-64";case"lg":return"w-80 min-w-80";default:return"w-64 min-w-64"}},x=()=>{switch(h){case"none":return"rounded-none";case"sm":return"rounded-sm";case"md":return"rounded-lg";case"lg":return"rounded-xl";default:return"rounded-lg"}},f=()=>{switch(l){case"none":return"";case"sm":return"shadow-sm hover:shadow-md";case"md":return"shadow-md hover:shadow-lg";case"lg":return"shadow-lg hover:shadow-xl";default:return"shadow-sm hover:shadow-md"}},v=()=>m==="dark"?"bg-gray-900 text-white":m==="light"?"bg-white text-gray-900":"bg-white dark:bg-gray-900 text-gray-900 dark:text-white",T=p=>{var y;if(r)r(p);else{const k=p.click_url||p.admesh_link||p.url||((y=p.creative_input)==null?void 0:y.cta_url);k&&window.open(k,"_blank","noopener,noreferrer")}};return!t||t.length===0?null:i.jsxs("div",{className:V("w-full",o),children:[n&&i.jsxs("div",{className:"mb-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:e}),i.jsx("div",{className:"mt-1 h-0.5 w-12 bg-blue-500"})]}),i.jsxs("div",{className:"relative",children:[u.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"No products to display"}):i.jsx("div",{className:"flex gap-4 overflow-x-auto pb-4 scrollbar-hide",children:u.map(p=>{var M,C,_,R,E,A,w,L,j,I,F,z,H,O,K,q,G,N,D,B,Y;const y=p.product_id||p.id||p.ad_id,k=p.ad_id||p.product_id||"",S=p.product_id||"";return i.jsx($,{adId:k,productId:S,className:V(b(),x(),f(),v(),"flex-shrink-0 border border-gray-200 dark:border-gray-700 transition-all duration-200 cursor-pointer hover:scale-[1.02]",a),onClick:()=>T(p),children:i.jsxs("div",{children:[i.jsx("div",{className:"relative aspect-square w-full overflow-hidden",children:(C=(M=p.creative_input)==null?void 0:M.assets)!=null&&C.logo_url||(E=(R=(_=p.creative_input)==null?void 0:_.assets)==null?void 0:R.image_urls)!=null&&E[0]||(A=p.product_logo)!=null&&A.url?i.jsx("img",{src:((j=(L=(w=p.creative_input)==null?void 0:w.assets)==null?void 0:L.image_urls)==null?void 0:j[0])||((F=(I=p.creative_input)==null?void 0:I.assets)==null?void 0:F.logo_url)||((z=p.product_logo)==null?void 0:z.url),alt:((H=p.creative_input)==null?void 0:H.product_name)||p.title||p.product_title||"Product",className:"h-full w-full object-cover transition-transform duration-200 hover:scale-105",loading:"lazy",onError:Z=>{Z.target.style.display="none"}}):i.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gray-100 dark:bg-gray-800",children:i.jsx("svg",{className:"h-12 w-12 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})})}),i.jsxs("div",{className:"p-3",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-2 leading-tight",children:((O=p.creative_input)==null?void 0:O.product_name)||p.title||p.product_title||""}),(((K=p.creative_input)==null?void 0:K.short_description)||((q=p.creative_input)==null?void 0:q.context_snippet)||p.weave_summary)&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-400 line-clamp-2 mb-2",children:((G=p.creative_input)==null?void 0:G.short_description)||((N=p.creative_input)==null?void 0:N.context_snippet)||p.weave_summary}),((D=p.creative_input)==null?void 0:D.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-500 line-clamp-2 mb-2 italic",children:p.creative_input.offer_summary}),((B=p.creative_input)==null?void 0:B.value_props)&&p.creative_input.value_props.length>0&&i.jsx("div",{className:"mb-2",children:i.jsx("ul",{className:"space-y-1",children:p.creative_input.value_props.slice(0,2).map((Z,ne)=>i.jsxs("li",{className:"flex items-start gap-1.5 text-xs text-gray-600 dark:text-gray-400",children:[i.jsx("svg",{className:"w-3 h-3 mt-0.5 flex-shrink-0 text-green-500",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),i.jsx("span",{className:"line-clamp-1",children:Z})]},ne))})}),(!((Y=p.creative_input)!=null&&Y.value_props)||p.creative_input.value_props.length===0)&&p.categories&&p.categories.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:p.categories.slice(0,2).map((Z,ne)=>i.jsx("span",{className:"text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded",children:Z},ne))}),p.trust_score!==void 0&&i.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-400",children:["Trust Score: ",(p.trust_score*100).toFixed(0),"%"]})]})]})},y)})}),u.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute top-1/2 -left-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),i.jsx("div",{className:"absolute top-1/2 -right-2 transform -translate-y-1/2 bg-white dark:bg-gray-800 rounded-full shadow-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("svg",{className:"w-4 h-4 text-gray-600 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]})]}),i.jsxs("div",{className:"flex justify-between items-center mt-3 pt-2 border-t border-gray-200 dark:border-gray-700",children:[i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sponsored"}),i.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500"})]}),i.jsx("style",{dangerouslySetInnerHTML:{__html:`
|
|
974
974
|
.scrollbar-hide {
|
|
975
975
|
-ms-overflow-style: none;
|
|
976
976
|
scrollbar-width: none;
|
|
@@ -984,5 +984,5 @@
|
|
|
984
984
|
-webkit-box-orient: vertical;
|
|
985
985
|
overflow: hidden;
|
|
986
986
|
}
|
|
987
|
-
`}})]})},Me=({recommendation:t,theme:e,variation:o="default",expandable:n=!1,className:d,style:r})=>{var g,c,u,p,b;if(!t)return console.log("[AdMesh Inline Card] No recommendation provided - not rendering"),null;const i={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},l=V("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":n&&(o==="question"||o==="statement")},d);return s.jsx("div",{className:l,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((c=(g=e==null?void 0:e.components)==null?void 0:g.inlineRecommendation)==null?void 0:c.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...r},"data-admesh-theme":e==null?void 0:e.mode,children:s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((p=t.product_logo)==null?void 0:p.url)&&s.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:f=>{f.target.style.display="none"}}),s.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:i.title})]}),s.jsx("div",{className:"flex-shrink-0",children:s.jsx(G,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((b=t.creative_input)==null?void 0:b.cta_url)||t.url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:s.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[o==="question"?"Try":"Visit",s.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),i.description&&s.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:i.description}),s.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:s.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[s.jsx("span",{children:"Sponsored"}),s.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};Me.displayName="AdMeshInlineCard";const ot={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},nt={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},Ae=({type:t,variant:e,size:o="md",className:n,style:d})=>{const r=e||ot[t]||"secondary",a=nt[t],i=V("admesh-component","admesh-badge",`admesh-badge--${r}`,`admesh-badge--${o}`,n);return s.jsxs("span",{className:i,style:d,children:[a&&s.jsx("span",{className:"admesh-badge__icon",children:a}),s.jsx("span",{className:"admesh-badge__text",children:t})]})};Ae.displayName="AdMeshBadge";const Z="admesh:streamingStart",X="admesh:streamingComplete";function at(t,e){const o={messageId:t,sessionId:e,timestamp:Date.now()},n=new CustomEvent(Z,{detail:o});window.dispatchEvent(n),console.log("[StreamingEvents] ๐ข Dispatched streamingStart event")}function st(t,e,o){const n={messageId:t,sessionId:e,timestamp:Date.now(),metadata:o},d=new CustomEvent(X,{detail:n});window.dispatchEvent(d),console.log("[StreamingEvents] ๐ข Dispatched streamingComplete event")}function it(t,e,o){const n=d=>{const r=d;r.detail.messageId===t&&r.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingStart event"),o(r.detail))};return window.addEventListener(Z,n),()=>{window.removeEventListener(Z,n)}}function Ce(t,e,o){const n=d=>{const r=d;r.detail.messageId===t&&r.detail.sessionId===e&&(console.log("[StreamingEvents] ๐จ Received streamingComplete event"),o(r.detail))};return window.addEventListener(X,n),()=>{window.removeEventListener(X,n)}}const Q=()=>{const t=new Set,e=new Map,o=r=>{const a=e.get(r);a&&(a.observer.disconnect(),a.timeoutId&&clearTimeout(a.timeoutId),e.delete(r))};return{startTracking:({exposureUrl:r,adId:a,linkElement:i,sessionId:l,logPrefix:g="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!r||!i){g&&console.warn(`${g} โ ๏ธ Missing exposure tracking data`);return}const c=`${l||"anonymous"}::${a||r}`;if(t.has(c)||e.has(c))return;const u={observer:void 0,timeoutId:null,viewableStart:null},p=()=>{o(c),t.add(c),fetch(r,{method:"GET",keepalive:!0}).then(()=>{g&&console.log(`${g} โ
Exposure pixel fired`)}).catch(()=>{g&&console.warn(`${g} โ ๏ธ Failed to fire exposure pixel`),t.delete(c)})},b=new IntersectionObserver(f=>{f.forEach(x=>{x.intersectionRatio>=.5?u.viewableStart===null&&(u.viewableStart=performance.now(),u.timeoutId=setTimeout(p,1e3)):(u.viewableStart=null,u.timeoutId&&(clearTimeout(u.timeoutId),u.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});u.observer=b,b.observe(i),e.set(c,u)},cleanup:()=>{Array.from(e.keys()).forEach(o)}}},dt=({containerId:t,messageId:e,sessionId:o,sdk:n,onLinksFound:d,onNoLinksFound:r,children:a})=>{const[i,l]=h.useState(!1),[g,c]=h.useState(!0),[u,p]=h.useState(!1),b=h.useRef(Q()),f=h.useRef(d),x=h.useRef(r),y=h.useRef(t),m=h.useRef(n),_=h.useRef(o);h.useEffect(()=>{f.current=d,x.current=r,y.current=t,m.current=n,_.current=o},[d,r,t,n,o]),h.useEffect(()=>()=>{b.current.cleanup()},[]);const M=h.useCallback(({exposureUrl:k,adId:E,linkElement:v})=>{b.current.startTracking({exposureUrl:k,adId:E,linkElement:v,sessionId:_.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]),w=h.useCallback(()=>{console.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const k=document.getElementById(y.current);if(!k){console.warn("[FinalLinkDetectionCheck] โ Container not found"),l(!0),r();return}const v=new ie({autoAddLabels:!0,fireExposurePixels:!0}).scanAndProcessLinks(k,[],({exposureUrl:A,adId:T,linkElement:C})=>M({exposureUrl:A,adId:T,linkElement:C}));console.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${v.length} links`),v.length>0?(console.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),p(!0),f.current(v.length)):(console.log("[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will make API call)"),p(!1),x.current()),l(!0)}catch{console.error("[FinalLinkDetectionCheck] โ Error during final check"),l(!0),x.current()}},[M]);return h.useEffect(()=>{console.log("[FinalLinkDetectionCheck] โณ Setting up listener");const k=Ce(e,o,()=>{console.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event"),c(!1),setTimeout(()=>{w()},100)});return()=>{console.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),k()}},[e,o]),g?s.jsx(s.Fragment,{}):i?u?(console.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),s.jsx(s.Fragment,{})):(console.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),s.jsx(s.Fragment,{children:a})):s.jsx(s.Fragment,{})},ct=({messageId:t,children:e,fallbackFormat:o="tail",onLinksDetected:n,onNoLinksDetected:d,onError:r,className:a,query:i,onFallbackChange:l})=>{const{sessionId:g,sdk:c}=W(),u=h.useRef(null),p=`weave-ad-container-${t}`,b=h.useRef(Q()),f=h.useRef(!1),x=h.useRef(null);return h.useEffect(()=>(x.current||(x.current=new ie({autoAddLabels:!0,fireExposurePixels:!0})),()=>{x.current&&(x.current.stopWatching(),x.current.clearCache())}),[]),h.useEffect(()=>()=>{b.current.cleanup()},[]),h.useEffect(()=>{const y=u.current;if(!y||!x.current)return;const m=x.current,_=({exposureUrl:k,adId:E,linkElement:v})=>{b.current.startTracking({exposureUrl:k,adId:E,linkElement:v,sessionId:g,logPrefix:"[WeaveAdFormatContainer]"})},w=setTimeout(()=>{const k=m.scanAndProcessLinks(y,[],_);k.length>0&&!f.current&&(f.current=!0,n==null||n(k.length),l==null||l(!1))},100);return m.watchForNewLinks(y,[],_),()=>{clearTimeout(w),m.stopWatching()}},[e,g,n,l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:u,id:p,className:a,"data-weave-ad-format":"true","data-message-id":t,children:e}),i&&s.jsx(dt,{containerId:p,messageId:t,sessionId:g,sdk:c,onLinksFound:y=>{console.log(`[WeaveAdFormatContainer] โ
Links found (${y}) - no fallback needed`),n==null||n(y),l==null||l(!1)},onNoLinksFound:()=>{console.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),d==null||d(),l==null||l(!0)},children:s.jsx(_e,{format:o,messageId:t,query:i,fallback:!0,onError:r})})]})},lt=t=>{const{sdk:e,sessionId:o}=W(),n=h.useRef(!1),d=h.useRef(0),r=h.useRef(!1),a=h.useRef(!1),i=h.useRef(null),l=h.useRef(Q());h.useEffect(()=>()=>{l.current.cleanup()},[]);const g=h.useCallback(({exposureUrl:m,adId:_,linkElement:M})=>{l.current.startTracking({exposureUrl:m,adId:_,linkElement:M,sessionId:o,logPrefix:"[useWeaveAdFormat]"})},[o]),c=h.useRef(Date.now()),u=h.useRef(0),p=h.useRef(null),b=h.useRef([]),f=h.useRef(300),x=h.useCallback(async()=>{var m,_,M,w;if(!(!e||!o||n.current)){n.current=!0,d.current=0;try{const k=document.getElementById(t.llmOutputContainerId);if(!k)return;const E=(m=e.getWeaveProcessor)==null?void 0:m.call(e);if(!E)return;const v=E.scanAndProcessLinks(k,[],({exposureUrl:T,adId:C,linkElement:S})=>g({exposureUrl:T,adId:C,linkElement:S}));d.current=v.length;const A=v.length>0;if(A&&!r.current)r.current=!0,(_=t.onLinksDetected)==null||_.call(t,v.length),a.current=!0;else if(!A&&r.current)r.current=!1,a.current=!1;else if(!A&&!a.current){i.current&&clearTimeout(i.current),p.current&&clearInterval(p.current),u.current=0,c.current=Date.now();const T=Math.max(100,f.current/3);p.current=setInterval(()=>{var R;const S=Date.now()-c.current,I=f.current;S>=I?(u.current++,u.current>=2&&(p.current&&(clearInterval(p.current),p.current=null),!r.current&&!a.current&&((R=t.onNoLinksDetected)==null||R.call(t),a.current=!0))):u.current=0},T);const C=Math.max(1500,f.current*5);i.current=setTimeout(()=>{var S;p.current&&(clearInterval(p.current),p.current=null),!r.current&&!a.current&&((S=t.onNoLinksDetected)==null||S.call(t),a.current=!0)},C)}else A&&a.current&&!r.current&&(i.current&&(clearTimeout(i.current),i.current=null),r.current=!0,(M=t.onLinksDetected)==null||M.call(t,v.length),a.current=!0)}catch(k){const E=k instanceof Error?k:new Error(String(k));(w=t.onError)==null||w.call(t,E)}finally{n.current=!1}}},[e,o,t,g]),y=h.useCallback(()=>{const m=b.current;if(m.length<2){f.current=300;return}const _=[];for(let k=1;k<m.length;k++)_.push(m[k]-m[k-1]);const M=_.reduce((k,E)=>k+E,0)/_.length,w=Math.max(100,Math.min(M*3,1e3));f.current=w},[]);return h.useEffect(()=>{const m=document.getElementById(t.llmOutputContainerId);if(!m)return;x();const _=new MutationObserver(()=>{const M=Date.now();c.current=M,u.current=0,b.current.push(M),b.current.length>10&&b.current.shift(),y(),x()});return _.observe(m,{childList:!0,subtree:!0,characterData:!1}),()=>{_.disconnect(),i.current&&clearTimeout(i.current),p.current&&clearInterval(p.current)}},[t.llmOutputContainerId,x,y]),{isProcessing:n.current,detectedLinksCount:d.current,linksFound:r.current,shouldRenderFallback:!r.current&&a.current,processWeaveFormat:x}},mt="1.0.10";exports.AdMeshBadge=Ae;exports.AdMeshBridgeFormat=xe;exports.AdMeshContext=se;exports.AdMeshEcommerceCards=rt;exports.AdMeshInlineCard=Me;exports.AdMeshLayout=ye;exports.AdMeshLinkTracker=G;exports.AdMeshProductCard=ae;exports.AdMeshProvider=Je;exports.AdMeshRecommendations=Qe;exports.AdMeshRenderer=ke;exports.AdMeshSDK=J;exports.AdMeshSummaryLayout=ve;exports.AdMeshSummaryUnit=ne;exports.AdMeshTailAd=ne;exports.AdMeshTracker=we;exports.AdMeshViewabilityTracker=B;exports.STREAMING_COMPLETE_EVENT=X;exports.STREAMING_START_EVENT=Z;exports.VERSION=mt;exports.WeaveAdFormatContainer=ct;exports.WeaveAdFormatProvider=et;exports.WeaveFallbackRecommendations=_e;exports.WeaveResponseProcessor=ie;exports.createInlineExposureTracker=Q;exports.dispatchStreamingCompleteEvent=st;exports.dispatchStreamingStartEvent=at;exports.onStreamingComplete=Ce;exports.onStreamingStart=it;exports.useAdMesh=W;exports.useAdMeshContext=be;exports.useAdMeshStyles=fe;exports.useAdMeshTracker=ge;exports.useViewabilityTracker=pe;exports.useWeaveAdFormat=lt;exports.useWeaveAdFormatContext=tt;
|
|
987
|
+
`}})]})},Ee=({recommendation:t,theme:e,variation:n="default",expandable:o=!1,className:a,style:r})=>{var h,l,u,b,x,f;if(!t)return d.log("[AdMesh Inline Card] No recommendation provided - not rendering"),null;const s={title:t.product_title||t.title,description:t.weave_summary||t.reason||"",ctaText:t.product_title||t.title},m=V("rounded-xl shadow-sm border border-gray-200 dark:border-gray-800 p-4 bg-white dark:bg-slate-900","hover:shadow-md transition-shadow duration-200",{"cursor-pointer":o&&(n==="question"||n==="statement")},a);return i.jsx("div",{className:m,style:{fontFamily:(e==null?void 0:e.fontFamily)||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',width:((l=(h=e==null?void 0:e.components)==null?void 0:h.inlineRecommendation)==null?void 0:l.width)||"100%",...(u=e==null?void 0:e.components)==null?void 0:u.productCard,...r},"data-admesh-theme":e==null?void 0:e.mode,children:i.jsxs("div",{className:"h-full flex flex-col",children:[i.jsxs("div",{className:"flex justify-between items-center gap-3 mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[((b=t.product_logo)==null?void 0:b.url)&&i.jsx("img",{src:t.product_logo.url,alt:`${t.product_title} logo`,className:"w-5 h-5 rounded flex-shrink-0",onError:v=>{v.target.style.display="none"}}),i.jsx("h4",{className:"font-semibold text-gray-800 dark:text-gray-200 text-sm truncate",children:s.title})]}),i.jsx("div",{className:"flex-shrink-0",children:i.jsx(X,{adId:t.ad_id||"",admeshLink:t.click_url||t.admesh_link||((x=t.creative_input)==null?void 0:x.cta_url)||t.url,productId:t.product_id,trackingData:{title:t.product_title,matchScore:t.contextual_relevance_score,component:"inline_card_cta"},children:i.jsxs("button",{className:"text-xs px-2 py-1 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 flex items-center transition-all duration-200 transform hover:scale-105 shadow-sm whitespace-nowrap",children:[n==="question"?"Try":"Visit",i.jsx("svg",{className:"ml-1 h-3 w-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})})]}),s.description&&i.jsx("p",{className:"text-xs text-gray-600 dark:text-gray-300 mb-2 line-clamp-2",children:s.description}),((f=t.creative_input)==null?void 0:f.offer_summary)&&i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2 line-clamp-2 italic",children:t.creative_input.offer_summary}),i.jsx("div",{className:"mt-auto pt-2 border-t border-gray-100 dark:border-slate-700",children:i.jsxs("div",{className:"flex items-center justify-between text-[11px] text-gray-500 dark:text-gray-400",children:[i.jsx("span",{children:"Sponsored"}),i.jsx("span",{className:"text-gray-400 dark:text-gray-500"})]})})]})})};Ee.displayName="AdMeshInlineCard";const it={"Top Match":"primary","Free Tier":"success","AI Powered":"secondary",Popular:"warning",New:"primary","Trial Available":"success"},dt={"Top Match":"โ
","Free Tier":"โ","AI Powered":"โ",Popular:"โฒ",New:"โ","Trial Available":"โ"},Re=({type:t,variant:e,size:n="md",className:o,style:a})=>{const r=e||it[t]||"secondary",c=dt[t],s=V("admesh-component","admesh-badge",`admesh-badge--${r}`,`admesh-badge--${n}`,o);return i.jsxs("span",{className:s,style:a,children:[c&&i.jsx("span",{className:"admesh-badge__icon",children:c}),i.jsx("span",{className:"admesh-badge__text",children:t})]})};Re.displayName="AdMeshBadge";const Q="admesh:streamingStart",ee="admesh:streamingComplete";function ct(t,e){const n={messageId:t,sessionId:e,timestamp:Date.now()},o=new CustomEvent(Q,{detail:n});window.dispatchEvent(o),d.log("[StreamingEvents] ๐ข Dispatched streamingStart event")}function lt(t,e,n){const o={messageId:t,sessionId:e,timestamp:Date.now(),metadata:n},a=new CustomEvent(ee,{detail:o});window.dispatchEvent(a),d.log("[StreamingEvents] ๐ข Dispatched streamingComplete event")}function mt(t,e,n){const o=a=>{const r=a;r.detail.messageId===t&&r.detail.sessionId===e&&(d.log("[StreamingEvents] ๐จ Received streamingStart event"),n(r.detail))};return window.addEventListener(Q,o),()=>{window.removeEventListener(Q,o)}}function je(t,e,n){const o=a=>{const r=a;r.detail.messageId===t&&r.detail.sessionId===e&&(d.log("[StreamingEvents] ๐จ Received streamingComplete event"),n(r.detail))};return window.addEventListener(ee,o),()=>{window.removeEventListener(ee,o)}}const re=()=>{const t=new Set,e=new Map,n=r=>{const c=e.get(r);c&&(c.observer.disconnect(),c.timeoutId&&clearTimeout(c.timeoutId),e.delete(r))};return{startTracking:({exposureUrl:r,adId:c,linkElement:s,sessionId:m,logPrefix:h="[AdMesh Exposure]"})=>{if(typeof window>"u")return;if(!r||!s){h&&d.warn(`${h} โ ๏ธ Missing exposure tracking data`);return}const l=`${m||"anonymous"}::${c||r}`;if(t.has(l)||e.has(l))return;const u={observer:void 0,timeoutId:null,viewableStart:null},b=()=>{n(l),t.add(l),fetch(r,{method:"GET",keepalive:!0}).then(()=>{h&&d.log(`${h} โ
Exposure pixel fired`)}).catch(()=>{h&&d.warn(`${h} โ ๏ธ Failed to fire exposure pixel`),t.delete(l)})},x=new IntersectionObserver(f=>{f.forEach(v=>{v.intersectionRatio>=.5?u.viewableStart===null&&(u.viewableStart=performance.now(),u.timeoutId=setTimeout(b,1e3)):(u.viewableStart=null,u.timeoutId&&(clearTimeout(u.timeoutId),u.timeoutId=null))})},{threshold:[0,.25,.5,.75,1],rootMargin:"0px"});u.observer=x,x.observe(s),e.set(l,u)},cleanup:()=>{Array.from(e.keys()).forEach(n)}}},ut=({containerId:t,messageId:e,sessionId:n,sdk:o,query:a,onLinksFound:r,onNoLinksFound:c,children:s})=>{const[m,h]=g.useState(!1),[l,u]=g.useState(!0),[b,x]=g.useState(!1),[f,v]=g.useState([]),T=g.useRef(re()),p=g.useRef(r),y=g.useRef(c),k=g.useRef(t),S=g.useRef(o),M=g.useRef(n),C=g.useRef(a);g.useEffect(()=>{p.current=r,y.current=c,k.current=t,S.current=o,M.current=n,C.current=a},[r,c,t,o,n,a]),g.useEffect(()=>()=>{T.current.cleanup()},[]);const _=g.useCallback(({exposureUrl:E,adId:A,linkElement:w})=>{T.current.startTracking({exposureUrl:E,adId:A,linkElement:w,sessionId:M.current,logPrefix:"[FinalLinkDetectionCheck]"})},[]);g.useEffect(()=>{(async()=>{var A;if(!S.current||!((A=C.current)!=null&&A.trim())||!e){d.log("[FinalLinkDetectionCheck] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{d.log("[FinalLinkDetectionCheck] ๐ค Fetching recommendations from SDK for brand URL matching");const w=await S.current.fetchRecommendationFromAIPContext({query:C.current.trim(),sessionId:M.current,messageId:e}),L=w?[w]:[];v(L),d.log("[FinalLinkDetectionCheck] โ
Fetched recommendations:",L.length)}catch(w){d.warn("[FinalLinkDetectionCheck] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",w),v([])}})()},[e]);const R=g.useCallback(()=>{d.log("[FinalLinkDetectionCheck] ๐ Performing final link detection...");try{const E=document.getElementById(k.current);if(!E){d.warn("[FinalLinkDetectionCheck] โ Container not found"),h(!0),c();return}const A=new le({autoAddLabels:!0,fireExposurePixels:!0}),w=f.length>0?f:[];d.log(`[FinalLinkDetectionCheck] ๐ Using ${w.length} recommendations for link detection`);const L=A.scanAndProcessLinks(E,w,({exposureUrl:j,adId:I,linkElement:F})=>_({exposureUrl:j,adId:I,linkElement:F}));d.log(`[FinalLinkDetectionCheck] ๐ Final check result: ${L.length} links`),L.length>0?(d.log("[FinalLinkDetectionCheck] โ
Links detected - canceling fallback (no API call)"),x(!0),p.current(L.length)):(d.log("[FinalLinkDetectionCheck] โ ๏ธ No links found - rendering fallback (will make API call)"),x(!1),y.current()),h(!0)}catch{d.error("[FinalLinkDetectionCheck] โ Error during final check"),h(!0),y.current()}},[_,f]);return g.useEffect(()=>{d.log("[FinalLinkDetectionCheck] โณ Setting up listener");const E=je(e,n,()=>{d.log("[FinalLinkDetectionCheck] ๐ฏ Received streamingComplete event"),u(!1),setTimeout(()=>{R()},100)});return()=>{d.log("[FinalLinkDetectionCheck] ๐งน Cleaning up listener"),E()}},[e,n]),l?i.jsx(i.Fragment,{}):m?b?(d.log("[FinalLinkDetectionCheck] ๐ซ Links found - NOT rendering fallback"),i.jsx(i.Fragment,{})):(d.log("[FinalLinkDetectionCheck] โ
No links found - rendering fallback"),i.jsx(i.Fragment,{children:s})):i.jsx(i.Fragment,{})},pt=({messageId:t,children:e,fallbackFormat:n="tail",onLinksDetected:o,onNoLinksDetected:a,onError:r,className:c,query:s,onFallbackChange:m,onWeaveAttempt:h,onWeaveOutcome:l})=>{const{sessionId:u,sdk:b}=U(),x=g.useRef(null),f=`weave-ad-container-${t}`,v=g.useRef(re()),T=g.useRef(!1),p=g.useRef(null),[y,k]=g.useState([]);return g.useEffect(()=>(p.current||(p.current=new le({autoAddLabels:!0,fireExposurePixels:!0})),()=>{p.current&&(p.current.stopWatching(),p.current.clearCache())}),[]),g.useEffect(()=>()=>{v.current.cleanup()},[]),g.useEffect(()=>{(async()=>{if(!b||!(s!=null&&s.trim())||!t){d.log("[WeaveAdFormatContainer] โ ๏ธ Missing SDK, query, or messageId - using pattern-based detection");return}try{d.log("[WeaveAdFormatContainer] ๐ค Fetching recommendations from SDK for brand URL matching");const M=await b.fetchRecommendationFromAIPContext({query:s.trim(),sessionId:u,messageId:t}),C=M?[M]:[];k(C),d.log("[WeaveAdFormatContainer] โ
Fetched recommendations:",C.length)}catch(M){d.warn("[WeaveAdFormatContainer] โ ๏ธ Failed to fetch recommendations, falling back to pattern-based detection:",M),k([])}})()},[b,u,t,s]),g.useEffect(()=>{const S=x.current;if(!S||!p.current)return;const M=p.current,C=({exposureUrl:E,adId:A,linkElement:w})=>{v.current.startTracking({exposureUrl:E,adId:A,linkElement:w,sessionId:u,logPrefix:"[WeaveAdFormatContainer]"})},R=setTimeout(()=>{d.log("[WeaveAdFormatContainer] ๐ Weave injection attempt started"),h==null||h(t);const E=y.length>0?y:[];d.log(`[WeaveAdFormatContainer] ๐ Using ${E.length} recommendations for link detection`);try{const A=M.scanAndProcessLinks(S,E,C);A.length>0&&!T.current?(T.current=!0,d.log(`[WeaveAdFormatContainer] โ
Weave injection succeeded: ${A.length} links detected`),l==null||l(t,!0,`Found ${A.length} links`),o==null||o(A.length),m==null||m(!1)):T.current||d.log("[WeaveAdFormatContainer] โ ๏ธ Weave injection: no links found on initial scan")}catch(A){const w=A instanceof Error?A.message:String(A);d.error(`[WeaveAdFormatContainer] โ Weave injection failed: ${w}`),l==null||l(t,!1,w),a==null||a(),m==null||m(!0)}},100);return M.watchForNewLinks(S,y,C),()=>{clearTimeout(R),M.stopWatching()}},[e,u,t,o,m,h,l,y]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:x,id:f,className:c,"data-weave-ad-format":"true","data-message-id":t,children:e}),s&&i.jsx(ut,{containerId:f,messageId:t,sessionId:u,sdk:b,query:s,onLinksFound:S=>{d.log(`[WeaveAdFormatContainer] โ
Links found (${S}) - no fallback needed`),l==null||l(t,!0,`Found ${S} links in final check`),o==null||o(S),m==null||m(!1)},onNoLinksFound:()=>{d.log("[WeaveAdFormatContainer] โ ๏ธ No links found - rendering fallback"),l==null||l(t,!1,"No links detected in final check"),a==null||a(),m==null||m(!0)},children:i.jsx(Ce,{format:n,messageId:t,query:s,fallback:!0,onError:r})})]})},ht=t=>{const{sdk:e,sessionId:n}=U(),o=g.useRef(!1),a=g.useRef(0),r=g.useRef(!1),c=g.useRef(!1),s=g.useRef(null),m=g.useRef(re());g.useEffect(()=>()=>{m.current.cleanup()},[]);const h=g.useCallback(({exposureUrl:p,adId:y,linkElement:k})=>{m.current.startTracking({exposureUrl:p,adId:y,linkElement:k,sessionId:n,logPrefix:"[useWeaveAdFormat]"})},[n]),l=g.useRef(Date.now()),u=g.useRef(0),b=g.useRef(null),x=g.useRef([]),f=g.useRef(300),v=g.useCallback(async()=>{var p,y,k,S;if(!(!e||!n||o.current)){o.current=!0,a.current=0;try{const M=document.getElementById(t.llmOutputContainerId);if(!M)return;const C=(p=e.getWeaveProcessor)==null?void 0:p.call(e);if(!C)return;const _=C.scanAndProcessLinks(M,[],({exposureUrl:E,adId:A,linkElement:w})=>h({exposureUrl:E,adId:A,linkElement:w}));a.current=_.length;const R=_.length>0;if(R&&!r.current)r.current=!0,(y=t.onLinksDetected)==null||y.call(t,_.length),c.current=!0;else if(!R&&r.current)r.current=!1,c.current=!1;else if(!R&&!c.current){s.current&&clearTimeout(s.current),b.current&&clearInterval(b.current),u.current=0,l.current=Date.now();const E=Math.max(100,f.current/3);b.current=setInterval(()=>{var j;const w=Date.now()-l.current,L=f.current;w>=L?(u.current++,u.current>=2&&(b.current&&(clearInterval(b.current),b.current=null),!r.current&&!c.current&&((j=t.onNoLinksDetected)==null||j.call(t),c.current=!0))):u.current=0},E);const A=Math.max(1500,f.current*5);s.current=setTimeout(()=>{var w;b.current&&(clearInterval(b.current),b.current=null),!r.current&&!c.current&&((w=t.onNoLinksDetected)==null||w.call(t),c.current=!0)},A)}else R&&c.current&&!r.current&&(s.current&&(clearTimeout(s.current),s.current=null),r.current=!0,(k=t.onLinksDetected)==null||k.call(t,_.length),c.current=!0)}catch(M){const C=M instanceof Error?M:new Error(String(M));(S=t.onError)==null||S.call(t,C)}finally{o.current=!1}}},[e,n,t,h]),T=g.useCallback(()=>{const p=x.current;if(p.length<2){f.current=300;return}const y=[];for(let M=1;M<p.length;M++)y.push(p[M]-p[M-1]);const k=y.reduce((M,C)=>M+C,0)/y.length,S=Math.max(100,Math.min(k*3,1e3));f.current=S},[]);return g.useEffect(()=>{const p=document.getElementById(t.llmOutputContainerId);if(!p)return;v();const y=new MutationObserver(()=>{const k=Date.now();l.current=k,u.current=0,x.current.push(k),x.current.length>10&&x.current.shift(),T(),v()});return y.observe(p,{childList:!0,subtree:!0,characterData:!1}),()=>{y.disconnect(),s.current&&clearTimeout(s.current),b.current&&clearInterval(b.current)}},[t.llmOutputContainerId,v,T]),{isProcessing:o.current,detectedLinksCount:a.current,linksFound:r.current,shouldRenderFallback:!r.current&&c.current,processWeaveFormat:v}},gt="1.0.10";exports.AdMeshBadge=Re;exports.AdMeshBridgeFormat=_e;exports.AdMeshContext=ce;exports.AdMeshEcommerceCards=st;exports.AdMeshInlineCard=Ee;exports.AdMeshLayout=Se;exports.AdMeshLinkTracker=X;exports.AdMeshProductCard=de;exports.AdMeshProvider=rt;exports.AdMeshRecommendations=nt;exports.AdMeshRenderer=Me;exports.AdMeshSDK=te;exports.AdMeshSummaryLayout=ke;exports.AdMeshSummaryUnit=ie;exports.AdMeshTailAd=ie;exports.AdMeshTracker=Ae;exports.AdMeshViewabilityTracker=$;exports.STREAMING_COMPLETE_EVENT=ee;exports.STREAMING_START_EVENT=Q;exports.VERSION=gt;exports.WeaveAdFormatContainer=pt;exports.WeaveAdFormatProvider=ot;exports.WeaveFallbackRecommendations=Ce;exports.WeaveResponseProcessor=le;exports.createInlineExposureTracker=re;exports.dispatchStreamingCompleteEvent=lt;exports.dispatchStreamingStartEvent=ct;exports.onStreamingComplete=je;exports.onStreamingStart=mt;exports.useAdMesh=U;exports.useAdMeshContext=we;exports.useAdMeshStyles=ye;exports.useAdMeshTracker=ve;exports.useViewabilityTracker=xe;exports.useWeaveAdFormat=ht;exports.useWeaveAdFormatContext=at;
|
|
988
988
|
//# sourceMappingURL=index.js.map
|