@sentientui/core 0.33.0 → 0.34.1

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.
Files changed (54) hide show
  1. package/dist/chunk-DGRAS5VP.mjs +2 -0
  2. package/dist/chunk-DGRAS5VP.mjs.map +1 -0
  3. package/dist/chunk-G6VP7HGJ.mjs +2 -0
  4. package/dist/chunk-G6VP7HGJ.mjs.map +1 -0
  5. package/dist/chunk-NCLBL5V3.mjs +2 -0
  6. package/dist/chunk-NCLBL5V3.mjs.map +1 -0
  7. package/dist/{index-COl_pfNm.d.cts → index-DX-MuX8O.d.ts} +43 -4
  8. package/dist/{index-CgkImSaM.d.ts → index-DnQbmMkx.d.cts} +43 -4
  9. package/dist/index-engagement.js +1 -1
  10. package/dist/index-engagement.js.map +1 -1
  11. package/dist/index-engagement.mjs +1 -1
  12. package/dist/index-engagement.mjs.map +1 -1
  13. package/dist/index-graph.d.cts +6 -4
  14. package/dist/index-graph.d.ts +6 -4
  15. package/dist/index-graph.js +1 -1
  16. package/dist/index-graph.js.map +1 -1
  17. package/dist/index-graph.mjs +1 -1
  18. package/dist/index-graph.mjs.map +1 -1
  19. package/dist/index-local.d.cts +4 -2
  20. package/dist/index-local.d.ts +4 -2
  21. package/dist/index-region.d.cts +40 -0
  22. package/dist/index-region.d.ts +40 -0
  23. package/dist/index-region.js +2 -0
  24. package/dist/index-region.js.map +1 -0
  25. package/dist/index-region.mjs +2 -0
  26. package/dist/index-region.mjs.map +1 -0
  27. package/dist/index-server.d.cts +15 -2
  28. package/dist/index-server.d.ts +15 -2
  29. package/dist/index-server.js +1 -1
  30. package/dist/index-server.js.map +1 -1
  31. package/dist/index-server.mjs +1 -1
  32. package/dist/index-server.mjs.map +1 -1
  33. package/dist/index-style-sample.d.cts +12 -0
  34. package/dist/index-style-sample.d.ts +12 -0
  35. package/dist/index-style-sample.js +2 -0
  36. package/dist/index-style-sample.js.map +1 -0
  37. package/dist/index-style-sample.mjs +2 -0
  38. package/dist/index-style-sample.mjs.map +1 -0
  39. package/dist/index.d.cts +4 -2
  40. package/dist/index.d.ts +4 -2
  41. package/dist/index.js +1 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/index.mjs +1 -1
  44. package/dist/region-skeleton-D2ahkcbe.d.cts +61 -0
  45. package/dist/region-skeleton-D2ahkcbe.d.ts +61 -0
  46. package/dist/session-meta-B0sXgtFN.d.ts +226 -0
  47. package/dist/session-meta-Dk8ivs-l.d.cts +226 -0
  48. package/dist/style-vocabulary-BqviEw9O.d.cts +285 -0
  49. package/dist/style-vocabulary-BqviEw9O.d.ts +285 -0
  50. package/package.json +11 -1
  51. package/dist/chunk-EVYMV2C6.mjs +0 -2
  52. package/dist/chunk-EVYMV2C6.mjs.map +0 -1
  53. package/dist/session-meta-DydKfQiR.d.cts +0 -416
  54. package/dist/session-meta-DydKfQiR.d.ts +0 -416
@@ -1,2 +1,2 @@
1
- import{a as v}from"./chunk-WKXD7KI3.mjs";import{a as x,g as R}from"./chunk-Z6ILOYBD.mjs";import{A as qe,B as ze,C as Be,D as He,E as Ye,F as Ve,G as We,K as ee,L as O,M,N as te,O as P,a as J,b as X,c as Q,d as Z,i as ve,j as Ae,k as Ne,l as xe,m as Re,n as _e,o as Oe,p as Me,q as Pe,r as De,s as ke,t as Ge,u as $e,v as Le,w as je,x as Ke,y as Ue,z as Fe}from"./chunk-EVYMV2C6.mjs";import{a as _,b as w,c as T,j as U,k as F,l as q,o as z,p as B,r as H,s as Y,t as V,u as W}from"./chunk-2NVSFI4V.mjs";import{a as E,b as I}from"./chunk-TMCGHANO.mjs";var D="_snt_graph_edges",ne={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function oe(e){var t;return(t=ne[e])!=null?t:[]}function re(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function se(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ae=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function ie(e){return ae.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ce(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function G(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${_(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&se(a,[...t.values()])};if(typeof window!="undefined"){let o=re(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(D)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let g=new Map;for(let r of o){let m=(i=g.get(r.semanticType))!=null?i:[];m.push(r),g.set(r.semanticType,m)}let u=[],p=new Set;for(let r of o)for(let m of oe(r.semanticType)){let d=(c=g.get(m))!=null?c:[];for(let h of d){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;p.has(S)||(p.add(S),u.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let l=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!l.has(r.fromComponentId)||!l.has(r.toComponentId))continue;let m=`structural:${r.fromComponentId}->${r.toComponentId}`;p.has(m)||(p.add(m),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let f=I(E(E({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let m=ie(r.semanticType);return{componentId:r.componentId,semanticType:m,answers:r.answers,contentHash:ce(r.componentId,m,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:E({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(f)}).catch(()=>{})}catch(g){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(D)}catch(o){}}}}var de=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),pe="h1, h2, h3",ue="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",$=30,le=1500,me={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function L(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function ge(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function fe(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var A=new Set(x);function he(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&A.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&A.has(s))return s;let o=e.getAttribute("role");return o&&A.has(o)?o:R(e)}function Se(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function ye(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ee(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Se(ye(e))}`}function Ie(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(pe);return{componentId:Ee(e),semanticType:he(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Ie(e),reactComponentName:ge(e),dataAttributes:fe(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function j(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let g=i.parentElement,u=a;for(;g;){if(e.has(g)){u=e.get(g);let l=e.get(i),f=`${u}->${l}`;!n.has(f)&&u!==l&&(n.add(f),t.push({fromComponentId:u,toComponentId:l,weight:.6}));break}g=g.parentElement}let p=(o=s.get(u))!=null?o:[];p.push(i),s.set(u,p)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>$?i.slice(0,$):i;for(let g=0;g<c.length;g++)for(let u=g+1;u<c.length;u++){if(t.length>=le)return t;let p=e.get(c[g]),l=e.get(c[u]);if(p===l)continue;let f=`${p}->${l}::sib`,r=`${l}->${p}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:p,toComponentId:l,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:l,toComponentId:p,weight:.3}))}}return t}function Ce(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let g=N(c,e,t);n.push(g),s.set(c,g.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let g=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!g&&!u)return;a.add(c);let p=N(c,e,t);n.push(p),s.set(c,p.componentId)}),{nodes:n,edges:j(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return me;let n=null,a=0,s=null,o=new Map,i=p=>{try{let l=window.getComputedStyle(p),f=parseFloat(l.fontSize)||12,r=parseFloat(l.zIndex)||0,m=p.getBoundingClientRect(),d=Math.max(m.top,0),h=window.innerHeight||1,S=1/(d/h+1),y=L(f,12,48)*.4+S*.4+L(r,0,100)*.2;return Math.max(0,Math.min(1,y))}catch(l){return .5}};return{scan:()=>new Promise(p=>{let l=()=>{let{nodes:f,edges:r,elementToId:m}=Ce(i,t);o.clear();for(let[d,h]of m)o.set(d,h);p({nodes:f,edges:r,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(l,{timeout:100}):l()}catch(f){l()}}),observe:p=>{s=p;try{n=new MutationObserver(l=>{let f=[],r=new Set;for(let d of l)d.type==="childList"&&d.addedNodes.forEach(h=>{if(!(h instanceof Element))return;let S=[];de.has(h.tagName)&&(h.hasAttribute("data-sentient-id")||h.hasAttribute("aria-label"))&&S.push(h);try{h.querySelectorAll(ue).forEach(y=>S.push(y))}catch(y){}for(let y of S){if(o.has(y))continue;let b=N(y,i,t);f.push(b),r.add(b.componentId),o.set(y,b.componentId)}});if(f.length===0||!s)return;for(let d of[...o.keys()])d.isConnected||o.delete(d);let m=j(o).filter(d=>r.has(d.fromComponentId)||r.has(d.toComponentId));s({nodes:f,edges:m,addedAt:Date.now()})}),n.observe(document.body,{childList:!0,subtree:!0})}catch(l){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(p){}a=0,s=null,o.clear()}}}var be="https://api.sentient-ui.com/v1/events";function we(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(T(e)):void 0)!=null?n:t(w)}var C=new Map;function Te(e){var r;let t=P(e),n=e.respectDoNotTrack!==!1&&M(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||O(e.apiKey,m=>Te(m)),t;let i=C.get(e.apiKey);if(i)try{i()}catch(m){}let c=K({sectionTypes:e.sectionTypes}),g=(r=e.ingestUrl)!=null?r:be,u=G({syncUrl:g.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:we(e.apiKey)});c.scan().then(m=>{for(let d of m.nodes)u.addPageNode({id:d.componentId,componentId:d.componentId,semanticType:d.semanticType,answers:e.captureDomText&&d.headingText?[d.headingText]:[],prominenceScore:d.prominenceScore,depth:d.depth});for(let d of m.edges)u.addStructuralEdge(d);u.syncOnce()});let p=null,l=()=>{p!==null&&clearTimeout(p),p=setTimeout(()=>{p=null,u.syncOnce()},500)};c.observe(m=>{for(let d of m.nodes)u.addPageNode({id:d.componentId,componentId:d.componentId,semanticType:d.semanticType,answers:e.captureDomText&&d.headingText?[d.headingText]:[],prominenceScore:d.prominenceScore,depth:d.depth});for(let d of m.edges)u.addStructuralEdge(d);l()});let f=()=>{p!==null&&(clearTimeout(p),p=null),c.destroy(),u.destroy(),C.get(e.apiKey)===f&&C.delete(e.apiKey)};return C.set(e.apiKey,f),I(E({},t),{getGraph:()=>u.snapshot(),dispose:()=>{f(),t.dispose()},destroy:()=>{f(),t.destroy()}})}export{Ae as BLOCK_ALIGNS,Oe as BLOCK_EMPHASES,De as BLOCK_FITS,ve as BLOCK_GAPS,ke as BLOCK_GRID_COLUMNS,Ge as BLOCK_HEADING_LEVELS,Ne as BLOCK_JUSTIFIES,je as BLOCK_MAX_WIDTHS,Le as BLOCK_PADS,Pe as BLOCK_RATIOS,xe as BLOCK_SIZES,$e as BLOCK_SURFACES,Me as BLOCK_TEXT_ALIGNS,_e as BLOCK_TONES,Re as BLOCK_WEIGHTS,Ke as FORM_FIELD_KINDS,Ue as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ye as MAX_BLOCK_ARMS,He as MAX_BLOCK_CHILDREN,Be as MAX_BLOCK_DEPTH,ze as MAX_BLOCK_NODES,Ve as MAX_BLOCK_TEXT_LEN,Fe as MAX_FORM_FIELDS,qe as MAX_FORM_SELECT_OPTIONS,J as SNAPSHOT_STORAGE_KEY_PREFIX,W as armOfResult,ee as attachMicroSignalDetectors,Y as baselineResultFor,V as baselineSlots,We as containsFormBlock,B as deriveSessionSegment,U as detectDeviceClass,z as detectTimeOfDay,F as detectTrafficSource,te as grantConsent,Te as init,M as isDoNotTrackEnabled,v as locatorFromElement,X as readSnapshot,q as referrerDomainFromReferer,Z as renderPrePaintScript,k as sanitizePageUrl,T as sessionCookieName,H as toWireSlot,Q as writeSnapshot};
1
+ import{a as v}from"./chunk-WKXD7KI3.mjs";import{A as qe,B as ze,C as Be,D as He,E as Ye,F as Ve,G as We,K as ee,L as O,M,N as te,O as P,a as J,b as X,c as Q,d as Z,i as ve,j as Ae,k as Ne,l as xe,m as Re,n as _e,o as Oe,p as Me,q as Pe,r as De,s as ke,t as Ge,u as $e,v as Le,w as je,x as Ke,y as Ue,z as Fe}from"./chunk-DGRAS5VP.mjs";import"./chunk-NCLBL5V3.mjs";import{a as _,b as w,c as T,j as U,k as F,l as q,o as z,p as B,r as H,s as Y,t as V,u as W}from"./chunk-2NVSFI4V.mjs";import{a as x,g as R}from"./chunk-Z6ILOYBD.mjs";import{a as E,b as I}from"./chunk-TMCGHANO.mjs";var D="_snt_graph_edges",ne={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function oe(e){var t;return(t=ne[e])!=null?t:[]}function re(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function se(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ae=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function ie(e){return ae.has(e)?e:"generic"}function k(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function ce(e,t,n){let a=`${e}:${t}:${n.join(",")}`,s=5381;for(let o=0;o<a.length;o++)s=(s<<5)+s+a.charCodeAt(o)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function G(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${_(e==null?void 0:e.apiKey)}`,s=()=>{typeof window!="undefined"&&se(a,[...t.values()])};if(typeof window!="undefined"){let o=re(a,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(D)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),s()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,c;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let g=new Map;for(let r of o){let m=(i=g.get(r.semanticType))!=null?i:[];m.push(r),g.set(r.semanticType,m)}let u=[],p=new Set;for(let r of o)for(let m of oe(r.semanticType)){let d=(c=g.get(m))!=null?c:[];for(let h of d){if(h.componentId===r.componentId)continue;let S=`semantic:${r.componentId}->${h.componentId}`;p.has(S)||(p.add(S),u.push({fromComponentId:r.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let l=new Set(o.map(r=>r.componentId));for(let r of n.values()){if(!l.has(r.fromComponentId)||!l.has(r.toComponentId))continue;let m=`structural:${r.fromComponentId}->${r.toComponentId}`;p.has(m)||(p.add(m),u.push({fromComponentId:r.fromComponentId,toComponentId:r.toComponentId,type:"structural",weight:r.weight,confidence:1}))}let f=I(E(E({pageUrl:k(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(r=>{let m=ie(r.semanticType);return{componentId:r.componentId,semanticType:m,answers:r.answers,contentHash:ce(r.componentId,m,r.answers),prominenceScore:r.prominenceScore,depthInPage:r.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:E({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(f)}).catch(()=>{})}catch(g){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(D)}catch(o){}}}}var de=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),pe="h1, h2, h3",ue="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",$=30,le=1500,me={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function L(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function ge(e){var t,n,a;try{let s=e;for(let o of Object.keys(s)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=s[o],c=(a=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?a:(n=i==null?void 0:i.type)==null?void 0:n.name;if(c&&c.length>1)return c}}catch(s){}}function fe(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var A=new Set(x);function he(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&A.has(a))return a;let s=e.getAttribute("data-sentient-type");if(s&&A.has(s))return s;let o=e.getAttribute("role");return o&&A.has(o)?o:R(e)}function Se(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function ye(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let s=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${s}]`),n=a}return t.reverse().join("/")}function Ee(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Se(ye(e))}`}function Ie(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function N(e,t,n){var s,o,i,c;let a=e.querySelector(pe);return{componentId:Ee(e),semanticType:he(e,n),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(i=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?i:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Ie(e),reactComponentName:ge(e),dataAttributes:fe(e),locator:(c=v(e,e.ownerDocument))!=null?c:void 0}}function j(e){var o;let t=[],n=new Set,a="__root__",s=new Map;for(let[i,c]of e){let g=i.parentElement,u=a;for(;g;){if(e.has(g)){u=e.get(g);let l=e.get(i),f=`${u}->${l}`;!n.has(f)&&u!==l&&(n.add(f),t.push({fromComponentId:u,toComponentId:l,weight:.6}));break}g=g.parentElement}let p=(o=s.get(u))!=null?o:[];p.push(i),s.set(u,p)}for(let i of s.values()){if(i.length<2)continue;let c=i.length>$?i.slice(0,$):i;for(let g=0;g<c.length;g++)for(let u=g+1;u<c.length;u++){if(t.length>=le)return t;let p=e.get(c[g]),l=e.get(c[u]);if(p===l)continue;let f=`${p}->${l}::sib`,r=`${l}->${p}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:p,toComponentId:l,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:l,toComponentId:p,weight:.3}))}}return t}function Ce(e,t){let n=[],a=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(c=>{if(c instanceof Element&&!a.has(c)){a.add(c);let g=N(c,e,t);n.push(g),s.set(c,g.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(c=>{if(!(c instanceof Element)||a.has(c))return;let g=c.hasAttribute("aria-label"),u=c.hasAttribute("data-sentient-id");if(!g&&!u)return;a.add(c);let p=N(c,e,t);n.push(p),s.set(c,p.componentId)}),{nodes:n,edges:j(s),elementToId:s}}function K(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return me;let n=null,a=0,s=null,o=new Map,i=p=>{try{let l=window.getComputedStyle(p),f=parseFloat(l.fontSize)||12,r=parseFloat(l.zIndex)||0,m=p.getBoundingClientRect(),d=Math.max(m.top,0),h=window.innerHeight||1,S=1/(d/h+1),y=L(f,12,48)*.4+S*.4+L(r,0,100)*.2;return Math.max(0,Math.min(1,y))}catch(l){return .5}};return{scan:()=>new Promise(p=>{let l=()=>{let{nodes:f,edges:r,elementToId:m}=Ce(i,t);o.clear();for(let[d,h]of m)o.set(d,h);p({nodes:f,edges:r,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(l,{timeout:100}):l()}catch(f){l()}}),observe:p=>{s=p;try{n=new MutationObserver(l=>{let f=[],r=new Set;for(let d of l)d.type==="childList"&&d.addedNodes.forEach(h=>{if(!(h instanceof Element))return;let S=[];de.has(h.tagName)&&(h.hasAttribute("data-sentient-id")||h.hasAttribute("aria-label"))&&S.push(h);try{h.querySelectorAll(ue).forEach(y=>S.push(y))}catch(y){}for(let y of S){if(o.has(y))continue;let b=N(y,i,t);f.push(b),r.add(b.componentId),o.set(y,b.componentId)}});if(f.length===0||!s)return;for(let d of[...o.keys()])d.isConnected||o.delete(d);let m=j(o).filter(d=>r.has(d.fromComponentId)||r.has(d.toComponentId));s({nodes:f,edges:m,addedAt:Date.now()})}),n.observe(document.body,{childList:!0,subtree:!0})}catch(l){}},getProminenceScore:i,destroy:()=>{if(n&&(n.disconnect(),n=null),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(p){}a=0,s=null,o.clear()}}}var be="https://api.sentient-ui.com/v1/events";function we(e){var n;let t=a=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch(s){return}};return(n=e?t(T(e)):void 0)!=null?n:t(w)}var C=new Map;function Te(e){var r;let t=P(e),n=e.respectDoNotTrack!==!1&&M(),a=e.consent===!1||n,s=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!s;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||O(e.apiKey,m=>Te(m)),t;let i=C.get(e.apiKey);if(i)try{i()}catch(m){}let c=K({sectionTypes:e.sectionTypes}),g=(r=e.ingestUrl)!=null?r:be,u=G({syncUrl:g.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:we(e.apiKey)});c.scan().then(m=>{for(let d of m.nodes)u.addPageNode({id:d.componentId,componentId:d.componentId,semanticType:d.semanticType,answers:e.captureDomText&&d.headingText?[d.headingText]:[],prominenceScore:d.prominenceScore,depth:d.depth});for(let d of m.edges)u.addStructuralEdge(d);u.syncOnce()});let p=null,l=()=>{p!==null&&clearTimeout(p),p=setTimeout(()=>{p=null,u.syncOnce()},500)};c.observe(m=>{for(let d of m.nodes)u.addPageNode({id:d.componentId,componentId:d.componentId,semanticType:d.semanticType,answers:e.captureDomText&&d.headingText?[d.headingText]:[],prominenceScore:d.prominenceScore,depth:d.depth});for(let d of m.edges)u.addStructuralEdge(d);l()});let f=()=>{p!==null&&(clearTimeout(p),p=null),c.destroy(),u.destroy(),C.get(e.apiKey)===f&&C.delete(e.apiKey)};return C.set(e.apiKey,f),I(E({},t),{getGraph:()=>u.snapshot(),dispose:()=>{f(),t.dispose()},destroy:()=>{f(),t.destroy()}})}export{Ae as BLOCK_ALIGNS,Oe as BLOCK_EMPHASES,De as BLOCK_FITS,ve as BLOCK_GAPS,ke as BLOCK_GRID_COLUMNS,Ge as BLOCK_HEADING_LEVELS,Ne as BLOCK_JUSTIFIES,je as BLOCK_MAX_WIDTHS,Le as BLOCK_PADS,Pe as BLOCK_RATIOS,xe as BLOCK_SIZES,$e as BLOCK_SURFACES,Me as BLOCK_TEXT_ALIGNS,_e as BLOCK_TONES,Re as BLOCK_WEIGHTS,Ke as FORM_FIELD_KINDS,Ue as FORM_INPUT_TYPES,w as LEGACY_SESSION_COOKIE_NAME,Ye as MAX_BLOCK_ARMS,He as MAX_BLOCK_CHILDREN,Be as MAX_BLOCK_DEPTH,ze as MAX_BLOCK_NODES,Ve as MAX_BLOCK_TEXT_LEN,Fe as MAX_FORM_FIELDS,qe as MAX_FORM_SELECT_OPTIONS,J as SNAPSHOT_STORAGE_KEY_PREFIX,W as armOfResult,ee as attachMicroSignalDetectors,Y as baselineResultFor,V as baselineSlots,We as containsFormBlock,B as deriveSessionSegment,U as detectDeviceClass,z as detectTimeOfDay,F as detectTrafficSource,te as grantConsent,Te as init,M as isDoNotTrackEnabled,v as locatorFromElement,X as readSnapshot,q as referrerDomainFromReferer,Z as renderPrePaintScript,k as sanitizePageUrl,T as sessionCookieName,H as toWireSlot,Q as writeSnapshot};
2
2
  //# sourceMappingURL=index-graph.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph.ts","../src/scanner.ts","../src/index-graph.ts"],"sourcesContent":["/** In-memory context graph with persistence and backend sync. */\n\nimport { storageSuffix } from './storage-key.js';\n\nexport type PageNode = {\n id: string;\n componentId: string;\n semanticType: string;\n answers: string[];\n prominenceScore: number;\n depth: number;\n};\n\nexport type GraphSnapshot = {\n pageNodes: PageNode[];\n capturedAt: number;\n};\n\nexport type GraphConfig = {\n syncUrl?: string;\n apiKey?: string;\n projectId?: string;\n sessionId?: string;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n weight: number;\n};\n\nexport type GraphClient = {\n addPageNode(node: PageNode): void;\n /** Record a DOM-derived parent/child or sibling relationship between two components. */\n addStructuralEdge(edge: StructuralEdge): void;\n /** One-shot batch sync of all current page nodes to the backend. */\n syncOnce(): void;\n snapshot(): GraphSnapshot;\n destroy(): void;\n};\n\n// _snt_graph_edges was written by earlier builds but never synced to the backend.\n// We still read and clear any leftover key on init/destroy so old clients don't\n// accumulate stale data, but we no longer write it.\nconst STALE_EDGES_KEY = '_snt_graph_edges';\n\nconst SEMANTIC_NEIGHBOURS: Record<string, string[]> = {\n pricing: ['features', 'faq'],\n features: ['pricing'],\n faq: ['pricing'],\n social_proof: ['cta'],\n cta: ['social_proof', 'hero', 'trust'],\n hero: ['cta'],\n comparison: ['pricing'],\n trust: ['cta'],\n};\n\nfunction neighboursFor(semanticType: string): string[] {\n return SEMANTIC_NEIGHBOURS[semanticType] ?? [];\n}\n\nfunction readStorage<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return fallback;\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction writeStorage(key: string, value: unknown): void {\n try {\n localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\nconst VALID_SEMANTIC_TYPES = new Set([\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n]);\n\nfunction toValidSemanticType(type: string): string {\n return VALID_SEMANTIC_TYPES.has(type) ? type : 'generic';\n}\n\n/**\n * Path-only page URL for graph sync — strips query + fragment so tokens,\n * emails, and other sensitive URL params never leave the browser by default.\n */\nexport function sanitizePageUrl(href: string): string {\n try {\n const u = new URL(href);\n return `${u.origin}${u.pathname}`;\n } catch {\n return '/';\n }\n}\n\nfunction contentHashOf(componentId: string, semanticType: string, answers: string[]): string {\n const input = `${componentId}:${semanticType}:${answers.join(',')}`;\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Creates an in-memory graph client with optional persistence and sync.\n */\nexport function createGraphClient(config?: GraphConfig): GraphClient {\n const pageNodes = new Map<string, PageNode>();\n const structuralEdges = new Map<string, StructuralEdge>();\n\n // Per-project localStorage key so two projects on one origin don't share a\n // graph-node cache (see storage-key.ts). Legacy `_snt_graph_nodes` with no key.\n const nodesKey = `_snt_graph_nodes${storageSuffix(config?.apiKey)}`;\n\n const persist = (): void => {\n if (typeof window === 'undefined') return;\n writeStorage(nodesKey, [...pageNodes.values()]);\n };\n\n // serialize()/restore() were removed here: persisted-node restoration moved\n // into this constructor (below), leaving both dead — yet still shipping in\n // the graph bundle.\n if (typeof window !== 'undefined') {\n const storedNodes = readStorage<PageNode[]>(nodesKey, []);\n for (const node of storedNodes) {\n pageNodes.set(node.componentId, node);\n }\n // Clear any stale edge data written by older SDK versions.\n try { localStorage.removeItem(STALE_EDGES_KEY); } catch { /* ignore */ }\n }\n\n return {\n addPageNode(node: PageNode): void {\n pageNodes.set(node.componentId, node);\n persist();\n },\n\n addStructuralEdge(edge: StructuralEdge): void {\n const key = `${edge.fromComponentId}->${edge.toComponentId}`;\n structuralEdges.set(key, edge);\n },\n\n syncOnce(): void {\n if (!config?.syncUrl || typeof window === 'undefined') return;\n const nodes = [...pageNodes.values()];\n if (nodes.length === 0) return;\n try {\n // Build semantic edges from the SEMANTIC_NEIGHBOURS map. Each node emits\n // an edge to every present sibling that matches one of its neighbour types.\n // Weight matches propagate()'s 0.4 attention factor; confidence is high\n // because the mapping is curated, not inferred.\n const nodesByType = new Map<string, PageNode[]>();\n for (const n of nodes) {\n const list = nodesByType.get(n.semanticType) ?? [];\n list.push(n);\n nodesByType.set(n.semanticType, list);\n }\n const edges: Array<{\n fromComponentId: string;\n toComponentId: string;\n type: 'semantic' | 'structural';\n weight: number;\n confidence: number;\n }> = [];\n const seen = new Set<string>();\n for (const source of nodes) {\n for (const neighbourType of neighboursFor(source.semanticType)) {\n const targets = nodesByType.get(neighbourType) ?? [];\n for (const target of targets) {\n if (target.componentId === source.componentId) continue;\n const key = `semantic:${source.componentId}->${target.componentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: source.componentId,\n toComponentId: target.componentId,\n type: 'semantic',\n weight: 0.4,\n confidence: 0.9,\n });\n }\n }\n }\n\n // Structural edges from DOM relationships, recorded during scan.\n // Only emit when both endpoints are present in this page's node set —\n // a structural edge to/from a node that no longer exists would dangle.\n const componentIds = new Set(nodes.map((n) => n.componentId));\n for (const edge of structuralEdges.values()) {\n if (!componentIds.has(edge.fromComponentId) || !componentIds.has(edge.toComponentId)) continue;\n const key = `structural:${edge.fromComponentId}->${edge.toComponentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: edge.fromComponentId,\n toComponentId: edge.toComponentId,\n type: 'structural',\n weight: edge.weight,\n confidence: 1.0,\n });\n }\n\n const payload = {\n pageUrl: sanitizePageUrl(window.location.href),\n // Visitor/project attribution. The /graph/sync handler ignores unknown\n // top-level fields (Fastify additionalProperties + Zod strips extras),\n // so these ride along harmlessly and let beacons carry attribution.\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.projectId ? { projectId: config.projectId } : {}),\n nodes: nodes.map((n) => {\n const semanticType = toValidSemanticType(n.semanticType);\n return {\n componentId: n.componentId,\n semanticType,\n answers: n.answers,\n contentHash: contentHashOf(n.componentId, semanticType, n.answers),\n prominenceScore: n.prominenceScore,\n depthInPage: n.depth,\n };\n }),\n edges,\n };\n fetch(config.syncUrl, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),\n },\n body: JSON.stringify(payload),\n }).catch(() => undefined);\n } catch {\n /* ignore */\n }\n },\n\n snapshot(): GraphSnapshot {\n return {\n pageNodes: [...pageNodes.values()],\n capturedAt: Date.now(),\n };\n },\n\n destroy(): void {\n if (typeof window === 'undefined') return;\n try {\n localStorage.removeItem(nodesKey);\n localStorage.removeItem(STALE_EDGES_KEY);\n } catch {\n /* ignore */\n }\n },\n };\n}\n","/** Reads the rendered DOM to build the page-side context graph. */\n\nimport { classifySection, SEMANTIC_TYPES, type SemanticType } from './engagement/classify';\nimport { locatorFromElement } from './locator-from-dom.js';\nimport type { CompoundLocator } from './snapshot.js';\n\nexport type ScannedNode = {\n componentId: string;\n semanticType: string;\n ariaLabel?: string;\n headingText?: string;\n isAboveFold: boolean;\n prominenceScore: number;\n depth: number;\n reactComponentName?: string;\n dataAttributes: Record<string, string>;\n /** Compound locator for this element. The server hashes it into section_key —\n * the identity the crawler and the snippet resolve to for the same physical\n * section. Undefined when nothing resolves uniquely: the runtime never\n * guesses an identity it could not verify later. */\n locator?: CompoundLocator;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n /** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */\n weight: number;\n};\n\nexport type ScanResult = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n scannedAt: number;\n};\n\nexport type ContentAddedEvent = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n addedAt: number;\n};\n\nexport type DOMScanner = {\n scan(): Promise<ScanResult>;\n observe(onContentAdded: (event: ContentAddedEvent) => void): void;\n getProminenceScore(element: Element): number;\n destroy(): void;\n};\n\n// ASIDE included to match the initial scan (which queries `section, article,\n// main, aside`) — this set omitted it, so a server-rendered aside was captured\n// while an identical dynamically-inserted one was silently ignored.\nconst OBSERVE_TAGS = new Set(['SECTION', 'ARTICLE', 'MAIN', 'DIV', 'ASIDE']);\nconst HEADING_SELECTOR = 'h1, h2, h3';\n// Selector mirror of the initial scan's criteria (collectNodesAndEdges): any\n// element carrying a declared id, plus structural tags with an aria-label.\n// Used to walk INTO inserted subtrees — a SPA mounts ONE root node whose\n// interesting sections are all descendants, and inspecting only the root made\n// every framework-mounted component permanently invisible to graph capture.\nconst SUBTREE_SELECTOR =\n '[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]';\n\n// Sibling detection is O(n²) per group and emits two edges per pair, so a page\n// with hundreds of co-located components (e.g. a 200-cell product grid) would\n// otherwise emit tens of thousands of low-signal sibling edges. We cap the\n// sibling fan-out per group and the total structural edges per detection pass.\n// The total stays well under the server's 2000-edge-per-sync limit, leaving room\n// for semantic edges. Parent→child edges (higher signal) are emitted first, so\n// the cap sheds sibling edges before it ever touches them.\nconst MAX_SIBLINGS_PER_GROUP = 30;\nconst MAX_STRUCTURAL_EDGES = 1500;\n\nconst SSR_SCANNER: DOMScanner = {\n scan: async () => ({ nodes: [], edges: [], scannedAt: 0 }),\n observe: () => undefined,\n getProminenceScore: () => 0,\n destroy: () => undefined,\n};\n\nfunction normalize(value: number, min: number, max: number): number {\n if (max <= min) return 0;\n return Math.max(0, Math.min(1, (value - min) / (max - min)));\n}\n\nfunction readReactComponentName(element: Element): string | undefined {\n try {\n const record = element as unknown as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!key.startsWith('__reactFiber') && !key.startsWith('__reactInternalInstance')) {\n continue;\n }\n const fiber = record[key] as { type?: { name?: string; displayName?: string } };\n const name = fiber?.type?.displayName ?? fiber?.type?.name;\n if (name && name.length > 1) {\n return name;\n }\n }\n } catch {\n /* ignore */\n }\n return undefined;\n}\n\nfunction extractDataAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n if (attr.name.startsWith('data-')) {\n attrs[attr.name] = attr.value;\n }\n }\n return attrs;\n}\n\nconst SEMANTIC_SET: ReadonlySet<string> = new Set(SEMANTIC_TYPES);\n\nexport type DOMScannerOptions = {\n /**\n * Section types declared in code, keyed by `data-sentient-id`. Replaces the\n * per-element `data-sentient-type` attribute so a section needs one attribute\n * of markup. The content classifier misses sections whose copy carries no\n * strong signal (an \"About us\" band reads `generic`, not `trust`), and a\n * wrong type here reorders that section for the wrong personas.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// Declared type (sectionTypes) → legacy data-sentient-type markup → role →\n// heuristic → generic. Every output is normalized to the graph_nodes enum: an\n// out-of-vocabulary declared/markup/role value falls through to the next stage\n// instead of being emitted raw (raw values violated the graph_nodes CHECK\n// constraint on insert).\nfunction inferSemanticType(\n element: Element,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): SemanticType {\n const id = element.getAttribute('data-sentient-id');\n // The SEMANTIC_SET check also rejects inherited keys (an id of \"constructor\").\n const declared = id ? sectionTypes?.[id] : undefined;\n if (declared && SEMANTIC_SET.has(declared)) return declared as SemanticType;\n const explicit = element.getAttribute('data-sentient-type');\n if (explicit && SEMANTIC_SET.has(explicit)) return explicit as SemanticType;\n const role = element.getAttribute('role');\n if (role && SEMANTIC_SET.has(role)) return role as SemanticType;\n return classifySection(element);\n}\n\n// djb2 over a string → 8-hex-char digest. Stable and collision-resistant enough\n// to disambiguate co-located components that declare no id of their own.\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n// A structural path (tag + sibling index at each level up to the root) uniquely\n// and stably identifies an element's DOM position, so two id-less sections don't\n// hash to the same value the way a bare tagName would.\nfunction domPathSignature(element: Element): string {\n const parts: string[] = [];\n let current: Element | null = element;\n while (current) {\n const parent: Element | null = current.parentElement;\n if (!parent) {\n parts.push(current.tagName.toLowerCase());\n break;\n }\n const index = Array.prototype.indexOf.call(parent.children, current);\n parts.push(`${current.tagName.toLowerCase()}[${index}]`);\n current = parent;\n }\n return parts.reverse().join('/');\n}\n\n// Prefer an author-declared id. When none exists, synthesize a stable, unique id\n// from the element's DOM path — the old `tagName.toLowerCase()` fallback gave\n// every id-less <section> the same \"section\" id, so a second such node silently\n// overwrote the first in the componentId-keyed graph Map (node loss).\nfunction componentIdFor(element: Element): string {\n const declared =\n element.getAttribute('data-sentient-id') ?? element.getAttribute('id');\n if (declared) return declared;\n return `${element.tagName.toLowerCase()}-${shortHash(domPathSignature(element))}`;\n}\n\nfunction depthOf(element: Element): number {\n let depth = 0;\n let current: Element | null = element.parentElement;\n while (current) {\n depth++;\n current = current.parentElement;\n }\n return depth;\n}\n\nfunction scanElement(\n element: Element,\n getProminenceScore: (el: Element) => number,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element, sectionTypes),\n ariaLabel: element.getAttribute('aria-label') ?? undefined,\n headingText: heading?.textContent?.trim() ?? undefined,\n isAboveFold: element.getBoundingClientRect().top < window.innerHeight,\n prominenceScore: getProminenceScore(element),\n depth: depthOf(element),\n reactComponentName: readReactComponentName(element),\n dataAttributes: extractDataAttributes(element),\n locator: locatorFromElement(element, element.ownerDocument) ?? undefined,\n };\n}\n\n/**\n * Detects structural relationships between scanned component elements:\n * - parent → child (direct ancestor link, weight 0.6)\n * - sibling ↔ sibling (share nearest component ancestor, weight 0.3, bidirectional)\n * A pair appears at most once per direction.\n */\nfunction detectStructuralEdges(elementToId: Map<Element, string>): StructuralEdge[] {\n const edges: StructuralEdge[] = [];\n const seen = new Set<string>();\n const ROOT = '__root__';\n\n // Parent → child: nearest component ancestor only.\n const groups = new Map<string, Element[]>();\n for (const [el, _id] of elementToId) {\n let ancestor: Element | null = el.parentElement;\n let groupKey = ROOT;\n while (ancestor) {\n if (elementToId.has(ancestor)) {\n groupKey = elementToId.get(ancestor)!;\n const childId = elementToId.get(el)!;\n const key = `${groupKey}->${childId}`;\n if (!seen.has(key) && groupKey !== childId) {\n seen.add(key);\n edges.push({ fromComponentId: groupKey, toComponentId: childId, weight: 0.6 });\n }\n break;\n }\n ancestor = ancestor.parentElement;\n }\n const siblings = groups.get(groupKey) ?? [];\n siblings.push(el);\n groups.set(groupKey, siblings);\n }\n\n // Sibling ↔ sibling: same ancestor group.\n for (const sibs of groups.values()) {\n if (sibs.length < 2) continue;\n // Cap the fan-out of any single group before the O(n²) pairing.\n const capped = sibs.length > MAX_SIBLINGS_PER_GROUP ? sibs.slice(0, MAX_SIBLINGS_PER_GROUP) : sibs;\n for (let i = 0; i < capped.length; i++) {\n for (let j = i + 1; j < capped.length; j++) {\n if (edges.length >= MAX_STRUCTURAL_EDGES) return edges;\n const aId = elementToId.get(capped[i]!)!;\n const bId = elementToId.get(capped[j]!)!;\n if (aId === bId) continue;\n const fwd = `${aId}->${bId}::sib`;\n const rev = `${bId}->${aId}::sib`;\n if (!seen.has(fwd)) {\n seen.add(fwd);\n edges.push({ fromComponentId: aId, toComponentId: bId, weight: 0.3 });\n }\n if (!seen.has(rev)) {\n seen.add(rev);\n edges.push({ fromComponentId: bId, toComponentId: aId, weight: 0.3 });\n }\n }\n }\n }\n\n return edges;\n}\n\nfunction collectNodesAndEdges(\n getProminenceScore: (el: Element) => number,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): { nodes: ScannedNode[]; edges: StructuralEdge[]; elementToId: Map<Element, string> } {\n const nodes: ScannedNode[] = [];\n const seen = new Set<Element>();\n const elementToId = new Map<Element, string>();\n\n const registered = document.querySelectorAll('[data-sentient-id]');\n registered.forEach((el) => {\n if (el instanceof Element && !seen.has(el)) {\n seen.add(el);\n const node = scanElement(el, getProminenceScore, sectionTypes);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n }\n });\n\n const structural = document.querySelectorAll('section, article, main, aside');\n structural.forEach((el) => {\n if (!(el instanceof Element) || seen.has(el)) return;\n const hasAria = el.hasAttribute('aria-label');\n const hasSentientId = el.hasAttribute('data-sentient-id');\n if (!hasAria && !hasSentientId) return;\n seen.add(el);\n const node = scanElement(el, getProminenceScore, sectionTypes);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n });\n\n return { nodes, edges: detectStructuralEdges(elementToId), elementToId };\n}\n\n/**\n * Creates a DOM scanner that uses idle callbacks and mutation observation.\n */\nexport function createDOMScanner(options: DOMScannerOptions = {}): DOMScanner {\n const { sectionTypes } = options;\n if (typeof window === 'undefined') {\n return SSR_SCANNER;\n }\n\n let observer: MutationObserver | null = null;\n let idleCallbackId = 0;\n let contentCallback: ((event: ContentAddedEvent) => void) | null = null;\n // Element→componentId for every node registered so far (initial scan + prior\n // mutations). The MutationObserver detects edges against this whole set — not\n // just the nodes in the current mutation — so a child inserted under an\n // already-scanned parent still gets its parent→child edge.\n const knownElementToId = new Map<Element, string>();\n\n const getProminenceScore = (element: Element): number => {\n try {\n const styles = window.getComputedStyle(element);\n const fontSize = parseFloat(styles.fontSize) || 12;\n const zIndex = parseFloat(styles.zIndex) || 0;\n const rect = element.getBoundingClientRect();\n const distanceFromTop = Math.max(rect.top, 0);\n const viewportHeight = window.innerHeight || 1;\n const inverseDistance = 1 / (distanceFromTop / viewportHeight + 1);\n\n // inverseDistance is already in (0, 1] by construction, so it needs no\n // further normalization — only fontSize and zIndex are rescaled.\n const score =\n normalize(fontSize, 12, 48) * 0.4 +\n inverseDistance * 0.4 +\n normalize(zIndex, 0, 100) * 0.2;\n\n return Math.max(0, Math.min(1, score));\n } catch {\n return 0.5;\n }\n };\n\n const scan = (): Promise<ScanResult> =>\n new Promise((resolve) => {\n const run = (): void => {\n const { nodes, edges, elementToId } = collectNodesAndEdges(getProminenceScore, sectionTypes);\n // Seed the known-element registry so the observer can resolve parents that\n // were registered in this scan when later children are inserted.\n knownElementToId.clear();\n for (const [el, id] of elementToId) knownElementToId.set(el, id);\n resolve({ nodes, edges, scannedAt: Date.now() });\n };\n\n try {\n if (typeof requestIdleCallback === 'function') {\n idleCallbackId = requestIdleCallback(run, { timeout: 100 });\n } else {\n run();\n }\n } catch {\n run();\n }\n });\n\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n observer = new MutationObserver((mutations) => {\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const candidates: Element[] = [];\n if (\n OBSERVE_TAGS.has(node.tagName) &&\n (node.hasAttribute('data-sentient-id') || node.hasAttribute('aria-label'))\n ) {\n candidates.push(node);\n }\n // Also scan the inserted SUBTREE with the initial scan's criteria\n // (see SUBTREE_SELECTOR): the root of a SPA/framework mount is\n // usually a plain wrapper, and its sections arrive as descendants\n // of ONE childList mutation — inspecting only the root meant they\n // were never captured at all.\n try {\n node.querySelectorAll(SUBTREE_SELECTOR).forEach((el) => candidates.push(el));\n } catch {\n /* exotic host without querySelectorAll — root-only scan stands */\n }\n for (const el of candidates) {\n // Skip elements already registered: a parent and its child can\n // both appear in addedNodes (the child once via the parent's\n // subtree, once directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore, sectionTypes);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\n }\n });\n }\n if (added.length === 0 || !contentCallback) return;\n // Drop elements no longer in the document so removed nodes don't dangle\n // and the map stays bounded.\n for (const el of [...knownElementToId.keys()]) {\n if (!el.isConnected) knownElementToId.delete(el);\n }\n // Detect over the FULL known set so a child inserted under an already-\n // scanned parent still gets its parent→child edge, then surface only the\n // edges that touch a newly-added node (existing edges were already emitted).\n const edges = detectStructuralEdges(knownElementToId).filter(\n (e) => addedIds.has(e.fromComponentId) || addedIds.has(e.toComponentId),\n );\n contentCallback({ nodes: added, edges, addedAt: Date.now() });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n } catch {\n /* ignore */\n }\n };\n\n const destroy = (): void => {\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n if (idleCallbackId && typeof cancelIdleCallback === 'function') {\n try {\n cancelIdleCallback(idleCallbackId);\n } catch {\n /* ignore */\n }\n }\n idleCallbackId = 0;\n contentCallback = null;\n knownElementToId.clear();\n };\n\n return {\n scan,\n observe,\n getProminenceScore,\n destroy,\n };\n}\n","/**\n * Graph-capable entry point for @sentientui/core.\n *\n * Import from `@sentientui/core/graph` when you need DOM graph scanning and\n * page-structure sync. This entry pulls in `scanner.ts` and `graph.ts` at\n * build time, giving bundlers a real tree-shaking boundary. Standard A/B tests\n * should use `@sentientui/core` (the lean entry) instead.\n */\n\n// Re-export everything from the lean entry except `init`, which we override\n// below — so a graph consumer never needs dual-entry imports (importing the\n// lean entry alongside this one risks initialising two clients).\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n grantConsent,\n} from './index.js';\n// Sourced from their own modules (identical bindings to the lean barrel's):\n// snapshot/pre-paint helpers, slot helpers, blocks, micro-signals, and the\n// session cookie name — all were missing here, which made the comment above\n// a lie and forced consumers into dual-entry imports.\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\nexport type { SlotDeclInput, SlotResult } from './slots.js';\nexport * from './blocks.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n// SSR preload helpers moved to `@sentientui/core/server` in 0.6.0.\nexport type {\n SentientConfig,\n AssignResult,\n SentientClient,\n} from './index.js';\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n} from './index.js';\n// EventQueue/AssignmentCache are no longer on the lean barrel — source them from\n// their own modules so the `/graph` subpath keeps exposing them unchanged.\nexport type { EventQueue } from './queue.js';\nexport type { AssignmentCache } from './cache.js';\n// Scanner + graph types (live in this entry only).\nexport type {\n ScannedNode,\n ScanResult,\n ContentAddedEvent,\n DOMScanner,\n DOMScannerOptions,\n} from './scanner.js';\nexport type {\n PageNode,\n GraphSnapshot,\n GraphConfig,\n GraphClient,\n} from './graph.js';\nexport { sanitizePageUrl } from './graph.js';\nexport { locatorFromElement } from './locator-from-dom.js';\n\nimport {\n init as initLean,\n isDoNotTrackEnabled,\n _registerConsentUpgradeInit,\n type SentientConfig,\n type SentientClient,\n} from './index.js';\nexport { isDoNotTrackEnabled };\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\nimport { createDOMScanner } from './scanner.js';\nimport { createGraphClient } from './graph.js';\n\nexport type GraphSentientConfig = SentientConfig & {\n /**\n * Enable DOM graph scanning and page-structure sync. Wires a MutationObserver\n * and a localStorage-backed graph. When `false` (default) this entry behaves\n * identically to `@sentientui/core`.\n */\n graph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default —\n * headings can contain account names or user-generated content. Structure\n * (component ids, semantic types, prominence) still syncs when `graph: true`.\n */\n captureDomText?: boolean;\n /**\n * Section types declared in code, keyed by `data-sentient-id`\n * (e.g. `{ about: 'trust' }`). Wins over the content classifier and over\n * legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// The client writes the per-project SUFFIXED cookie (sessionCookieName in\n// storage-key.ts). This reader kept the bare `_snt_uid` after namespacing\n// landed, so graph sync sent `sessionId: undefined` for every keyed project.\n// The bare name stays as a fallback for pre-namespacing identities.\nfunction readSntUid(apiKey?: string): string | undefined {\n const read = (name: string): string | undefined => {\n try {\n // Cookie names are `_snt_uid` + `_` + a pk_ key prefix — no regex\n // metacharacters, so interpolation is safe (same pattern as session.ts).\n const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return m ? decodeURIComponent(m[1]!) : undefined;\n } catch {\n return undefined;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : undefined) ?? read(LEGACY_SESSION_COOKIE_NAME);\n}\n\n/**\n * Graph-capable variant of `init()`. Identical to the lean `init` when\n * `config.graph` is `false` (or omitted). When `config.graph: true`, mounts\n * a DOM scanner + graph client and enables `client.getGraph()`.\n *\n * Import from `@sentientui/core/graph` — do not call the lean `init` alongside\n * this function as that would initialise two clients.\n */\n// Teardown for the graph resources (scanner + MutationObserver + debounce\n// timer + graph client) bound to each apiKey. initLean already disposes the\n// lean client's own timers/listeners on re-init, but it knows nothing about\n// these graph resources, so this entry tracks and tears them down itself —\n// otherwise an HMR / consent-toggle / provider-remount re-init would leak a\n// live MutationObserver and a pending sync timer per mount.\nconst _graphTeardowns = new Map<string, () => void>();\n\nexport function init(config: GraphSentientConfig): SentientClient {\n const client = initLean(config);\n\n // Mirror initLean's opt-out gate: a DNT/GPC visitor (or consent:false) must\n // not get the DOM scanner + graph sync, which POST page-structure beacons and\n // read `_snt_uid` — tracking that bypasses the lean client's own gating, even\n // under `preConsentBehavior: 'statistical_winner'` (audit P1).\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Zero-network contract, mirroring the lean init's own gate: `localMode:\n // true` forces the on-device engine, and a missing OR INVALID (non-`pk_`)\n // key means the lean client is keyless-local or disabled. This used to check\n // only `!apiKey`, so a typo'd key — which the React provider's default\n // `graph: true` reaches — still mounted the scanner and POSTed\n // /v1/graph/sync into a client that discards everything.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n const zeroNetwork = config.localMode === true || !keyValid;\n if (!config.graph || zeroNetwork || typeof window === 'undefined') return client;\n\n if (gated) {\n // Consent may still be granted later: grantConsent() must re-init through\n // THIS entry so the post-consent client mounts the scanner — the lean init\n // it upgraded through before knows nothing about graph resources, so a\n // consent grant used to lose graph capture for the session. DNT-blocked\n // clients register nothing: consent cannot override a global opt-out.\n if (!dntBlocked) {\n _registerConsentUpgradeInit(config.apiKey, (c) => init(c as GraphSentientConfig));\n }\n return client;\n }\n\n // A prior graph mount for this key is now superseded — tear it down first so\n // its observer/timer don't leak alongside the new mount's.\n const prevTeardown = _graphTeardowns.get(config.apiKey);\n if (prevTeardown) {\n try {\n prevTeardown();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n const domScanner = createDOMScanner({ sectionTypes: config.sectionTypes });\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n const graphClient = createGraphClient({\n syncUrl: resolvedIngestUrl.replace(/\\/events\\/?$/, '/graph/sync'),\n apiKey: config.apiKey,\n projectId: config.apiKey,\n sessionId: readSntUid(config.apiKey),\n });\n\n // Persisted page-node state from a previous page load is restored by the graph\n // client's own constructor (it reads `_snt_graph_nodes` on creation). We no\n // longer re-read the key and call restore() here — that was a redundant second\n // load path that cleared and reloaded identical data.\n\n void domScanner.scan().then((result) => {\n for (const node of result.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of result.edges) {\n graphClient.addStructuralEdge(edge);\n }\n graphClient.syncOnce();\n });\n\n let syncDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n const debouncedSync = (): void => {\n if (syncDebounceTimer !== null) clearTimeout(syncDebounceTimer);\n syncDebounceTimer = setTimeout(() => {\n syncDebounceTimer = null;\n graphClient.syncOnce();\n }, 500);\n };\n\n domScanner.observe((event) => {\n for (const node of event.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of event.edges) {\n graphClient.addStructuralEdge(edge);\n }\n debouncedSync();\n });\n\n // Tears down only the graph resources; the caller pairs it with the lean\n // client's own dispose/destroy. Idempotent, and de-registers itself so a\n // later re-init or teardown can't run it twice on already-freed resources.\n const teardownGraph = (): void => {\n if (syncDebounceTimer !== null) {\n clearTimeout(syncDebounceTimer);\n syncDebounceTimer = null;\n }\n domScanner.destroy();\n graphClient.destroy();\n if (_graphTeardowns.get(config.apiKey) === teardownGraph) {\n _graphTeardowns.delete(config.apiKey);\n }\n };\n _graphTeardowns.set(config.apiKey, teardownGraph);\n\n return {\n ...client,\n getGraph: () => graphClient.snapshot(),\n dispose: () => {\n teardownGraph();\n client.dispose();\n },\n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EAAA,GACFtB,GADE,CAEL,SAAU,IAAMY,EAAY,SAAS,EACrC,QAAS,IAAM,CACbQ,EAAc,EACdpB,EAAO,QAAQ,CACjB,EACA,QAAS,IAAM,CACboB,EAAc,EACdpB,EAAO,QAAQ,CACjB,CACF,EACF","names":["STALE_EDGES_KEY","SEMANTIC_NEIGHBOURS","neighboursFor","semanticType","_a","readStorage","key","fallback","raw","e","writeStorage","value","VALID_SEMANTIC_TYPES","toValidSemanticType","type","sanitizePageUrl","href","u","contentHashOf","componentId","answers","input","h","i","createGraphClient","config","pageNodes","structuralEdges","nodesKey","storageSuffix","persist","storedNodes","node","edge","_b","nodes","nodesByType","n","list","edges","seen","source","neighbourType","targets","target","componentIds","payload","__spreadProps","__spreadValues","OBSERVE_TAGS","HEADING_SELECTOR","SUBTREE_SELECTOR","MAX_SIBLINGS_PER_GROUP","MAX_STRUCTURAL_EDGES","SSR_SCANNER","normalize","value","min","max","readReactComponentName","element","_a","_b","_c","record","key","fiber","name","e","extractDataAttributes","attrs","attr","SEMANTIC_SET","SEMANTIC_TYPES","inferSemanticType","sectionTypes","id","declared","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","depthOf","depth","scanElement","getProminenceScore","_d","heading","locatorFromElement","detectStructuralEdges","elementToId","edges","seen","ROOT","groups","el","_id","ancestor","groupKey","childId","siblings","sibs","capped","j","aId","bId","fwd","rev","collectNodesAndEdges","nodes","node","hasAria","hasSentientId","createDOMScanner","options","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","resolve","run","onContentAdded","mutations","added","addedIds","mutation","candidates","scanned","DEFAULT_INGEST_URL","readSntUid","apiKey","_a","read","name","m","e","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","_graphTeardowns","init","config","client","dntBlocked","isDoNotTrackEnabled","gated","keyValid","zeroNetwork","_registerConsentUpgradeInit","c","prevTeardown","domScanner","createDOMScanner","resolvedIngestUrl","graphClient","createGraphClient","result","node","edge","syncDebounceTimer","debouncedSync","event","teardownGraph","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/graph.ts","../src/scanner.ts","../src/index-graph.ts"],"sourcesContent":["/** In-memory context graph with persistence and backend sync. */\n\nimport { storageSuffix } from './storage-key.js';\n\nexport type PageNode = {\n id: string;\n componentId: string;\n semanticType: string;\n answers: string[];\n prominenceScore: number;\n depth: number;\n};\n\nexport type GraphSnapshot = {\n pageNodes: PageNode[];\n capturedAt: number;\n};\n\nexport type GraphConfig = {\n syncUrl?: string;\n apiKey?: string;\n projectId?: string;\n sessionId?: string;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n weight: number;\n};\n\nexport type GraphClient = {\n addPageNode(node: PageNode): void;\n /** Record a DOM-derived parent/child or sibling relationship between two components. */\n addStructuralEdge(edge: StructuralEdge): void;\n /** One-shot batch sync of all current page nodes to the backend. */\n syncOnce(): void;\n snapshot(): GraphSnapshot;\n destroy(): void;\n};\n\n// _snt_graph_edges was written by earlier builds but never synced to the backend.\n// We still read and clear any leftover key on init/destroy so old clients don't\n// accumulate stale data, but we no longer write it.\nconst STALE_EDGES_KEY = '_snt_graph_edges';\n\nconst SEMANTIC_NEIGHBOURS: Record<string, string[]> = {\n pricing: ['features', 'faq'],\n features: ['pricing'],\n faq: ['pricing'],\n social_proof: ['cta'],\n cta: ['social_proof', 'hero', 'trust'],\n hero: ['cta'],\n comparison: ['pricing'],\n trust: ['cta'],\n};\n\nfunction neighboursFor(semanticType: string): string[] {\n return SEMANTIC_NEIGHBOURS[semanticType] ?? [];\n}\n\nfunction readStorage<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return fallback;\n return JSON.parse(raw) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction writeStorage(key: string, value: unknown): void {\n try {\n localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* ignore */\n }\n}\n\nconst VALID_SEMANTIC_TYPES = new Set([\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n]);\n\nfunction toValidSemanticType(type: string): string {\n return VALID_SEMANTIC_TYPES.has(type) ? type : 'generic';\n}\n\n/**\n * Path-only page URL for graph sync — strips query + fragment so tokens,\n * emails, and other sensitive URL params never leave the browser by default.\n */\nexport function sanitizePageUrl(href: string): string {\n try {\n const u = new URL(href);\n return `${u.origin}${u.pathname}`;\n } catch {\n return '/';\n }\n}\n\nfunction contentHashOf(componentId: string, semanticType: string, answers: string[]): string {\n const input = `${componentId}:${semanticType}:${answers.join(',')}`;\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n/**\n * Creates an in-memory graph client with optional persistence and sync.\n */\nexport function createGraphClient(config?: GraphConfig): GraphClient {\n const pageNodes = new Map<string, PageNode>();\n const structuralEdges = new Map<string, StructuralEdge>();\n\n // Per-project localStorage key so two projects on one origin don't share a\n // graph-node cache (see storage-key.ts). Legacy `_snt_graph_nodes` with no key.\n const nodesKey = `_snt_graph_nodes${storageSuffix(config?.apiKey)}`;\n\n const persist = (): void => {\n if (typeof window === 'undefined') return;\n writeStorage(nodesKey, [...pageNodes.values()]);\n };\n\n // serialize()/restore() were removed here: persisted-node restoration moved\n // into this constructor (below), leaving both dead — yet still shipping in\n // the graph bundle.\n if (typeof window !== 'undefined') {\n const storedNodes = readStorage<PageNode[]>(nodesKey, []);\n for (const node of storedNodes) {\n pageNodes.set(node.componentId, node);\n }\n // Clear any stale edge data written by older SDK versions.\n try { localStorage.removeItem(STALE_EDGES_KEY); } catch { /* ignore */ }\n }\n\n return {\n addPageNode(node: PageNode): void {\n pageNodes.set(node.componentId, node);\n persist();\n },\n\n addStructuralEdge(edge: StructuralEdge): void {\n const key = `${edge.fromComponentId}->${edge.toComponentId}`;\n structuralEdges.set(key, edge);\n },\n\n syncOnce(): void {\n if (!config?.syncUrl || typeof window === 'undefined') return;\n const nodes = [...pageNodes.values()];\n if (nodes.length === 0) return;\n try {\n // Build semantic edges from the SEMANTIC_NEIGHBOURS map. Each node emits\n // an edge to every present sibling that matches one of its neighbour types.\n // Weight matches propagate()'s 0.4 attention factor; confidence is high\n // because the mapping is curated, not inferred.\n const nodesByType = new Map<string, PageNode[]>();\n for (const n of nodes) {\n const list = nodesByType.get(n.semanticType) ?? [];\n list.push(n);\n nodesByType.set(n.semanticType, list);\n }\n const edges: Array<{\n fromComponentId: string;\n toComponentId: string;\n type: 'semantic' | 'structural';\n weight: number;\n confidence: number;\n }> = [];\n const seen = new Set<string>();\n for (const source of nodes) {\n for (const neighbourType of neighboursFor(source.semanticType)) {\n const targets = nodesByType.get(neighbourType) ?? [];\n for (const target of targets) {\n if (target.componentId === source.componentId) continue;\n const key = `semantic:${source.componentId}->${target.componentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: source.componentId,\n toComponentId: target.componentId,\n type: 'semantic',\n weight: 0.4,\n confidence: 0.9,\n });\n }\n }\n }\n\n // Structural edges from DOM relationships, recorded during scan.\n // Only emit when both endpoints are present in this page's node set —\n // a structural edge to/from a node that no longer exists would dangle.\n const componentIds = new Set(nodes.map((n) => n.componentId));\n for (const edge of structuralEdges.values()) {\n if (!componentIds.has(edge.fromComponentId) || !componentIds.has(edge.toComponentId)) continue;\n const key = `structural:${edge.fromComponentId}->${edge.toComponentId}`;\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({\n fromComponentId: edge.fromComponentId,\n toComponentId: edge.toComponentId,\n type: 'structural',\n weight: edge.weight,\n confidence: 1.0,\n });\n }\n\n const payload = {\n pageUrl: sanitizePageUrl(window.location.href),\n // Visitor/project attribution. The /graph/sync handler ignores unknown\n // top-level fields (Fastify additionalProperties + Zod strips extras),\n // so these ride along harmlessly and let beacons carry attribution.\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.projectId ? { projectId: config.projectId } : {}),\n nodes: nodes.map((n) => {\n const semanticType = toValidSemanticType(n.semanticType);\n return {\n componentId: n.componentId,\n semanticType,\n answers: n.answers,\n contentHash: contentHashOf(n.componentId, semanticType, n.answers),\n prominenceScore: n.prominenceScore,\n depthInPage: n.depth,\n };\n }),\n edges,\n };\n fetch(config.syncUrl, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),\n },\n body: JSON.stringify(payload),\n }).catch(() => undefined);\n } catch {\n /* ignore */\n }\n },\n\n snapshot(): GraphSnapshot {\n return {\n pageNodes: [...pageNodes.values()],\n capturedAt: Date.now(),\n };\n },\n\n destroy(): void {\n if (typeof window === 'undefined') return;\n try {\n localStorage.removeItem(nodesKey);\n localStorage.removeItem(STALE_EDGES_KEY);\n } catch {\n /* ignore */\n }\n },\n };\n}\n","/** Reads the rendered DOM to build the page-side context graph. */\n\nimport { classifySection, SEMANTIC_TYPES, type SemanticType } from './engagement/classify';\nimport { locatorFromElement } from './locator-from-dom.js';\nimport type { CompoundLocator } from './snapshot.js';\n\nexport type ScannedNode = {\n componentId: string;\n semanticType: string;\n ariaLabel?: string;\n headingText?: string;\n isAboveFold: boolean;\n prominenceScore: number;\n depth: number;\n reactComponentName?: string;\n dataAttributes: Record<string, string>;\n /** Compound locator for this element. The server hashes it into section_key —\n * the identity the crawler and the snippet resolve to for the same physical\n * section. Undefined when nothing resolves uniquely: the runtime never\n * guesses an identity it could not verify later. */\n locator?: CompoundLocator;\n};\n\nexport type StructuralEdge = {\n fromComponentId: string;\n toComponentId: string;\n /** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */\n weight: number;\n};\n\nexport type ScanResult = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n scannedAt: number;\n};\n\nexport type ContentAddedEvent = {\n nodes: ScannedNode[];\n edges: StructuralEdge[];\n addedAt: number;\n};\n\nexport type DOMScanner = {\n scan(): Promise<ScanResult>;\n observe(onContentAdded: (event: ContentAddedEvent) => void): void;\n getProminenceScore(element: Element): number;\n destroy(): void;\n};\n\n// ASIDE included to match the initial scan (which queries `section, article,\n// main, aside`) — this set omitted it, so a server-rendered aside was captured\n// while an identical dynamically-inserted one was silently ignored.\nconst OBSERVE_TAGS = new Set(['SECTION', 'ARTICLE', 'MAIN', 'DIV', 'ASIDE']);\nconst HEADING_SELECTOR = 'h1, h2, h3';\n// Selector mirror of the initial scan's criteria (collectNodesAndEdges): any\n// element carrying a declared id, plus structural tags with an aria-label.\n// Used to walk INTO inserted subtrees — a SPA mounts ONE root node whose\n// interesting sections are all descendants, and inspecting only the root made\n// every framework-mounted component permanently invisible to graph capture.\nconst SUBTREE_SELECTOR =\n '[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]';\n\n// Sibling detection is O(n²) per group and emits two edges per pair, so a page\n// with hundreds of co-located components (e.g. a 200-cell product grid) would\n// otherwise emit tens of thousands of low-signal sibling edges. We cap the\n// sibling fan-out per group and the total structural edges per detection pass.\n// The total stays well under the server's 2000-edge-per-sync limit, leaving room\n// for semantic edges. Parent→child edges (higher signal) are emitted first, so\n// the cap sheds sibling edges before it ever touches them.\nconst MAX_SIBLINGS_PER_GROUP = 30;\nconst MAX_STRUCTURAL_EDGES = 1500;\n\nconst SSR_SCANNER: DOMScanner = {\n scan: async () => ({ nodes: [], edges: [], scannedAt: 0 }),\n observe: () => undefined,\n getProminenceScore: () => 0,\n destroy: () => undefined,\n};\n\nfunction normalize(value: number, min: number, max: number): number {\n if (max <= min) return 0;\n return Math.max(0, Math.min(1, (value - min) / (max - min)));\n}\n\nfunction readReactComponentName(element: Element): string | undefined {\n try {\n const record = element as unknown as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!key.startsWith('__reactFiber') && !key.startsWith('__reactInternalInstance')) {\n continue;\n }\n const fiber = record[key] as { type?: { name?: string; displayName?: string } };\n const name = fiber?.type?.displayName ?? fiber?.type?.name;\n if (name && name.length > 1) {\n return name;\n }\n }\n } catch {\n /* ignore */\n }\n return undefined;\n}\n\nfunction extractDataAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n if (attr.name.startsWith('data-')) {\n attrs[attr.name] = attr.value;\n }\n }\n return attrs;\n}\n\nconst SEMANTIC_SET: ReadonlySet<string> = new Set(SEMANTIC_TYPES);\n\nexport type DOMScannerOptions = {\n /**\n * Section types declared in code, keyed by `data-sentient-id`. Replaces the\n * per-element `data-sentient-type` attribute so a section needs one attribute\n * of markup. The content classifier misses sections whose copy carries no\n * strong signal (an \"About us\" band reads `generic`, not `trust`), and a\n * wrong type here reorders that section for the wrong personas.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// Declared type (sectionTypes) → legacy data-sentient-type markup → role →\n// heuristic → generic. Every output is normalized to the graph_nodes enum: an\n// out-of-vocabulary declared/markup/role value falls through to the next stage\n// instead of being emitted raw (raw values violated the graph_nodes CHECK\n// constraint on insert).\nfunction inferSemanticType(\n element: Element,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): SemanticType {\n const id = element.getAttribute('data-sentient-id');\n // The SEMANTIC_SET check also rejects inherited keys (an id of \"constructor\").\n const declared = id ? sectionTypes?.[id] : undefined;\n if (declared && SEMANTIC_SET.has(declared)) return declared as SemanticType;\n const explicit = element.getAttribute('data-sentient-type');\n if (explicit && SEMANTIC_SET.has(explicit)) return explicit as SemanticType;\n const role = element.getAttribute('role');\n if (role && SEMANTIC_SET.has(role)) return role as SemanticType;\n return classifySection(element);\n}\n\n// djb2 over a string → 8-hex-char digest. Stable and collision-resistant enough\n// to disambiguate co-located components that declare no id of their own.\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) & 0xffffffff;\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n\n// A structural path (tag + sibling index at each level up to the root) uniquely\n// and stably identifies an element's DOM position, so two id-less sections don't\n// hash to the same value the way a bare tagName would.\nfunction domPathSignature(element: Element): string {\n const parts: string[] = [];\n let current: Element | null = element;\n while (current) {\n const parent: Element | null = current.parentElement;\n if (!parent) {\n parts.push(current.tagName.toLowerCase());\n break;\n }\n const index = Array.prototype.indexOf.call(parent.children, current);\n parts.push(`${current.tagName.toLowerCase()}[${index}]`);\n current = parent;\n }\n return parts.reverse().join('/');\n}\n\n// Prefer an author-declared id. When none exists, synthesize a stable, unique id\n// from the element's DOM path — the old `tagName.toLowerCase()` fallback gave\n// every id-less <section> the same \"section\" id, so a second such node silently\n// overwrote the first in the componentId-keyed graph Map (node loss).\nfunction componentIdFor(element: Element): string {\n const declared =\n element.getAttribute('data-sentient-id') ?? element.getAttribute('id');\n if (declared) return declared;\n return `${element.tagName.toLowerCase()}-${shortHash(domPathSignature(element))}`;\n}\n\nfunction depthOf(element: Element): number {\n let depth = 0;\n let current: Element | null = element.parentElement;\n while (current) {\n depth++;\n current = current.parentElement;\n }\n return depth;\n}\n\nfunction scanElement(\n element: Element,\n getProminenceScore: (el: Element) => number,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): ScannedNode {\n const heading = element.querySelector(HEADING_SELECTOR);\n return {\n componentId: componentIdFor(element),\n semanticType: inferSemanticType(element, sectionTypes),\n ariaLabel: element.getAttribute('aria-label') ?? undefined,\n headingText: heading?.textContent?.trim() ?? undefined,\n isAboveFold: element.getBoundingClientRect().top < window.innerHeight,\n prominenceScore: getProminenceScore(element),\n depth: depthOf(element),\n reactComponentName: readReactComponentName(element),\n dataAttributes: extractDataAttributes(element),\n locator: locatorFromElement(element, element.ownerDocument) ?? undefined,\n };\n}\n\n/**\n * Detects structural relationships between scanned component elements:\n * - parent → child (direct ancestor link, weight 0.6)\n * - sibling ↔ sibling (share nearest component ancestor, weight 0.3, bidirectional)\n * A pair appears at most once per direction.\n */\nfunction detectStructuralEdges(elementToId: Map<Element, string>): StructuralEdge[] {\n const edges: StructuralEdge[] = [];\n const seen = new Set<string>();\n const ROOT = '__root__';\n\n // Parent → child: nearest component ancestor only.\n const groups = new Map<string, Element[]>();\n for (const [el, _id] of elementToId) {\n let ancestor: Element | null = el.parentElement;\n let groupKey = ROOT;\n while (ancestor) {\n if (elementToId.has(ancestor)) {\n groupKey = elementToId.get(ancestor)!;\n const childId = elementToId.get(el)!;\n const key = `${groupKey}->${childId}`;\n if (!seen.has(key) && groupKey !== childId) {\n seen.add(key);\n edges.push({ fromComponentId: groupKey, toComponentId: childId, weight: 0.6 });\n }\n break;\n }\n ancestor = ancestor.parentElement;\n }\n const siblings = groups.get(groupKey) ?? [];\n siblings.push(el);\n groups.set(groupKey, siblings);\n }\n\n // Sibling ↔ sibling: same ancestor group.\n for (const sibs of groups.values()) {\n if (sibs.length < 2) continue;\n // Cap the fan-out of any single group before the O(n²) pairing.\n const capped = sibs.length > MAX_SIBLINGS_PER_GROUP ? sibs.slice(0, MAX_SIBLINGS_PER_GROUP) : sibs;\n for (let i = 0; i < capped.length; i++) {\n for (let j = i + 1; j < capped.length; j++) {\n if (edges.length >= MAX_STRUCTURAL_EDGES) return edges;\n const aId = elementToId.get(capped[i]!)!;\n const bId = elementToId.get(capped[j]!)!;\n if (aId === bId) continue;\n const fwd = `${aId}->${bId}::sib`;\n const rev = `${bId}->${aId}::sib`;\n if (!seen.has(fwd)) {\n seen.add(fwd);\n edges.push({ fromComponentId: aId, toComponentId: bId, weight: 0.3 });\n }\n if (!seen.has(rev)) {\n seen.add(rev);\n edges.push({ fromComponentId: bId, toComponentId: aId, weight: 0.3 });\n }\n }\n }\n }\n\n return edges;\n}\n\nfunction collectNodesAndEdges(\n getProminenceScore: (el: Element) => number,\n sectionTypes: Readonly<Partial<Record<string, string>>> | undefined,\n): { nodes: ScannedNode[]; edges: StructuralEdge[]; elementToId: Map<Element, string> } {\n const nodes: ScannedNode[] = [];\n const seen = new Set<Element>();\n const elementToId = new Map<Element, string>();\n\n const registered = document.querySelectorAll('[data-sentient-id]');\n registered.forEach((el) => {\n if (el instanceof Element && !seen.has(el)) {\n seen.add(el);\n const node = scanElement(el, getProminenceScore, sectionTypes);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n }\n });\n\n const structural = document.querySelectorAll('section, article, main, aside');\n structural.forEach((el) => {\n if (!(el instanceof Element) || seen.has(el)) return;\n const hasAria = el.hasAttribute('aria-label');\n const hasSentientId = el.hasAttribute('data-sentient-id');\n if (!hasAria && !hasSentientId) return;\n seen.add(el);\n const node = scanElement(el, getProminenceScore, sectionTypes);\n nodes.push(node);\n elementToId.set(el, node.componentId);\n });\n\n return { nodes, edges: detectStructuralEdges(elementToId), elementToId };\n}\n\n/**\n * Creates a DOM scanner that uses idle callbacks and mutation observation.\n */\nexport function createDOMScanner(options: DOMScannerOptions = {}): DOMScanner {\n const { sectionTypes } = options;\n if (typeof window === 'undefined') {\n return SSR_SCANNER;\n }\n\n let observer: MutationObserver | null = null;\n let idleCallbackId = 0;\n let contentCallback: ((event: ContentAddedEvent) => void) | null = null;\n // Element→componentId for every node registered so far (initial scan + prior\n // mutations). The MutationObserver detects edges against this whole set — not\n // just the nodes in the current mutation — so a child inserted under an\n // already-scanned parent still gets its parent→child edge.\n const knownElementToId = new Map<Element, string>();\n\n const getProminenceScore = (element: Element): number => {\n try {\n const styles = window.getComputedStyle(element);\n const fontSize = parseFloat(styles.fontSize) || 12;\n const zIndex = parseFloat(styles.zIndex) || 0;\n const rect = element.getBoundingClientRect();\n const distanceFromTop = Math.max(rect.top, 0);\n const viewportHeight = window.innerHeight || 1;\n const inverseDistance = 1 / (distanceFromTop / viewportHeight + 1);\n\n // inverseDistance is already in (0, 1] by construction, so it needs no\n // further normalization — only fontSize and zIndex are rescaled.\n const score =\n normalize(fontSize, 12, 48) * 0.4 +\n inverseDistance * 0.4 +\n normalize(zIndex, 0, 100) * 0.2;\n\n return Math.max(0, Math.min(1, score));\n } catch {\n return 0.5;\n }\n };\n\n const scan = (): Promise<ScanResult> =>\n new Promise((resolve) => {\n const run = (): void => {\n const { nodes, edges, elementToId } = collectNodesAndEdges(getProminenceScore, sectionTypes);\n // Seed the known-element registry so the observer can resolve parents that\n // were registered in this scan when later children are inserted.\n knownElementToId.clear();\n for (const [el, id] of elementToId) knownElementToId.set(el, id);\n resolve({ nodes, edges, scannedAt: Date.now() });\n };\n\n try {\n if (typeof requestIdleCallback === 'function') {\n idleCallbackId = requestIdleCallback(run, { timeout: 100 });\n } else {\n run();\n }\n } catch {\n run();\n }\n });\n\n const observe = (onContentAdded: (event: ContentAddedEvent) => void): void => {\n contentCallback = onContentAdded;\n try {\n observer = new MutationObserver((mutations) => {\n const added: ScannedNode[] = [];\n const addedIds = new Set<string>();\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') continue;\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const candidates: Element[] = [];\n if (\n OBSERVE_TAGS.has(node.tagName) &&\n (node.hasAttribute('data-sentient-id') || node.hasAttribute('aria-label'))\n ) {\n candidates.push(node);\n }\n // Also scan the inserted SUBTREE with the initial scan's criteria\n // (see SUBTREE_SELECTOR): the root of a SPA/framework mount is\n // usually a plain wrapper, and its sections arrive as descendants\n // of ONE childList mutation — inspecting only the root meant they\n // were never captured at all.\n try {\n node.querySelectorAll(SUBTREE_SELECTOR).forEach((el) => candidates.push(el));\n } catch {\n /* exotic host without querySelectorAll — root-only scan stands */\n }\n for (const el of candidates) {\n // Skip elements already registered: a parent and its child can\n // both appear in addedNodes (the child once via the parent's\n // subtree, once directly), which would emit duplicate nodes.\n if (knownElementToId.has(el)) continue;\n const scanned = scanElement(el, getProminenceScore, sectionTypes);\n added.push(scanned);\n addedIds.add(scanned.componentId);\n knownElementToId.set(el, scanned.componentId);\n }\n });\n }\n if (added.length === 0 || !contentCallback) return;\n // Drop elements no longer in the document so removed nodes don't dangle\n // and the map stays bounded.\n for (const el of [...knownElementToId.keys()]) {\n if (!el.isConnected) knownElementToId.delete(el);\n }\n // Detect over the FULL known set so a child inserted under an already-\n // scanned parent still gets its parent→child edge, then surface only the\n // edges that touch a newly-added node (existing edges were already emitted).\n const edges = detectStructuralEdges(knownElementToId).filter(\n (e) => addedIds.has(e.fromComponentId) || addedIds.has(e.toComponentId),\n );\n contentCallback({ nodes: added, edges, addedAt: Date.now() });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n } catch {\n /* ignore */\n }\n };\n\n const destroy = (): void => {\n if (observer) {\n observer.disconnect();\n observer = null;\n }\n if (idleCallbackId && typeof cancelIdleCallback === 'function') {\n try {\n cancelIdleCallback(idleCallbackId);\n } catch {\n /* ignore */\n }\n }\n idleCallbackId = 0;\n contentCallback = null;\n knownElementToId.clear();\n };\n\n return {\n scan,\n observe,\n getProminenceScore,\n destroy,\n };\n}\n","/**\n * Graph-capable entry point for @sentientui/core.\n *\n * Import from `@sentientui/core/graph` when you need DOM graph scanning and\n * page-structure sync. This entry pulls in `scanner.ts` and `graph.ts` at\n * build time, giving bundlers a real tree-shaking boundary. Standard A/B tests\n * should use `@sentientui/core` (the lean entry) instead.\n */\n\n// Re-export everything from the lean entry except `init`, which we override\n// below — so a graph consumer never needs dual-entry imports (importing the\n// lean entry alongside this one risks initialising two clients).\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n referrerDomainFromReferer,\n grantConsent,\n} from './index.js';\n// Sourced from their own modules (identical bindings to the lean barrel's):\n// snapshot/pre-paint helpers, slot helpers, blocks, micro-signals, and the\n// session cookie name — all were missing here, which made the comment above\n// a lie and forced consumers into dual-entry imports.\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\nexport type { SlotDeclInput, SlotResult } from './slots.js';\nexport * from './blocks.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n// SSR preload helpers moved to `@sentientui/core/server` in 0.6.0.\nexport type {\n SentientConfig,\n AssignResult,\n SentientClient,\n} from './index.js';\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n} from './index.js';\n// EventQueue/AssignmentCache are no longer on the lean barrel — source them from\n// their own modules so the `/graph` subpath keeps exposing them unchanged.\nexport type { EventQueue } from './queue.js';\nexport type { AssignmentCache } from './cache.js';\n// Scanner + graph types (live in this entry only).\nexport type {\n ScannedNode,\n ScanResult,\n ContentAddedEvent,\n DOMScanner,\n DOMScannerOptions,\n} from './scanner.js';\nexport type {\n PageNode,\n GraphSnapshot,\n GraphConfig,\n GraphClient,\n} from './graph.js';\nexport { sanitizePageUrl } from './graph.js';\nexport { locatorFromElement } from './locator-from-dom.js';\n\nimport {\n init as initLean,\n isDoNotTrackEnabled,\n _registerConsentUpgradeInit,\n type SentientConfig,\n type SentientClient,\n} from './index.js';\nexport { isDoNotTrackEnabled };\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\nimport { createDOMScanner } from './scanner.js';\nimport { createGraphClient } from './graph.js';\n\nexport type GraphSentientConfig = SentientConfig & {\n /**\n * Enable DOM graph scanning and page-structure sync. Wires a MutationObserver\n * and a localStorage-backed graph. When `false` (default) this entry behaves\n * identically to `@sentientui/core`.\n */\n graph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default —\n * headings can contain account names or user-generated content. Structure\n * (component ids, semantic types, prominence) still syncs when `graph: true`.\n */\n captureDomText?: boolean;\n /**\n * Section types declared in code, keyed by `data-sentient-id`\n * (e.g. `{ about: 'trust' }`). Wins over the content classifier and over\n * legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n};\n\n// The client writes the per-project SUFFIXED cookie (sessionCookieName in\n// storage-key.ts). This reader kept the bare `_snt_uid` after namespacing\n// landed, so graph sync sent `sessionId: undefined` for every keyed project.\n// The bare name stays as a fallback for pre-namespacing identities.\nfunction readSntUid(apiKey?: string): string | undefined {\n const read = (name: string): string | undefined => {\n try {\n // Cookie names are `_snt_uid` + `_` + a pk_ key prefix — no regex\n // metacharacters, so interpolation is safe (same pattern as session.ts).\n const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return m ? decodeURIComponent(m[1]!) : undefined;\n } catch {\n return undefined;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : undefined) ?? read(LEGACY_SESSION_COOKIE_NAME);\n}\n\n/**\n * Graph-capable variant of `init()`. Identical to the lean `init` when\n * `config.graph` is `false` (or omitted). When `config.graph: true`, mounts\n * a DOM scanner + graph client and enables `client.getGraph()`.\n *\n * Import from `@sentientui/core/graph` — do not call the lean `init` alongside\n * this function as that would initialise two clients.\n */\n// Teardown for the graph resources (scanner + MutationObserver + debounce\n// timer + graph client) bound to each apiKey. initLean already disposes the\n// lean client's own timers/listeners on re-init, but it knows nothing about\n// these graph resources, so this entry tracks and tears them down itself —\n// otherwise an HMR / consent-toggle / provider-remount re-init would leak a\n// live MutationObserver and a pending sync timer per mount.\nconst _graphTeardowns = new Map<string, () => void>();\n\nexport function init(config: GraphSentientConfig): SentientClient {\n const client = initLean(config);\n\n // Mirror initLean's opt-out gate: a DNT/GPC visitor (or consent:false) must\n // not get the DOM scanner + graph sync, which POST page-structure beacons and\n // read `_snt_uid` — tracking that bypasses the lean client's own gating, even\n // under `preConsentBehavior: 'statistical_winner'` (audit P1).\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Zero-network contract, mirroring the lean init's own gate: `localMode:\n // true` forces the on-device engine, and a missing OR INVALID (non-`pk_`)\n // key means the lean client is keyless-local or disabled. This used to check\n // only `!apiKey`, so a typo'd key — which the React provider's default\n // `graph: true` reaches — still mounted the scanner and POSTed\n // /v1/graph/sync into a client that discards everything.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n const zeroNetwork = config.localMode === true || !keyValid;\n if (!config.graph || zeroNetwork || typeof window === 'undefined') return client;\n\n if (gated) {\n // Consent may still be granted later: grantConsent() must re-init through\n // THIS entry so the post-consent client mounts the scanner — the lean init\n // it upgraded through before knows nothing about graph resources, so a\n // consent grant used to lose graph capture for the session. DNT-blocked\n // clients register nothing: consent cannot override a global opt-out.\n if (!dntBlocked) {\n _registerConsentUpgradeInit(config.apiKey, (c) => init(c as GraphSentientConfig));\n }\n return client;\n }\n\n // A prior graph mount for this key is now superseded — tear it down first so\n // its observer/timer don't leak alongside the new mount's.\n const prevTeardown = _graphTeardowns.get(config.apiKey);\n if (prevTeardown) {\n try {\n prevTeardown();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n const domScanner = createDOMScanner({ sectionTypes: config.sectionTypes });\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n const graphClient = createGraphClient({\n syncUrl: resolvedIngestUrl.replace(/\\/events\\/?$/, '/graph/sync'),\n apiKey: config.apiKey,\n projectId: config.apiKey,\n sessionId: readSntUid(config.apiKey),\n });\n\n // Persisted page-node state from a previous page load is restored by the graph\n // client's own constructor (it reads `_snt_graph_nodes` on creation). We no\n // longer re-read the key and call restore() here — that was a redundant second\n // load path that cleared and reloaded identical data.\n\n void domScanner.scan().then((result) => {\n for (const node of result.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of result.edges) {\n graphClient.addStructuralEdge(edge);\n }\n graphClient.syncOnce();\n });\n\n let syncDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n const debouncedSync = (): void => {\n if (syncDebounceTimer !== null) clearTimeout(syncDebounceTimer);\n syncDebounceTimer = setTimeout(() => {\n syncDebounceTimer = null;\n graphClient.syncOnce();\n }, 500);\n };\n\n domScanner.observe((event) => {\n for (const node of event.nodes) {\n graphClient.addPageNode({\n id: node.componentId,\n componentId: node.componentId,\n semanticType: node.semanticType,\n answers: config.captureDomText && node.headingText ? [node.headingText] : [],\n prominenceScore: node.prominenceScore,\n depth: node.depth,\n });\n }\n for (const edge of event.edges) {\n graphClient.addStructuralEdge(edge);\n }\n debouncedSync();\n });\n\n // Tears down only the graph resources; the caller pairs it with the lean\n // client's own dispose/destroy. Idempotent, and de-registers itself so a\n // later re-init or teardown can't run it twice on already-freed resources.\n const teardownGraph = (): void => {\n if (syncDebounceTimer !== null) {\n clearTimeout(syncDebounceTimer);\n syncDebounceTimer = null;\n }\n domScanner.destroy();\n graphClient.destroy();\n if (_graphTeardowns.get(config.apiKey) === teardownGraph) {\n _graphTeardowns.delete(config.apiKey);\n }\n };\n _graphTeardowns.set(config.apiKey, teardownGraph);\n\n return {\n ...client,\n getGraph: () => graphClient.snapshot(),\n dispose: () => {\n teardownGraph();\n client.dispose();\n },\n destroy: () => {\n teardownGraph();\n client.destroy();\n },\n };\n}\n"],"mappings":"kkBA4CA,IAAMA,EAAkB,mBAElBC,GAAgD,CACpD,QAAS,CAAC,WAAY,KAAK,EAC3B,SAAU,CAAC,SAAS,EACpB,IAAK,CAAC,SAAS,EACf,aAAc,CAAC,KAAK,EACpB,IAAK,CAAC,eAAgB,OAAQ,OAAO,EACrC,KAAM,CAAC,KAAK,EACZ,WAAY,CAAC,SAAS,EACtB,MAAO,CAAC,KAAK,CACf,EAEA,SAASC,GAAcC,EAAgC,CAzDvD,IAAAC,EA0DE,OAAOA,EAAAH,GAAoBE,CAAY,IAAhC,KAAAC,EAAqC,CAAC,CAC/C,CAEA,SAASC,G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EAEpCJ,EAAY,SAAS,CACvB,CAAC,EAED,IAAIK,EAA0D,KACxDC,EAAgB,IAAY,CAC5BD,IAAsB,MAAM,aAAaA,CAAiB,EAC9DA,EAAoB,WAAW,IAAM,CACnCA,EAAoB,KACpBL,EAAY,SAAS,CACvB,EAAG,GAAG,CACR,EAEAH,EAAW,QAASU,GAAU,CAC5B,QAAWJ,KAAQI,EAAM,MACvBP,EAAY,YAAY,CACtB,GAAIG,EAAK,YACT,YAAaA,EAAK,YAClB,aAAcA,EAAK,aACnB,QAAShB,EAAO,gBAAkBgB,EAAK,YAAc,CAACA,EAAK,WAAW,EAAI,CAAC,EAC3E,gBAAiBA,EAAK,gBACtB,MAAOA,EAAK,KACd,CAAC,EAEH,QAAWC,KAAQG,EAAM,MACvBP,EAAY,kBAAkBI,CAAI,EAEpCE,EAAc,CAChB,CAAC,EAKD,IAAME,EAAgB,IAAY,CAC5BH,IAAsB,OACxB,aAAaA,CAAiB,EAC9BA,EAAoB,MAEtBR,EAAW,QAAQ,EACnBG,EAAY,QAAQ,EAChBf,EAAgB,IAAIE,EAAO,MAAM,IAAMqB,GACzCvB,EAAgB,OAAOE,EAAO,MAAM,CAExC,EACA,OAAAF,EAAgB,IAAIE,EAAO,OAAQqB,CAAa,EAEzCC,EAAAC,EAAA,GACFtB,GADE,CAEL,SAAU,IAAMY,EAAY,SAAS,EACrC,QAAS,IAAM,CACbQ,EAAc,EACdpB,EAAO,QAAQ,CACjB,EACA,QAAS,IAAM,CACboB,EAAc,EACdpB,EAAO,QAAQ,CACjB,CACF,EACF","names":["STALE_EDGES_KEY","SEMANTIC_NEIGHBOURS","neighboursFor","semanticType","_a","readStorage","key","fallback","raw","e","writeStorage","value","VALID_SEMANTIC_TYPES","toValidSemanticType","type","sanitizePageUrl","href","u","contentHashOf","componentId","answers","input","h","i","createGraphClient","config","pageNodes","structuralEdges","nodesKey","storageSuffix","persist","storedNodes","node","edge","_b","nodes","nodesByType","n","list","edges","seen","source","neighbourType","targets","target","componentIds","payload","__spreadProps","__spreadValues","OBSERVE_TAGS","HEADING_SELECTOR","SUBTREE_SELECTOR","MAX_SIBLINGS_PER_GROUP","MAX_STRUCTURAL_EDGES","SSR_SCANNER","normalize","value","min","max","readReactComponentName","element","_a","_b","_c","record","key","fiber","name","e","extractDataAttributes","attrs","attr","SEMANTIC_SET","SEMANTIC_TYPES","inferSemanticType","sectionTypes","id","declared","explicit","role","classifySection","shortHash","input","h","i","domPathSignature","parts","current","parent","index","componentIdFor","depthOf","depth","scanElement","getProminenceScore","_d","heading","locatorFromElement","detectStructuralEdges","elementToId","edges","seen","ROOT","groups","el","_id","ancestor","groupKey","childId","siblings","sibs","capped","j","aId","bId","fwd","rev","collectNodesAndEdges","nodes","node","hasAria","hasSentientId","createDOMScanner","options","observer","idleCallbackId","contentCallback","knownElementToId","styles","fontSize","zIndex","rect","distanceFromTop","viewportHeight","inverseDistance","score","resolve","run","onContentAdded","mutations","added","addedIds","mutation","candidates","scanned","DEFAULT_INGEST_URL","readSntUid","apiKey","_a","read","name","m","e","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","_graphTeardowns","init","config","client","dntBlocked","isDoNotTrackEnabled","gated","keyValid","zeroNetwork","_registerConsentUpgradeInit","c","prevTeardown","domScanner","createDOMScanner","resolvedIngestUrl","graphClient","createGraphClient","result","node","edge","syncDebounceTimer","debouncedSync","event","teardownGraph","__spreadProps","__spreadValues"]}
@@ -1,5 +1,7 @@
1
- import { d as DecideOutcome } from './index-COl_pfNm.cjs';
2
- import { a2 as SlotDeclInput } from './session-meta-DydKfQiR.cjs';
1
+ import { e as DecideOutcome } from './index-DnQbmMkx.cjs';
2
+ import { e as SlotDeclInput } from './session-meta-Dk8ivs-l.cjs';
3
+ import './style-vocabulary-BqviEw9O.cjs';
4
+ import './region-skeleton-D2ahkcbe.cjs';
3
5
  import '@sentientui/policy';
4
6
 
5
7
  /**
@@ -1,5 +1,7 @@
1
- import { d as DecideOutcome } from './index-CgkImSaM.js';
2
- import { a2 as SlotDeclInput } from './session-meta-DydKfQiR.js';
1
+ import { e as DecideOutcome } from './index-DX-MuX8O.js';
2
+ import { e as SlotDeclInput } from './session-meta-B0sXgtFN.js';
3
+ import './style-vocabulary-BqviEw9O.js';
4
+ import './region-skeleton-D2ahkcbe.js';
3
5
  import '@sentientui/policy';
4
6
 
5
7
  /**
@@ -0,0 +1,40 @@
1
+ import { R as RegionSkeleton } from './region-skeleton-D2ahkcbe.cjs';
2
+
3
+ declare function normalizeLeafText(s: string): string;
4
+ /** 16 hex chars over the normalized leaf texts. Text-only on purpose: React
5
+ * must compute the same value from its element tree at decide time, when no
6
+ * DOM for the baseline may exist (a served arm is on screen). */
7
+ declare function skeletonFingerprint(leaves: string[]): string;
8
+ /** The addressing half of a capture: which text nodes the region has, which
9
+ * element owns each, and the fingerprint. No computed colours, classes or
10
+ * roles — this is all the snippet needs on every page view (fingerprint for
11
+ * the decide, owners for applying edits), and keeping it separate keeps the
12
+ * descriptive half out of the always-on bundle. */
13
+ type RegionAddress = {
14
+ textNodes: Text[];
15
+ ownerEls: Element[];
16
+ leafToNode: number[];
17
+ leaves: string[];
18
+ fp: string;
19
+ };
20
+ declare function regionAddress(root: Element, maxNodes?: number): RegionAddress | {
21
+ reason: 'too_large' | 'empty';
22
+ };
23
+ declare function captureRegionDom(root: Element, maxNodes?: number): {
24
+ skeleton: RegionSkeleton;
25
+ textNodes: Text[];
26
+ ownerEls: Element[];
27
+ } | {
28
+ skeleton: null;
29
+ reason: 'too_large' | 'empty';
30
+ };
31
+ declare function captureRegionSkeleton(root: Element, opts?: {
32
+ maxNodes?: number;
33
+ }): {
34
+ skeleton: RegionSkeleton;
35
+ } | {
36
+ skeleton: null;
37
+ reason: 'too_large' | 'empty' | 'unaddressable';
38
+ };
39
+
40
+ export { type RegionAddress, captureRegionDom, captureRegionSkeleton, normalizeLeafText, regionAddress, skeletonFingerprint };
@@ -0,0 +1,40 @@
1
+ import { R as RegionSkeleton } from './region-skeleton-D2ahkcbe.js';
2
+
3
+ declare function normalizeLeafText(s: string): string;
4
+ /** 16 hex chars over the normalized leaf texts. Text-only on purpose: React
5
+ * must compute the same value from its element tree at decide time, when no
6
+ * DOM for the baseline may exist (a served arm is on screen). */
7
+ declare function skeletonFingerprint(leaves: string[]): string;
8
+ /** The addressing half of a capture: which text nodes the region has, which
9
+ * element owns each, and the fingerprint. No computed colours, classes or
10
+ * roles — this is all the snippet needs on every page view (fingerprint for
11
+ * the decide, owners for applying edits), and keeping it separate keeps the
12
+ * descriptive half out of the always-on bundle. */
13
+ type RegionAddress = {
14
+ textNodes: Text[];
15
+ ownerEls: Element[];
16
+ leafToNode: number[];
17
+ leaves: string[];
18
+ fp: string;
19
+ };
20
+ declare function regionAddress(root: Element, maxNodes?: number): RegionAddress | {
21
+ reason: 'too_large' | 'empty';
22
+ };
23
+ declare function captureRegionDom(root: Element, maxNodes?: number): {
24
+ skeleton: RegionSkeleton;
25
+ textNodes: Text[];
26
+ ownerEls: Element[];
27
+ } | {
28
+ skeleton: null;
29
+ reason: 'too_large' | 'empty';
30
+ };
31
+ declare function captureRegionSkeleton(root: Element, opts?: {
32
+ maxNodes?: number;
33
+ }): {
34
+ skeleton: RegionSkeleton;
35
+ } | {
36
+ skeleton: null;
37
+ reason: 'too_large' | 'empty' | 'unaddressable';
38
+ };
39
+
40
+ export { type RegionAddress, captureRegionDom, captureRegionSkeleton, normalizeLeafText, regionAddress, skeletonFingerprint };
@@ -0,0 +1,2 @@
1
+ "use strict";var h=Object.defineProperty,U=Object.defineProperties,X=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertyNames,_=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var I=(e,t,n)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p=(e,t)=>{for(var n in t||(t={}))O.call(t,n)&&I(e,n,t[n]);if(_)for(var n of _(t))q.call(t,n)&&I(e,n,t[n]);return e},x=(e,t)=>U(e,j(t));var Q=(e,t)=>{for(var n in t)h(e,n,{get:t[n],enumerable:!0})},W=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of z(t))!O.call(e,o)&&o!==n&&h(e,o,{get:()=>t[o],enumerable:!(r=X(t,o))||r.enumerable});return e};var Y=e=>W(h({},"__esModule",{value:!0}),e);var ue={};Q(ue,{captureRegionDom:()=>R,captureRegionSkeleton:()=>F,normalizeLeafText:()=>S,regionAddress:()=>A,skeletonFingerprint:()=>k});module.exports=Y(ue);var J=/(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([^()]*\)|#[0-9a-f]{3,8}\b/gi,Z=/^rgba?\(\s*[\d.]+[,\s]+[\d.]+[,\s]+[\d.]+(?:[,\s/]+[\d.]+%?)?\s*\)$/i,E;function ee(e){if(E!==void 0)return E;try{let t=e.createElement("canvas");t.width=t.height=1,E=t.getContext("2d",{willReadFrequently:!0})}catch(t){E=null}return E}function b(e,t){let n=(e!=null?e:"").trim();if(n===""||n==="transparent")return n==="transparent"?"rgba(0, 0, 0, 0)":"";if(Z.test(n)||/^#[0-9a-f]{3,8}$/i.test(n))return n;let r=ee(t);if(!r)return"";try{if(r.fillStyle="#010203",r.fillStyle=n,String(r.fillStyle).toLowerCase()==="#010203"&&n.toLowerCase()!=="#010203")return"";r.clearRect(0,0,1,1),r.fillRect(0,0,1,1);let[o,l,a,i]=r.getImageData(0,0,1,1).data;return i===255?`rgb(${o}, ${l}, ${a})`:`rgba(${o}, ${l}, ${a}, ${Math.round(i/255*1e3)/1e3})`}catch(o){return""}}function v(e,t){var n;return!e||e==="none"||!/gradient/i.test(e)?[]:((n=e.match(J))!=null?n:[]).map(r=>b(r,t)).filter(r=>r!=="")}function S(e){return e.replace(/\s+/g," ").trim().slice(0,300)}function $(e,t){let n=t>>>0;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function k(e){let t=e.join("");return $(t,2166136261)+$(t,1523705862)}var ne=new Set(["A","BUTTON"]),P=/^H([1-6])$/,re=new Set(["P","LI","LABEL","BLOCKQUOTE","FIGCAPTION","DT","DD","TD","TH"]),oe=new Set(["LABEL","FIGCAPTION","DT"]),le=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"]);function G(e){return ne.has(e.tagName)||e.getAttribute("role")==="button"?!0:e.tagName==="INPUT"&&/^(submit|button)$/i.test(e.type)}function ae(e){if(P.test(e.tagName)||re.has(e.tagName))return!0;let t=e.ownerDocument.defaultView,n=t?t.getComputedStyle(e).display:"";return n!==""&&n!=="inline"&&n!=="contents"}function se(e,t){let n=null;for(let r=e.parentElement;r&&r!==t.parentElement;r=r.parentElement){if(G(r)){n=r;break}if(r===t)break}if(n)return n;for(let r=e.parentElement;r;r=r.parentElement)if(r===t||ae(r))return r;return t}function B(e,t){var n,r;if(e)try{let o=new URL(e,(r=(n=t.location)==null?void 0:n.href)!=null?r:"https://relative.invalid/");return o.protocol!=="https:"&&o.protocol!=="http:"?void 0:t.location&&o.origin===t.location.origin?o.pathname:`${o.origin}${o.pathname}`}catch(o){return}}function M(e){return e===""||e==="transparent"||/rgba\([^)]*,\s*0\)$/.test(e)}function ie(e){let t=e.ownerDocument,n=t.defaultView;if(!n)return{bg:null};for(let r=e;r;r=r.parentElement){let o=n.getComputedStyle(r),l=v(o.backgroundImage,t);if(l.length>0)return p({bg:l[0]},l.length>1?{alt:l[l.length-1]}:{});let a=b(o.backgroundColor,t);if(!M(a))return{bg:a}}return{bg:null}}function A(e,t=40){var i,u,m;let n=e.ownerDocument.createTreeWalker(e,4),r=[];for(let s=n.nextNode();s;s=n.nextNode())if(((i=s.nodeValue)!=null?i:"").trim()!==""&&!le.has((m=(u=s.parentElement)==null?void 0:u.tagName)!=null?m:"")&&(r.push(s),r.length>120))return{reason:"too_large"};if(r.length===0)return{reason:"empty"};let o=[],l=[];for(let s of r){let c=se(s,e),f=o.indexOf(c);f===-1&&(o.push(c),f=o.length-1),l.push(f)}if(o.length>t)return{reason:"too_large"};let a=r.map(s=>{var c;return S((c=s.nodeValue)!=null?c:"")});return{textNodes:r,ownerEls:o,leafToNode:l,leaves:a,fp:k(a)}}function R(e,t=40){var w;let n=A(e,t);if(!("fp"in n))return{skeleton:null,reason:n.reason};let{textNodes:r,ownerEls:o,leafToNode:l,leaves:a}=n,i=e.ownerDocument,u=i.defaultView,m=[],s=o.map((g,K)=>{var D,L;let d=u==null?void 0:u.getComputedStyle(g),C=(D=g.parentElement)!=null?D:e,T=m.indexOf(C);T===-1&&(m.push(C),T=m.length-1);let N=P.exec(g.tagName),y=G(g)?"action":N?"heading":oe.has(g.tagName)?"label":"text",V=S(a.filter((ge,H)=>l[H]===K).join(" "));return x(p(x(p({tag:g.tagName.toLowerCase(),role:y},N?{level:Number(N[1])}:{}),{text:V,classes:((L=g.getAttribute("class"))!=null?L:"").replace(/\s+/g," ").trim()}),y==="action"?p({filled:!!d&&(!M(b(d.backgroundColor,e.ownerDocument))||d.backgroundImage!==""&&d.backgroundImage!=="none")},B(g.getAttribute("href"),i)!==void 0?{href:B(g.getAttribute("href"),i)}:{}):{}),{color:b(d==null?void 0:d.color,e.ownerDocument),group:T,restylable:!0})}),c=ie(e),f=u==null?void 0:u.getComputedStyle(e);return{skeleton:{v:1,root:x(p({tag:e.tagName.toLowerCase(),classes:((w=e.getAttribute("class"))!=null?w:"").replace(/\s+/g," ").trim(),ambientBg:c.bg},c.alt?{ambientBgAlt:c.alt}:{}),{ambientText:b(f==null?void 0:f.color,e.ownerDocument)}),nodes:s,leaves:a,leafToNode:l,fp:k(a)},textNodes:r,ownerEls:o}}function F(e,t){try{let n=R(e,t==null?void 0:t.maxNodes);return n.skeleton?{skeleton:n.skeleton}:n}catch(n){return{skeleton:null,reason:"unaddressable"}}}0&&(module.exports={captureRegionDom,captureRegionSkeleton,normalizeLeafText,regionAddress,skeletonFingerprint});
2
+ //# sourceMappingURL=index-region.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index-region.ts","../src/css-color.ts","../src/region-capture.ts"],"sourcesContent":["/**\n * `@sentientui/core/region`: region skeleton capture and fingerprinting for\n * the React SDK, the snippet and the API. Split from the lean entry for bundle\n * size — see region-capture.ts.\n */\nexport { captureRegionDom, captureRegionSkeleton, normalizeLeafText, regionAddress, skeletonFingerprint } from './region-capture.js';\nexport type { RegionAddress } from './region-capture.js';\n","// Browser colour normalization for capture (spec 2026-09-23 §4.1/§4.2).\n// Chrome reports Tailwind v4 colours as `lab(…)` / `oklch(…)`, and the\n// contrast math, the server's colour check and the prompts all read `rgb()`.\n// Without this, a Tailwind v4 site's blue primary button had no measurable\n// fill (captured as a secondary button), its grey body text had no colour\n// (unusable under the contrast gate) and a slate gradient lost a stop —\n// found on bodyshopmanchester.co.uk, 2026-09-23.\n//\n// The browser is the one colour-space converter that is always right, so the\n// colour is painted to a 1×1 canvas and read back. No canvas (jsdom, some\n// privacy modes) → '' for non-rgb input: unknown, which every consumer\n// already treats as \"not measured\" rather than guessing.\n\nconst FN = /(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\([^()]*\\)|#[0-9a-f]{3,8}\\b/gi;\nconst RGB = /^rgba?\\(\\s*[\\d.]+[,\\s]+[\\d.]+[,\\s]+[\\d.]+(?:[,\\s/]+[\\d.]+%?)?\\s*\\)$/i;\n\nlet ctx: CanvasRenderingContext2D | null | undefined;\n\nfunction context(doc: Document): CanvasRenderingContext2D | null {\n if (ctx !== undefined) return ctx;\n try {\n const c = doc.createElement('canvas');\n c.width = c.height = 1;\n ctx = c.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D | null;\n } catch {\n ctx = null;\n }\n return ctx;\n}\n\n/** `rgb(r, g, b)` / `rgba(r, g, b, a)` for any CSS colour; '' when unknown. */\nexport function toRgb(color: string | null | undefined, doc: Document): string {\n const c = (color ?? '').trim();\n if (c === '' || c === 'transparent') return c === 'transparent' ? 'rgba(0, 0, 0, 0)' : '';\n if (RGB.test(c) || /^#[0-9a-f]{3,8}$/i.test(c)) return c;\n const g = context(doc);\n if (!g) return '';\n try {\n // A sentinel detects an unparsable value: assigning garbage to fillStyle\n // is silently ignored, which would otherwise read back the sentinel.\n g.fillStyle = '#010203';\n g.fillStyle = c;\n if (String(g.fillStyle).toLowerCase() === '#010203' && c.toLowerCase() !== '#010203') return '';\n g.clearRect(0, 0, 1, 1);\n g.fillRect(0, 0, 1, 1);\n const [r, gr, b, a] = g.getImageData(0, 0, 1, 1).data as unknown as number[];\n return a === 255 ? `rgb(${r}, ${gr}, ${b})` : `rgba(${r}, ${gr}, ${b}, ${Math.round((a! / 255) * 1000) / 1000})`;\n } catch {\n return '';\n }\n}\n\n/** Colour stops of a `background-image` gradient, normalized; [] for none. */\nexport function gradientStopsRgb(img: string | null | undefined, doc: Document): string[] {\n if (!img || img === 'none' || !/gradient/i.test(img)) return [];\n return (img.match(FN) ?? []).map((s) => toRgb(s, doc)).filter((s) => s !== '');\n}\n\n/** Test seam: forget the cached canvas context. */\nexport function resetColorCanvas(): void {\n ctx = undefined;\n}\n","// DOM capture of a region skeleton (spec 2026-09-23 §4.1). Its own entry —\n// `@sentientui/core/region` — so the lean core that every plain-JS install\n// downloads doesn't carry ~2 KB of capture code only React and the snippet use.\nimport {\n MAX_SKELETON_LEAVES,\n MAX_SKELETON_NODES,\n MAX_SKELETON_TEXT,\n type RegionSkeleton,\n type SkeletonNode,\n type SkeletonRole,\n} from './region-skeleton.js';\nimport { gradientStopsRgb, toRgb } from './css-color.js';\n\nexport function normalizeLeafText(s: string): string {\n return s.replace(/\\s+/g, ' ').trim().slice(0, MAX_SKELETON_TEXT);\n}\n\nfunction fnv(str: string, seed: number): string {\n let h = seed >>> 0;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h.toString(16).padStart(8, '0');\n}\n\n/** 16 hex chars over the normalized leaf texts. Text-only on purpose: React\n * must compute the same value from its element tree at decide time, when no\n * DOM for the baseline may exist (a served arm is on screen). */\nexport function skeletonFingerprint(leaves: string[]): string {\n const s = leaves.join('\\u001f');\n return fnv(s, 0x811c9dc5) + fnv(s, 0x01000193 ^ 0x5bd1e995);\n}\n\n\nconst ACTION_TAGS = new Set(['A', 'BUTTON']);\nconst HEADING_RE = /^H([1-6])$/;\nconst BLOCK_TAGS = new Set(['P', 'LI', 'LABEL', 'BLOCKQUOTE', 'FIGCAPTION', 'DT', 'DD', 'TD', 'TH']);\nconst LABEL_TAGS = new Set(['LABEL', 'FIGCAPTION', 'DT']);\nconst SKIP_PARENTS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);\n\nfunction isAction(el: Element): boolean {\n if (ACTION_TAGS.has(el.tagName)) return true;\n if (el.getAttribute('role') === 'button') return true;\n return el.tagName === 'INPUT' && /^(submit|button)$/i.test((el as HTMLInputElement).type);\n}\n\nfunction isBlock(el: Element): boolean {\n if (HEADING_RE.test(el.tagName) || BLOCK_TAGS.has(el.tagName)) return true;\n const view = el.ownerDocument.defaultView;\n const d = view ? view.getComputedStyle(el).display : '';\n return d !== '' && d !== 'inline' && d !== 'contents';\n}\n\n/** Owner of a text node: the nearest ACTION ancestor inside the region if any\n * (a styled button wrapping a display:block span is still a button), else the\n * nearest block ancestor, else the region root. */\nfunction ownerOf(text: Text, root: Element): Element {\n let action: Element | null = null;\n for (let el = text.parentElement; el && el !== root.parentElement; el = el.parentElement) {\n if (isAction(el)) { action = el; break; }\n if (el === root) break;\n }\n if (action) return action;\n for (let el = text.parentElement; el; el = el.parentElement) {\n if (el === root || isBlock(el)) return el;\n }\n return root;\n}\n\nfunction linkOf(raw: string | null, doc: Document): string | undefined {\n if (!raw) return undefined;\n try {\n const u = new URL(raw, doc.location?.href ?? 'https://relative.invalid/');\n if (u.protocol !== 'https:' && u.protocol !== 'http:') return undefined;\n return doc.location && u.origin === doc.location.origin ? u.pathname : `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n\nfunction transparent(c: string): boolean {\n return c === '' || c === 'transparent' || /rgba\\([^)]*,\\s*0\\)$/.test(c);\n}\n\nfunction ambient(root: Element): { bg: string | null; alt?: string } {\n const doc = root.ownerDocument;\n const view = doc.defaultView;\n if (!view) return { bg: null };\n for (let el: Element | null = root; el; el = el.parentElement) {\n const cs = view.getComputedStyle(el);\n // lab()/oklch() stops (Tailwind v4) normalized, or the gradient's second\n // stop was silently dropped (css-color.ts).\n const stops = gradientStopsRgb(cs.backgroundImage, doc);\n if (stops.length > 0) return { bg: stops[0]!, ...(stops.length > 1 ? { alt: stops[stops.length - 1]! } : {}) };\n const bg = toRgb(cs.backgroundColor, doc);\n if (!transparent(bg)) return { bg };\n }\n return { bg: null };\n}\n\n/** The addressing half of a capture: which text nodes the region has, which\n * element owns each, and the fingerprint. No computed colours, classes or\n * roles — this is all the snippet needs on every page view (fingerprint for\n * the decide, owners for applying edits), and keeping it separate keeps the\n * descriptive half out of the always-on bundle. */\nexport type RegionAddress = { textNodes: Text[]; ownerEls: Element[]; leafToNode: number[]; leaves: string[]; fp: string };\n\nexport function regionAddress(\n root: Element,\n maxNodes = MAX_SKELETON_NODES,\n): RegionAddress | { reason: 'too_large' | 'empty' } {\n const walker = root.ownerDocument.createTreeWalker(root, 4 /* SHOW_TEXT */);\n const textNodes: Text[] = [];\n for (let n = walker.nextNode(); n; n = walker.nextNode()) {\n if ((n.nodeValue ?? '').trim() === '') continue;\n if (SKIP_PARENTS.has(n.parentElement?.tagName ?? '')) continue;\n textNodes.push(n as Text);\n if (textNodes.length > MAX_SKELETON_LEAVES) return { reason: 'too_large' };\n }\n if (textNodes.length === 0) return { reason: 'empty' };\n const ownerEls: Element[] = [];\n const leafToNode: number[] = [];\n for (const t of textNodes) {\n const owner = ownerOf(t, root);\n let idx = ownerEls.indexOf(owner);\n if (idx === -1) { ownerEls.push(owner); idx = ownerEls.length - 1; }\n leafToNode.push(idx);\n }\n if (ownerEls.length > maxNodes) return { reason: 'too_large' };\n const leaves = textNodes.map((t) => normalizeLeafText(t.nodeValue ?? ''));\n return { textNodes, ownerEls, leafToNode, leaves, fp: skeletonFingerprint(leaves) };\n}\n\nexport function captureRegionDom(\n root: Element,\n maxNodes = MAX_SKELETON_NODES,\n): { skeleton: RegionSkeleton; textNodes: Text[]; ownerEls: Element[] } | { skeleton: null; reason: 'too_large' | 'empty' } {\n const addr = regionAddress(root, maxNodes);\n if (!('fp' in addr)) return { skeleton: null, reason: addr.reason };\n const { textNodes, ownerEls, leafToNode, leaves } = addr;\n const doc = root.ownerDocument;\n const view = doc.defaultView;\n\n const parents: Element[] = [];\n const nodes: SkeletonNode[] = ownerEls.map((el, i) => {\n const cs = view?.getComputedStyle(el);\n const parent = el.parentElement ?? root;\n let group = parents.indexOf(parent);\n if (group === -1) { parents.push(parent); group = parents.length - 1; }\n const h = HEADING_RE.exec(el.tagName);\n const role: SkeletonRole = isAction(el) ? 'action' : h ? 'heading' : LABEL_TAGS.has(el.tagName) ? 'label' : 'text';\n const text = normalizeLeafText(leaves.filter((_, li) => leafToNode[li] === i).join(' '));\n return {\n tag: el.tagName.toLowerCase(),\n role,\n ...(h ? { level: Number(h[1]) as SkeletonNode['level'] } : {}),\n text,\n classes: (el.getAttribute('class') ?? '').replace(/\\s+/g, ' ').trim(),\n ...(role === 'action'\n ? {\n filled: !!cs && (!transparent(toRgb(cs.backgroundColor, root.ownerDocument)) || (cs.backgroundImage !== '' && cs.backgroundImage !== 'none')),\n ...(linkOf(el.getAttribute('href'), doc) !== undefined ? { href: linkOf(el.getAttribute('href'), doc)! } : {}),\n }\n : {}),\n color: toRgb(cs?.color, root.ownerDocument),\n group,\n restylable: true,\n };\n });\n const amb = ambient(root);\n const rootCs = view?.getComputedStyle(root);\n const skeleton: RegionSkeleton = {\n v: 1,\n root: {\n tag: root.tagName.toLowerCase(),\n classes: (root.getAttribute('class') ?? '').replace(/\\s+/g, ' ').trim(),\n ambientBg: amb.bg,\n ...(amb.alt ? { ambientBgAlt: amb.alt } : {}),\n ambientText: toRgb(rootCs?.color, root.ownerDocument),\n },\n nodes,\n leaves,\n leafToNode,\n fp: skeletonFingerprint(leaves),\n };\n return { skeleton, textNodes, ownerEls };\n}\n\nexport function captureRegionSkeleton(\n root: Element,\n opts?: { maxNodes?: number },\n): { skeleton: RegionSkeleton } | { skeleton: null; reason: 'too_large' | 'empty' | 'unaddressable' } {\n try {\n const out = captureRegionDom(root, opts?.maxNodes);\n return out.skeleton ? { skeleton: out.skeleton } : out;\n } catch {\n return { skeleton: null, reason: 'unaddressable' };\n }\n}\n"],"mappings":"owBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,sBAAAE,EAAA,0BAAAC,EAAA,sBAAAC,EAAA,kBAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAP,ICaA,IAAMQ,EAAK,6EACLC,EAAM,uEAERC,EAEJ,SAASC,GAAQC,EAAgD,CAC/D,GAAIF,IAAQ,OAAW,OAAOA,EAC9B,GAAI,CACF,IAAMG,EAAID,EAAI,cAAc,QAAQ,EACpCC,EAAE,MAAQA,EAAE,OAAS,EACrBH,EAAMG,EAAE,WAAW,KAAM,CAAE,mBAAoB,EAAK,CAAC,CACvD,OAAQC,EAAA,CACNJ,EAAM,IACR,CACA,OAAOA,CACT,CAGO,SAASK,EAAMC,EAAkCJ,EAAuB,CAC7E,IAAMC,GAAKG,GAAA,KAAAA,EAAS,IAAI,KAAK,EAC7B,GAAIH,IAAM,IAAMA,IAAM,cAAe,OAAOA,IAAM,cAAgB,mBAAqB,GACvF,GAAIJ,EAAI,KAAKI,CAAC,GAAK,oBAAoB,KAAKA,CAAC,EAAG,OAAOA,EACvD,IAAMI,EAAIN,GAAQC,CAAG,EACrB,GAAI,CAACK,EAAG,MAAO,GACf,GAAI,CAKF,GAFAA,EAAE,UAAY,UACdA,EAAE,UAAYJ,EACV,OAAOI,EAAE,SAAS,EAAE,YAAY,IAAM,WAAaJ,EAAE,YAAY,IAAM,UAAW,M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AAG,EAAE,KAAK,EACtE,UAAWkC,EAAI,IACXA,EAAI,IAAM,CAAE,aAAcA,EAAI,GAAI,EAAI,CAAC,GAJvC,CAKJ,YAAatB,EAAMuB,GAAA,YAAAA,EAAQ,MAAOxC,EAAK,aAAa,CACtD,GACA,MAAAgC,EACA,OAAA7C,EACA,WAAAsC,EACA,GAAIvC,EAAoBC,CAAM,CAChC,EACmB,UAAAmC,EAAW,SAAAE,CAAS,CACzC,CAEO,SAASiB,EACdzC,EACA0C,EACoG,CACpG,GAAI,CACF,IAAMC,EAAMd,EAAiB7B,EAAM0C,GAAA,YAAAA,EAAM,QAAQ,EACjD,OAAOC,EAAI,SAAW,CAAE,SAAUA,EAAI,QAAS,EAAIA,CACrD,OAAQnC,EAAA,CACN,MAAO,CAAE,SAAU,KAAM,OAAQ,eAAgB,CACnD,CACF","names":["index_region_exports","__export","captureRegionDom","captureRegionSkeleton","normalizeLeafText","regionAddress","skeletonFingerprint","__toCommonJS","FN","RGB","ctx","context","doc","c","e","toRgb","color","g","r","gr","b","a","gradientStopsRgb","img","_a","s","normalizeLeafText","s","fnv","str","seed","h","i","skeletonFingerprint","leaves","ACTION_TAGS","HEADING_RE","BLOCK_TAGS","LABEL_TAGS","SKIP_PARENTS","isAction","el","isBlock","view","d","ownerOf","text","root","action","linkOf","raw","doc","_a","_b","u","e","transparent","c","ambient","cs","stops","gradientStopsRgb","__spreadValues","bg","toRgb","regionAddress","maxNodes","_c","walker","textNodes","n","ownerEls","leafToNode","t","owner","idx","captureRegionDom","addr","parents","nodes","parent","group","role","_","li","__spreadProps","amb","rootCs","captureRegionSkeleton","opts","out"]}
@@ -0,0 +1,2 @@
1
+ import{a as R,b as M,c as V}from"./chunk-NCLBL5V3.mjs";import{a as E,b as y}from"./chunk-G6VP7HGJ.mjs";import{a as p,b}from"./chunk-TMCGHANO.mjs";function k(e){return e.replace(/\s+/g," ").trim().slice(0,300)}function D(e,o){let n=o>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function S(e){let o=e.join("");return D(o,2166136261)+D(o,1523705862)}var $=new Set(["A","BUTTON"]),O=/^H([1-6])$/,F=new Set(["P","LI","LABEL","BLOCKQUOTE","FIGCAPTION","DT","DD","TD","TH"]),H=new Set(["LABEL","FIGCAPTION","DT"]),U=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"]);function C(e){return $.has(e.tagName)||e.getAttribute("role")==="button"?!0:e.tagName==="INPUT"&&/^(submit|button)$/i.test(e.type)}function X(e){if(O.test(e.tagName)||F.has(e.tagName))return!0;let o=e.ownerDocument.defaultView,n=o?o.getComputedStyle(e).display:"";return n!==""&&n!=="inline"&&n!=="contents"}function j(e,o){let n=null;for(let t=e.parentElement;t&&t!==o.parentElement;t=t.parentElement){if(C(t)){n=t;break}if(t===o)break}if(n)return n;for(let t=e.parentElement;t;t=t.parentElement)if(t===o||X(t))return t;return o}function _(e,o){var n,t;if(e)try{let r=new URL(e,(t=(n=o.location)==null?void 0:n.href)!=null?t:"https://relative.invalid/");return r.protocol!=="https:"&&r.protocol!=="http:"?void 0:o.location&&r.origin===o.location.origin?r.pathname:`${r.origin}${r.pathname}`}catch(r){return}}function I(e){return e===""||e==="transparent"||/rgba\([^)]*,\s*0\)$/.test(e)}function z(e){let o=e.ownerDocument,n=o.defaultView;if(!n)return{bg:null};for(let t=e;t;t=t.parentElement){let r=n.getComputedStyle(t),l=y(r.backgroundImage,o);if(l.length>0)return p({bg:l[0]},l.length>1?{alt:l[l.length-1]}:{});let s=E(r.backgroundColor,o);if(!I(s))return{bg:s}}return{bg:null}}function B(e,o=40){var f,i,d;let n=e.ownerDocument.createTreeWalker(e,4),t=[];for(let a=n.nextNode();a;a=n.nextNode())if(((f=a.nodeValue)!=null?f:"").trim()!==""&&!U.has((d=(i=a.parentElement)==null?void 0:i.tagName)!=null?d:"")&&(t.push(a),t.length>120))return{reason:"too_large"};if(t.length===0)return{reason:"empty"};let r=[],l=[];for(let a of t){let u=j(a,e),g=r.indexOf(u);g===-1&&(r.push(u),g=r.length-1),l.push(g)}if(r.length>o)return{reason:"too_large"};let s=t.map(a=>{var u;return k((u=a.nodeValue)!=null?u:"")});return{textNodes:t,ownerEls:r,leafToNode:l,leaves:s,fp:S(s)}}function P(e,o=40){var h;let n=B(e,o);if(!("fp"in n))return{skeleton:null,reason:n.reason};let{textNodes:t,ownerEls:r,leafToNode:l,leaves:s}=n,f=e.ownerDocument,i=f.defaultView,d=[],a=r.map((c,v)=>{var w,L;let m=i==null?void 0:i.getComputedStyle(c),x=(w=c.parentElement)!=null?w:e,T=d.indexOf(x);T===-1&&(d.push(x),T=d.length-1);let N=O.exec(c.tagName),A=C(c)?"action":N?"heading":H.has(c.tagName)?"label":"text",G=k(s.filter((Y,K)=>l[K]===v).join(" "));return b(p(b(p({tag:c.tagName.toLowerCase(),role:A},N?{level:Number(N[1])}:{}),{text:G,classes:((L=c.getAttribute("class"))!=null?L:"").replace(/\s+/g," ").trim()}),A==="action"?p({filled:!!m&&(!I(E(m.backgroundColor,e.ownerDocument))||m.backgroundImage!==""&&m.backgroundImage!=="none")},_(c.getAttribute("href"),f)!==void 0?{href:_(c.getAttribute("href"),f)}:{}):{}),{color:E(m==null?void 0:m.color,e.ownerDocument),group:T,restylable:!0})}),u=z(e),g=i==null?void 0:i.getComputedStyle(e);return{skeleton:{v:1,root:b(p({tag:e.tagName.toLowerCase(),classes:((h=e.getAttribute("class"))!=null?h:"").replace(/\s+/g," ").trim(),ambientBg:u.bg},u.alt?{ambientBgAlt:u.alt}:{}),{ambientText:E(g==null?void 0:g.color,e.ownerDocument)}),nodes:a,leaves:s,leafToNode:l,fp:S(s)},textNodes:t,ownerEls:r}}function Q(e,o){try{let n=P(e,o==null?void 0:o.maxNodes);return n.skeleton?{skeleton:n.skeleton}:n}catch(n){return{skeleton:null,reason:"unaddressable"}}}export{P as captureRegionDom,Q as captureRegionSkeleton,k as normalizeLeafText,B as regionAddress,S as skeletonFingerprint};
2
+ //# sourceMappingURL=index-region.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/region-capture.ts"],"sourcesContent":["// DOM capture of a region skeleton (spec 2026-09-23 §4.1). Its own entry —\n// `@sentientui/core/region` — so the lean core that every plain-JS install\n// downloads doesn't carry ~2 KB of capture code only React and the snippet use.\nimport {\n MAX_SKELETON_LEAVES,\n MAX_SKELETON_NODES,\n MAX_SKELETON_TEXT,\n type RegionSkeleton,\n type SkeletonNode,\n type SkeletonRole,\n} from './region-skeleton.js';\nimport { gradientStopsRgb, toRgb } from './css-color.js';\n\nexport function normalizeLeafText(s: string): string {\n return s.replace(/\\s+/g, ' ').trim().slice(0, MAX_SKELETON_TEXT);\n}\n\nfunction fnv(str: string, seed: number): string {\n let h = seed >>> 0;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193) >>> 0;\n }\n return h.toString(16).padStart(8, '0');\n}\n\n/** 16 hex chars over the normalized leaf texts. Text-only on purpose: React\n * must compute the same value from its element tree at decide time, when no\n * DOM for the baseline may exist (a served arm is on screen). */\nexport function skeletonFingerprint(leaves: string[]): string {\n const s = leaves.join('\\u001f');\n return fnv(s, 0x811c9dc5) + fnv(s, 0x01000193 ^ 0x5bd1e995);\n}\n\n\nconst ACTION_TAGS = new Set(['A', 'BUTTON']);\nconst HEADING_RE = /^H([1-6])$/;\nconst BLOCK_TAGS = new Set(['P', 'LI', 'LABEL', 'BLOCKQUOTE', 'FIGCAPTION', 'DT', 'DD', 'TD', 'TH']);\nconst LABEL_TAGS = new Set(['LABEL', 'FIGCAPTION', 'DT']);\nconst SKIP_PARENTS = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);\n\nfunction isAction(el: Element): boolean {\n if (ACTION_TAGS.has(el.tagName)) return true;\n if (el.getAttribute('role') === 'button') return true;\n return el.tagName === 'INPUT' && /^(submit|button)$/i.test((el as HTMLInputElement).type);\n}\n\nfunction isBlock(el: Element): boolean {\n if (HEADING_RE.test(el.tagName) || BLOCK_TAGS.has(el.tagName)) return true;\n const view = el.ownerDocument.defaultView;\n const d = view ? view.getComputedStyle(el).display : '';\n return d !== '' && d !== 'inline' && d !== 'contents';\n}\n\n/** Owner of a text node: the nearest ACTION ancestor inside the region if any\n * (a styled button wrapping a display:block span is still a button), else the\n * nearest block ancestor, else the region root. */\nfunction ownerOf(text: Text, root: Element): Element {\n let action: Element | null = null;\n for (let el = text.parentElement; el && el !== root.parentElement; el = el.parentElement) {\n if (isAction(el)) { action = el; break; }\n if (el === root) break;\n }\n if (action) return action;\n for (let el = text.parentElement; el; el = el.parentElement) {\n if (el === root || isBlock(el)) return el;\n }\n return root;\n}\n\nfunction linkOf(raw: string | null, doc: Document): string | undefined {\n if (!raw) return undefined;\n try {\n const u = new URL(raw, doc.location?.href ?? 'https://relative.invalid/');\n if (u.protocol !== 'https:' && u.protocol !== 'http:') return undefined;\n return doc.location && u.origin === doc.location.origin ? u.pathname : `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n\nfunction transparent(c: string): boolean {\n return c === '' || c === 'transparent' || /rgba\\([^)]*,\\s*0\\)$/.test(c);\n}\n\nfunction ambient(root: Element): { bg: string | null; alt?: string } {\n const doc = root.ownerDocument;\n const view = doc.defaultView;\n if (!view) return { bg: null };\n for (let el: Element | null = root; el; el = el.parentElement) {\n const cs = view.getComputedStyle(el);\n // lab()/oklch() stops (Tailwind v4) normalized, or the gradient's second\n // stop was silently dropped (css-color.ts).\n const stops = gradientStopsRgb(cs.backgroundImage, doc);\n if (stops.length > 0) return { bg: stops[0]!, ...(stops.length > 1 ? { alt: stops[stops.length - 1]! } : {}) };\n const bg = toRgb(cs.backgroundColor, doc);\n if (!transparent(bg)) return { bg };\n }\n return { bg: null };\n}\n\n/** The addressing half of a capture: which text nodes the region has, which\n * element owns each, and the fingerprint. No computed colours, classes or\n * roles — this is all the snippet needs on every page view (fingerprint for\n * the decide, owners for applying edits), and keeping it separate keeps the\n * descriptive half out of the always-on bundle. */\nexport type RegionAddress = { textNodes: Text[]; ownerEls: Element[]; leafToNode: number[]; leaves: string[]; fp: string };\n\nexport function regionAddress(\n root: Element,\n maxNodes = MAX_SKELETON_NODES,\n): RegionAddress | { reason: 'too_large' | 'empty' } {\n const walker = root.ownerDocument.createTreeWalker(root, 4 /* SHOW_TEXT */);\n const textNodes: Text[] = [];\n for (let n = walker.nextNode(); n; n = walker.nextNode()) {\n if ((n.nodeValue ?? '').trim() === '') continue;\n if (SKIP_PARENTS.has(n.parentElement?.tagName ?? '')) continue;\n textNodes.push(n as Text);\n if (textNodes.length > MAX_SKELETON_LEAVES) return { reason: 'too_large' };\n }\n if (textNodes.length === 0) return { reason: 'empty' };\n const ownerEls: Element[] = [];\n const leafToNode: number[] = [];\n for (const t of textNodes) {\n const owner = ownerOf(t, root);\n let idx = ownerEls.indexOf(owner);\n if (idx === -1) { ownerEls.push(owner); idx = ownerEls.length - 1; }\n leafToNode.push(idx);\n }\n if (ownerEls.length > maxNodes) return { reason: 'too_large' };\n const leaves = textNodes.map((t) => normalizeLeafText(t.nodeValue ?? ''));\n return { textNodes, ownerEls, leafToNode, leaves, fp: skeletonFingerprint(leaves) };\n}\n\nexport function captureRegionDom(\n root: Element,\n maxNodes = MAX_SKELETON_NODES,\n): { skeleton: RegionSkeleton; textNodes: Text[]; ownerEls: Element[] } | { skeleton: null; reason: 'too_large' | 'empty' } {\n const addr = regionAddress(root, maxNodes);\n if (!('fp' in addr)) return { skeleton: null, reason: addr.reason };\n const { textNodes, ownerEls, leafToNode, leaves } = addr;\n const doc = root.ownerDocument;\n const view = doc.defaultView;\n\n const parents: Element[] = [];\n const nodes: SkeletonNode[] = ownerEls.map((el, i) => {\n const cs = view?.getComputedStyle(el);\n const parent = el.parentElement ?? root;\n let group = parents.indexOf(parent);\n if (group === -1) { parents.push(parent); group = parents.length - 1; }\n const h = HEADING_RE.exec(el.tagName);\n const role: SkeletonRole = isAction(el) ? 'action' : h ? 'heading' : LABEL_TAGS.has(el.tagName) ? 'label' : 'text';\n const text = normalizeLeafText(leaves.filter((_, li) => leafToNode[li] === i).join(' '));\n return {\n tag: el.tagName.toLowerCase(),\n role,\n ...(h ? { level: Number(h[1]) as SkeletonNode['level'] } : {}),\n text,\n classes: (el.getAttribute('class') ?? '').replace(/\\s+/g, ' ').trim(),\n ...(role === 'action'\n ? {\n filled: !!cs && (!transparent(toRgb(cs.backgroundColor, root.ownerDocument)) || (cs.backgroundImage !== '' && cs.backgroundImage !== 'none')),\n ...(linkOf(el.getAttribute('href'), doc) !== undefined ? { href: linkOf(el.getAttribute('href'), doc)! } : {}),\n }\n : {}),\n color: toRgb(cs?.color, root.ownerDocument),\n group,\n restylable: true,\n };\n });\n const amb = ambient(root);\n const rootCs = view?.getComputedStyle(root);\n const skeleton: RegionSkeleton = {\n v: 1,\n root: {\n tag: root.tagName.toLowerCase(),\n classes: (root.getAttribute('class') ?? '').replace(/\\s+/g, ' ').trim(),\n ambientBg: amb.bg,\n ...(amb.alt ? { ambientBgAlt: amb.alt } : {}),\n ambientText: toRgb(rootCs?.color, root.ownerDocument),\n },\n nodes,\n leaves,\n leafToNode,\n fp: skeletonFingerprint(leaves),\n };\n return { skeleton, textNodes, ownerEls };\n}\n\nexport function captureRegionSkeleton(\n root: Element,\n opts?: { maxNodes?: number },\n): { skeleton: RegionSkeleton } | { skeleton: null; reason: 'too_large' | 'empty' | 'unaddressable' } {\n try {\n const out = captureRegionDom(root, opts?.maxNodes);\n return out.skeleton ? { skeleton: out.skeleton } : out;\n } catch {\n return { skeleton: null, reason: 'unaddressable' };\n }\n}\n"],"mappings":"kJAaO,SAASA,EAAkBC,EAAmB,CACnD,OAAOA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAG,GAAiB,CACjE,CAEA,SAASC,EAAIC,EAAaC,EAAsB,CAC9C,IAAIC,EAAID,IAAS,EACjB,QAASE,EAAI,EAAGA,EA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C,GAXA,CAYL,MAAOa,EAAML,GAAA,YAAAA,EAAI,MAAOZ,EAAK,aAAa,EAC1C,MAAAkC,EACA,WAAY,EACd,EACF,CAAC,EACKK,EAAM5B,EAAQX,CAAI,EAClBwC,EAAS5C,GAAA,YAAAA,EAAM,iBAAiBI,GAetC,MAAO,CAAE,SAdwB,CAC/B,EAAG,EACH,KAAMsC,EAAAvB,EAAA,CACJ,IAAKf,EAAK,QAAQ,YAAY,EAC9B,UAAUK,EAAAL,EAAK,aAAa,OAAO,IAAzB,KAAAK,EAA8B,IAAI,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACtE,UAAWkC,EAAI,IACXA,EAAI,IAAM,CAAE,aAAcA,EAAI,GAAI,EAAI,CAAC,GAJvC,CAKJ,YAAatB,EAAMuB,GAAA,YAAAA,EAAQ,MAAOxC,EAAK,aAAa,CACtD,GACA,MAAAgC,EACA,OAAA7C,EACA,WAAAsC,EACA,GAAIvC,EAAoBC,CAAM,CAChC,EACmB,UAAAmC,EAAW,SAAAE,CAAS,CACzC,CAEO,SAASiB,EACdzC,EACA0C,EACoG,CACpG,GAAI,CACF,IAAMC,EAAMd,EAAiB7B,EAAM0C,GAAA,YAAAA,EAAM,QAAQ,EACjD,OAAOC,EAAI,SAAW,CAAE,SAAUA,EAAI,QAAS,EAAIA,CACrD,OAAQnC,EAAA,CACN,MAAO,CAAE,SAAU,KAAM,OAAQ,eAAgB,CACnD,CACF","names":["normalizeLeafText","s","fnv","str","seed","h","i","skeletonFingerprint","leaves","ACTION_TAGS","HEADING_RE","BLOCK_TAGS","LABEL_TAGS","SKIP_PARENTS","isAction","el","isBlock","view","d","ownerOf","text","root","action","linkOf","raw","doc","_a","_b","u","e","transparent","c","ambient","cs","stops","gradientStopsRgb","__spreadValues","bg","toRgb","regionAddress","maxNodes","_c","walker","textNodes","n","ownerEls","leafToNode","t","owner","idx","captureRegionDom","addr","parents","nodes","parent","group","role","_","li","__spreadProps","amb","rootCs","captureRegionSkeleton","opts","out"]}
@@ -1,5 +1,7 @@
1
- import { a1 as SlotConfigEntry, a0 as SitePalette, a2 as SlotDeclInput } from './session-meta-DydKfQiR.cjs';
2
- export { H as CLICK_ID_KEYS, $ as SessionUpsertPayload, ac as buildSessionUpsertPayload, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, aj as extractTrackedParams, am as referrerDomainFromReferer } from './session-meta-DydKfQiR.cjs';
1
+ import { $ as SitePalette, a4 as StyleVocabulary } from './style-vocabulary-BqviEw9O.cjs';
2
+ import { d as SlotConfigEntry, e as SlotDeclInput } from './session-meta-Dk8ivs-l.cjs';
3
+ export { C as CLICK_ID_KEYS, c as SessionUpsertPayload, l as buildSessionUpsertPayload, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, u as referrerDomainFromReferer } from './session-meta-Dk8ivs-l.cjs';
4
+ import { c as RenderCaps } from './region-skeleton-D2ahkcbe.cjs';
3
5
  import { SlotResult } from '@sentientui/policy';
4
6
  export { SlotResult } from '@sentientui/policy';
5
7
 
@@ -108,6 +110,8 @@ type DecideResult = {
108
110
  slotConfig?: Record<string, SlotConfigEntry>;
109
111
  /** Registry mode only: site palette for block rendering. */
110
112
  palette?: SitePalette;
113
+ /** Registry mode only: site styles the served Redesign arms borrow. */
114
+ vocabulary?: StyleVocabulary;
111
115
  };
112
116
  /**
113
117
  * Single-roundtrip SSR call returning layout order, component assignments,
@@ -137,6 +141,15 @@ declare function preloadDecisions(params: {
137
141
  * silently minting those trials.
138
142
  */
139
143
  registrySlotIds?: string[];
144
+ /**
145
+ * Registry mode: what each slot on this page can render (CONTRACTS §2).
146
+ * The server has no DOM here, so no fingerprint is sent and a Rewrite arm
147
+ * is assumed to match; a real mismatch is reported from the browser as
148
+ * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a
149
+ * form arm can be drawn that this page will refuse. Default per slot:
150
+ * `{ forms: true, compose: true }`.
151
+ */
152
+ renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;
140
153
  }, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
141
154
 
142
155
  type AgentCaptureOptions = {