@base44-preview/vite-plugin 0.2.20-pr.27.20fa529 → 0.2.20-pr.27.45bb4b6

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 (38) hide show
  1. package/dist/bridge.d.ts +5 -17
  2. package/dist/bridge.d.ts.map +1 -1
  3. package/dist/bridge.js +5 -30
  4. package/dist/bridge.js.map +1 -1
  5. package/dist/html-injections-plugin.d.ts +3 -4
  6. package/dist/html-injections-plugin.d.ts.map +1 -1
  7. package/dist/html-injections-plugin.js +125 -33
  8. package/dist/html-injections-plugin.js.map +1 -1
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/injections/navigation-notifier.d.ts +1 -2
  14. package/dist/injections/navigation-notifier.d.ts.map +1 -1
  15. package/dist/injections/navigation-notifier.js +2 -2
  16. package/dist/injections/navigation-notifier.js.map +1 -1
  17. package/dist/injections/sandbox-hmr-notifier.d.ts +1 -4
  18. package/dist/injections/sandbox-hmr-notifier.d.ts.map +1 -1
  19. package/dist/injections/sandbox-hmr-notifier.js +4 -4
  20. package/dist/injections/sandbox-hmr-notifier.js.map +1 -1
  21. package/dist/injections/sandbox-mount-observer.d.ts +1 -2
  22. package/dist/injections/sandbox-mount-observer.d.ts.map +1 -1
  23. package/dist/injections/sandbox-mount-observer.js +2 -2
  24. package/dist/injections/sandbox-mount-observer.js.map +1 -1
  25. package/dist/injections/unhandled-errors-handlers.d.ts +1 -4
  26. package/dist/injections/unhandled-errors-handlers.d.ts.map +1 -1
  27. package/dist/injections/unhandled-errors-handlers.js +67 -69
  28. package/dist/injections/unhandled-errors-handlers.js.map +1 -1
  29. package/dist/statics/index.mjs +1 -1
  30. package/dist/statics/index.mjs.map +1 -1
  31. package/package.json +1 -1
  32. package/src/bridge.ts +5 -34
  33. package/src/html-injections-plugin.ts +154 -40
  34. package/src/index.ts +4 -1
  35. package/src/injections/navigation-notifier.ts +1 -2
  36. package/src/injections/sandbox-hmr-notifier.ts +3 -4
  37. package/src/injections/sandbox-mount-observer.ts +2 -2
  38. package/src/injections/unhandled-errors-handlers.ts +80 -84
@@ -1,2 +1,2 @@
1
- function I(r){window.removeEventListener("unhandledrejection",a),window.removeEventListener("error",f),window.addEventListener("unhandledrejection",a),window.addEventListener("error",f);let d=!0,p=null;r&&(r.on("vite:beforeUpdate",()=>{d=!1,p&&clearTimeout(p),p=setTimeout(()=>{d=!0,p=null},1e4)}),r.on("vite:beforeFullReload",()=>{d=!1,p&&(clearTimeout(p),p=null)}));function g({title:s,details:w,componentName:u,originalError:m}){m?.response?.status===402||!d||window.parent?.postMessage({type:"app_error",error:{title:s.toString(),details:w?.toString(),componentName:u?.toString(),stack:m?.stack?.toString()}},"*")}function a(s){let u=s.reason.stack.match(/at\s+(\w+)\s+\(eval/)?.[1],m=u?`Error in ${u}: ${s.reason.toString()}`:s.reason.toString();g({title:m,details:s.reason.toString(),componentName:u,originalError:s.reason})}function f(s){let u=(s.error?.stack).match(/at\s+(\w+)\s+\(eval/)?.[1];u==="eval"&&(u=null);let m=u?`in ${u}: ${s.error.toString()}`:s.error.toString();g({title:m,details:s.error.toString(),componentName:u,originalError:s.error})}}function x(r){r.on("vite:beforeUpdate",()=>{window.parent?.postMessage({type:"sandbox:beforeUpdate"},"*")}),r.on("vite:afterUpdate",()=>{window.parent?.postMessage({type:"sandbox:afterUpdate"},"*")})}function O(){new MutationObserver(d=>{let p=d.some(a=>a.addedNodes.length>0),g=d.some(a=>a.removedNodes.length>0);(p||g)&&(document.body.querySelectorAll("[data-source-location], [data-dynamic-content]").length>0?window.parent?.postMessage({type:"sandbox:onMounted"},"*"):window.parent?.postMessage({type:"sandbox:onUnmounted"},"*"))}).observe(document.body,{childList:!0,subtree:!0})}function k(){let r=window.location.href;function d(){let a=window.location.href;a!==r&&(r=a,window.parent?.postMessage({type:"app_changed_url",url:a},"*"))}let p=history.pushState.bind(history);history.pushState=function(...a){p(...a),d()};let g=history.replaceState.bind(history);history.replaceState=function(...a){g(...a),d()},window.addEventListener("popstate",d),window.parent?.postMessage({type:"app_changed_url",url:window.location.href},"*")}function E(r){if(!r)return[];let d=Array.from(document.querySelectorAll(`[data-source-location="${r}"]`));return d.length>0?d:Array.from(document.querySelectorAll(`[data-visual-selector-id="${r}"]`))}function C(r,d){r.forEach(p=>{p.setAttribute("class",d)})}function A(){let r=!1,d=!1,p=!1,g=[],a=[],f=[],s=null,w=(n=!1)=>{let e=document.createElement("div");return e.style.position="absolute",e.style.pointerEvents="none",e.style.transition="all 0.1s ease-in-out",e.style.zIndex="9999",n?e.style.border="2px solid #2563EB":(e.style.border="2px solid #95a5fc",e.style.backgroundColor="rgba(99, 102, 241, 0.05)"),e},u=(n,e,t=!1)=>{if(!e||!r)return;e.offsetWidth;let o=e.getBoundingClientRect();n.style.top=`${o.top+window.scrollY}px`,n.style.left=`${o.left+window.scrollX}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;let i=n.querySelector("div");i||(i=document.createElement("div"),i.textContent=e.tagName.toLowerCase(),i.style.position="absolute",i.style.top="-27px",i.style.left="-2px",i.style.padding="2px 8px",i.style.fontSize="11px",i.style.fontWeight=t?"500":"400",i.style.color=t?"#ffffff":"#526cff",i.style.backgroundColor=t?"#526cff":"#DBEAFE",i.style.borderRadius="3px",i.style.minWidth="24px",i.style.textAlign="center",n.appendChild(i))},m=()=>{g.forEach(n=>{n&&n.parentNode&&n.remove()}),g=[],f=[]},N=n=>{if(!r||d)return;let e=n.target;if(p){m();return}if(e.tagName.toLowerCase()==="path"){m();return}let t=e.closest("[data-source-location], [data-visual-selector-id]");if(!t){m();return}let l=t,o=l.dataset.sourceLocation||l.dataset.visualSelectorId;if(s===o){m();return}let i=E(o||null);m(),i.forEach(c=>{let h=w(!1);document.body.appendChild(h),g.push(h),u(h,c)}),f=i},M=()=>{d||m()},S=n=>{if(!r)return;let e=n.target;if(p){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),window.parent.postMessage({type:"close-dropdowns"},"*");return}if(e.tagName.toLowerCase()==="path")return;n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation();let t=e.closest("[data-source-location], [data-visual-selector-id]");if(!t)return;let l=t,o=l.dataset.sourceLocation||l.dataset.visualSelectorId;a.forEach(v=>{v&&v.parentNode&&v.remove()}),a=[],E(o||null).forEach(v=>{let L=w(!0);document.body.appendChild(L),a.push(L),u(L,v,!0)}),s=o||null,m();let c=t.getBoundingClientRect(),h={top:c.top,left:c.left,right:c.right,bottom:c.bottom,width:c.width,height:c.height,centerX:c.left+c.width/2,centerY:c.top+c.height/2},y=t,_={type:"element-selected",tagName:t.tagName,classes:y.className?.baseVal||t.className||"",visualSelectorId:o,content:t.innerText,dataSourceLocation:l.dataset.sourceLocation,isDynamicContent:l.dataset.dynamicContent==="true",linenumber:l.dataset.linenumber,filename:l.dataset.filename,position:h};window.parent.postMessage(_,"*")},H=()=>{a.forEach(n=>{n&&n.parentNode&&n.remove()}),a=[],s=null},R=(n,e)=>{let t=E(n);t.length!==0&&(C(t,e),setTimeout(()=>{s===n&&a.forEach((l,o)=>{o<t.length&&u(l,t[o])}),f.length>0&&f[0]?.dataset?.visualSelectorId===n&&g.forEach((i,c)=>{c<f.length&&u(i,f[c])})},50))},D=(n,e)=>{let t=E(n);t.length!==0&&(t.forEach(l=>{l.innerText=e}),setTimeout(()=>{s===n&&a.forEach((l,o)=>{o<t.length&&u(l,t[o])})},50))},U=n=>{r=n,n?(document.body.style.cursor="crosshair",document.addEventListener("mouseover",N),document.addEventListener("mouseout",M),document.addEventListener("click",S,!0)):(m(),a.forEach(e=>{e&&e.parentNode&&e.remove()}),a=[],f=[],s=null,document.body.style.cursor="default",document.removeEventListener("mouseover",N),document.removeEventListener("mouseout",M),document.removeEventListener("click",S,!0))},T=()=>{if(s){let n=E(s);if(n.length>0){let t=n[0].getBoundingClientRect(),l=window.innerHeight,o=window.innerWidth,i=t.top<l&&t.bottom>0&&t.left<o&&t.right>0,c={top:t.top,left:t.left,right:t.right,bottom:t.bottom,width:t.width,height:t.height,centerX:t.left+t.width/2,centerY:t.top+t.height/2};window.parent.postMessage({type:"element-position-update",position:c,isInViewport:i,visualSelectorId:s},"*")}}},P=n=>{let e=n.data;switch(e.type){case"toggle-visual-edit-mode":U(e.data.enabled);break;case"update-classes":e.data&&e.data.classes!==void 0?R(e.data.visualSelectorId,e.data.classes):console.warn("[VisualEditAgent] Invalid update-classes message:",e);break;case"unselect-element":H();break;case"refresh-page":window.location.reload();break;case"update-content":e.data&&e.data.content!==void 0?D(e.data.visualSelectorId,e.data.content):console.warn("[VisualEditAgent] Invalid update-content message:",e);break;case"request-element-position":if(s){let t=E(s);if(t.length>0){let o=t[0].getBoundingClientRect(),i=window.innerHeight,c=window.innerWidth,h=o.top<i&&o.bottom>0&&o.left<c&&o.right>0,y={top:o.top,left:o.left,right:o.right,bottom:o.bottom,width:o.width,height:o.height,centerX:o.left+o.width/2,centerY:o.top+o.height/2};window.parent.postMessage({type:"element-position-update",position:y,isInViewport:h,visualSelectorId:s},"*")}}break;case"popover-drag-state":e.data&&e.data.isDragging!==void 0&&(d=e.data.isDragging,e.data.isDragging&&m());break;case"dropdown-state":e.data&&e.data.isOpen!==void 0&&(p=e.data.isOpen,e.data.isOpen&&m());break;default:break}},b=()=>{if(s){let n=E(s);a.forEach((e,t)=>{t<n.length&&u(e,n[t])})}f.length>0&&g.forEach((n,e)=>{e<f.length&&u(n,f[e])})};document.querySelectorAll("[data-linenumber]:not([data-visual-selector-id])").forEach((n,e)=>{let t=n,l=`visual-id-${t.dataset.filename}-${t.dataset.linenumber}-${e}`;t.dataset.visualSelectorId=l});let V=new MutationObserver(n=>{n.some(t=>{let l=i=>{if(i.nodeType===Node.ELEMENT_NODE){let c=i;if(c.dataset&&c.dataset.visualSelectorId)return!0;for(let h=0;h<c.children.length;h++)if(l(c.children[h]))return!0}return!1};return t.type==="attributes"&&(t.attributeName==="style"||t.attributeName==="class"||t.attributeName==="width"||t.attributeName==="height")&&l(t.target)})&&setTimeout(b,50)});window.addEventListener("message",P),window.addEventListener("scroll",T,!0),document.addEventListener("scroll",T,!0),window.addEventListener("resize",b),window.addEventListener("scroll",b),V.observe(document.body,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["style","class","width","height"]}),window.parent.postMessage({type:"visual-edit-agent-ready"},"*")}function Z(r={},d){window.self!==window.top&&(globalThis.__sandboxBridgeInitialized||(globalThis.__sandboxBridgeInitialized=!0,r.unhandledErrors!==!1&&I(d),r.mountObserver!==!1&&O(),r.hmrNotifier&&d&&x(d),r.navigationNotifier&&k(),r.visualEditAgent&&A()))}export{Z as init};
1
+ function f(d){if(!d)return[];let h=Array.from(document.querySelectorAll(`[data-source-location="${d}"]`));return h.length>0?h:Array.from(document.querySelectorAll(`[data-visual-selector-id="${d}"]`))}function T(d,h){d.forEach(g=>{g.setAttribute("class",h)})}function V(){let d=!1,h=!1,g=!1,E=[],c=[],u=[],l=null,L=(n=!1)=>{let e=document.createElement("div");return e.style.position="absolute",e.style.pointerEvents="none",e.style.transition="all 0.1s ease-in-out",e.style.zIndex="9999",n?e.style.border="2px solid #2563EB":(e.style.border="2px solid #95a5fc",e.style.backgroundColor="rgba(99, 102, 241, 0.05)"),e},p=(n,e,t=!1)=>{if(!e||!d)return;e.offsetWidth;let s=e.getBoundingClientRect();n.style.top=`${s.top+window.scrollY}px`,n.style.left=`${s.left+window.scrollX}px`,n.style.width=`${s.width}px`,n.style.height=`${s.height}px`;let o=n.querySelector("div");o||(o=document.createElement("div"),o.textContent=e.tagName.toLowerCase(),o.style.position="absolute",o.style.top="-27px",o.style.left="-2px",o.style.padding="2px 8px",o.style.fontSize="11px",o.style.fontWeight=t?"500":"400",o.style.color=t?"#ffffff":"#526cff",o.style.backgroundColor=t?"#526cff":"#DBEAFE",o.style.borderRadius="3px",o.style.minWidth="24px",o.style.textAlign="center",n.appendChild(o))},m=()=>{E.forEach(n=>{n&&n.parentNode&&n.remove()}),E=[],u=[]},M=n=>{if(!d||h)return;let e=n.target;if(g){m();return}if(e.tagName.toLowerCase()==="path"){m();return}let t=e.closest("[data-source-location], [data-visual-selector-id]");if(!t){m();return}let a=t,s=a.dataset.sourceLocation||a.dataset.visualSelectorId;if(l===s){m();return}let o=f(s||null);m(),o.forEach(i=>{let r=L(!1);document.body.appendChild(r),E.push(r),p(r,i)}),u=o},I=()=>{h||m()},C=n=>{if(!d)return;let e=n.target;if(g){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),window.parent.postMessage({type:"close-dropdowns"},"*");return}if(e.tagName.toLowerCase()==="path")return;n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation();let t=e.closest("[data-source-location], [data-visual-selector-id]");if(!t)return;let a=t,s=a.dataset.sourceLocation||a.dataset.visualSelectorId;c.forEach(v=>{v&&v.parentNode&&v.remove()}),c=[],f(s||null).forEach(v=>{let y=L(!0);document.body.appendChild(y),c.push(y),p(y,v,!0)}),l=s||null,m();let i=t.getBoundingClientRect(),r={top:i.top,left:i.left,right:i.right,bottom:i.bottom,width:i.width,height:i.height,centerX:i.left+i.width/2,centerY:i.top+i.height/2},b=t,O={type:"element-selected",tagName:t.tagName,classes:b.className?.baseVal||t.className||"",visualSelectorId:s,content:t.innerText,dataSourceLocation:a.dataset.sourceLocation,isDynamicContent:a.dataset.dynamicContent==="true",linenumber:a.dataset.linenumber,filename:a.dataset.filename,position:r};window.parent.postMessage(O,"*")},H=()=>{c.forEach(n=>{n&&n.parentNode&&n.remove()}),c=[],l=null},x=(n,e)=>{let t=f(n);t.length!==0&&(T(t,e),setTimeout(()=>{l===n&&c.forEach((a,s)=>{s<t.length&&p(a,t[s])}),u.length>0&&u[0]?.dataset?.visualSelectorId===n&&E.forEach((o,i)=>{i<u.length&&p(o,u[i])})},50))},D=(n,e)=>{let t=f(n);t.length!==0&&(t.forEach(a=>{a.innerText=e}),setTimeout(()=>{l===n&&c.forEach((a,s)=>{s<t.length&&p(a,t[s])})},50))},S=n=>{d=n,n?(document.body.style.cursor="crosshair",document.addEventListener("mouseover",M),document.addEventListener("mouseout",I),document.addEventListener("click",C,!0)):(m(),c.forEach(e=>{e&&e.parentNode&&e.remove()}),c=[],u=[],l=null,document.body.style.cursor="default",document.removeEventListener("mouseover",M),document.removeEventListener("mouseout",I),document.removeEventListener("click",C,!0))},N=()=>{if(l){let n=f(l);if(n.length>0){let t=n[0].getBoundingClientRect(),a=window.innerHeight,s=window.innerWidth,o=t.top<a&&t.bottom>0&&t.left<s&&t.right>0,i={top:t.top,left:t.left,right:t.right,bottom:t.bottom,width:t.width,height:t.height,centerX:t.left+t.width/2,centerY:t.top+t.height/2};window.parent.postMessage({type:"element-position-update",position:i,isInViewport:o,visualSelectorId:l},"*")}}},k=n=>{let e=n.data;switch(e.type){case"toggle-visual-edit-mode":S(e.data.enabled);break;case"update-classes":e.data&&e.data.classes!==void 0?x(e.data.visualSelectorId,e.data.classes):console.warn("[VisualEditAgent] Invalid update-classes message:",e);break;case"unselect-element":H();break;case"refresh-page":window.location.reload();break;case"update-content":e.data&&e.data.content!==void 0?D(e.data.visualSelectorId,e.data.content):console.warn("[VisualEditAgent] Invalid update-content message:",e);break;case"request-element-position":if(l){let t=f(l);if(t.length>0){let s=t[0].getBoundingClientRect(),o=window.innerHeight,i=window.innerWidth,r=s.top<o&&s.bottom>0&&s.left<i&&s.right>0,b={top:s.top,left:s.left,right:s.right,bottom:s.bottom,width:s.width,height:s.height,centerX:s.left+s.width/2,centerY:s.top+s.height/2};window.parent.postMessage({type:"element-position-update",position:b,isInViewport:r,visualSelectorId:l},"*")}}break;case"popover-drag-state":e.data&&e.data.isDragging!==void 0&&(h=e.data.isDragging,e.data.isDragging&&m());break;case"dropdown-state":e.data&&e.data.isOpen!==void 0&&(g=e.data.isOpen,e.data.isOpen&&m());break;default:break}},w=()=>{if(l){let n=f(l);c.forEach((e,t)=>{t<n.length&&p(e,n[t])})}u.length>0&&E.forEach((n,e)=>{e<u.length&&p(n,u[e])})};document.querySelectorAll("[data-linenumber]:not([data-visual-selector-id])").forEach((n,e)=>{let t=n,a=`visual-id-${t.dataset.filename}-${t.dataset.linenumber}-${e}`;t.dataset.visualSelectorId=a});let A=new MutationObserver(n=>{n.some(t=>{let a=o=>{if(o.nodeType===Node.ELEMENT_NODE){let i=o;if(i.dataset&&i.dataset.visualSelectorId)return!0;for(let r=0;r<i.children.length;r++)if(a(i.children[r]))return!0}return!1};return t.type==="attributes"&&(t.attributeName==="style"||t.attributeName==="class"||t.attributeName==="width"||t.attributeName==="height")&&a(t.target)})&&setTimeout(w,50)});window.addEventListener("message",k),window.addEventListener("scroll",N,!0),document.addEventListener("scroll",N,!0),window.addEventListener("resize",w),window.addEventListener("scroll",w),A.observe(document.body,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["style","class","width","height"]}),window.parent.postMessage({type:"visual-edit-agent-ready"},"*")}export{V as setupVisualEditAgent};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/injections/unhandled-errors-handlers.ts","../../src/injections/sandbox-hmr-notifier.ts","../../src/injections/sandbox-mount-observer.ts","../../src/injections/navigation-notifier.ts","../../src/injections/utils.ts","../../src/injections/visual-edit-agent.ts","../../src/bridge.ts"],"sourcesContent":["/** Register global error and unhandled-rejection listeners that report to the parent window. */\n\nconst ERROR_SUPPRESSION_TIMEOUT = 10000;\n\nexport function setupUnhandledErrors(hmr?: { on(event: string, cb: (...args: any[]) => void): void }) {\n window.removeEventListener(\"unhandledrejection\", handleUnhandledRejection);\n window.removeEventListener(\"error\", handleWindowError);\n\n window.addEventListener(\"unhandledrejection\", handleUnhandledRejection);\n window.addEventListener(\"error\", handleWindowError);\n\n let shouldPropagateErrors = true;\n let suppressionTimer: ReturnType<typeof setTimeout> | null = null;\n\n if (hmr) {\n hmr.on(\"vite:beforeUpdate\", () => {\n shouldPropagateErrors = false;\n\n if (suppressionTimer) {\n clearTimeout(suppressionTimer);\n }\n\n suppressionTimer = setTimeout(() => {\n shouldPropagateErrors = true;\n suppressionTimer = null;\n }, ERROR_SUPPRESSION_TIMEOUT);\n });\n hmr.on(\"vite:beforeFullReload\", () => {\n shouldPropagateErrors = false;\n if (suppressionTimer) {\n clearTimeout(suppressionTimer);\n suppressionTimer = null;\n }\n });\n }\n\n function onAppError({\n title,\n details,\n componentName,\n originalError,\n }: {\n title: string;\n details: string;\n componentName: string;\n originalError: any;\n }) {\n if (originalError?.response?.status === 402 || !shouldPropagateErrors) {\n return;\n }\n window.parent?.postMessage(\n {\n type: \"app_error\",\n error: {\n title: title.toString(),\n details: details?.toString(),\n componentName: componentName?.toString(),\n stack: originalError?.stack?.toString(),\n },\n },\n \"*\"\n );\n }\n\n function handleUnhandledRejection(event: any) {\n const stack = event.reason.stack;\n // extract function name from \"at X (eval\" where x is the function name\n const functionName = stack.match(/at\\s+(\\w+)\\s+\\(eval/)?.[1];\n const msg = functionName\n ? `Error in ${functionName}: ${event.reason.toString()}`\n : event.reason.toString();\n onAppError({\n title: msg,\n details: event.reason.toString(),\n componentName: functionName,\n originalError: event.reason,\n });\n }\n\n function handleWindowError(event: any) {\n const stack = event.error?.stack;\n let functionName = stack.match(/at\\s+(\\w+)\\s+\\(eval/)?.[1];\n if (functionName === \"eval\") {\n functionName = null;\n }\n\n const msg = functionName\n ? `in ${functionName}: ${event.error.toString()}`\n : event.error.toString();\n onAppError({\n title: msg,\n details: event.error.toString(),\n componentName: functionName,\n originalError: event.error,\n });\n }\n}\n","/** Forward Vite HMR lifecycle events (beforeUpdate / afterUpdate) to the parent window. */\nexport function setupHmrNotifier(hmr: { on(event: string, cb: (...args: any[]) => void): void }) {\n hmr.on(\"vite:beforeUpdate\", () => {\n window.parent?.postMessage({ type: \"sandbox:beforeUpdate\" }, \"*\");\n });\n hmr.on(\"vite:afterUpdate\", () => {\n window.parent?.postMessage({ type: \"sandbox:afterUpdate\" }, \"*\");\n });\n}\n","/** Observe DOM mutations and notify the parent when instrumented elements are mounted or unmounted. */\nexport function setupMountObserver() {\n const observer = new MutationObserver((mutations) => {\n const nodesAdded = mutations.some(\n (mutation) => mutation.addedNodes.length > 0\n );\n const nodesRemoved = mutations.some(\n (mutation) => mutation.removedNodes.length > 0\n );\n if (nodesAdded || nodesRemoved) {\n const foundElmWithDataAttribute =\n document.body.querySelectorAll(\n \"[data-source-location], [data-dynamic-content]\"\n ).length > 0;\n\n if (foundElmWithDataAttribute) {\n window.parent?.postMessage({ type: \"sandbox:onMounted\" }, \"*\");\n } else {\n window.parent?.postMessage({ type: \"sandbox:onUnmounted\" }, \"*\");\n }\n }\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n}\n","/** Intercept pushState / replaceState / popstate and notify the parent of URL changes. */\nexport function setupNavigationNotifier() {\n let lastUrl = window.location.href;\n\n function notifyNavigation() {\n const currentUrl = window.location.href;\n if (currentUrl !== lastUrl) {\n lastUrl = currentUrl;\n window.parent?.postMessage(\n {\n type: \"app_changed_url\",\n url: currentUrl,\n },\n \"*\"\n );\n }\n }\n\n // Intercept history.pushState\n const originalPushState = history.pushState.bind(history);\n history.pushState = function (...args) {\n originalPushState(...args);\n notifyNavigation();\n };\n\n // Intercept history.replaceState\n const originalReplaceState = history.replaceState.bind(history);\n history.replaceState = function (...args) {\n originalReplaceState(...args);\n notifyNavigation();\n };\n\n // Handle browser back/forward navigation\n window.addEventListener(\"popstate\", notifyNavigation);\n\n // Notify initial URL on load\n window.parent?.postMessage(\n {\n type: \"app_changed_url\",\n url: window.location.href,\n },\n \"*\"\n );\n}\n","/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */\nexport function findElementsById(id: string | null): Element[] {\n if (!id) return [];\n const sourceElements = Array.from(\n document.querySelectorAll(`[data-source-location=\"${id}\"]`)\n );\n if (sourceElements.length > 0) {\n return sourceElements;\n }\n return Array.from(\n document.querySelectorAll(`[data-visual-selector-id=\"${id}\"]`)\n );\n}\n\n/**\n * Update element classes by visual selector ID.\n * Uses setAttribute instead of className to support both HTML and SVG elements.\n */\nexport function updateElementClasses(elements: Element[], classes: string): void {\n elements.forEach((element) => {\n element.setAttribute(\"class\", classes);\n }); \n}\n","import { findElementsById, updateElementClasses } from \"./utils.js\";\n\nexport function setupVisualEditAgent() {\n // State variables (replacing React useState/useRef)\n let isVisualEditMode = false;\n let isPopoverDragging = false;\n let isDropdownOpen = false;\n let hoverOverlays: HTMLDivElement[] = [];\n let selectedOverlays: HTMLDivElement[] = [];\n let currentHighlightedElements: Element[] = [];\n let selectedElementId: string | null = null;\n\n // Create overlay element\n const createOverlay = (isSelected = false): HTMLDivElement => {\n const overlay = document.createElement(\"div\");\n overlay.style.position = \"absolute\";\n overlay.style.pointerEvents = \"none\";\n overlay.style.transition = \"all 0.1s ease-in-out\";\n overlay.style.zIndex = \"9999\";\n\n if (isSelected) {\n overlay.style.border = \"2px solid #2563EB\";\n } else {\n overlay.style.border = \"2px solid #95a5fc\";\n overlay.style.backgroundColor = \"rgba(99, 102, 241, 0.05)\";\n }\n\n return overlay;\n };\n\n // Position overlay relative to element\n const positionOverlay = (\n overlay: HTMLDivElement,\n element: Element,\n isSelected = false\n ) => {\n if (!element || !isVisualEditMode) return;\n\n const htmlElement = element as HTMLElement;\n // Force layout recalculation\n void htmlElement.offsetWidth;\n\n const rect = element.getBoundingClientRect();\n overlay.style.top = `${rect.top + window.scrollY}px`;\n overlay.style.left = `${rect.left + window.scrollX}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.height = `${rect.height}px`;\n\n // Check if label already exists in overlay\n let label = overlay.querySelector(\"div\") as HTMLDivElement | null;\n\n if (!label) {\n label = document.createElement(\"div\");\n label.textContent = element.tagName.toLowerCase();\n label.style.position = \"absolute\";\n label.style.top = \"-27px\";\n label.style.left = \"-2px\";\n label.style.padding = \"2px 8px\";\n label.style.fontSize = \"11px\";\n label.style.fontWeight = isSelected ? \"500\" : \"400\";\n label.style.color = isSelected ? \"#ffffff\" : \"#526cff\";\n label.style.backgroundColor = isSelected ? \"#526cff\" : \"#DBEAFE\";\n label.style.borderRadius = \"3px\";\n label.style.minWidth = \"24px\";\n label.style.textAlign = \"center\";\n overlay.appendChild(label);\n }\n };\n\n // Clear hover overlays\n const clearHoverOverlays = () => {\n hoverOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n hoverOverlays = [];\n currentHighlightedElements = [];\n };\n\n // Handle mouse over event\n const handleMouseOver = (e: MouseEvent) => {\n if (!isVisualEditMode || isPopoverDragging) return;\n\n const target = e.target as Element;\n\n // Prevent hover effects when a dropdown is open\n if (isDropdownOpen) {\n clearHoverOverlays();\n return;\n }\n\n // Prevent hover effects on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n clearHoverOverlays();\n return;\n }\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n clearHoverOverlays();\n return;\n }\n\n // Prefer data-source-location, fallback to data-visual-selector-id\n const htmlElement = element as HTMLElement;\n const selectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Skip if this element is already selected\n if (selectedElementId === selectorId) {\n clearHoverOverlays();\n return;\n }\n\n // Find all elements with the same ID\n const elements = findElementsById(selectorId || null);\n\n // Clear previous hover overlays\n clearHoverOverlays();\n\n // Create overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(false);\n document.body.appendChild(overlay);\n hoverOverlays.push(overlay);\n positionOverlay(overlay, el);\n });\n\n currentHighlightedElements = elements;\n };\n\n // Handle mouse out event\n const handleMouseOut = () => {\n if (isPopoverDragging) return;\n clearHoverOverlays();\n };\n\n // Handle element click\n const handleElementClick = (e: MouseEvent) => {\n if (!isVisualEditMode) return;\n\n const target = e.target as Element;\n\n // Close dropdowns when clicking anywhere in iframe if a dropdown is open\n if (isDropdownOpen) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n window.parent.postMessage({ type: \"close-dropdowns\" }, \"*\");\n return;\n }\n\n // Prevent clicking on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n return;\n }\n\n // Prevent default behavior immediately when in visual edit mode\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n return;\n }\n\n const htmlElement = element as HTMLElement;\n const visualSelectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Clear any existing selected overlays\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n // Find all elements with the same ID\n const elements = findElementsById(visualSelectorId || null);\n\n // Create selected overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(true);\n document.body.appendChild(overlay);\n selectedOverlays.push(overlay);\n positionOverlay(overlay, el, true);\n });\n\n selectedElementId = visualSelectorId || null;\n\n // Clear hover overlays\n clearHoverOverlays();\n\n // Calculate element position for popover positioning\n const rect = element.getBoundingClientRect();\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n // Send message to parent window with element info including position\n const svgElement = element as SVGElement;\n const elementData = {\n type: \"element-selected\",\n tagName: element.tagName,\n classes:\n (svgElement.className as unknown as SVGAnimatedString)?.baseVal ||\n element.className ||\n \"\",\n visualSelectorId: visualSelectorId,\n content: (element as HTMLElement).innerText,\n dataSourceLocation: htmlElement.dataset.sourceLocation,\n isDynamicContent: htmlElement.dataset.dynamicContent === \"true\",\n linenumber: htmlElement.dataset.linenumber,\n filename: htmlElement.dataset.filename,\n position: elementPosition,\n };\n window.parent.postMessage(elementData, \"*\");\n };\n\n // Unselect the current element\n const unselectElement = () => {\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n selectedElementId = null;\n };\n\n const updateElementClassesAndReposition = (visualSelectorId: string, classes: string) => {\n const elements = findElementsById(visualSelectorId);\n if (elements.length === 0) return;\n\n updateElementClasses(elements, classes);\n\n // Use a small delay to allow the browser to recalculate layout before repositioning\n setTimeout(() => {\n // Reposition selected overlays\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n // Reposition hover overlays if needed\n if (currentHighlightedElements.length > 0) {\n const hoveredElement = currentHighlightedElements[0] as HTMLElement;\n const hoveredId = hoveredElement?.dataset?.visualSelectorId;\n if (hoveredId === visualSelectorId) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n }\n }, 50);\n };\n\n // Update element content by visual selector ID\n const updateElementContent = (visualSelectorId: string, content: string) => {\n const elements = findElementsById(visualSelectorId);\n\n if (elements.length === 0) {\n return;\n }\n\n elements.forEach((element) => {\n (element as HTMLElement).innerText = content;\n });\n\n setTimeout(() => {\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n }, 50);\n };\n\n // Toggle visual edit mode\n const toggleVisualEditMode = (isEnabled: boolean) => {\n isVisualEditMode = isEnabled;\n\n if (!isEnabled) {\n clearHoverOverlays();\n\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n currentHighlightedElements = [];\n selectedElementId = null;\n document.body.style.cursor = \"default\";\n\n document.removeEventListener(\"mouseover\", handleMouseOver);\n document.removeEventListener(\"mouseout\", handleMouseOut);\n document.removeEventListener(\"click\", handleElementClick, true);\n } else {\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mouseover\", handleMouseOver);\n document.addEventListener(\"mouseout\", handleMouseOut);\n document.addEventListener(\"click\", handleElementClick, true);\n }\n };\n\n // Handle scroll events to update popover position\n const handleScroll = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n };\n\n // Handle messages from parent window\n const handleMessage = (event: MessageEvent) => {\n const message = event.data;\n\n switch (message.type) {\n case \"toggle-visual-edit-mode\":\n toggleVisualEditMode(message.data.enabled);\n break;\n\n case \"update-classes\":\n if (message.data && message.data.classes !== undefined) {\n updateElementClassesAndReposition(\n message.data.visualSelectorId,\n message.data.classes\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-classes message:\",\n message\n );\n }\n break;\n\n case \"unselect-element\":\n unselectElement();\n break;\n\n case \"refresh-page\":\n window.location.reload();\n break;\n\n case \"update-content\":\n if (message.data && message.data.content !== undefined) {\n updateElementContent(\n message.data.visualSelectorId,\n message.data.content\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-content message:\",\n message\n );\n }\n break;\n\n case \"request-element-position\":\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n break;\n\n case \"popover-drag-state\":\n if (message.data && message.data.isDragging !== undefined) {\n isPopoverDragging = message.data.isDragging;\n if (message.data.isDragging) {\n clearHoverOverlays();\n }\n }\n break;\n\n case \"dropdown-state\":\n if (message.data && message.data.isOpen !== undefined) {\n isDropdownOpen = message.data.isOpen;\n if (message.data.isOpen) {\n clearHoverOverlays();\n }\n }\n break;\n\n default:\n break;\n }\n };\n\n // Handle window resize to reposition overlays\n const handleResize = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n if (currentHighlightedElements.length > 0) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n };\n\n // Initialize: Add IDs to elements that don't have them but have linenumbers\n const elementsWithLineNumber = document.querySelectorAll(\n \"[data-linenumber]:not([data-visual-selector-id])\"\n );\n elementsWithLineNumber.forEach((el, index) => {\n const htmlEl = el as HTMLElement;\n const id = `visual-id-${htmlEl.dataset.filename}-${htmlEl.dataset.linenumber}-${index}`;\n htmlEl.dataset.visualSelectorId = id;\n });\n\n // Create mutation observer to detect layout changes\n const mutationObserver = new MutationObserver((mutations) => {\n const needsUpdate = mutations.some((mutation) => {\n const hasVisualId = (node: Node): boolean => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n if (el.dataset && el.dataset.visualSelectorId) {\n return true;\n }\n for (let i = 0; i < el.children.length; i++) {\n if (hasVisualId(el.children[i]!)) {\n return true;\n }\n }\n }\n return false;\n };\n\n const isLayoutChange =\n mutation.type === \"attributes\" &&\n (mutation.attributeName === \"style\" ||\n mutation.attributeName === \"class\" ||\n mutation.attributeName === \"width\" ||\n mutation.attributeName === \"height\");\n\n return isLayoutChange && hasVisualId(mutation.target);\n });\n\n if (needsUpdate) {\n setTimeout(handleResize, 50);\n }\n });\n\n // Set up event listeners\n window.addEventListener(\"message\", handleMessage);\n window.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"scroll\", handleScroll, true);\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Start observing DOM mutations\n mutationObserver.observe(document.body, {\n attributes: true,\n childList: true,\n subtree: true,\n attributeFilter: [\"style\", \"class\", \"width\", \"height\"],\n });\n\n // Send ready message to parent\n window.parent.postMessage({ type: \"visual-edit-agent-ready\" }, \"*\");\n}","/**\n * Sandbox bridge entry point — dynamically imported by the inline script\n * injected via html-injections-plugin. Conditionally initialises each\n * sandbox-side feature based on the supplied options.\n */\n\nimport { setupUnhandledErrors } from \"./injections/unhandled-errors-handlers.js\";\nimport { setupHmrNotifier } from \"./injections/sandbox-hmr-notifier.js\";\nimport { setupMountObserver } from \"./injections/sandbox-mount-observer.js\";\nimport { setupNavigationNotifier } from \"./injections/navigation-notifier.js\";\nimport { setupVisualEditAgent } from \"./injections/visual-edit-agent.js\";\n\n/**\n * Initialise the sandbox bridge. Called once from the injected inline script.\n * @param options Feature flags — each defaults to enabled unless explicitly disabled.\n * @param hmr Vite's HMR client (`import.meta.hot`), passed only in dev mode.\n */\nexport function init(\n options: {\n unhandledErrors?: boolean;\n mountObserver?: boolean;\n hmrNotifier?: boolean;\n navigationNotifier?: boolean;\n visualEditAgent?: boolean;\n } = {},\n hmr?: { on(event: string, cb: (...args: any[]) => void): void }\n) {\n if (window.self === window.top) return;\n if ((globalThis as any).__sandboxBridgeInitialized) return;\n (globalThis as any).__sandboxBridgeInitialized = true;\n\n if (options.unhandledErrors !== false) setupUnhandledErrors(hmr);\n if (options.mountObserver !== false) setupMountObserver();\n if (options.hmrNotifier && hmr) setupHmrNotifier(hmr);\n if (options.navigationNotifier) setupNavigationNotifier();\n if (options.visualEditAgent) setupVisualEditAgent();\n}\n"],"mappings":"AAIO,SAASA,EAAqBC,EAAiE,CACpG,OAAO,oBAAoB,qBAAsBC,CAAwB,EACzE,OAAO,oBAAoB,QAASC,CAAiB,EAErD,OAAO,iBAAiB,qBAAsBD,CAAwB,EACtE,OAAO,iBAAiB,QAASC,CAAiB,EAElD,IAAIC,EAAwB,GACxBC,EAAyD,KAEzDJ,IACFA,EAAI,GAAG,oBAAqB,IAAM,CAChCG,EAAwB,GAEpBC,GACF,aAAaA,CAAgB,EAG/BA,EAAmB,WAAW,IAAM,CAClCD,EAAwB,GACxBC,EAAmB,IACrB,EAAG,GAAyB,CAC9B,CAAC,EACDJ,EAAI,GAAG,wBAAyB,IAAM,CACpCG,EAAwB,GACpBC,IACF,aAAaA,CAAgB,EAC7BA,EAAmB,KAEvB,CAAC,GAGH,SAASC,EAAW,CAClB,MAAAC,EACA,QAAAC,EACA,cAAAC,EACA,cAAAC,CACF,EAKG,CACGA,GAAe,UAAU,SAAW,KAAO,CAACN,GAGhD,OAAO,QAAQ,YACb,CACE,KAAM,YACN,MAAO,CACL,MAAOG,EAAM,SAAS,EACtB,QAASC,GAAS,SAAS,EAC3B,cAAeC,GAAe,SAAS,EACvC,MAAOC,GAAe,OAAO,SAAS,CACxC,CACF,EACA,GACF,CACF,CAEA,SAASR,EAAyBS,EAAY,CAG5C,IAAMC,EAFQD,EAAM,OAAO,MAEA,MAAM,qBAAqB,IAAI,CAAC,EACrDE,EAAMD,EACR,YAAYA,CAAY,KAAKD,EAAM,OAAO,SAAS,CAAC,GACpDA,EAAM,OAAO,SAAS,EAC1BL,EAAW,CACT,MAAOO,EACP,QAASF,EAAM,OAAO,SAAS,EAC/B,cAAeC,EAC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EAAS,gBAAkB,WAENC,EAAYD,EAAS,MAAM,CACtD,CAAC,GAGC,WAAWL,EAAc,EAAE,CAE/B,CAAC,EAGD,OAAO,iBAAiB,UAAWH,CAAa,EAChD,OAAO,iBAAiB,SAAUJ,EAAc,EAAI,EACpD,SAAS,iBAAiB,SAAUA,EAAc,EAAI,EACtD,OAAO,iBAAiB,SAAUO,CAAY,EAC9C,OAAO,iBAAiB,SAAUA,CAAY,EAG9CG,EAAiB,QAAQ,SAAS,KAAM,CACtC,WAAY,GACZ,UAAW,GACX,QAAS,GACT,gBAAiB,CAAC,QAAS,QAAS,QAAS,QAAQ,CACvD,CAAC,EAGD,OAAO,OAAO,YAAY,CAAE,KAAM,yBAA0B,EAAG,GAAG,CACpE,CC/hBO,SAASM,EACdC,EAMI,CAAC,EACLC,EACA,CACI,OAAO,OAAS,OAAO,MACtB,WAAmB,6BACvB,WAAmB,2BAA6B,GAE7CD,EAAQ,kBAAoB,IAAOE,EAAqBD,CAAG,EAC3DD,EAAQ,gBAAkB,IAAOG,EAAmB,EACpDH,EAAQ,aAAeC,GAAKG,EAAiBH,CAAG,EAChDD,EAAQ,oBAAoBK,EAAwB,EACpDL,EAAQ,iBAAiBM,EAAqB,GACpD","names":["setupUnhandledErrors","hmr","handleUnhandledRejection","handleWindowError","shouldPropagateErrors","suppressionTimer","onAppError","title","details","componentName","originalError","event","functionName","msg","setupHmrNotifier","hmr","setupMountObserver","mutations","nodesAdded","mutation","nodesRemoved","setupNavigationNotifier","lastUrl","notifyNavigation","currentUrl","originalPushState","args","originalReplaceState","findElementsById","id","sourceElements","updateElementClasses","elements","classes","element","setupVisualEditAgent","isVisualEditMode","isPopoverDragging","isDropdownOpen","hoverOverlays","selectedOverlays","currentHighlightedElements","selectedElementId","createOverlay","isSelected","overlay","positionOverlay","element","rect","label","clearHoverOverlays","handleMouseOver","e","target","htmlElement","selectorId","elements","findElementsById","el","handleMouseOut","handleElementClick","visualSelectorId","elementPosition","svgElement","elementData","unselectElement","updateElementClassesAndReposition","classes","updateElementClasses","index","updateElementContent","content","toggleVisualEditMode","isEnabled","handleScroll","viewportHeight","viewportWidth","isInViewport","handleMessage","event","message","handleResize","htmlEl","id","mutationObserver","mutations","mutation","hasVisualId","node","i","init","options","hmr","setupUnhandledErrors","setupMountObserver","setupHmrNotifier","setupNavigationNotifier","setupVisualEditAgent"]}
1
+ {"version":3,"sources":["../../src/injections/utils.ts","../../src/injections/visual-edit-agent.ts"],"sourcesContent":["/** Find elements by ID - first try data-source-location, fallback to data-visual-selector-id */\nexport function findElementsById(id: string | null): Element[] {\n if (!id) return [];\n const sourceElements = Array.from(\n document.querySelectorAll(`[data-source-location=\"${id}\"]`)\n );\n if (sourceElements.length > 0) {\n return sourceElements;\n }\n return Array.from(\n document.querySelectorAll(`[data-visual-selector-id=\"${id}\"]`)\n );\n}\n\n/**\n * Update element classes by visual selector ID.\n * Uses setAttribute instead of className to support both HTML and SVG elements.\n */\nexport function updateElementClasses(elements: Element[], classes: string): void {\n elements.forEach((element) => {\n element.setAttribute(\"class\", classes);\n }); \n}\n","import { findElementsById, updateElementClasses } from \"./utils.js\";\n\nexport function setupVisualEditAgent() {\n // State variables (replacing React useState/useRef)\n let isVisualEditMode = false;\n let isPopoverDragging = false;\n let isDropdownOpen = false;\n let hoverOverlays: HTMLDivElement[] = [];\n let selectedOverlays: HTMLDivElement[] = [];\n let currentHighlightedElements: Element[] = [];\n let selectedElementId: string | null = null;\n\n // Create overlay element\n const createOverlay = (isSelected = false): HTMLDivElement => {\n const overlay = document.createElement(\"div\");\n overlay.style.position = \"absolute\";\n overlay.style.pointerEvents = \"none\";\n overlay.style.transition = \"all 0.1s ease-in-out\";\n overlay.style.zIndex = \"9999\";\n\n if (isSelected) {\n overlay.style.border = \"2px solid #2563EB\";\n } else {\n overlay.style.border = \"2px solid #95a5fc\";\n overlay.style.backgroundColor = \"rgba(99, 102, 241, 0.05)\";\n }\n\n return overlay;\n };\n\n // Position overlay relative to element\n const positionOverlay = (\n overlay: HTMLDivElement,\n element: Element,\n isSelected = false\n ) => {\n if (!element || !isVisualEditMode) return;\n\n const htmlElement = element as HTMLElement;\n // Force layout recalculation\n void htmlElement.offsetWidth;\n\n const rect = element.getBoundingClientRect();\n overlay.style.top = `${rect.top + window.scrollY}px`;\n overlay.style.left = `${rect.left + window.scrollX}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.height = `${rect.height}px`;\n\n // Check if label already exists in overlay\n let label = overlay.querySelector(\"div\") as HTMLDivElement | null;\n\n if (!label) {\n label = document.createElement(\"div\");\n label.textContent = element.tagName.toLowerCase();\n label.style.position = \"absolute\";\n label.style.top = \"-27px\";\n label.style.left = \"-2px\";\n label.style.padding = \"2px 8px\";\n label.style.fontSize = \"11px\";\n label.style.fontWeight = isSelected ? \"500\" : \"400\";\n label.style.color = isSelected ? \"#ffffff\" : \"#526cff\";\n label.style.backgroundColor = isSelected ? \"#526cff\" : \"#DBEAFE\";\n label.style.borderRadius = \"3px\";\n label.style.minWidth = \"24px\";\n label.style.textAlign = \"center\";\n overlay.appendChild(label);\n }\n };\n\n // Clear hover overlays\n const clearHoverOverlays = () => {\n hoverOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n hoverOverlays = [];\n currentHighlightedElements = [];\n };\n\n // Handle mouse over event\n const handleMouseOver = (e: MouseEvent) => {\n if (!isVisualEditMode || isPopoverDragging) return;\n\n const target = e.target as Element;\n\n // Prevent hover effects when a dropdown is open\n if (isDropdownOpen) {\n clearHoverOverlays();\n return;\n }\n\n // Prevent hover effects on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n clearHoverOverlays();\n return;\n }\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n clearHoverOverlays();\n return;\n }\n\n // Prefer data-source-location, fallback to data-visual-selector-id\n const htmlElement = element as HTMLElement;\n const selectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Skip if this element is already selected\n if (selectedElementId === selectorId) {\n clearHoverOverlays();\n return;\n }\n\n // Find all elements with the same ID\n const elements = findElementsById(selectorId || null);\n\n // Clear previous hover overlays\n clearHoverOverlays();\n\n // Create overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(false);\n document.body.appendChild(overlay);\n hoverOverlays.push(overlay);\n positionOverlay(overlay, el);\n });\n\n currentHighlightedElements = elements;\n };\n\n // Handle mouse out event\n const handleMouseOut = () => {\n if (isPopoverDragging) return;\n clearHoverOverlays();\n };\n\n // Handle element click\n const handleElementClick = (e: MouseEvent) => {\n if (!isVisualEditMode) return;\n\n const target = e.target as Element;\n\n // Close dropdowns when clicking anywhere in iframe if a dropdown is open\n if (isDropdownOpen) {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n window.parent.postMessage({ type: \"close-dropdowns\" }, \"*\");\n return;\n }\n\n // Prevent clicking on SVG path elements\n if (target.tagName.toLowerCase() === \"path\") {\n return;\n }\n\n // Prevent default behavior immediately when in visual edit mode\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n\n // Support both data-source-location and data-visual-selector-id\n const element = target.closest(\n \"[data-source-location], [data-visual-selector-id]\"\n );\n if (!element) {\n return;\n }\n\n const htmlElement = element as HTMLElement;\n const visualSelectorId =\n htmlElement.dataset.sourceLocation ||\n htmlElement.dataset.visualSelectorId;\n\n // Clear any existing selected overlays\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n // Find all elements with the same ID\n const elements = findElementsById(visualSelectorId || null);\n\n // Create selected overlays for all matching elements\n elements.forEach((el) => {\n const overlay = createOverlay(true);\n document.body.appendChild(overlay);\n selectedOverlays.push(overlay);\n positionOverlay(overlay, el, true);\n });\n\n selectedElementId = visualSelectorId || null;\n\n // Clear hover overlays\n clearHoverOverlays();\n\n // Calculate element position for popover positioning\n const rect = element.getBoundingClientRect();\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n // Send message to parent window with element info including position\n const svgElement = element as SVGElement;\n const elementData = {\n type: \"element-selected\",\n tagName: element.tagName,\n classes:\n (svgElement.className as unknown as SVGAnimatedString)?.baseVal ||\n element.className ||\n \"\",\n visualSelectorId: visualSelectorId,\n content: (element as HTMLElement).innerText,\n dataSourceLocation: htmlElement.dataset.sourceLocation,\n isDynamicContent: htmlElement.dataset.dynamicContent === \"true\",\n linenumber: htmlElement.dataset.linenumber,\n filename: htmlElement.dataset.filename,\n position: elementPosition,\n };\n window.parent.postMessage(elementData, \"*\");\n };\n\n // Unselect the current element\n const unselectElement = () => {\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n selectedElementId = null;\n };\n\n const updateElementClassesAndReposition = (visualSelectorId: string, classes: string) => {\n const elements = findElementsById(visualSelectorId);\n if (elements.length === 0) return;\n\n updateElementClasses(elements, classes);\n\n // Use a small delay to allow the browser to recalculate layout before repositioning\n setTimeout(() => {\n // Reposition selected overlays\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n // Reposition hover overlays if needed\n if (currentHighlightedElements.length > 0) {\n const hoveredElement = currentHighlightedElements[0] as HTMLElement;\n const hoveredId = hoveredElement?.dataset?.visualSelectorId;\n if (hoveredId === visualSelectorId) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n }\n }, 50);\n };\n\n // Update element content by visual selector ID\n const updateElementContent = (visualSelectorId: string, content: string) => {\n const elements = findElementsById(visualSelectorId);\n\n if (elements.length === 0) {\n return;\n }\n\n elements.forEach((element) => {\n (element as HTMLElement).innerText = content;\n });\n\n setTimeout(() => {\n if (selectedElementId === visualSelectorId) {\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n }, 50);\n };\n\n // Toggle visual edit mode\n const toggleVisualEditMode = (isEnabled: boolean) => {\n isVisualEditMode = isEnabled;\n\n if (!isEnabled) {\n clearHoverOverlays();\n\n selectedOverlays.forEach((overlay) => {\n if (overlay && overlay.parentNode) {\n overlay.remove();\n }\n });\n selectedOverlays = [];\n\n currentHighlightedElements = [];\n selectedElementId = null;\n document.body.style.cursor = \"default\";\n\n document.removeEventListener(\"mouseover\", handleMouseOver);\n document.removeEventListener(\"mouseout\", handleMouseOut);\n document.removeEventListener(\"click\", handleElementClick, true);\n } else {\n document.body.style.cursor = \"crosshair\";\n document.addEventListener(\"mouseover\", handleMouseOver);\n document.addEventListener(\"mouseout\", handleMouseOut);\n document.addEventListener(\"click\", handleElementClick, true);\n }\n };\n\n // Handle scroll events to update popover position\n const handleScroll = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n };\n\n // Handle messages from parent window\n const handleMessage = (event: MessageEvent) => {\n const message = event.data;\n\n switch (message.type) {\n case \"toggle-visual-edit-mode\":\n toggleVisualEditMode(message.data.enabled);\n break;\n\n case \"update-classes\":\n if (message.data && message.data.classes !== undefined) {\n updateElementClassesAndReposition(\n message.data.visualSelectorId,\n message.data.classes\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-classes message:\",\n message\n );\n }\n break;\n\n case \"unselect-element\":\n unselectElement();\n break;\n\n case \"refresh-page\":\n window.location.reload();\n break;\n\n case \"update-content\":\n if (message.data && message.data.content !== undefined) {\n updateElementContent(\n message.data.visualSelectorId,\n message.data.content\n );\n } else {\n console.warn(\n \"[VisualEditAgent] Invalid update-content message:\",\n message\n );\n }\n break;\n\n case \"request-element-position\":\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n if (elements.length > 0) {\n const element = elements[0];\n const rect = element!.getBoundingClientRect();\n\n const viewportHeight = window.innerHeight;\n const viewportWidth = window.innerWidth;\n const isInViewport =\n rect.top < viewportHeight &&\n rect.bottom > 0 &&\n rect.left < viewportWidth &&\n rect.right > 0;\n\n const elementPosition = {\n top: rect.top,\n left: rect.left,\n right: rect.right,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n centerX: rect.left + rect.width / 2,\n centerY: rect.top + rect.height / 2,\n };\n\n window.parent.postMessage(\n {\n type: \"element-position-update\",\n position: elementPosition,\n isInViewport: isInViewport,\n visualSelectorId: selectedElementId,\n },\n \"*\"\n );\n }\n }\n break;\n\n case \"popover-drag-state\":\n if (message.data && message.data.isDragging !== undefined) {\n isPopoverDragging = message.data.isDragging;\n if (message.data.isDragging) {\n clearHoverOverlays();\n }\n }\n break;\n\n case \"dropdown-state\":\n if (message.data && message.data.isOpen !== undefined) {\n isDropdownOpen = message.data.isOpen;\n if (message.data.isOpen) {\n clearHoverOverlays();\n }\n }\n break;\n\n default:\n break;\n }\n };\n\n // Handle window resize to reposition overlays\n const handleResize = () => {\n if (selectedElementId) {\n const elements = findElementsById(selectedElementId);\n selectedOverlays.forEach((overlay, index) => {\n if (index < elements.length) {\n positionOverlay(overlay, elements[index]!);\n }\n });\n }\n\n if (currentHighlightedElements.length > 0) {\n hoverOverlays.forEach((overlay, index) => {\n if (index < currentHighlightedElements.length) {\n positionOverlay(overlay, currentHighlightedElements[index]!);\n }\n });\n }\n };\n\n // Initialize: Add IDs to elements that don't have them but have linenumbers\n const elementsWithLineNumber = document.querySelectorAll(\n \"[data-linenumber]:not([data-visual-selector-id])\"\n );\n elementsWithLineNumber.forEach((el, index) => {\n const htmlEl = el as HTMLElement;\n const id = `visual-id-${htmlEl.dataset.filename}-${htmlEl.dataset.linenumber}-${index}`;\n htmlEl.dataset.visualSelectorId = id;\n });\n\n // Create mutation observer to detect layout changes\n const mutationObserver = new MutationObserver((mutations) => {\n const needsUpdate = mutations.some((mutation) => {\n const hasVisualId = (node: Node): boolean => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n if (el.dataset && el.dataset.visualSelectorId) {\n return true;\n }\n for (let i = 0; i < el.children.length; i++) {\n if (hasVisualId(el.children[i]!)) {\n return true;\n }\n }\n }\n return false;\n };\n\n const isLayoutChange =\n mutation.type === \"attributes\" &&\n (mutation.attributeName === \"style\" ||\n mutation.attributeName === \"class\" ||\n mutation.attributeName === \"width\" ||\n mutation.attributeName === \"height\");\n\n return isLayoutChange && hasVisualId(mutation.target);\n });\n\n if (needsUpdate) {\n setTimeout(handleResize, 50);\n }\n });\n\n // Set up event listeners\n window.addEventListener(\"message\", handleMessage);\n window.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"scroll\", handleScroll, true);\n window.addEventListener(\"resize\", handleResize);\n window.addEventListener(\"scroll\", handleResize);\n\n // Start observing DOM mutations\n mutationObserver.observe(document.body, {\n attributes: true,\n childList: true,\n subtree: true,\n attributeFilter: [\"style\", \"class\", \"width\", \"height\"],\n });\n\n // Send ready message to parent\n window.parent.postMessage({ type: \"visual-edit-agent-ready\" }, \"*\");\n}"],"mappings":"AACO,SAASA,EAAiBC,EAA8B,CAC7D,GAAI,CAACA,EAAI,MAAO,CAAC,EACjB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A0B,EAAG,GAAG,CACpE","names":["findElementsById","id","sourceElements","updateElementClasses","elements","classes","element","setupVisualEditAgent","isVisualEditMode","isPopoverDragging","isDropdownOpen","hoverOverlays","selectedOverlays","currentHighlightedElements","selectedElementId","createOverlay","isSelected","overlay","positionOverlay","element","rect","label","clearHoverOverlays","handleMouseOver","e","target","htmlElement","selectorId","elements","findElementsById","el","handleMouseOut","handleElementClick","visualSelectorId","elementPosition","svgElement","elementData","unselectElement","updateElementClassesAndReposition","classes","updateElementClasses","index","updateElementContent","content","toggleVisualEditMode","isEnabled","handleScroll","viewportHeight","viewportWidth","isInViewport","handleMessage","event","message","handleResize","htmlEl","id","mutationObserver","mutations","mutation","hasVisualId","node","i"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/vite-plugin",
3
- "version": "0.2.20-pr.27.20fa529",
3
+ "version": "0.2.20-pr.27.45bb4b6",
4
4
  "description": "The Vite plugin for base44 based applications",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/bridge.ts CHANGED
@@ -1,37 +1,8 @@
1
1
  /**
2
- * Sandbox bridge entry point dynamically imported by the inline script
3
- * injected via html-injections-plugin. Conditionally initialises each
4
- * sandbox-side feature based on the supplied options.
2
+ * Sandbox bridge — bundled via tsup into dist/statics/index.mjs.
3
+ * Only the visual edit agent needs the bridge (for local dev iteration
4
+ * via ?sandbox-bridge=local). All other features load as individual
5
+ * sync script tags from node_modules.
5
6
  */
6
7
 
7
- import { setupUnhandledErrors } from "./injections/unhandled-errors-handlers.js";
8
- import { setupHmrNotifier } from "./injections/sandbox-hmr-notifier.js";
9
- import { setupMountObserver } from "./injections/sandbox-mount-observer.js";
10
- import { setupNavigationNotifier } from "./injections/navigation-notifier.js";
11
- import { setupVisualEditAgent } from "./injections/visual-edit-agent.js";
12
-
13
- /**
14
- * Initialise the sandbox bridge. Called once from the injected inline script.
15
- * @param options Feature flags — each defaults to enabled unless explicitly disabled.
16
- * @param hmr Vite's HMR client (`import.meta.hot`), passed only in dev mode.
17
- */
18
- export function init(
19
- options: {
20
- unhandledErrors?: boolean;
21
- mountObserver?: boolean;
22
- hmrNotifier?: boolean;
23
- navigationNotifier?: boolean;
24
- visualEditAgent?: boolean;
25
- } = {},
26
- hmr?: { on(event: string, cb: (...args: any[]) => void): void }
27
- ) {
28
- if (window.self === window.top) return;
29
- if ((globalThis as any).__sandboxBridgeInitialized) return;
30
- (globalThis as any).__sandboxBridgeInitialized = true;
31
-
32
- if (options.unhandledErrors !== false) setupUnhandledErrors(hmr);
33
- if (options.mountObserver !== false) setupMountObserver();
34
- if (options.hmrNotifier && hmr) setupHmrNotifier(hmr);
35
- if (options.navigationNotifier) setupNavigationNotifier();
36
- if (options.visualEditAgent) setupVisualEditAgent();
37
- }
8
+ export { setupVisualEditAgent } from "./injections/visual-edit-agent.js";
@@ -1,51 +1,165 @@
1
- import type { Plugin } from "vite";
1
+ import type { Plugin, HtmlTagDescriptor } from "vite";
2
+ import { loadEnv } from "vite";
2
3
 
3
- interface HtmlInjectionOptions {
4
- hmrNotifier: boolean;
5
- navigationNotifier: boolean;
6
- visualEditAgent: boolean;
4
+ type Injection = {
5
+ /** Script src path for dev mode (served from node_modules) */
6
+ src?: string;
7
+ injectTo: "head" | "body";
8
+ mode: "dev" | "production";
9
+ /** Inline content for production builds (src paths don't work in built output) */
10
+ inlineContent?: string;
11
+ };
12
+
13
+ const ANALYTICS_TRACKER_SCRIPT = `
14
+ let lastPath = "";
15
+ function getPageNameFromPath(path) {
16
+ const segments = path.split("/").filter(Boolean);
17
+ return segments[0] || null;
18
+ }
19
+ function trackPageView() {
20
+ const path = window.location.pathname;
21
+ if (path === lastPath) return;
22
+ lastPath = path;
23
+ const pageName = getPageNameFromPath(path) || "home";
24
+ const appId = import.meta.env.VITE_BASE44_APP_ID;
25
+ const serverUrl = import.meta.env.VITE_BASE44_BACKEND_URL || "";
26
+ if (!appId) return;
27
+ fetch(\`\${serverUrl}/app-logs/\${appId}/log-user-in-app/\${pageName}\`, {
28
+ method: "POST",
29
+ }).catch(() => {});
7
30
  }
31
+ const originalPushState = history.pushState.bind(history);
32
+ history.pushState = function (...args) {
33
+ originalPushState(...args);
34
+ trackPageView();
35
+ };
36
+ const originalReplaceState = history.replaceState.bind(history);
37
+ history.replaceState = function (...args) {
38
+ originalReplaceState(...args);
39
+ trackPageView();
40
+ };
41
+ window.addEventListener("popstate", trackPageView);
42
+ trackPageView();
43
+ `;
44
+
45
+ const INJECTIONS: Record<string, Injection> = {
46
+ unhandledErrors: {
47
+ src: "/node_modules/@base44/vite-plugin/dist/injections/unhandled-errors-handlers.js",
48
+ injectTo: "head",
49
+ mode: "dev",
50
+ },
51
+ sandboxMount: {
52
+ src: "/node_modules/@base44/vite-plugin/dist/injections/sandbox-mount-observer.js",
53
+ injectTo: "body",
54
+ mode: "dev",
55
+ },
56
+ hmrNotifier: {
57
+ src: "/node_modules/@base44/vite-plugin/dist/injections/sandbox-hmr-notifier.js",
58
+ injectTo: "head",
59
+ mode: "dev",
60
+ },
61
+ navigationNotifier: {
62
+ src: "/node_modules/@base44/vite-plugin/dist/injections/navigation-notifier.js",
63
+ injectTo: "head",
64
+ mode: "dev",
65
+ },
66
+ analyticsTracker: {
67
+ injectTo: "head",
68
+ mode: "production",
69
+ inlineContent: ANALYTICS_TRACKER_SCRIPT,
70
+ },
71
+ };
8
72
 
9
73
  export function htmlInjectionsPlugin({
10
74
  hmrNotifier,
11
75
  navigationNotifier,
12
76
  visualEditAgent,
13
- }: HtmlInjectionOptions): Plugin {
77
+ analyticsTracker,
78
+ }: {
79
+ hmrNotifier: boolean;
80
+ navigationNotifier: boolean;
81
+ visualEditAgent: boolean;
82
+ analyticsTracker: boolean;
83
+ }) {
84
+ const enabledInjections: Record<string, boolean> = {
85
+ unhandledErrors: true,
86
+ sandboxMount: true,
87
+ hmrNotifier,
88
+ navigationNotifier,
89
+ analyticsTracker,
90
+ };
91
+
92
+ let resolvedEnv: Record<string, string> = {};
93
+
14
94
  return {
15
95
  name: "html-injections",
16
- apply: (config) => config.mode !== "production",
17
-
18
- transformIndexHtml() {
19
- const options = JSON.stringify({
20
- hmrNotifier,
21
- navigationNotifier,
22
- visualEditAgent,
23
- unhandledErrors: true,
24
- mountObserver: true,
25
- });
26
- return [
27
- {
28
- tag: "script",
29
- attrs: { type: "module" },
30
- children: [
31
- `if (window.self !== window.top) {`,
32
- ` (async () => {`,
33
- ` try {`,
34
- ` const mode = new URLSearchParams(location.search).get("sandbox-bridge");`,
35
- ` const url = mode === "local"`,
36
- ` ? "https://localhost:3201/index.mjs"`,
37
- ` : "/node_modules/@base44/vite-plugin/dist/statics/index.mjs";`,
38
- ` const mod = await import(url);`,
39
- ` if (typeof mod.init === "function") mod.init(${options}, import.meta.hot);`,
40
- ` } catch (e) {`,
41
- ` console.error("[sandbox-bridge] Failed to load:", e);`,
42
- ` }`,
43
- ` })();`,
44
- `}`,
45
- ].join("\n"),
46
- injectTo: "head",
47
- },
48
- ];
96
+ configResolved(config) {
97
+ // Capture env vars for use in transformIndexHtml
98
+ // loadEnv gets all env vars including VITE_ prefixed ones
99
+ resolvedEnv = loadEnv(config.mode, config.root, "");
49
100
  },
50
- };
101
+ transformIndexHtml: {
102
+ handler(_html, ctx) {
103
+ const currentMode = ctx.server ? "dev" : "production";
104
+
105
+ const tags = Object.entries(INJECTIONS)
106
+ .filter(
107
+ ([key, injection]) =>
108
+ enabledInjections[key] && injection.mode === currentMode
109
+ )
110
+ .map(([, injection]): HtmlTagDescriptor => {
111
+ // Production injections use inline content (src paths don't work in built output)
112
+ if (injection.inlineContent) {
113
+ // Replace import.meta.env references with actual values
114
+ // Vite doesn't replace these in inline script content
115
+ let content = injection.inlineContent;
116
+ content = content.replace(
117
+ /import\.meta\.env\.(\w+)/g,
118
+ (_, envKey) => JSON.stringify(resolvedEnv[envKey] ?? "")
119
+ );
120
+
121
+ return {
122
+ tag: "script",
123
+ attrs: { type: "module" },
124
+ children: content,
125
+ injectTo: injection.injectTo,
126
+ };
127
+ }
128
+ // Dev injections use src path (served from node_modules)
129
+ return {
130
+ tag: "script",
131
+ attrs: {
132
+ src: injection.src,
133
+ type: "module",
134
+ },
135
+ injectTo: injection.injectTo,
136
+ };
137
+ });
138
+
139
+ // Visual edit agent — loaded via dynamic import to support
140
+ // local dev iteration with ?sandbox-bridge=local
141
+ if (currentMode === "dev" && visualEditAgent) {
142
+ const dist = "/node_modules/@base44/vite-plugin/dist";
143
+ tags.push({
144
+ tag: "script",
145
+ attrs: { type: "module" },
146
+ children: [
147
+ `if (window.self !== window.top) {`,
148
+ ` const mode = new URLSearchParams(location.search).get("sandbox-bridge");`,
149
+ ` const url = mode === "local"`,
150
+ ` ? "https://localhost:3201/index.mjs"`,
151
+ ` : "${dist}/statics/index.mjs";`,
152
+ ` import(url)`,
153
+ ` .then(mod => { if (typeof mod.setupVisualEditAgent === "function") mod.setupVisualEditAgent(); })`,
154
+ ` .catch(e => console.error("[visual-edit-agent] Failed to load:", e));`,
155
+ `}`,
156
+ ].join("\n"),
157
+ injectTo: "body",
158
+ });
159
+ }
160
+
161
+ return tags;
162
+ },
163
+ },
164
+ } as Plugin;
51
165
  }
package/src/index.ts CHANGED
@@ -13,6 +13,7 @@ export default function vitePlugin(
13
13
  hmrNotifier?: boolean;
14
14
  navigationNotifier?: boolean;
15
15
  visualEditAgent?: boolean;
16
+ analyticsTracker?: boolean;
16
17
  } = {}
17
18
  ) {
18
19
  const {
@@ -20,6 +21,7 @@ export default function vitePlugin(
20
21
  hmrNotifier = false,
21
22
  navigationNotifier = false,
22
23
  visualEditAgent = false,
24
+ analyticsTracker = false,
23
25
  } = opts;
24
26
 
25
27
  return [
@@ -215,8 +217,9 @@ export default function vitePlugin(
215
217
  } as Plugin,
216
218
  errorOverlayPlugin(),
217
219
  visualEditPlugin(),
218
- htmlInjectionsPlugin({ hmrNotifier, navigationNotifier, visualEditAgent }),
219
220
  ]
220
221
  : []),
222
+ // HTML injections - handles both dev (sandbox) and production injections
223
+ htmlInjectionsPlugin({ hmrNotifier, navigationNotifier, visualEditAgent, analyticsTracker }),
221
224
  ];
222
225
  }
@@ -1,5 +1,4 @@
1
- /** Intercept pushState / replaceState / popstate and notify the parent of URL changes. */
2
- export function setupNavigationNotifier() {
1
+ if (window.self !== window.top) {
3
2
  let lastUrl = window.location.href;
4
3
 
5
4
  function notifyNavigation() {
@@ -1,9 +1,8 @@
1
- /** Forward Vite HMR lifecycle events (beforeUpdate / afterUpdate) to the parent window. */
2
- export function setupHmrNotifier(hmr: { on(event: string, cb: (...args: any[]) => void): void }) {
3
- hmr.on("vite:beforeUpdate", () => {
1
+ if (import.meta.hot) {
2
+ import.meta.hot.on("vite:beforeUpdate", () => {
4
3
  window.parent?.postMessage({ type: "sandbox:beforeUpdate" }, "*");
5
4
  });
6
- hmr.on("vite:afterUpdate", () => {
5
+ import.meta.hot.on("vite:afterUpdate", () => {
7
6
  window.parent?.postMessage({ type: "sandbox:afterUpdate" }, "*");
8
7
  });
9
8
  }
@@ -1,5 +1,5 @@
1
- /** Observe DOM mutations and notify the parent when instrumented elements are mounted or unmounted. */
2
- export function setupMountObserver() {
1
+
2
+ if (window.self !== window.top) {
3
3
  const observer = new MutationObserver((mutations) => {
4
4
  const nodesAdded = mutations.some(
5
5
  (mutation) => mutation.addedNodes.length > 0