@careerdriver/black-box 1.2.3 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.global.js +1 -1
- package/dist/runtime.global.js.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/runtime.js.map +1 -1
- package/package.json +1 -1
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Panthera Black Box Runtime v1.2.0 - Safe, Declarative Website Control with Periodic Telemetry */
|
|
2
|
-
var w=class{constructor(e){this.runtimeVersion="1.3.0";this.privacyPolicyVersion="2026-03-v2";this.config=null;this.initialized=!1;this.periodicIntervalId=null;this.heartbeatIntervalId=null;this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0};this.configUrl=e.configUrl,this.telemetryUrl=e.telemetryUrl,this._siteId=e.siteId,this._siteId}async init(){if(!this.initialized)try{let e=await fetch(this.configUrl,{method:"GET",headers:{Accept:"application/json"},cache:"no-cache"});if(!e.ok)throw new Error(`Failed to load config: ${e.status}`);let t=await e.json();if(!t.panthera_blackbox||!t.panthera_blackbox.site)throw new Error("Invalid config structure");this.config=t,this.initialized=!0,this.applyConfig(),this.config.panthera_blackbox.telemetry?.emit&&this.startTelemetry()}catch(e){console.error("[Panthera Black Box] Initialization failed:",e)}}applyConfig(){if(!this.config)return;let e=this.config.panthera_blackbox;this.injectSchema(e),this.injectMetaTags(e),this.injectStructureEnhancements(e),this.injectContentEnhancements(e),this.injectContentDepth(e),e.autofill?.enabled&&e.autofill.forms&&this.initializeAutoFill(e),e.ads?.slots&&this.initializeAdSlots(e)}injectSchema(e){if(typeof document>"u")return;document.querySelectorAll('script[type="application/ld+json"][data-panthera]').forEach(i=>i.remove());let n=e.tier??"bronze";this.generateSchemasForTier(e,n).forEach((i,s)=>{let a=document.createElement("script");a.type="application/ld+json",a.setAttribute("data-panthera","true"),a.setAttribute("data-schema-index",s.toString()),a.textContent=JSON.stringify(i),document.head.appendChild(a)})}generateSchemasForTier(e,t){let n=[],r={"@context":"https://schema.org","@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`};if(e.authority_grove?.node&&(r.sameAs=e.authority_grove.node.sameAs,r.keywords=e.authority_grove.node.keywords),n.push(r),(t==="silver"||t==="gold")&&(e.products&&e.products.forEach(s=>{n.push({"@context":"https://schema.org","@type":"Product",name:s.name||e.site.brand,description:s.description,brand:{"@type":"Brand",name:e.site.brand},url:`https://${e.site.domain}`})}),e.services&&e.services.forEach(s=>{n.push({"@context":"https://schema.org","@type":"Service",name:s.name||e.site.brand,description:s.description,provider:{"@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`}})}),e.site.geo&&e.site.geo.length>0&&n.push({"@context":"https://schema.org","@type":"LocalBusiness",name:e.site.brand,url:`https://${e.site.domain}`,areaServed:e.site.geo}),e.faqs)){let i=e.faqs;i.length>0&&n.push({"@context":"https://schema.org","@type":"FAQPage",mainEntity:i.map(s=>({"@type":"Question",name:s.question,acceptedAnswer:{"@type":"Answer",text:s.answer}}))})}return n}injectMetaTags(e){if(typeof document>"u")return;let t=e.seo_enhancements;if(t){if(t.meta_description&&!document.querySelector('meta[name="description"]')){let r=document.createElement("meta");r.setAttribute("name","description"),r.setAttribute("content",t.meta_description),r.setAttribute("data-panthera","true"),document.head.appendChild(r)}if(t.canonical_enabled&&!document.querySelector('link[rel="canonical"]')){let r=document.createElement("link");r.setAttribute("rel","canonical"),r.setAttribute("href",window.location.href),r.setAttribute("data-panthera","true"),document.head.appendChild(r)}}}injectContentEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_enhancements;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let r=document.createElement("section");if(r.setAttribute("data-panthera","true"),r.setAttribute("data-panthera-type","ai-readiness"),r.setAttribute("aria-hidden","true"),r.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;",t.what){let i=document.createElement("div");i.textContent=t.what,r.appendChild(i)}if(t.who){let i=document.createElement("div");i.textContent=t.who,r.appendChild(i)}if(t.how){let i=document.createElement("div");i.textContent=t.how,r.appendChild(i)}if(t.trust){let i=document.createElement("div");i.textContent=t.trust,r.appendChild(i)}n.appendChild(r)}injectContentDepth(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_depth;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let r=n.querySelectorAll("h2").length,i=t.min_h2_count||6,a=(n.textContent||"").length,l=Math.max(0,6e3-a),o=document.createElement("section");o.setAttribute("data-panthera","true"),o.setAttribute("data-panthera-type","content-depth"),o.setAttribute("aria-hidden","true"),o.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;";let d=0,h=Math.max(0,i-r);for(let u=0;u<h||d<l;u++){let g=document.createElement("h2");g.textContent=t.h2_templates?.[u]||`Section ${u+1}`,o.appendChild(g),d+=g.textContent.length;let p=t.content_templates?.[u]||t.default_content||"This section provides additional context and information for AI search engines. Our platform helps businesses optimize their online presence and improve visibility in AI-powered search results. We provide comprehensive solutions that enhance content discoverability and ensure your website is properly structured for modern search technologies.",b=p.length,f=Math.ceil((l-d)/b)||1;for(let m=0;m<Math.max(1,f)&&d<l;m++){let S=document.createElement("p");S.textContent=p,o.appendChild(S),d+=p.length}}o.children.length>0&&n.appendChild(o)}injectStructureEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.structure_enhancements;if(t){if(t.inject_h1_if_missing&&!document.querySelector("h1")&&t.h1_text){let r=document.body;if(r){let i=document.createElement("h1");i.textContent=t.h1_text,i.setAttribute("data-panthera","true");let s=r.firstElementChild;s?r.insertBefore(i,s):r.appendChild(i)}}if(t.enhance_title){let n=document.querySelector("title"),r=n?.textContent||"",i=t.min_title_length||30;if(r.length<i&&t.title_template){let s=t.title_template.replace("{brand}",e.site.brand);if(n)n.textContent=s,n.setAttribute("data-panthera-enhanced","true");else{let a=document.createElement("title");a.textContent=s,a.setAttribute("data-panthera","true"),document.head.appendChild(a)}}}}}initializeAutoFill(e){typeof window>"u"||!e.autofill?.forms||e.autofill.forms.forEach(t=>{let n=document.querySelector(t.selector);n&&(n.pantheraAutoFill=t,n.addEventListener("focusin",r=>{let i=r.target;(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="SELECT")&&this.triggerAutoFill(t)},{once:!0}))})}async triggerAutoFill(e){let t={},n=document.querySelector(e.selector);if(n)for(let[r,i]of Object.entries(e.map)){let s=n.querySelector(i);s&&t[r]&&(s.value=t[r],s.dispatchEvent(new Event("input",{bubbles:!0})))}}initializeAdSlots(e){typeof window>"u"||!e.ads?.slots||e.ads.slots.forEach(t=>{let n=String(t.id||"").trim();if(n=n.replace(/["']/g,""),n=n.trim(),!!n)try{let r=n.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\$&");if(r.includes('"')||r.includes("'"))throw new Error(`Slot ID contains quotes after sanitization: ${r}`);let i=`[data-ad-slot="${r}"]`,s=document.querySelector(i);s&&(s.pantheraAdSlot=t,this.loadAdCreative(t))}catch(r){console.error(`[Panthera Black Box] Invalid ad slot selector for ID: ${t.id}`,r)}})}async loadAdCreative(e){console.debug("[Panthera Black Box] Ad slot initialized:",e.id)}startTelemetry(){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(this.sendTelemetry("page_view",{url:window.location.href,referrer:document.referrer}),typeof window<"u"){let n=null,r=()=>{let l=Date.now(),o=l-this.periodicState.lastActivityAt;if(o>0){let d=Math.min(o,1e3);this.periodicState.activeTimeMs+=d,o>d&&(this.periodicState.idleTimeMs+=o-d)}this.periodicState.lastActivityAt=l},i=l=>{if(r(),typeof window<"u"){let o=Math.max(document.documentElement.scrollTop||0,document.body.scrollTop||0),d=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,1),h=window.innerHeight||0,u=Math.min(1,(o+h)/d);this.periodicState.scrollDepthMax=Math.max(this.periodicState.scrollDepthMax,u)}if(l&&l.type==="click"){let d=l.target?.closest('a,button,[role="button"],input[type="submit"]'),h=d?.textContent?.trim()||"";if(h&&/buy|start|book|contact|get demo|sign up|trial|pricing/i.test(h)&&this.periodicState.ctaClicks.push(h.slice(0,80)),d?.tagName.toLowerCase()==="a"){let u=d.href;try{let g=new URL(u,window.location.href);g.origin!==window.location.origin&&this.periodicState.outboundClicks.push(g.href)}catch{}}}n||(n=window.setTimeout(()=>{this.sendTelemetry("interaction",{timestamp:new Date().toISOString()}),n=null},1e3))};document.addEventListener("click",l=>i(l),{passive:!0}),document.addEventListener("scroll",l=>i(l),{passive:!0}),document.addEventListener("mousemove",r,{passive:!0}),document.addEventListener("keydown",r,{passive:!0});let s=0,a=0,c="";document.addEventListener("click",l=>{let d=(l.target?.textContent||"").trim().slice(0,80),h=Date.now();if(h-s>1500||d!==c){s=h,a=1,c=d;return}a+=1,a>=4&&(this.periodicState.rageClicks+=1,a=0)},{passive:!0}),window.addEventListener("error",l=>{this.periodicState.jsErrorsCount+=1;let o=String(l.message||"unknown-js-error").slice(0,120);this.periodicState.errorSignatures.push(o),this.periodicState.errorSignatures.length>20&&this.periodicState.errorSignatures.shift()}),window.addEventListener("unhandledrejection",()=>{this.periodicState.jsErrorsCount+=1}),window.addEventListener("error",l=>{l.target&&l.message===""&&(this.periodicState.resourceFailures+=1)},!0)}let e=this.config.panthera_blackbox.telemetry.periodic;if((e?.enabled??!0)&&typeof window<"u"){let n=e?.intervalMs||3e5;this.periodicIntervalId!==null&&window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=window.setInterval(()=>{this.sendPeriodicTelemetry()},n),window.setTimeout(()=>{this.sendPeriodicTelemetry()},1e3),this.setupCleanup()}else typeof window<"u"&&(this.heartbeatIntervalId!==null&&window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=window.setInterval(()=>{this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()})},3e5),this.setupCleanup())}setupCleanup(){if(typeof window>"u")return;let e=()=>{this.periodicIntervalId!==null&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.heartbeatIntervalId!==null&&(window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.hidden&&(this.config?.panthera_blackbox.telemetry?.periodic?.enabled??!0?this.sendPeriodicTelemetry():this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()}))})}hashString(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}redactText(e){let t=e,n=t;return t=t.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi,"[redacted-email]"),t=t.replace(/\\+?\\d[\\d\\s().-]{7,}\\d/g,"[redacted-phone]"),t=t.replace(/\\b(name|full name|first name|last name)\\s*[:=-]?\\s*[a-z ,.'-]{2,}/gi,"$1:[redacted-name]"),{value:t,redacted:t!==n}}buildSamplingMeta(e,t,n){return e>0||t>0||this.periodicState.jsErrorsCount>0?{tier:"critical",reason:"Detected friction or technical issues"}:n>0||this.periodicState.pageViews>20?{tier:"full",reason:"Coverage gaps or high activity"}:{tier:"sampled",reason:"Healthy low-risk traffic sample"}}getConfigFrameworkVersion(){let e=this.config?.panthera_blackbox?.ai_readability?.frameworkVersion;return typeof e=="string"&&e.trim().length>0?e:void 0}getActiveReadabilityActionIds(e=3){let t=this.config?.panthera_blackbox?.ai_readability?.recommendedActions;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"&&n.trim().length>0).slice(0,e):[]}buildJourneyContext(){let e=this.periodicState.pageHistory,t=e[0]?.url,n=e[e.length-1]?.url,r=e.map(c=>c.url).filter(Boolean).slice(0,25),i=0,s=0,a=new Set;for(let c=0;c<r.length;c++)a.has(r[c])&&i++,a.add(r[c]),c>1&&r[c]===r[c-2]&&s++;return{entryUrl:t,exitUrl:n,path:r,stepCount:r.length,timeOnPathMs:e.length>1?e[e.length-1].timestamp-e[0].timestamp:0,loops:i,backtracks:s,stallPoints:this.detectDeadEnds().map(c=>c.url).slice(0,5)}}buildIntentSignals(){let e=this.detectIntent(),t=[{intent:e,confidence:.7},{intent:this.detectFunnelStage()==="decision"?"pricing":"general",confidence:.45},{intent:"support",confidence:.2}],n=["url_pattern","keyword_match"];return typeof document<"u"&&document.querySelectorAll('a[href*="demo"],button').length>0&&n.push("cta_match"),typeof document<"u"&&document.querySelectorAll('script[type="application/ld+json"]').length>0&&n.push("schema_hint"),{detectedIntent:e,confidence:t[0].confidence,topCandidates:t,reasonFlags:n}}buildSearchDiagnostics(e){let t=this.periodicState.searchQueries[this.periodicState.searchQueries.length-1]?.query,n=i=>{let s=i.toLowerCase();return s.includes("price")||s.includes("pricing")||s.includes("cost")?"price":s.includes("compare")||s.includes("vs")||s.includes("alternative")?"compare":s.includes("support")||s.includes("error")||s.includes("help")?"support":s.split(" ").length<=2?"nav":"info"},r=this.periodicState.searchQueries.map(i=>i.query).slice(-5);return{query:t,queryHash:t?this.hashString(t.toLowerCase()):void 0,queryClass:t?n(t):void 0,reformulations:r,zeroResultHints:e.length>0?["Repeated searches may indicate weak or missing answers"]:[],repeatedQueryFingerprint:e.length>0?this.hashString(e.map(i=>i.query).join("|")):void 0}}buildPageQualityContext(){if(typeof document>"u")return{};let e=document.body?.textContent||"",t=e.split(/\\s+/).filter(Boolean).length||1,n=Math.max(1,e.split(/[.!?]+/).filter(Boolean).length),r=Math.max(0,Math.min(1,1-Math.min(1,t/n/35))),i=document.querySelectorAll('a[href*="contact"],a[href*="pricing"],button').length>0,s=document.querySelectorAll("a").length,a=Array.from(document.querySelectorAll("a")).filter(d=>(d.textContent||"").trim().length>5).length,c=s>0?a/s:.5,l=document.querySelectorAll('script[type="application/ld+json"]').length>0,o=l&&/faq/i.test(e);return{readabilityScore:r,aboveFoldClarity:i?.8:.45,ctaPresence:i,linkClarityScore:c,schemaPresence:{jsonLd:l,faq:o},faqPresence:o}}buildTechnicalSignals(){let e=this.periodicState.jsErrorsCount>0?"needs-attention":"healthy";return{jsErrorsCount:this.periodicState.jsErrorsCount,errorSignatures:this.periodicState.errorSignatures.slice(-8),resourceFailures:this.periodicState.resourceFailures,lcpBucket:e,fidBucket:this.periodicState.rageClicks>0?"needs-attention":"healthy",clsBucket:"unknown",routeTransitionMsBucket:"unknown"}}applyPrivacy(e){let t=[],n=!1;if(e.search?.query){let i=this.redactText(e.search.query);i.redacted&&(n=!0),e.search.query=i.value,t.push(`search.query:${this.hashString(i.value.toLowerCase())}`)}if(e.page?.title){let i=this.redactText(e.page.title);i.redacted&&(n=!0),e.page.title=i.value,t.push(`page.title:${this.hashString(i.value.toLowerCase())}`)}let r=e.context||void 0;if(r&&typeof r=="object"){let i=s=>{let a=r[s];if(typeof a!="string")return;let c=this.redactText(a);r[s]=c.value,c.redacted&&(n=!0),t.push(`${s}:${this.hashString(c.value.toLowerCase())}`)};i("search_query"),i("query"),i("url"),r.privacy={redactionApplied:n,hashedFields:t.slice(0,12),policyVersion:this.privacyPolicyVersion},e.context=r}return e}async sendTelemetry(e,t){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(e==="page_view")this.periodicState.pageViews++,typeof window<"u"&&(this.periodicState.pageHistory.push({url:window.location.href,path:window.location.pathname,title:document.title,intent:this.detectIntent(),funnelStage:this.detectFunnelStage(),timestamp:Date.now()}),this.periodicState.pageHistory.length>50&&this.periodicState.pageHistory.shift());else if(e==="interaction")this.periodicState.interactions++;else if(e==="search"){this.periodicState.searches++;let p=t.search?.query||t.context?.search_query;p&&(this.periodicState.searchQueries.push({query:p,timestamp:Date.now()}),this.periodicState.searchQueries.length>50&&this.periodicState.searchQueries.shift())}let{page:n,search:r,...i}=t,s=this.getSessionId(),a=e==="page_view",c=n||(a&&typeof window<"u"?{url:window.location.href,path:window.location.pathname,title:document.title}:void 0),l=i.search_query||i.query,o=i.results_count,d=i.selected_result,h=e==="search"?r||(l?{query:l,results_count:o,selected_result:d}:void 0):void 0,u={event_type:e,...i};a&&(u.intent===void 0&&(u.intent=this.detectIntent()),u.funnelStage===void 0&&(u.funnelStage=this.detectFunnelStage())),u.captureMeta===void 0&&(u.captureMeta={runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion()});let g=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:["page_view","interaction","search"].includes(e)?e:"custom",session_id:s,page:c,search:h,context:Object.keys(u).length>0?u:void 0,metrics:this.collectMetrics()});try{if(navigator.sendBeacon){let p=new Blob([JSON.stringify(g)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,p)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),keepalive:!0})}catch(p){console.debug("[Panthera Black Box] Telemetry failed:",p)}}async sendPeriodicTelemetry(){if(this.config?.panthera_blackbox.telemetry?.emit&&!(typeof window>"u"))try{let e=Date.now(),t=e-this.periodicState.lastSent,n=this.collectMetrics(),r=this.detectRepeatedSearches(),i=this.detectDeadEnds(),s=this.detectDropOffs(),a=this.buildJourneyContext(),c=this.buildIntentSignals(),l={scrollDepthMax:this.periodicState.scrollDepthMax,activeTimeMs:this.periodicState.activeTimeMs,idleTimeMs:this.periodicState.idleTimeMs,ctaClicks:this.periodicState.ctaClicks.slice(-10),outboundClicks:this.periodicState.outboundClicks.slice(-10),rageClicks:this.periodicState.rageClicks},o=this.buildSearchDiagnostics(r),d=this.buildPageQualityContext(),h=this.buildTechnicalSignals(),u=this.detectContentGaps(),g=this.detectFunnelStage(),p=this.detectIntent(),b={what:u.includes("what"),who:u.includes("who"),how:u.includes("how"),trust:u.includes("trust")},f=[];i.length>0&&f.push("Add clear next-step links and calls-to-action on dead-end pages."),r.length>0&&f.push("Improve clarity for repeated search topics with dedicated sections and internal links."),u.length>0&&f.push(`Fill missing content dimensions: ${u.join(", ")}.`);let m=this.buildSamplingMeta(i.length,s.length,u.length),S=this.getActiveReadabilityActionIds(),k={periodic:!0,timeSinceLastSend:t,aggregated:{pageViews:this.periodicState.pageViews,interactions:this.periodicState.interactions,searches:this.periodicState.searches},confusion:{repeatedSearches:r.length,deadEnds:i.length,dropOffs:s.length,repeatedSearchesDetail:r.slice(0,10),deadEndsDetail:i.slice(0,10),dropOffsDetail:s.slice(0,10)},coverage:{contentGaps:u.length,contentGapsDetail:u,funnelStage:g,intent:p,page:{url:window.location.href,path:window.location.pathname,title:document.title},missingContentDimensions:b,pageMetadata:{hasJsonLd:document.querySelectorAll('script[type="application/ld+json"]').length>0,h1Count:document.querySelectorAll("h1").length,h2Count:document.querySelectorAll("h2").length,textLength:document.body?.textContent?.length||0},recommendedFocus:f.slice(0,3)},journey:a,intentSignals:c,engagement:l,searchDiagnostics:o,pageQuality:d,technicalSignals:h,recommendationFeedback:{recommendationId:`rec-${this.detectFunnelStage()}`,exposed:!0,reachedNextStep:s.length===0&&i.length===0,activeReadabilityActionIds:S},captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:m.tier,samplingReason:m.reason},intent:p,funnelStage:g},x=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"custom",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:k,metrics:n});if(navigator.sendBeacon){let v=new Blob([JSON.stringify(x)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,v)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),keepalive:!0});let C=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"page_view",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:{periodic:!0,heartbeat:!0,captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:m.tier,samplingReason:m.reason},aggregatedMetrics:n,aggregatedPageViews:this.periodicState.pageViews,aggregatedInteractions:this.periodicState.interactions,aggregatedSearches:this.periodicState.searches},metrics:n});if(navigator.sendBeacon){let v=new Blob([JSON.stringify(C)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,v)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C),keepalive:!0});this.periodicState.pageViews=0,this.periodicState.interactions=0,this.periodicState.searches=0,this.periodicState.lastSent=e,this.periodicState.ctaClicks=[],this.periodicState.outboundClicks=[],this.periodicState.rageClicks=0,this.periodicState.scrollDepthMax=0,this.periodicState.activeTimeMs=0,this.periodicState.idleTimeMs=0,this.periodicState.jsErrorsCount=0,this.periodicState.errorSignatures=[],this.periodicState.resourceFailures=0}catch(e){console.debug("[Panthera Black Box] Periodic telemetry failed:",e)}}detectRepeatedSearches(){let e=new Map;this.periodicState.searchQueries.forEach(({query:n})=>{e.set(n,(e.get(n)||0)+1)});let t=[];return e.forEach((n,r)=>{n>1&&t.push({query:r,count:n,intent:this.detectIntent(),funnelStage:this.detectFunnelStage()})}),t}detectDeadEnds(){let e=[];if(this.periodicState.pageHistory.length<2)return e;for(let i=0;i<this.periodicState.pageHistory.length-1;i++){let s=this.periodicState.pageHistory[i],c=this.periodicState.pageHistory[i+1].timestamp-s.timestamp;c>6e4&&e.push({url:s.url,path:s.path,title:s.title,at:new Date(s.timestamp).toISOString(),dwellMs:c,reason:"No next meaningful action within expected time window"})}let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],r=Date.now()-n.timestamp;return r>6e4&&e.push({url:n.url,path:n.path,title:n.title,at:new Date(n.timestamp).toISOString(),dwellMs:r,reason:"Session stalled after page view"}),e}detectDropOffs(){let e=[];if(this.periodicState.pageViews+this.periodicState.interactions+this.periodicState.searches<=2&&this.periodicState.pageHistory.length>0){let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],r=this.getSessionId();r&&e.push({sessionId:r,lastEvent:new Date(n.timestamp).toISOString(),lastUrl:n.url,stage:n.funnelStage,intent:n.intent})}return e}detectContentGaps(){if(typeof document>"u")return[];let e=[],t=document.body;if(!t)return e;let n=t.textContent?.toLowerCase()||"",r=this.config?.panthera_blackbox.seo_enhancements?.content_enhancements;return!r?.what&&!n.includes("what")&&!n.includes("do")&&e.push("what"),!r?.who&&!n.includes("who")&&!n.includes("for")&&e.push("who"),!r?.how&&!n.includes("how")&&!n.includes("work")&&e.push("how"),!r?.trust&&!n.includes("trust")&&!n.includes("certified")&&e.push("trust"),e}detectFunnelStage(){if(typeof window>"u")return"awareness";let e=window.location.href.toLowerCase(),t=window.location.pathname.toLowerCase();return e.includes("pricing")||e.includes("signup")||e.includes("checkout")||t.includes("pricing")?"decision":e.includes("docs")||e.includes("case-study")||e.includes("guides")||t.includes("docs")?"consideration":e.includes("support")||e.includes("account")||e.includes("dashboard")||t.includes("account")?"retention":"awareness"}detectIntent(){if(typeof window>"u")return"general";let e=window.location.href.toLowerCase(),t=document.title?.toLowerCase()||"",n=`${e} ${t}`;return n.includes("pricing")?"pricing":n.includes("demo")?"demo":n.includes("docs")?"docs":n.includes("case study")?"case-study":"general"}collectMetrics(){let e={},t=this.config?.panthera_blackbox.telemetry?.keys||[],n=["ts.authority","ai.schemaCompleteness","ai.structuredDataQuality","ai.authoritySignals","ai.searchVisibility"];return new Set([...t,...n]).forEach(i=>{i.startsWith("ai.")?i==="ai.schemaCompleteness"?e[i]=this.calculateSchemaCompleteness():i==="ai.structuredDataQuality"?e[i]=this.calculateStructuredDataQuality():i==="ai.authoritySignals"?e[i]=this.calculateAuthoritySignals():i==="ai.searchVisibility"?e[i]=this.calculateSearchVisibility():e[i]=.6+Math.random()*.35:i.startsWith("ts.")?i==="ts.authority"?e[i]=this.calculateAuthorityScore():e[i]=.5+Math.random()*.4:e[i]=0}),e}calculateSchemaCompleteness(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]'),t=document.querySelectorAll('script[type="application/ld+json"][data-panthera]'),n=0;e.length>0&&(n=.3),t.length>0&&(n=.5);let r=new Set;return e.forEach(i=>{try{let s=i.textContent;if(s){let a=JSON.parse(s);a["@type"]&&r.add(a["@type"])}}catch{}}),n+=Math.min(.5,r.size*.1),Math.min(1,n)}calculateStructuredDataQuality(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length===0)return 0;let t=0,n=0,r=0;if(e.forEach(c=>{try{let l=c.textContent;if(!l)return;let o=JSON.parse(l);if(!o["@context"]||!o["@type"])return;t++;let d=Object.keys(o);n+=d.length;let h=o["@type"];h==="Organization"&&o.name&&o.url?r+=2:(h==="Product"&&o.name||h==="Service"&&o.name||h==="FAQPage"&&Array.isArray(o.mainEntity))&&(r+=1)}catch{}}),t===0)return 0;let i=Math.min(.5,t*.25),s=Math.min(.3,n/t/10),a=Math.min(.2,r*.1);return Math.min(1,i+s+a)}calculateAuthoritySignals(){if(typeof document>"u")return 0;let e=0,t=document.body;if(!t)return 0;let n=t.textContent?.toLowerCase()||"",i=["certified","award","trusted","verified","accredited","licensed"].filter(c=>n.includes(c));e+=Math.min(.3,i.length*.05);let a=["review","testimonial","rating","star","customer"].filter(c=>n.includes(c));if(e+=Math.min(.3,a.length*.05),this.config?.panthera_blackbox.authority_grove?.node?.sameAs){let c=this.config.panthera_blackbox.authority_grove.node.sameAs.length;e+=Math.min(.4,c*.1)}return Math.min(1,e)}calculateSearchVisibility(){if(typeof document>"u")return 0;let e=0,t=document.querySelector('meta[name="description"]');t&&t.getAttribute("content")&&t.getAttribute("content").length>50&&(e+=.2);let n=document.querySelector("title");n&&n.textContent&&n.textContent.length>30&&(e+=.2);let r=document.querySelector("h1");r&&r.textContent&&(e+=.2),document.querySelectorAll('script[type="application/ld+json"]').length>0&&(e+=.2);let s=document.querySelectorAll("h2"),a=document.body?.textContent?.length||0;return s.length>=3&&a>1e3&&(e+=.2),Math.min(1,e)}calculateAuthorityScore(){if(!this.config?.panthera_blackbox.authority_grove?.node)return .5;let e=this.config.panthera_blackbox.authority_grove.node,t=.3;return e.sameAs&&e.sameAs.length>0&&(t+=Math.min(.4,e.sameAs.length*.1)),e.keywords&&e.keywords.length>0&&(t+=Math.min(.3,e.keywords.length*.05)),Math.min(1,t)}getSessionId(){if(typeof window>"u")return;let e=window.sessionStorage,t=window.localStorage,n="panthera_session_id",r="panthera_session_ts",i=Date.now(),s=1800*1e3,a=d=>{if(!d)return null;try{let h=d.getItem(n),u=Number(d.getItem(r)||0);if(h&&u&&i-u<s)return d.setItem(r,String(i)),h}catch{return null}return null},c=(d,h)=>{if(!d)return!1;try{return d.setItem(n,h),d.setItem(r,String(i)),!0}catch{return!1}},l=a(e)||a(t);if(l)return l;if(this.memorySessionId&&this.memorySessionTs&&i-this.memorySessionTs<s)return this.memorySessionTs=i,this.memorySessionId;let o=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${i}-${Math.random().toString(16).slice(2)}`;return c(e,o)||c(t,o),this.memorySessionId=o,this.memorySessionTs=i,o}getConfig(){return this.config}async reload(){this.periodicIntervalId!==null&&typeof window<"u"&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0},this.initialized=!1,await this.init()}};(function(){if(typeof window>"u")return;let y=document.currentScript;if(!y)return;let e=y.getAttribute("data-config-url"),t=y.getAttribute("data-telemetry-url"),n=y.getAttribute("data-site-id");if(!e||!t||!n){console.warn("[Panthera Black Box] Missing required data attributes");return}let r=new w({configUrl:e,telemetryUrl:t,siteId:n});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>r.init()):r.init(),window.PantheraBlackBox=w,window.panthera=r})();var A=w;export{w as PantheraBlackBox,A as default};
|
|
2
|
+
var w=class{constructor(e){this.runtimeVersion="1.4.0";this.privacyPolicyVersion="2026-03-v2";this.config=null;this.initialized=!1;this.periodicIntervalId=null;this.heartbeatIntervalId=null;this.routeTrackingInstalled=!1;this.webVitalsTrackingInstalled=!1;this.startedForms=new Set;this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0,routeChanges:0,formStarts:0,formSubmits:0,formAbandons:0,webVitals:{}};this.configUrl=e.configUrl,this.telemetryUrl=e.telemetryUrl,this._siteId=e.siteId,this._siteId}async init(){if(!this.initialized)try{let e=await fetch(this.configUrl,{method:"GET",headers:{Accept:"application/json"},cache:"no-cache"});if(!e.ok)throw new Error(`Failed to load config: ${e.status}`);let t=await e.json();if(!t.panthera_blackbox||!t.panthera_blackbox.site)throw new Error("Invalid config structure");this.config=t,this.initialized=!0,this.applyConfig(),this.config.panthera_blackbox.telemetry?.emit&&this.startTelemetry()}catch(e){console.error("[Panthera Black Box] Initialization failed:",e)}}applyConfig(){if(!this.config)return;let e=this.config.panthera_blackbox;e.frontend_mode==="context_only"||e.invisible_context_only===!0||(this.injectSchema(e),this.injectMetaTags(e),this.injectStructureEnhancements(e),this.injectContentEnhancements(e),this.injectContentDepth(e),e.autofill?.enabled&&e.autofill.forms&&this.initializeAutoFill(e),e.ads?.slots&&this.initializeAdSlots(e))}injectSchema(e){if(typeof document>"u")return;document.querySelectorAll('script[type="application/ld+json"][data-panthera]').forEach(r=>r.remove());let n=e.tier??"bronze";this.generateSchemasForTier(e,n).forEach((r,a)=>{let s=document.createElement("script");s.type="application/ld+json",s.setAttribute("data-panthera","true"),s.setAttribute("data-schema-index",a.toString()),s.textContent=JSON.stringify(r),document.head.appendChild(s)})}generateSchemasForTier(e,t){let n=[],i={"@context":"https://schema.org","@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`};if(e.authority_grove?.node&&(i.sameAs=e.authority_grove.node.sameAs,i.keywords=e.authority_grove.node.keywords),n.push(i),(t==="silver"||t==="gold")&&(e.products&&e.products.forEach(a=>{n.push({"@context":"https://schema.org","@type":"Product",name:a.name||e.site.brand,description:a.description,brand:{"@type":"Brand",name:e.site.brand},url:`https://${e.site.domain}`})}),e.services&&e.services.forEach(a=>{n.push({"@context":"https://schema.org","@type":"Service",name:a.name||e.site.brand,description:a.description,provider:{"@type":"Organization",name:e.site.brand,url:`https://${e.site.domain}`}})}),e.site.geo&&e.site.geo.length>0&&n.push({"@context":"https://schema.org","@type":"LocalBusiness",name:e.site.brand,url:`https://${e.site.domain}`,areaServed:e.site.geo}),e.faqs)){let r=e.faqs;r.length>0&&n.push({"@context":"https://schema.org","@type":"FAQPage",mainEntity:r.map(a=>({"@type":"Question",name:a.question,acceptedAnswer:{"@type":"Answer",text:a.answer}}))})}return n}injectMetaTags(e){if(typeof document>"u")return;let t=e.seo_enhancements;if(t){if(t.meta_description&&!document.querySelector('meta[name="description"]')){let i=document.createElement("meta");i.setAttribute("name","description"),i.setAttribute("content",t.meta_description),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}if(t.canonical_enabled&&!document.querySelector('link[rel="canonical"]')){let i=document.createElement("link");i.setAttribute("rel","canonical"),i.setAttribute("href",window.location.href),i.setAttribute("data-panthera","true"),document.head.appendChild(i)}}}injectContentEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_enhancements;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let i=document.createElement("section");if(i.setAttribute("data-panthera","true"),i.setAttribute("data-panthera-type","ai-readiness"),i.setAttribute("aria-hidden","true"),i.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;",t.what){let r=document.createElement("div");r.textContent=t.what,i.appendChild(r)}if(t.who){let r=document.createElement("div");r.textContent=t.who,i.appendChild(r)}if(t.how){let r=document.createElement("div");r.textContent=t.how,i.appendChild(r)}if(t.trust){let r=document.createElement("div");r.textContent=t.trust,i.appendChild(r)}n.appendChild(i)}injectContentDepth(e){if(typeof document>"u")return;let t=e.seo_enhancements?.content_depth;if(!t||!t.enabled)return;let n=document.body;if(!n)return;let i=n.querySelectorAll("h2").length,r=t.min_h2_count||6,s=(n.textContent||"").length,l=Math.max(0,6e3-s),c=document.createElement("section");c.setAttribute("data-panthera","true"),c.setAttribute("data-panthera-type","content-depth"),c.setAttribute("aria-hidden","true"),c.style.cssText="position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;";let d=0,u=Math.max(0,r-i);for(let h=0;h<u||d<l;h++){let p=document.createElement("h2");p.textContent=t.h2_templates?.[h]||`Section ${h+1}`,c.appendChild(p),d+=p.textContent.length;let m=t.content_templates?.[h]||t.default_content||"This section provides additional context and information for AI search engines. Our platform helps businesses optimize their online presence and improve visibility in AI-powered search results. We provide comprehensive solutions that enhance content discoverability and ensure your website is properly structured for modern search technologies.",y=m.length,b=Math.ceil((l-d)/y)||1;for(let f=0;f<Math.max(1,b)&&d<l;f++){let g=document.createElement("p");g.textContent=m,c.appendChild(g),d+=m.length}}c.children.length>0&&n.appendChild(c)}injectStructureEnhancements(e){if(typeof document>"u")return;let t=e.seo_enhancements?.structure_enhancements;if(t){if(t.inject_h1_if_missing&&!document.querySelector("h1")&&t.h1_text){let i=document.body;if(i){let r=document.createElement("h1");r.textContent=t.h1_text,r.setAttribute("data-panthera","true");let a=i.firstElementChild;a?i.insertBefore(r,a):i.appendChild(r)}}if(t.enhance_title){let n=document.querySelector("title"),i=n?.textContent||"",r=t.min_title_length||30;if(i.length<r&&t.title_template){let a=t.title_template.replace("{brand}",e.site.brand);if(n)n.textContent=a,n.setAttribute("data-panthera-enhanced","true");else{let s=document.createElement("title");s.textContent=a,s.setAttribute("data-panthera","true"),document.head.appendChild(s)}}}}}initializeAutoFill(e){typeof window>"u"||!e.autofill?.forms||e.autofill.forms.forEach(t=>{let n=document.querySelector(t.selector);n&&(n.pantheraAutoFill=t,n.addEventListener("focusin",i=>{let r=i.target;(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.tagName==="SELECT")&&this.triggerAutoFill(t)},{once:!0}))})}async triggerAutoFill(e){let t={},n=document.querySelector(e.selector);if(n)for(let[i,r]of Object.entries(e.map)){let a=n.querySelector(r);a&&t[i]&&(a.value=t[i],a.dispatchEvent(new Event("input",{bubbles:!0})))}}initializeAdSlots(e){typeof window>"u"||!e.ads?.slots||e.ads.slots.forEach(t=>{let n=String(t.id||"").trim();if(n=n.replace(/["']/g,""),n=n.trim(),!!n)try{let i=n.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g,"\\$&");if(i.includes('"')||i.includes("'"))throw new Error(`Slot ID contains quotes after sanitization: ${i}`);let r=`[data-ad-slot="${i}"]`,a=document.querySelector(r);a&&(a.pantheraAdSlot=t,this.loadAdCreative(t))}catch(i){console.error(`[Panthera Black Box] Invalid ad slot selector for ID: ${t.id}`,i)}})}async loadAdCreative(e){console.debug("[Panthera Black Box] Ad slot initialized:",e.id)}startTelemetry(){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(this.sendTelemetry("page_view",{url:window.location.href,referrer:document.referrer}),typeof window<"u"){let n=null,i=()=>{let l=Date.now(),c=l-this.periodicState.lastActivityAt;if(c>0){let d=Math.min(c,1e3);this.periodicState.activeTimeMs+=d,c>d&&(this.periodicState.idleTimeMs+=c-d)}this.periodicState.lastActivityAt=l},r=l=>{if(i(),typeof window<"u"){let c=Math.max(document.documentElement.scrollTop||0,document.body.scrollTop||0),d=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,1),u=window.innerHeight||0,h=Math.min(1,(c+u)/d);this.periodicState.scrollDepthMax=Math.max(this.periodicState.scrollDepthMax,h)}if(l&&l.type==="click"){let d=l.target?.closest('a,button,[role="button"],input[type="submit"]'),u=d?.textContent?.trim()||"";if(u&&/buy|start|book|contact|get demo|sign up|trial|pricing/i.test(u)&&this.periodicState.ctaClicks.push(this.safeText(u,80)),d?.tagName.toLowerCase()==="a"){let h=d.href;try{let p=new URL(h,window.location.href);p.origin!==window.location.origin&&this.periodicState.outboundClicks.push(this.sanitizeUrlForTelemetry(p.href))}catch{}}}n||(n=window.setTimeout(()=>{this.sendTelemetry("interaction",{timestamp:new Date().toISOString()}),n=null},1e3))};document.addEventListener("click",l=>r(l),{passive:!0}),document.addEventListener("scroll",l=>r(l),{passive:!0}),document.addEventListener("mousemove",i,{passive:!0}),document.addEventListener("keydown",i,{passive:!0}),document.addEventListener("focusin",l=>this.trackFormStart(l),{passive:!0}),document.addEventListener("submit",()=>{this.periodicState.formSubmits+=1},{passive:!0});let a=0,s=0,o="";document.addEventListener("click",l=>{let d=(l.target?.textContent||"").trim().slice(0,80),u=Date.now();if(u-a>1500||d!==o){a=u,s=1,o=d;return}s+=1,s>=4&&(this.periodicState.rageClicks+=1,s=0)},{passive:!0}),window.addEventListener("error",l=>{this.periodicState.jsErrorsCount+=1;let c=String(l.message||"unknown-js-error").slice(0,120);this.periodicState.errorSignatures.push(c),this.periodicState.errorSignatures.length>20&&this.periodicState.errorSignatures.shift()}),window.addEventListener("unhandledrejection",()=>{this.periodicState.jsErrorsCount+=1}),window.addEventListener("error",l=>{l.target&&l.message===""&&(this.periodicState.resourceFailures+=1)},!0),this.setupRouteTracking(),this.setupWebVitalsTracking()}let e=this.config.panthera_blackbox.telemetry.periodic;if((e?.enabled??!0)&&typeof window<"u"){let n=e?.intervalMs||3e5;this.periodicIntervalId!==null&&window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=window.setInterval(()=>{this.sendPeriodicTelemetry()},n),window.setTimeout(()=>{this.sendPeriodicTelemetry()},1e3),this.setupCleanup()}else typeof window<"u"&&(this.heartbeatIntervalId!==null&&window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=window.setInterval(()=>{this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()})},3e5),this.setupCleanup())}setupCleanup(){if(typeof window>"u")return;let e=()=>{this.periodicIntervalId!==null&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.heartbeatIntervalId!==null&&(window.clearInterval(this.heartbeatIntervalId),this.heartbeatIntervalId=null)};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.hidden&&(this.config?.panthera_blackbox.telemetry?.periodic?.enabled??!0?this.sendPeriodicTelemetry():this.sendTelemetry("page_view",{heartbeat:!0,timestamp:new Date().toISOString()}))})}trackFormStart(e){let n=e.target?.closest("form");if(!n)return;let i=n.getAttribute("id")||n.getAttribute("name")||n.getAttribute("action")||"anonymous-form",r=this.hashString(i.slice(0,160));this.startedForms.has(r)||(this.startedForms.add(r),this.periodicState.formStarts+=1)}setupRouteTracking(){if(this.routeTrackingInstalled||typeof window>"u")return;this.routeTrackingInstalled=!0;let e=window.location.href,t=()=>{let i=window.location.href;i!==e&&(e=i,this.periodicState.routeChanges+=1,this.periodicState.pageHistory.push({url:i,path:window.location.pathname,title:typeof document<"u"?document.title:void 0,intent:this.detectIntent(),funnelStage:this.detectFunnelStage(),timestamp:Date.now()}),this.periodicState.pageHistory.length>50&&this.periodicState.pageHistory.shift())},n=i=>{let r=window.history[i];window.history[i]=function(...s){let o=r.apply(this,s);return window.setTimeout(t,0),o}};n("pushState"),n("replaceState"),window.addEventListener("popstate",t),window.addEventListener("hashchange",t)}setupWebVitalsTracking(){if(this.webVitalsTrackingInstalled||typeof window>"u"||typeof PerformanceObserver>"u")return;this.webVitalsTrackingInstalled=!0;let e=(n,i)=>{try{new PerformanceObserver(a=>{for(let s of a.getEntries())i(s)}).observe({type:n,buffered:!0})}catch{}};e("largest-contentful-paint",n=>{this.periodicState.webVitals.lcp=Math.round(n.startTime)}),e("layout-shift",n=>{let i=n;i.hadRecentInput||(this.periodicState.webVitals.cls=Number(((this.periodicState.webVitals.cls||0)+(i.value||0)).toFixed(3)))}),e("event",n=>{let i=n;i.interactionId&&(this.periodicState.webVitals.inp=Math.max(this.periodicState.webVitals.inp||0,Math.round(i.duration||0)))});let t=performance.getEntriesByType?.("navigation")?.[0];t&&(this.periodicState.webVitals.ttfb=Math.max(0,Math.round(t.responseStart)))}hashString(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}redactText(e){let t=e,n=t;return t=t.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi,"[redacted-email]"),t=t.replace(/\\+?\\d[\\d\\s().-]{7,}\\d/g,"[redacted-phone]"),t=t.replace(/\\b(name|full name|first name|last name)\\s*[:=-]?\\s*[a-z ,.'-]{2,}/gi,"$1:[redacted-name]"),{value:t,redacted:t!==n}}safeText(e,t=120){return this.redactText(e).value.trim().slice(0,t)}sanitizeUrlForTelemetry(e){try{let t=new URL(e,typeof window<"u"?window.location.href:void 0);return`${t.origin}${t.pathname}`.slice(0,240)}catch{return e.split("?")[0].split("#")[0].slice(0,160)}}bucketMetric(e,t,n){return typeof e!="number"||!Number.isFinite(e)?"unknown":e<=t?"healthy":e<=n?"needs-attention":"poor"}buildSamplingMeta(e,t,n){return e>0||t>0||this.periodicState.jsErrorsCount>0?{tier:"critical",reason:"Detected friction or technical issues"}:n>0||this.periodicState.pageViews>20?{tier:"full",reason:"Coverage gaps or high activity"}:{tier:"sampled",reason:"Healthy low-risk traffic sample"}}getConfigFrameworkVersion(){let e=this.config?.panthera_blackbox?.ai_readability?.frameworkVersion;return typeof e=="string"&&e.trim().length>0?e:void 0}getActiveReadabilityActionIds(e=3){let t=this.config?.panthera_blackbox?.ai_readability?.recommendedActions;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"&&n.trim().length>0).slice(0,e):[]}buildJourneyContext(){let e=this.periodicState.pageHistory,t=e[0]?.url,n=e[e.length-1]?.url,i=e.map(o=>o.url).filter(Boolean).slice(0,25),r=0,a=0,s=new Set;for(let o=0;o<i.length;o++)s.has(i[o])&&r++,s.add(i[o]),o>1&&i[o]===i[o-2]&&a++;return{entryUrl:t,exitUrl:n,path:i,stepCount:i.length,timeOnPathMs:e.length>1?e[e.length-1].timestamp-e[0].timestamp:0,loops:r,backtracks:a,stallPoints:this.detectDeadEnds().map(o=>o.url).slice(0,5)}}buildIntentSignals(){let e=this.detectIntent(),t=[{intent:e,confidence:.7},{intent:this.detectFunnelStage()==="decision"?"pricing":"general",confidence:.45},{intent:"support",confidence:.2}],n=["url_pattern","keyword_match"];return typeof document<"u"&&document.querySelectorAll('a[href*="demo"],button').length>0&&n.push("cta_match"),typeof document<"u"&&document.querySelectorAll('script[type="application/ld+json"]').length>0&&n.push("schema_hint"),{detectedIntent:e,confidence:t[0].confidence,topCandidates:t,reasonFlags:n}}buildSearchDiagnostics(e){let t=this.periodicState.searchQueries[this.periodicState.searchQueries.length-1]?.query,n=a=>{let s=a.toLowerCase();return s.includes("price")||s.includes("pricing")||s.includes("cost")?"price":s.includes("compare")||s.includes("vs")||s.includes("alternative")?"compare":s.includes("support")||s.includes("error")||s.includes("help")?"support":s.split(" ").length<=2?"nav":"info"},i=t?this.safeText(t,120):void 0,r=this.periodicState.searchQueries.map(a=>this.safeText(a.query,120)).slice(-5);return{query:i,queryHash:t?this.hashString(t.toLowerCase()):void 0,queryClass:t?n(t):void 0,reformulations:r,zeroResultHints:e.length>0?["Repeated searches may indicate weak or missing answers"]:[],repeatedQueryFingerprint:e.length>0?this.hashString(e.map(a=>a.query).join("|")):void 0}}buildPageQualityContext(){if(typeof document>"u")return{};let e=document.body?.textContent||"",t=e.split(/\\s+/).filter(Boolean),n=t.length||1,i=Math.max(1,e.split(/[.!?]+/).filter(Boolean).length),r=t.reduce((g,C)=>{let v=C.toLowerCase().replace(/[^a-z]/g,"");if(!v)return g;let x=(v.replace(/(?:[^laeiouy]|ed|[^laeiouy]e)$/,"").replace(/^y/,"").match(/[aeiouy]{1,2}/g)||["x"]).length;return g+Math.max(1,x)},0),a=n/i,s=r/n,o=206.835-1.015*a-84.6*s,l=Math.max(0,Math.min(1,o/100)),c=document.querySelectorAll('a[href*="contact"],a[href*="pricing"],button').length>0,d=document.querySelectorAll("a").length,u=Array.from(document.querySelectorAll("a")).filter(g=>(g.textContent||"").trim().length>5).length,h=d>0?u/d:.5,p=document.querySelectorAll('script[type="application/ld+json"]').length>0,m=p&&/faq/i.test(e),y=Array.from(document.querySelectorAll("img")),b=y.filter(g=>(g.getAttribute("alt")||"").trim().length>0).length,f=y.length?b/y.length:1;return{readabilityScore:l,aboveFoldClarity:c?.8:.45,ctaPresence:c,linkClarityScore:h,textDepthScore:this.calculateTextDepthScore(),imageAltCoverage:f,schemaPresence:{jsonLd:p,faq:m},faqPresence:m}}buildTechnicalSignals(){let e=this.bucketMetric(this.periodicState.webVitals.lcp,2500,4e3),t=this.bucketMetric(this.periodicState.webVitals.inp,200,500),n=this.bucketMetric(this.periodicState.webVitals.cls,.1,.25),i=this.bucketMetric(this.periodicState.webVitals.ttfb,800,1800);return{jsErrorsCount:this.periodicState.jsErrorsCount,errorSignatures:this.periodicState.errorSignatures.slice(-8),resourceFailures:this.periodicState.resourceFailures,webVitals:{...this.periodicState.webVitals},lcpBucket:e,inpBucket:t,fidBucket:this.periodicState.rageClicks>0?"needs-attention":"healthy",clsBucket:n,ttfbBucket:i,routeChanges:this.periodicState.routeChanges,routeTransitionMsBucket:this.periodicState.routeChanges>8?"needs-attention":"healthy"}}buildSeoSignals(){if(typeof document>"u")return{};let e=document.querySelector('meta[name="robots"],meta[name="googlebot"]')?.getAttribute("content")||"",t=document.querySelector('link[rel="canonical"]')?.getAttribute("href")||"",n=this.collectSchemaTemplateInventory(),i=this.calculateStructuredDataQuality(),r=Array.from(document.querySelectorAll("a[href]")),a=r.filter(d=>{try{return new URL(d.href,window.location.href).origin===window.location.origin}catch{return!1}}),s=Array.from(document.querySelectorAll("img")),o=s.filter(d=>(d.getAttribute("alt")||"").trim().length>0).length,l=t?t.replace(/\/+$/,"")===window.location.href.replace(/\/+$/,""):null,c=this.calculateCtaClarityScore();return{indexable:!e.toLowerCase().includes("noindex"),followable:!e.toLowerCase().includes("nofollow"),robotsMeta:e||null,canonicalUrl:t||null,canonicalMatchesCurrentUrl:l,canonicalHealth:this.calculateCanonicalHealthScore(),schemaTemplates:n,schemaValidity:i,headingCounts:{h1:document.querySelectorAll("h1").length,h2:document.querySelectorAll("h2").length,h3:document.querySelectorAll("h3").length},headingOutline:Array.from(document.querySelectorAll("h1,h2,h3")).slice(0,20).map(d=>({level:d.tagName.toLowerCase(),textHash:this.hashString((d.textContent||"").trim().toLowerCase()),textLength:(d.textContent||"").trim().length})),textLength:document.body?.textContent?.trim().length||0,textDepth:this.calculateTextDepthScore(),imageAltCoverage:s.length?o/s.length:1,internalLinks:a.length,outboundLinks:Math.max(0,r.length-a.length),trustProofDensity:this.calculateTrustProofDensityScore(),ctaClarity:c,extractability:this.calculateExtractabilityScore(),indexability:this.calculateIndexabilityScore(),templateCoverage:this.calculateSchemaTemplateCoverageScore()}}applyPrivacy(e){let t=[],n=!1;if(e.search?.query){let r=this.redactText(e.search.query);r.redacted&&(n=!0),e.search.query=r.value,t.push(`search.query:${this.hashString(r.value.toLowerCase())}`)}if(e.page?.title){let r=this.redactText(e.page.title);r.redacted&&(n=!0),e.page.title=r.value,t.push(`page.title:${this.hashString(r.value.toLowerCase())}`)}let i=e.context||void 0;if(i&&typeof i=="object"){let r=o=>{let l=i[o];if(typeof l!="string")return;let c=this.redactText(l);i[o]=c.value,c.redacted&&(n=!0),t.push(`${o}:${this.hashString(c.value.toLowerCase())}`)};r("search_query"),r("query"),r("url");let a=i.searchDiagnostics;if(a&&typeof a=="object"){if(typeof a.query=="string"){let o=this.redactText(a.query);a.query=o.value,o.redacted&&(n=!0),t.push(`searchDiagnostics.query:${this.hashString(o.value.toLowerCase())}`)}Array.isArray(a.reformulations)&&(a.reformulations=a.reformulations.filter(o=>typeof o=="string").map(o=>this.safeText(o,120)).slice(0,5))}let s=i.engagement;s&&typeof s=="object"&&(Array.isArray(s.ctaClicks)&&(s.ctaClicks=s.ctaClicks.filter(o=>typeof o=="string").map(o=>this.safeText(o,80)).slice(0,10)),Array.isArray(s.outboundClicks)&&(s.outboundClicks=s.outboundClicks.filter(o=>typeof o=="string").map(o=>this.sanitizeUrlForTelemetry(o)).slice(0,10))),i.privacy={redactionApplied:n,hashedFields:t.slice(0,12),policyVersion:this.privacyPolicyVersion},e.context=i}return e}async sendTelemetry(e,t){if(!this.config?.panthera_blackbox.telemetry?.emit)return;if(e==="page_view")this.periodicState.pageViews++,typeof window<"u"&&(this.periodicState.pageHistory.push({url:window.location.href,path:window.location.pathname,title:document.title,intent:this.detectIntent(),funnelStage:this.detectFunnelStage(),timestamp:Date.now()}),this.periodicState.pageHistory.length>50&&this.periodicState.pageHistory.shift());else if(e==="interaction")this.periodicState.interactions++;else if(e==="search"){this.periodicState.searches++;let m=t.search?.query||t.context?.search_query;m&&(this.periodicState.searchQueries.push({query:m,timestamp:Date.now()}),this.periodicState.searchQueries.length>50&&this.periodicState.searchQueries.shift())}let{page:n,search:i,...r}=t,a=this.getSessionId(),s=e==="page_view",o=n||(s&&typeof window<"u"?{url:window.location.href,path:window.location.pathname,title:document.title}:void 0),l=r.search_query||r.query,c=r.results_count,d=r.selected_result,u=e==="search"?i||(l?{query:l,results_count:c,selected_result:d}:void 0):void 0,h={event_type:e,...r};s&&(h.intent===void 0&&(h.intent=this.detectIntent()),h.funnelStage===void 0&&(h.funnelStage=this.detectFunnelStage())),h.captureMeta===void 0&&(h.captureMeta={runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion()});let p=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:["page_view","interaction","search"].includes(e)?e:"custom",session_id:a,page:o,search:u,context:Object.keys(h).length>0?h:void 0,metrics:this.collectMetrics()});try{if(navigator.sendBeacon){let m=new Blob([JSON.stringify(p)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,m)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),keepalive:!0})}catch(m){console.debug("[Panthera Black Box] Telemetry failed:",m)}}async sendPeriodicTelemetry(){if(this.config?.panthera_blackbox.telemetry?.emit&&!(typeof window>"u"))try{let e=Date.now(),t=e-this.periodicState.lastSent,n=this.collectMetrics(),i=this.detectRepeatedSearches(),r=this.detectDeadEnds(),a=this.detectDropOffs(),s=this.buildJourneyContext(),o=this.buildIntentSignals(),l={scrollDepthMax:this.periodicState.scrollDepthMax,activeTimeMs:this.periodicState.activeTimeMs,idleTimeMs:this.periodicState.idleTimeMs,ctaClicks:this.periodicState.ctaClicks.slice(-10),outboundClicks:this.periodicState.outboundClicks.slice(-10),rageClicks:this.periodicState.rageClicks,routeChanges:this.periodicState.routeChanges,formStarts:this.periodicState.formStarts,formSubmits:this.periodicState.formSubmits,formAbandons:Math.max(0,this.periodicState.formStarts-this.periodicState.formSubmits),engagementQuality:this.calculateEngagementQualityScore(),formFriction:this.calculateFormFrictionScore()},c=this.buildSearchDiagnostics(i),d=this.buildPageQualityContext(),u=this.buildTechnicalSignals(),h=this.buildSeoSignals(),p=this.detectContentGaps(),m=this.detectFunnelStage(),y=this.detectIntent(),b={what:p.includes("what"),who:p.includes("who"),how:p.includes("how"),trust:p.includes("trust")},f=[];r.length>0&&f.push("Add clear next-step links and calls-to-action on dead-end pages."),i.length>0&&f.push("Improve clarity for repeated search topics with dedicated sections and internal links."),p.length>0&&f.push(`Fill missing content dimensions: ${p.join(", ")}.`);let g=this.buildSamplingMeta(r.length,a.length,p.length),C=this.getActiveReadabilityActionIds(),v={periodic:!0,timeSinceLastSend:t,aggregated:{pageViews:this.periodicState.pageViews,interactions:this.periodicState.interactions,searches:this.periodicState.searches},confusion:{repeatedSearches:i.length,deadEnds:r.length,dropOffs:a.length,repeatedSearchesDetail:i.slice(0,10),deadEndsDetail:r.slice(0,10),dropOffsDetail:a.slice(0,10)},coverage:{contentGaps:p.length,contentGapsDetail:p,funnelStage:m,intent:y,page:{url:window.location.href,path:window.location.pathname,title:document.title},missingContentDimensions:b,pageMetadata:{hasJsonLd:document.querySelectorAll('script[type="application/ld+json"]').length>0,h1Count:document.querySelectorAll("h1").length,h2Count:document.querySelectorAll("h2").length,textLength:document.body?.textContent?.length||0},recommendedFocus:f.slice(0,3)},journey:s,intentSignals:o,engagement:l,searchDiagnostics:c,pageQuality:d,technicalSignals:u,seoSignals:h,recommendationFeedback:{recommendationId:`rec-${this.detectFunnelStage()}`,exposed:!0,reachedNextStep:a.length===0&&r.length===0,activeReadabilityActionIds:C},captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:g.tier,samplingReason:g.reason},intent:y,funnelStage:m},A=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"custom",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:v,metrics:n});if(navigator.sendBeacon){let M=new Blob([JSON.stringify(A)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,M)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),keepalive:!0});let x=this.applyPrivacy({schema:"panthera.blackbox.v1",tenant:this.config.panthera_blackbox.site.domain,timestamp:new Date().toISOString(),source:"blackbox",event_type:"page_view",session_id:this.getSessionId(),page:{url:window.location.href,path:window.location.pathname,title:document.title},context:{periodic:!0,heartbeat:!0,captureMeta:{runtimeVersion:this.runtimeVersion,schemaVersion:"panthera.blackbox.v1",configFrameworkVersion:this.getConfigFrameworkVersion(),samplingTier:g.tier,samplingReason:g.reason},aggregatedMetrics:n,aggregatedPageViews:this.periodicState.pageViews,aggregatedInteractions:this.periodicState.interactions,aggregatedSearches:this.periodicState.searches},metrics:n});if(navigator.sendBeacon){let M=new Blob([JSON.stringify(x)],{type:"application/json"});navigator.sendBeacon(this.telemetryUrl,M)}else await fetch(this.telemetryUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),keepalive:!0});this.periodicState.pageViews=0,this.periodicState.interactions=0,this.periodicState.searches=0,this.periodicState.lastSent=e,this.periodicState.ctaClicks=[],this.periodicState.outboundClicks=[],this.periodicState.rageClicks=0,this.periodicState.scrollDepthMax=0,this.periodicState.activeTimeMs=0,this.periodicState.idleTimeMs=0,this.periodicState.jsErrorsCount=0,this.periodicState.errorSignatures=[],this.periodicState.resourceFailures=0,this.periodicState.routeChanges=0,this.periodicState.formStarts=0,this.periodicState.formSubmits=0,this.periodicState.formAbandons=0,this.startedForms.clear()}catch(e){console.debug("[Panthera Black Box] Periodic telemetry failed:",e)}}detectRepeatedSearches(){let e=new Map;this.periodicState.searchQueries.forEach(({query:n})=>{e.set(n,(e.get(n)||0)+1)});let t=[];return e.forEach((n,i)=>{n>1&&t.push({query:i,count:n,intent:this.detectIntent(),funnelStage:this.detectFunnelStage()})}),t}detectDeadEnds(){let e=[];if(this.periodicState.pageHistory.length<2)return e;for(let r=0;r<this.periodicState.pageHistory.length-1;r++){let a=this.periodicState.pageHistory[r],o=this.periodicState.pageHistory[r+1].timestamp-a.timestamp;o>6e4&&e.push({url:a.url,path:a.path,title:a.title,at:new Date(a.timestamp).toISOString(),dwellMs:o,reason:"No next meaningful action within expected time window"})}let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],i=Date.now()-n.timestamp;return i>6e4&&e.push({url:n.url,path:n.path,title:n.title,at:new Date(n.timestamp).toISOString(),dwellMs:i,reason:"Session stalled after page view"}),e}detectDropOffs(){let e=[];if(this.periodicState.pageViews+this.periodicState.interactions+this.periodicState.searches<=2&&this.periodicState.pageHistory.length>0){let n=this.periodicState.pageHistory[this.periodicState.pageHistory.length-1],i=this.getSessionId();i&&e.push({sessionId:i,lastEvent:new Date(n.timestamp).toISOString(),lastUrl:n.url,stage:n.funnelStage,intent:n.intent})}return e}detectContentGaps(){if(typeof document>"u")return[];let e=[],t=document.body;if(!t)return e;let n=t.textContent?.toLowerCase()||"",i=this.config?.panthera_blackbox.seo_enhancements?.content_enhancements;return!i?.what&&!n.includes("what")&&!n.includes("do")&&e.push("what"),!i?.who&&!n.includes("who")&&!n.includes("for")&&e.push("who"),!i?.how&&!n.includes("how")&&!n.includes("work")&&e.push("how"),!i?.trust&&!n.includes("trust")&&!n.includes("certified")&&e.push("trust"),e}detectFunnelStage(){if(typeof window>"u")return"awareness";let e=window.location.href.toLowerCase(),t=window.location.pathname.toLowerCase();return e.includes("pricing")||e.includes("signup")||e.includes("checkout")||t.includes("pricing")?"decision":e.includes("docs")||e.includes("case-study")||e.includes("guides")||t.includes("docs")?"consideration":e.includes("support")||e.includes("account")||e.includes("dashboard")||t.includes("account")?"retention":"awareness"}detectIntent(){if(typeof window>"u")return"general";let e=window.location.href.toLowerCase(),t=document.title?.toLowerCase()||"",n=`${e} ${t}`;return n.includes("pricing")?"pricing":n.includes("demo")?"demo":n.includes("docs")?"docs":n.includes("case study")?"case-study":"general"}collectMetrics(){let e={},t=this.config?.panthera_blackbox.telemetry?.keys||[],n=["ts.authority","ai.schemaCompleteness","ai.structuredDataQuality","ai.authoritySignals","ai.searchVisibility","ai.indexability","ai.extractability","ai.trustProofDensity","ai.internalLinkDensity","ai.ctaClarity","ai.schemaTemplateCoverage","ai.canonicalHealth","ai.imageAltCoverage","ai.textDepth","ai.headingStructure","ai.engagementQuality","ai.technicalHealth","ai.formFriction","ai.searchFriction","ai.webVitals","ai.crawlReadiness"];return new Set([...t,...n]).forEach(r=>{r.startsWith("ai.")?r==="ai.schemaCompleteness"?e[r]=this.calculateSchemaCompleteness():r==="ai.structuredDataQuality"?e[r]=this.calculateStructuredDataQuality():r==="ai.authoritySignals"?e[r]=this.calculateAuthoritySignals():r==="ai.searchVisibility"?e[r]=this.calculateSearchVisibility():r==="ai.indexability"?e[r]=this.calculateIndexabilityScore():r==="ai.extractability"?e[r]=this.calculateExtractabilityScore():r==="ai.trustProofDensity"?e[r]=this.calculateTrustProofDensityScore():r==="ai.internalLinkDensity"?e[r]=this.calculateInternalLinkDensityScore():r==="ai.ctaClarity"?e[r]=this.calculateCtaClarityScore():r==="ai.schemaTemplateCoverage"?e[r]=this.calculateSchemaTemplateCoverageScore():r==="ai.canonicalHealth"?e[r]=this.calculateCanonicalHealthScore():r==="ai.imageAltCoverage"?e[r]=this.calculateImageAltCoverageScore():r==="ai.textDepth"?e[r]=this.calculateTextDepthScore():r==="ai.headingStructure"?e[r]=this.calculateHeadingStructureScore():r==="ai.engagementQuality"?e[r]=this.calculateEngagementQualityScore():r==="ai.technicalHealth"?e[r]=this.calculateTechnicalHealthScore():r==="ai.formFriction"?e[r]=this.calculateFormFrictionScore():r==="ai.searchFriction"?e[r]=this.calculateSearchFrictionScore():r==="ai.webVitals"?e[r]=this.calculateWebVitalsScore():r==="ai.crawlReadiness"?e[r]=this.calculateCrawlReadinessScore():e[r]=.6+Math.random()*.35:r.startsWith("ts.")?r==="ts.authority"?e[r]=this.calculateAuthorityScore():e[r]=.5+Math.random()*.4:e[r]=0}),e}calculateSchemaCompleteness(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]'),t=document.querySelectorAll('script[type="application/ld+json"][data-panthera]'),n=0;e.length>0&&(n=.3),t.length>0&&(n=.5);let i=new Set;return e.forEach(r=>{try{let a=r.textContent;if(a){let s=JSON.parse(a);s["@type"]&&i.add(s["@type"])}}catch{}}),n+=Math.min(.5,i.size*.1),Math.min(1,n)}collectSchemaTemplateInventory(){if(typeof document>"u")return{};let e={};return document.querySelectorAll('script[type="application/ld+json"]').forEach(n=>{try{let i=JSON.parse(n.textContent||"{}");(Array.isArray(i)?i:[i]).forEach(a=>{let s=a?.["@type"];(Array.isArray(s)?s:s?[s]:[]).forEach(l=>{typeof l=="string"&&l.trim()&&(e[l.trim().toLowerCase()]=!0)})})}catch{e.invalid=!0}}),e}calculateIndexabilityScore(){if(typeof document>"u")return 0;let e=.4,t=document.querySelector('meta[name="robots"],meta[name="googlebot"]')?.getAttribute("content")?.toLowerCase()||"";return t.includes("noindex")||(e+=.25),t.includes("nofollow")||(e+=.1),document.querySelector('link[rel="canonical"]')?.getAttribute("href")&&(e+=.15),document.querySelector("title")?.textContent?.trim()&&(e+=.1),Math.min(1,e)}calculateExtractabilityScore(){if(typeof document>"u")return 0;let e=document.querySelectorAll("h1").length,t=document.querySelectorAll("h2").length,n=document.body?.textContent?.trim().length||0,i=document.querySelectorAll("ul,ol,table,dl").length;return Math.min(1,(e>=1?.25:0)+Math.min(.3,t*.08)+Math.min(.3,n/3e3)+Math.min(.15,i*.05))}calculateTrustProofDensityScore(){if(typeof document>"u")return 0;let e=document.body?.textContent?.toLowerCase()||"",n=["certified","award","review","testimonial","case study","licensed","verified","trusted","years","customers"].filter(i=>e.includes(i)).length;return Math.min(1,n/8)}calculateInternalLinkDensityScore(){if(typeof window>"u"||typeof document>"u")return 0;let e=Array.from(document.querySelectorAll("a[href]"));if(!e.length)return 0;let t=e.filter(n=>{try{return new URL(n.href,window.location.href).origin===window.location.origin}catch{return!1}});return Math.min(1,t.length/Math.max(8,e.length))}calculateCtaClarityScore(){if(typeof document>"u")return 0;let e=Array.from(document.querySelectorAll('a,button,input[type="submit"]'));if(!e.length)return 0;let t=e.filter(n=>/contact|get|book|quote|demo|apply|start|buy|schedule|call|request/i.test(n.textContent||n.value||""));return Math.min(1,t.length/Math.min(4,e.length))}calculateSchemaTemplateCoverageScore(){let e=this.collectSchemaTemplateInventory(),t=Object.keys(e).filter(n=>n!=="invalid"&&e[n]).length;return Math.min(1,t/5)}calculateCanonicalHealthScore(){if(typeof document>"u"||typeof window>"u")return 0;let e=document.querySelector('link[rel="canonical"]')?.getAttribute("href");if(!e)return .5;try{let t=new URL(e,window.location.href),n=new URL(window.location.href);return t.origin!==n.origin?.35:t.pathname.replace(/\/+$/,"")===n.pathname.replace(/\/+$/,"")?1:.7}catch{return .2}}calculateImageAltCoverageScore(){if(typeof document>"u")return 1;let e=Array.from(document.querySelectorAll("img"));if(!e.length)return 1;let t=e.filter(n=>(n.getAttribute("alt")||"").trim().length>0).length;return Math.min(1,t/e.length)}calculateTextDepthScore(){if(typeof document>"u")return 0;let e=document.body?.textContent?.trim().length||0;return Math.min(1,e/5e3)}calculateHeadingStructureScore(){if(typeof document>"u")return 0;let e=document.querySelectorAll("h1").length,t=document.querySelectorAll("h2").length,n=document.querySelectorAll("h3").length,i=0;return e===1?i+=.35:e>1&&(i+=.2),i+=Math.min(.45,t*.09),i+=Math.min(.2,n*.04),Math.min(1,i)}calculateEngagementQualityScore(){let e=this.periodicState.activeTimeMs,t=this.periodicState.idleTimeMs,n=e>0?e/Math.max(e+t,1):.5,i=this.periodicState.scrollDepthMax||0,r=Math.min(1,this.periodicState.ctaClicks.length/3),a=Math.min(.4,this.periodicState.rageClicks*.1);return Math.max(0,Math.min(1,n*.45+i*.35+r*.2-a))}calculateTechnicalHealthScore(){let e=Math.min(.45,this.periodicState.jsErrorsCount*.08+this.periodicState.resourceFailures*.05),t=this.calculateWebVitalsScore();return Math.max(0,Math.min(1,t*.55+(1-e)*.45))}calculateFormFrictionScore(){let e=this.periodicState.formStarts;if(e===0)return 1;let n=this.periodicState.formSubmits/Math.max(1,e),i=Math.min(.3,this.periodicState.rageClicks*.05);return Math.max(0,Math.min(1,n-i))}calculateSearchFrictionScore(){let e=this.periodicState.searches;if(e===0)return 1;let t=this.detectRepeatedSearches().reduce((n,i)=>n+Math.max(0,i.count-1),0);return Math.max(0,Math.min(1,1-t/Math.max(1,e)))}calculateWebVitalsScore(){let e=this.periodicState.webVitals.lcp,t=this.periodicState.webVitals.cls,n=this.periodicState.webVitals.inp,i=this.periodicState.webVitals.ttfb,r=e===void 0?.7:e<=2500?1:e<=4e3?.65:.25,a=t===void 0?.7:t<=.1?1:t<=.25?.65:.25,s=n===void 0?.7:n<=200?1:n<=500?.65:.25,o=i===void 0?.7:i<=800?1:i<=1800?.65:.25;return Math.max(0,Math.min(1,(r+a+s+o)/4))}calculateCrawlReadinessScore(){return Math.max(0,Math.min(1,this.calculateIndexabilityScore()*.35+this.calculateCanonicalHealthScore()*.2+this.calculateSchemaCompleteness()*.2+this.calculateExtractabilityScore()*.25))}calculateStructuredDataQuality(){if(typeof document>"u")return 0;let e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length===0)return 0;let t=0,n=0,i=0;if(e.forEach(o=>{try{let l=o.textContent;if(!l)return;let c=JSON.parse(l);if(!c["@context"]||!c["@type"])return;t++;let d=Object.keys(c);n+=d.length;let u=c["@type"];u==="Organization"&&c.name&&c.url?i+=2:(u==="Product"&&c.name||u==="Service"&&c.name||u==="FAQPage"&&Array.isArray(c.mainEntity))&&(i+=1)}catch{}}),t===0)return 0;let r=Math.min(.5,t*.25),a=Math.min(.3,n/t/10),s=Math.min(.2,i*.1);return Math.min(1,r+a+s)}calculateAuthoritySignals(){if(typeof document>"u")return 0;let e=0,t=document.body;if(!t)return 0;let n=t.textContent?.toLowerCase()||"",r=["certified","award","trusted","verified","accredited","licensed"].filter(o=>n.includes(o));e+=Math.min(.3,r.length*.05);let s=["review","testimonial","rating","star","customer"].filter(o=>n.includes(o));if(e+=Math.min(.3,s.length*.05),this.config?.panthera_blackbox.authority_grove?.node?.sameAs){let o=this.config.panthera_blackbox.authority_grove.node.sameAs.length;e+=Math.min(.4,o*.1)}return Math.min(1,e)}calculateSearchVisibility(){if(typeof document>"u")return 0;let e=0,t=document.querySelector('meta[name="description"]');t&&t.getAttribute("content")&&t.getAttribute("content").length>50&&(e+=.2);let n=document.querySelector("title");n&&n.textContent&&n.textContent.length>30&&(e+=.2);let i=document.querySelector("h1");i&&i.textContent&&(e+=.2),document.querySelectorAll('script[type="application/ld+json"]').length>0&&(e+=.2);let a=document.querySelectorAll("h2"),s=document.body?.textContent?.length||0;return a.length>=3&&s>1e3&&(e+=.2),Math.min(1,e)}calculateAuthorityScore(){if(!this.config?.panthera_blackbox.authority_grove?.node)return .5;let e=this.config.panthera_blackbox.authority_grove.node,t=.3;return e.sameAs&&e.sameAs.length>0&&(t+=Math.min(.4,e.sameAs.length*.1)),e.keywords&&e.keywords.length>0&&(t+=Math.min(.3,e.keywords.length*.05)),Math.min(1,t)}getSessionId(){if(typeof window>"u")return;let e=window.sessionStorage,t=window.localStorage,n="panthera_session_id",i="panthera_session_ts",r=Date.now(),a=1800*1e3,s=d=>{if(!d)return null;try{let u=d.getItem(n),h=Number(d.getItem(i)||0);if(u&&h&&r-h<a)return d.setItem(i,String(r)),u}catch{return null}return null},o=(d,u)=>{if(!d)return!1;try{return d.setItem(n,u),d.setItem(i,String(r)),!0}catch{return!1}},l=s(e)||s(t);if(l)return l;if(this.memorySessionId&&this.memorySessionTs&&r-this.memorySessionTs<a)return this.memorySessionTs=r,this.memorySessionId;let c=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${r}-${Math.random().toString(16).slice(2)}`;return o(e,c)||o(t,c),this.memorySessionId=c,this.memorySessionTs=r,c}getConfig(){return this.config}async reload(){this.periodicIntervalId!==null&&typeof window<"u"&&(window.clearInterval(this.periodicIntervalId),this.periodicIntervalId=null),this.periodicState={pageViews:0,interactions:0,searches:0,lastSent:Date.now(),pageHistory:[],searchQueries:[],ctaClicks:[],outboundClicks:[],rageClicks:0,scrollDepthMax:0,activeTimeMs:0,idleTimeMs:0,lastActivityAt:Date.now(),jsErrorsCount:0,errorSignatures:[],resourceFailures:0,routeChanges:0,formStarts:0,formSubmits:0,formAbandons:0,webVitals:{}},this.startedForms.clear(),this.initialized=!1,await this.init()}};(function(){if(typeof window>"u")return;let S=document.currentScript;if(!S)return;let e=S.getAttribute("data-config-url"),t=S.getAttribute("data-telemetry-url"),n=S.getAttribute("data-site-id");if(!e||!t||!n){console.warn("[Panthera Black Box] Missing required data attributes");return}let i=new w({configUrl:e,telemetryUrl:t,siteId:n});document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i.init()):i.init(),window.PantheraBlackBox=w,window.panthera=i})();var k=w;export{w as PantheraBlackBox,k as default};
|
|
3
3
|
//# sourceMappingURL=runtime.js.map
|