@vcp-dev/site-edit-bridge 0.6.8 → 0.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -31,6 +31,6 @@ function mt(e){let t=new Map,n=[],r=new Map,o=[],i=e.pageComposition.status==="s
|
|
|
31
31
|
`,c.appendChild(m);let P=Wo.map(_=>{let A=s.createElement("div");return A.setAttribute(h,_),A.setAttribute("aria-hidden","true"),a.appendChild(A),A}),x=null,T=null,B=()=>{x?.removeAttribute(d),T?.(),T=null,x=null},O=_=>{B(),x=_,T=Ze(_,o),_.setAttribute(d,"true"),P.forEach(A=>A.style.removeProperty("display"))};O(l);let J=!1,b=null,L=()=>{if(!b||!l)return;let _=(A,C,f)=>{C?l.style.setProperty(A,C,f):l.style.removeProperty(A)};_("width",b.widthValue,b.widthPriority),_("height",b.heightValue,b.heightPriority)},H=(_,A,C)=>b?{version:1,phase:_,sessionId:b.sessionId,pointerId:b.pointerId,edge:b.edge,ref:t,startWidth:b.startWidth,startHeight:b.startHeight,width:A,height:C}:null,$=_=>{if(!b||!l?.isConnected||_.pointerId!==b.pointerId)return!1;let A=Number(_.clientX)-b.startX,C=Number(_.clientY)-b.startY,f=Math.max(1,Math.round(b.startWidth+A)),v=Math.max(1,Math.round(b.startHeight+C));return(b.edge==="e"||b.edge==="se")&&l.style.setProperty("width",`${f}px`,"important"),(b.edge==="s"||b.edge==="se")&&l.style.setProperty("height",`${v}px`,"important"),!0},U=()=>{if(J)return;let _=u();if(_===l&&_?.isConnected)return;L();let A=b?.captureTarget,C=b?.pointerId;b=null,C!==void 0&&A?.releasePointerCapture?.(C),B(),l=_,l?.isConnected?O(l):P.forEach(f=>f.style.setProperty("display","none","important"))},z=e.MutationObserver,Y=typeof z=="function"?new z(U):null;return Y?.observe(s.documentElement,{attributeFilter:["data-vcp-edit-key"],attributes:!0,childList:!0,subtree:!0}),{begin(_,A){if(J||b||!l?.isConnected)return null;let C=l.getBoundingClientRect();return b={sessionId:`resize-${r}-${_.pointerId}`,pointerId:_.pointerId,edge:A,startX:Number(_.clientX),startY:Number(_.clientY),startWidth:C.width,startHeight:C.height,widthValue:l.style.getPropertyValue("width"),widthPriority:l.style.getPropertyPriority("width"),heightValue:l.style.getPropertyValue("height"),heightPriority:l.style.getPropertyPriority("height"),captureTarget:_.target},H("start",C.width,C.height)},update:$,finish(_,A){if(!b||_.pointerId!==b.pointerId)return null;A==="commit"&&$(_);let C=Math.max(1,Math.round(b.startWidth+Number(_.clientX)-b.startX)),f=Math.max(1,Math.round(b.startHeight+Number(_.clientY)-b.startY)),v=H(A,A==="commit"?C:b.startWidth,A==="commit"?f:b.startHeight),F=b.captureTarget,k=b.pointerId;return L(),b=null,F?.releasePointerCapture?.(k),v},cleanup(){if(J)return;J=!0,Y?.disconnect(),L();let _=b?.captureTarget,A=b?.pointerId;b=null,A!==void 0&&_?.releasePointerCapture?.(A),B(),l=null,P.forEach(C=>C.remove()),m.remove()}}}function xn(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function Ko(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Uo({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,setCurrentDocument:i,onBridgeRequestError:s,windowLike:c}){let a=c.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let u=await a.initializeSession({routeId:e.payload.routeId});i?.(u.data.document),On(c,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await a.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await a.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.acknowledgeDocumentVersion?await a.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:jo(u,e.payload.key,c.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let u=await a.execute(e.payload.request),l=o?.()?.routeId;if(u.ok&&l&&a.acknowledgeDocumentVersion&&Ko(e.payload.request)){let d=await a.acknowledgeDocumentVersion(l,u.data.resultVersion);i?.(d.data)}n({type:"response",ok:!0,result:u});return}case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let l=a.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:u}})});r.set(u,l),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let u=e.payload.subscriptionId;r.get(u)?.(),r.delete(u),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(u){s?.(u,e),n({type:"response",ok:!1,error:Zo(u)})}}function jo(e,t,n,r){if(!e.ok)return e;let o=he(n,{key:t},r),i=o?Go(o):null;return i?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...i}}}:e}function Go(e){let t=e.ownerDocument.defaultView;if(!t)return null;let n=t.getComputedStyle(e);return{color:n.color,backgroundColor:n.backgroundColor,borderColor:n.borderColor}}function Yo(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,i=n(),s=()=>{let u=n();u!==i&&(i=u,t())},c=()=>s(),a=()=>s();return e.history.pushState=function(...l){let d=r.apply(this,l);return s(),d},e.history.replaceState=function(...l){let d=o.apply(this,l);return s(),d},e.addEventListener("popstate",c),e.addEventListener("hashchange",a),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",a)}}function Xo(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function et(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function tt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function On(e,t){e.dispatchEvent(new CustomEvent(Tt,{detail:t}))}function Jo(e,t){e.dispatchEvent(new CustomEvent(Pt,{detail:t}))}function Lo(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Qo(e,t){return e.routeId===t}function Nt(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Mn(e){let t=Nt(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Zo(e){let t=Nt(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Mn(t)?"Site edit bridge disconnected":t}function xe(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return/authentication|auth failed|auth rejected|bridge key|session|unauthorized|forbidden|expired/i.test(t)}function Vn(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Bt(e){return So.has(Wn(e))}function ei(e){return Eo.has(Wn(e))}function zn(e){return e.operationSummary?{canUpdateText:e.operationSummary.canUpdateText,canInsertChild:e.operationSummary.canInsertChild,canMove:e.operationSummary.canMove,canRemove:e.operationSummary.canRemove}:e.fallbackMode!=="preview"?{canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1}:{canUpdateText:ei(e.tagName),canInsertChild:Bt(e.tagName),canMove:!1,canRemove:!1}}function Wn(e){return e?.trim().toLowerCase()??""}function Cn(e,t){return e.key!==t.key||e.instanceIndex!==t.instanceIndex||e.instanceCount!==t.instanceCount?!1:typeof e.textSegmentIndex=="number"&&typeof t.textSegmentIndex=="number"?e.textSegmentIndex===t.textSegmentIndex:!0}function ti(e,t,n){let r=he(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=ni(r,t.ref.textSegmentIndex);return o?(o.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function ni(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function ri(e,t,n,r,o){let i=Me(e,t,n,r),s=Dt(i);if(!s)return null;let c=s.getAttribute("data-vcp-edit-key")??"",a=pe(e,s,r),u=o?.(a.key)??o?.(c);if(!zn({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let d=oi(e,t,n,s);if(d){let h=si(s,d);if(h!==null)return{element:s,textNode:d,textSegmentIndex:h}}return at(s)?null:{element:s}}function oi(e,t,n,r){let o=ii(e,t,n);return!o||o.parentElement!==r?null:o}function ii(e,t,n){let r=e,i=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(nt(i))return i;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return nt(c)?c:null}function si(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!nt(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function nt(e){return e?.nodeType===3}function ai(e,t,n){return(typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean))[0]??null}function ci(e,t,n){let r=t;for(;r&&!r.getAttribute("data-site-block-id");)r=r.parentElement;if(!r)return null;let o=r.getAttribute("data-site-block-id")??"",i=r.getAttribute("data-vcp-edit-key")??"";return!o||!i?null:{blockId:o,ref:rt(e,r,n),rect:ve(r.getBoundingClientRect()),targetIsSectionRoot:t===r}}function ui(e,t){return Array.from(e.querySelectorAll("[data-site-block-id]")).filter(n=>{let r=n.parentElement;for(;r;){if(r.getAttribute("data-site-block-id"))return!1;r=r.parentElement}return!!(n.getAttribute("data-site-block-id")&&n.getAttribute("data-vcp-edit-key"))}).map(n=>({element:n,blockId:n.getAttribute("data-site-block-id")??"",ref:rt(e,n,t),rect:ve(n.getBoundingClientRect())})).filter(({rect:n})=>n.width>0&&n.height>0).sort((n,r)=>n.rect.top-r.rect.top||n.rect.left-r.rect.left)}function li(e,t,n){let r=ui(e,n),o=r[0],i=r.at(-1);return!o||!i?null:[{anchorBlockId:o.blockId,anchorRef:o.ref,placement:"before",boundary:{top:o.rect.top,left:o.rect.left,width:o.rect.width}},...r.slice(1).map(c=>({anchorBlockId:c.blockId,anchorRef:c.ref,placement:"before",boundary:{top:c.rect.top,left:c.rect.left,width:c.rect.width}})),{anchorBlockId:i.blockId,anchorRef:i.ref,placement:"after",boundary:{top:i.rect.top+i.rect.height,left:i.rect.left,width:i.rect.width}}].find(({boundary:c})=>t.clientX>=c.left&&t.clientX<=c.left+c.width&&Math.abs(t.clientY-c.top)<=pn)??null}function Me(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let i of o){let s=Dt(i),c=s?.getAttribute("data-vcp-edit-key")??"";if(s&&qn(s,r,c))return s}return null}function Dt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ft(t))return n??t;!di(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ft(e){return e.getAttribute(bo)!==null}function di(e){return pi(e.split("::")[0]??"")}function pi(e){if(!e)return!1;let t=hi(e);return t===Ye||t.startsWith(`${Ye}/`)||t.includes(`/${Ye}/`)||t.endsWith(`/${Ye}`)}function hi(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function pe(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,r);if(o.length<=1)return{key:_n(n,r,0)};let i=o.indexOf(t);return i>=0?{key:_n(n,r,i),instanceIndex:i,instanceCount:o.length}:{key:r}}function rt(e,t,n){return pe(e,t,n)}function he(e,t,n){let r=ot(t.key)??t.key,o=$n(Un(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ln(r)}"]`))),n,t.key);if(o.length===0)return null;let i=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,s=(ot(t.key)??t.key)!==t.key;if(i!==null&&!s)return o[i]??null;let c=fi(n,t.key);return c!==null&&c>=0&&c<o.length?o[c]??null:i!==null?o[i]??null:o[0]??null}function _n(e,t,n){return Hn(e,t)[n]?.key??t}function fi(e,t){let n=ot(t);if(!n)return null;let o=Hn(e,n).findIndex(i=>i.key===t);return o>=0?o:null}function Hn(e,t){return(e?.entries??[]).filter(n=>(ot(n.key)??n.key)===t)}function $n(e,t,n){let r=Kn(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function qn(e,t,n){let r=Kn(t,n);return!r||e.tagName.toLowerCase()===r}function Kn(e,t){return null}var mi=2,gi=4;function Un(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&gi)!==0?-1:(r&mi)!==0?1:0})}function ot(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Sn);if(n<0)break;let r=Number(t.slice(n+Sn.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function st(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...wt(n),paddingTop:ie(n?.paddingTop),paddingRight:ie(n?.paddingRight),paddingBottom:ie(n?.paddingBottom),paddingLeft:ie(n?.paddingLeft),borderTopWidth:ie(n?.borderTopWidth),borderRightWidth:ie(n?.borderRightWidth),borderBottomWidth:ie(n?.borderBottomWidth),borderLeftWidth:ie(n?.borderLeftWidth),columnGap:ie(n?.columnGap),rowGap:ie(n?.rowGap)}}function wt(e){return{marginTop:ie(e?.marginTop,!0),marginRight:ie(e?.marginRight,!0),marginBottom:ie(e?.marginBottom,!0),marginLeft:ie(e?.marginLeft,!0)}}function ie(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function Ot(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:ve(n.getBoundingClientRect()),margin:wt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function yi(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>ve(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}var Tn=new WeakMap,Pn=0;function we(e){let t=Tn.get(e);if(t)return t;Pn+=1;let n=`runtime-node-${Pn}`;return Tn.set(e,n),n}function jn(e,t,n){let r=n??e.ownerDocument?.defaultView,o=e.ownerDocument?.defaultView?.getComputedStyle(e),i=ve(t),s=K(r?.scrollX),c=K(r?.scrollY),a=o?.position||"static";return{version:xt,runtimeNodeId:we(e),rect:{viewport:i,document:{top:i.top+c,left:i.left+s,width:i.width,height:i.height}},layout:{position:a,transform:o?.transform||"none",containingBlock:Si(e,a)},scrollContext:{scrollX:s,scrollY:c,viewportWidth:K(r?.innerWidth),viewportHeight:K(r?.innerHeight),scrollContainers:bi(e)}}}function bi(e){let t=e.ownerDocument,n=t?.defaultView,r=[],o=e.parentElement;for(;o;){if(o!==t?.body&&o!==t?.documentElement){let i=n?.getComputedStyle(o),s=i?.overflowX||i?.overflow||"visible",c=i?.overflowY||i?.overflow||"visible",a=K(o.scrollLeft),u=K(o.scrollTop),l=a!==0||An(s)&&K(o.scrollWidth)>K(o.clientWidth),d=u!==0||An(c)&&K(o.scrollHeight)>K(o.clientHeight);(l||d)&&r.push({runtimeNodeId:we(o),scrollLeft:a,scrollTop:u})}o=o.parentElement}return r}function An(e){return["auto","scroll","overlay","hidden"].includes(e)}function Si(e,t){if(t==="fixed"){let r=kn(e.parentElement,!0);return r?{kind:"element",runtimeNodeId:we(r)}:{kind:"viewport"}}if(t==="absolute"){let r=e.offsetParent,o=Ei(r)??kn(e.parentElement,!1);return o?{kind:"element",runtimeNodeId:we(o)}:{kind:"document"}}let n=e.parentElement;return n?{kind:"element",runtimeNodeId:we(n)}:{kind:"document"}}function kn(e,t){let n=e;for(;n;){let r=n.ownerDocument?.defaultView?.getComputedStyle(n);if(!!(r?.transform&&r.transform!=="none")||!!(r?.perspective&&r.perspective!=="none")||!!(r?.filter&&r.filter!=="none")||(r?.willChange??"").split(",").some(i=>["transform","perspective","filter"].includes(i.trim()))||!t&&(r?.position||"static")!=="static")return n;n=n.parentElement}return null}function Ei(e){return e&&typeof e.getBoundingClientRect=="function"?e:null}function de(e,t,n,r="full",o){let i=e.getBoundingClientRect(),s=n?.(t.key)??null,c=e.tagName.toLowerCase(),a=Ve(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([T,B])=>[T,B??""])),attributes:Object.fromEntries(e.getAttributeNames().map(T=>[T,e.getAttribute(T)??""]))}:{},l=zn({operationSummary:s?.operationSummary,tagName:c,fallbackMode:"preview"}),d=Ft(e),h=!0,m=Gn(e)?.getAttribute("data-vcp-edit-key")??null,P=Ot(e),x=jn(e,i,o);return{ref:t,key:t.key,detailLevel:r,tagName:c,...s?{sourceKind:"jsx"}:{},...m?{parentKey:m}:{},...s?.pageCompositionUnitKey?{pageCompositionUnitKey:s.pageCompositionUnitKey}:{},...u,runtimeFlags:{selectable:!0,movable:l.canMove,removable:l.canRemove,textEditable:l.canUpdateText,container:d?!1:!!at(e)||l.canInsertChild||h&&Bt(c)},layoutSnapshot:x,layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:P,childRects:P.map(({rect:T})=>T),spacing:st(e)}}function Nn(e,t,n,r){let o=e.getBoundingClientRect(),i=jn(e,o,n);if(r==="light")return{ref:t,layoutSnapshot:i};if(r==="child-rects")return{ref:t,layoutSnapshot:i,childRects:yi(e)};let s=Ot(e);return{ref:t,layoutSnapshot:i,childBoxes:s,childRects:s.map(({rect:c})=>c),layout:Ve(e),spacing:st(e)}}function Bn(e){let t=e.layout?.display??"",n=e.spacing;return["flex","inline-flex","grid","inline-grid"].includes(t)&&!!(n&&(n.columnGap>0||n.rowGap>0)&&(e.childRects?.length??0)>=2)}function vi(e,t,n,r,o){let i=t,s=Nn(i,n,e,"detailed"),c=Bn(s),a=null,u=null,l="mutation",d=Ce(e),h=d,m=!1,P=!1,x=({reason:Y,sourceEventAt:_,forceEmit:A=!1,includeDetailedGeometry:C=!1})=>{(a===null||(Y==="scroll"?0:1)>=(l==="scroll"?0:1))&&(l=Y,d=_),m=m||A,P=P||C,a===null&&(a=et(e,T))},T=()=>{let Y=Ce(e);a=null;let _=l,A=d,C=m,f=P;m=!1,P=!1;let v=he(e.document,n,r?.()??null);if(!v)return;v!==i&&(H?.unobserve(i),i=v,H?.observe(i),f=!0);let F=f?"detailed":c?"child-rects":"light",k=Nn(i,n,e,F),Q=k.layoutSnapshot.rect.viewport;Q.width<=0||Q.height<=0||!C&&!Ii(s,k)||(s=k,F==="detailed"&&(c=Bn(k)),o(_,k,{sourceEventAt:A,captureStartedAt:Y,capturedAt:Ce(e)}))},B=()=>{u!==null&&(e.clearTimeout(u),u=null)},O=()=>{B(),x({reason:"resize",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},J=()=>{B(),x({reason:"mutation",sourceEventAt:Ce(e),includeDetailedGeometry:!0})},b=()=>{h=Ce(e),x({reason:"scroll",sourceEventAt:h}),B(),u=e.setTimeout(()=>{u=null,x({reason:"scroll",sourceEventAt:h,forceEmit:!0,includeDetailedGeometry:!0})},mo)},L=e.ResizeObserver,H=typeof L=="function"?new L(O):null;H?.observe(i);let $=e.MutationObserver,U=typeof $=="function"?new $(J):null;U?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",O,{passive:!0}),e.addEventListener("scroll",b,{passive:!0});let z=e.visualViewport;return z?.addEventListener?.("resize",O,{passive:!0}),z?.addEventListener?.("scroll",b,{passive:!0}),e.document.addEventListener("scroll",b,{capture:!0,passive:!0}),e.document.addEventListener("load",J,!0),()=>{a!==null&&(tt(e,a),a=null),B(),H?.disconnect(),U?.disconnect(),e.removeEventListener("resize",O),e.removeEventListener("scroll",b),z?.removeEventListener?.("resize",O),z?.removeEventListener?.("scroll",b),e.document.removeEventListener("scroll",b,!0),e.document.removeEventListener("load",J,!0)}}function Ce(e){let t=e.performance;return t&&Number.isFinite(t.timeOrigin)&&typeof t.now=="function"?t.timeOrigin+t.now():Date.now()}function Ii(e,t){return Ri(e.layoutSnapshot,t.layoutSnapshot)||t.childBoxes!==void 0&&Ci(e.childBoxes,t.childBoxes)||t.childRects!==void 0&&_i(e.childRects,t.childRects)||t.layout!==void 0&&At(e.layout,t.layout)||t.spacing!==void 0&&At(e.spacing,t.spacing)}function Ri(e,t){return!e||!t?e!==t:e.version!==t.version||e.runtimeNodeId!==t.runtimeNodeId||it(e.rect.viewport,t.rect.viewport)||it(e.rect.document,t.rect.document)||e.layout.position!==t.layout.position||e.layout.transform!==t.layout.transform||e.layout.containingBlock.kind!==t.layout.containingBlock.kind||e.layout.containingBlock.kind==="element"&&t.layout.containingBlock.kind==="element"&&e.layout.containingBlock.runtimeNodeId!==t.layout.containingBlock.runtimeNodeId||e.scrollContext.scrollX!==t.scrollContext.scrollX||e.scrollContext.scrollY!==t.scrollContext.scrollY||e.scrollContext.viewportWidth!==t.scrollContext.viewportWidth||e.scrollContext.viewportHeight!==t.scrollContext.viewportHeight||xi(e.scrollContext.scrollContainers,t.scrollContext.scrollContainers)}function xi(e,t){return e.length!==t.length||e.some((n,r)=>{let o=t[r];return!o||n.runtimeNodeId!==o.runtimeNodeId||n.scrollLeft!==o.scrollLeft||n.scrollTop!==o.scrollTop})}function Ci(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>{let s=r[i];return!s||it(o.rect,s.rect)||At(o.margin,s.margin)})}function _i(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>it(o,r[i]??o))}function At(e,t){let n=e??{},r=t??{},o=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(o).some(i=>n[i]!==r[i])}function ve(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function it(e,t){return Math.abs(e.top-t.top)>.5||Math.abs(e.left-t.left)>.5||Math.abs(e.width-t.width)>.5||Math.abs(e.height-t.height)>.5}function Ti(e,t,n,r,o,i,s){let c=e.document,a=Me(c,t,n,i);if(!a)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?he(c,o,i):null;if(u&&kt(a,u))return Je(c,a,"self-or-descendant",i,s);if(r==="move"&&u){let x=Ni(c,a,u,i,s);if(x){let T=Ct(x.child,x.targetParent,t,n,"nearest");if(T)return Le(c,x.child,x.targetParent,T,i,s)}}let l=null,d=!1,h=a,m=a.parentElement;for(;m;){if(m.getAttribute("data-vcp-edit-key")){if(u&&kt(m,u))return Je(c,a,"self-or-descendant",i,s);let x=Dn(m,r,s);if(x==="accept"){l={child:h,targetParent:m};break}x==="blocked"&&(d=!0),h=m}m=m.parentElement}let P=Dn(a,r,s);if(P==="accept"){if(l){let x=Ct(l.child,l.targetParent,t,n,"edge");if(x)return Le(c,l.child,l.targetParent,x,i,s)}return Le(c,a,a,Pi(a,t,n),i,s)}if(l){let x=Ct(l.child,l.targetParent,t,n,"nearest");return Le(c,l.child,l.targetParent,x??"after",i,s)}return P==="blocked"||d?Je(c,a,"operation-boundary-blocked",i,s):Je(c,a,"no-accepting-parent",i,s)}function Je(e,t,n,r,o){return{anchorHit:de(t,pe(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Le(e,t,n,r,o,i){let s=de(t,pe(e,t,o),i,"summary"),c=de(n,pe(e,n,o),i,"summary"),a=Ve(n).indicatorOrientation,u=r==="append"||r==="prepend"?Ai(n.getBoundingClientRect(),a,r):ki(t.getBoundingClientRect(),a,r);return{anchorHit:s,targetParentHit:c,relation:r,indicatorOrientation:a,indicatorBounds:u}}function Dn(e,t,n){if(Ft(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":at(e)?"blocked":"not-container";let i=e.tagName.toLowerCase();return Bt(i)?"accept":"not-container"}function Ct(e,t,n,r,o){let i=Ve(t).indicatorOrientation,s=e.getBoundingClientRect(),c=i==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return o==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function Pi(e,t,n){let r=Ve(e).indicatorOrientation,o=e.getBoundingClientRect();return(r==="vertical"?o.width>0?(t-o.left)/o.width:.5:o.height>0?(n-o.top)/o.height:.5)<.5?"prepend":"append"}function Ve(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,i=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(i??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...i?{gridAutoFlow:i}:{},indicatorOrientation:s}}function Ai(e,t,n){if(t==="vertical")return{left:n==="prepend"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="prepend"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function ki(e,t,n){if(t==="vertical")return{left:n==="before"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="before"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function kt(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Ni(e,t,n,r,o){let i=Bi(e,t,n,r,o);if(i)return i;let s=Gn(n);if(!s||t===s)return null;let c=t,a=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==s;)c.getAttribute("data-vcp-edit-key")&&(a=c),c=c.parentElement;return c!==s||!a||a===s||a===n||kt(a,n)?null:{child:a,targetParent:s}}function Bi(e,t,n,r,o){return null}function Gn(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function at(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=at(n);if(r)return r}return null}function Qe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:K(e.scrollX),scrollY:K(e.scrollY),scrollWidth:Math.max(K(t?.scrollWidth),K(n?.scrollWidth),K(e.innerWidth)),scrollHeight:Math.max(K(t?.scrollHeight),K(n?.scrollHeight),K(e.innerHeight)),viewportWidth:K(e.innerWidth),viewportHeight:K(e.innerHeight)}}function Di(e,t){Object.entries(t.attributes??{}).forEach(([r,o])=>{if(o===null){e.removeAttribute(r);return}e.setAttribute(r,o)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,o])=>{if(n.has(r))return;let i=e.style,s=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(o==null||o===""){i.removeProperty(s);return}i.setProperty(s,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,i=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),s=r.value;if(s==null||s===""){o.removeProperty(i);return}o.setProperty(i,String(s),r.priority)})}var Fi=500,Fe=new Map;function wi(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Oi(e,t){if(Fe.size>=Fi){let n=Fe.keys().next().value;n&&Fe.delete(n)}Fe.set(e,t)}var Oe=new Set;function Mi(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,i]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,i));for(let o of Oe)r.has(o)||n?.removeProperty(o);Oe.clear();for(let o of r)Oe.add(o);$i(e,t.stylesheets??[])}function Vi(e){let t=e.documentElement?.style;for(let n of Oe)t?.removeProperty(n);Oe.clear();for(let n of Jn(e))n.remove()}function zi(e,t){let n=Array.from(new Set(t.filter(s=>typeof s=="string"&&s.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,i={};for(let s of n){let c=Yn(o,s);c&&(i[s]=c)}return i}function Yn(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Xn(e,r,n)}function Xn(e,t,n){if(!t)return null;let r=Wi(t);if(!r)return t;let o=Yn(e,r.name,n);return o||(r.fallback?Xn(e,r.fallback,n)??r.fallback:null)}function Wi(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Hi(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let i=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:i||null}}function Hi(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function $i(e,t){let n=new Set(t.filter(i=>typeof i=="string"&&i.length>0)),r=new Map;for(let i of Jn(e)){let s=i.getAttribute("href")??"";if(!n.has(s)||r.has(s)){i.remove();continue}r.set(s,i)}let o=e.head;if(o)for(let i of n){if(r.has(i))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(Fn,"true"),s.setAttribute("href",i),o.appendChild(s)}}function Jn(e){return Array.from(e.querySelectorAll(`link[${Fn}]`))}function qi(e,t,n,r,o={}){let i=o.textNode?Ki(e.document,o.textNode):null;if(o.textNode&&!i)throw new Error("Failed to prepare text segment editor");let s=i?.element??t,c=s.textContent??"",a=i?void 0:t.innerHTML,u=Ui(s),l=!1,d=()=>{e.document.removeEventListener("pointerdown",m,!0),s.removeEventListener("keydown",P),s.removeEventListener("blur",x),s.removeEventListener("input",T),Gi(s,u)},h=B=>{if(l)return;l=!0;let O=s.textContent??"";if(d(),B==="cancel"){i?.restore(c),i||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(i?.restore(O),B==="commit"&&O!==c){o.onCommitSnapshot?.({ref:n,initialText:c,...a!==void 0?{initialHtml:a}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:O}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function m(B){let O=B.target;O&&s.contains(O)||h("commit")}function P(B){if(B.key==="Escape"){B.preventDefault(),h("cancel");return}B.key==="Enter"&&(B.metaKey||B.ctrlKey)&&(B.preventDefault(),h("commit"))}function x(){h("commit")}function T(){r({kind:"text-edit-input",payload:{ref:n,hit:de(t,n,void 0,"full")}})}return ji(s),e.document.addEventListener("pointerdown",m,!0),s.addEventListener("keydown",P),s.addEventListener("blur",x),s.addEventListener("input",T),Ji(s),Li(s,e.document),d}function Ki(e,t){let n=t.parentNode;if(!n)return null;let r=e.createElement("span");return r.setAttribute("data-vcp-text-segment-editor","true"),r.textContent=t.textContent??"",n.replaceChild(r,t),{element:r,restore(o){t.nodeValue=o,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Ui(e){return{contentEditable:e.getAttribute("contenteditable"),spellcheck:e.getAttribute("spellcheck"),marker:e.getAttribute("data-vcp-edit-text-editing"),cursor:e.style.cursor,userSelect:e.style.userSelect}}function ji(e){Yi(e.ownerDocument),e.setAttribute("contenteditable","plaintext-only"),e.setAttribute("spellcheck","false"),e.setAttribute("data-vcp-edit-text-editing","true"),e.style.cursor="text",e.style.userSelect="text"}function Gi(e,t){_t(e,"contenteditable",t.contentEditable),_t(e,"spellcheck",t.spellcheck),_t(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Yi(e){if(e.getElementById("vcp-text-edit-base-style"))return;let t=e.createElement("style");t.id="vcp-text-edit-base-style",t.textContent='[data-vcp-edit-text-editing="true"]{outline:0!important;outline-offset:0!important;}',e.head.appendChild(t)}function _t(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Xi(e){let t=[e.documentElement,e.body].filter(r=>!!r?.style),n=t.map(r=>({element:r,userSelect:r.style.userSelect}));for(let r of t)r.style.userSelect="none";return()=>{for(let r of n)r.element.style.userSelect=r.userSelect}}function Ji(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Li(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ln(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(e){let t=Number(e);return Number.isFinite(t)?t:0}import Qi from"node:http";import{createHash as rr,randomBytes as Zi,timingSafeEqual as es}from"node:crypto";import zt from"node:path";import{WebSocket as or,WebSocketServer as ts}from"ws";import{createPreviewSiteEditEngineRuntime as ns,openFileHistoryStore as rs}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as os,scanNextAppRouterRoutes as is}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ss}from"@vcp-dev/site-edit-engine/source-watcher";var ct=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as as}from"@vcp-dev/contracts";var cs="127.0.0.1",us=30218,ls="/__vcp/site-edit/bridge",ir=6*1024*1024,ds=ir*2,ps=3e3,Qn=50,Zn="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function za(e){let t=ar(e),n=ur(t),r=cr(),o=r.get(n);if(o)return o;let i=new ut(t);r.set(n,i);try{i.start()}catch(s){throw r.delete(n),i.stop(),s}return i}function sr(e,t,n={}){let r=new ut(ar(t),e,!1,n);return r.start({listen:!1}),r}var ut=class{constructor(t,n=Qi.createServer((i,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ct,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=fs({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new ss({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??Qn,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=cr(),n=ur(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??ns)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let s of this.eventListeners)s(i)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=o,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:r,resolvedRouteId:o}=await this.activateRoute(t.routeId),i=r.getDocument(o).data;await this.recordRuntimeVersion(i.version);let s=(await r.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:s}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),o=n.getDocument(r);return await this.recordRuntimeVersion(o.data.version),o},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),o=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,o)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=await this.bindHistorySession(this.options.snapshotId);if(!r.ok)return Mt(r,t);let o=await this.getRuntime().executeOperation(this.normalizeRequest(t));return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion),o}),undo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return Mt(t);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??rs)(hs({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,o),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??Qn;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of t)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:is(this.options.projectRoot),n=new Map(this.routes.map(o=>[o.routeId,o.entryFile])),r=new Set(t.map(o=>o.routeId));this.routes=t;for(let o of t)n.get(o.routeId)!==o.entryFile&&this.runtime?.registerRoute(o.routeId,o.entryFile);for(let o of n.keys())r.has(o)||this.runtime?.unregisterRoute(o)}resolveRouteId(t){let n=os(t,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function ar(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:zt.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??cs,port:e.port??us,path:e.path??ls,sessionKey:e.sessionKey??vs(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function hs(e){return zt.join(zt.resolve(e.root),er(e.siteId),er(e.snapshotId),rr("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function er(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:rr("sha256").update(e).digest("hex").slice(0,32)}function cr(){let e=globalThis;return e[Zn]??=new Map,e[Zn]}function ur(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Mt(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function fs(e){let t=new ts({maxPayload:ir,noServer:!0}),n=new WeakSet,r=i=>{new Ke({socket:new Wt(i),engine:e.engine,validateOperationRequest:s=>as.safeParse(s).success})},o=(i,s,c)=>{if(!ms(i,e))return;let a=gs(i,e);if(!a){s.write(`HTTP/1.1 401 Unauthorized\r
|
|
32
32
|
Connection: close\r
|
|
33
33
|
\r
|
|
34
|
-
`),s.destroy();return}a.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,s,c,u=>{t.emit("connection",u,i)})};return e.server.on("upgrade",o),t.on("connection",(i,s)=>{if(n.has(s)){r(i);return}ys(i,e.sessionKey,()=>{r(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var Wt=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===or.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ds){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ms(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function gs(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Vt(e.headers["x-vcp-site-edit-key"]),o=lr(r,t.sessionKey),i=Vt(e.headers.host),s=Vt(e.headers.origin);return i&&!bs(i,t.host,s)?null:s?Es(s,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ys(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ps),o,i=()=>{clearTimeout(r),e.off("message",o),e.off("close",i)},s=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let a=oe.parseMessage(c.toString());if(a.type!=="auth"||!lr(a.payload.key,t)){s();return}i(),e.readyState===or.OPEN&&e.send(oe.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",o),e.on("close",i)}function lr(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&es(n,r)}function bs(e,t,n){let r=nr(e),o=nr(t);return r===o||tr(o)&&tr(r)&&(!n||Ht(n,e))||Ss(o)&&(!n||Ht(n,e))}function Ss(e){return e==="0.0.0.0"||e==="::"}function tr(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Es(e,t,n){return n.includes(e)||(t?Ht(e,t):!1)}function Ht(e,t){try{return new URL(e).host===dr(t)}catch{return!1}}function nr(e){let t=dr(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function dr(e){return e.trim().toLowerCase()}function Vt(e){return Array.isArray(e)?e[0]:e}function vs(){return Zi(32).toString("base64url")}import Is from"node:http";import{existsSync as Te,readFileSync as _e}from"node:fs";import{createRequire as mr}from"node:module";import ze from"node:path";import{basename as gr,dirname as We,join as He}from"node:path";import{fileURLToPath as yr}from"node:url";var Rs="next",xs="127.0.0.1",Cs=3e3,dt="/__vcp/site-edit/bridge",br="/__vcp/site-edit/health",pt="/__vcp/site-edit/client/",_s=`${pt}auto-bootstrap.js`,Sr='data-vcp-site-edit-bootstrap="true"',Ts=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ps="@vcp-dev/site-edit-engine/webpack-loader",As=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ks=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ns=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ya(e={},t={}){let n=t.process??process,r=t.createServer??Is.createServer,o=t.attachBridgeServer??sr,i=t.loadNext??ia,s=ze.resolve(e.projectRoot??process.cwd()),c=e.host??xs,a=e.port??ua(n.env.PORT)??Cs,u=e.bridgePath??dt,l=Vs(u),d=ea(),h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",m=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,P=await i(s),x=Bs(s),T=P({dev:!0,dir:s,hostname:c,port:a,...Ds(x)}),B=T.getRequestHandler(),O=e.siteId??n.env.VCP_SITE_ID??"site_preview",J=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ca(s),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,L=b?.trim()?ze.resolve(b):void 0,H=null,$=r((A,C)=>{Us({basePath:h,bridgePath:u,bridgeHealthPath:l,bridgeSessionKey:d,getBridgeHealth:()=>H?.getHealth()??Gs(u),handle:B,request:A,response:C}).catch(f=>{console.error(f),C.headersSent||(C.statusCode=500),C.end("site edit preview request failed")})}),U=null,z=null,Y=()=>z||(lt(()=>n.off("SIGINT",_)),lt(()=>n.off("SIGTERM",_)),lt(()=>U?.()),U=null,lt(()=>H?.stop()),H=null,z=Promise.allSettled([da($),pa(()=>T.close())]).then(()=>{}),z),_=()=>{Y()};try{return await T.prepare(),H=o($,{...m?{tenantId:m}:{},siteId:O,snapshotId:J,projectRoot:s,basePath:h,host:c,port:a,path:u,sessionKey:d,...L?{historyRoot:L}:{}}),U=Os({server:$,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",_),n.on("SIGTERM",_),await la($,a,c),{bundler:x,close:Y,host:c,port:ha($,a),server:$}}catch(A){throw await Y(),A}}function Bs(e){let t=Fs(e);return t&&ws(t)?"webpack":"turbopack"}function Ds(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Fs(e){for(let t of Ts){let n=He(e,t);if(Te(n))return _e(n,"utf8")}return null}function ws(e){return e.includes(Ps)?!0:As.test(e)&&ks.some(t=>t.test(e))}function Os(e){let t=(n,r,o)=>{Ms(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(i=>{console.error(i),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Ms(e,t){return new URL(e??"/","http://localhost").pathname===t}function Vs(e=dt){if(e===dt)return br;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function zs(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ws()});return`<script type="module" ${Sr}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(_s)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ws(){return{bridge:$t("@vcp-dev/site-edit-bridge"),contracts:$t("@vcp-dev/contracts"),engine:$t("@vcp-dev/site-edit-engine")}}function $t(e){let t=mr(import.meta.url);try{let n=t.resolve(e),r=Hs(n,e);if(!r)return;let o=JSON.parse(_e(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Hs(e,t){let n=ze.parse(e).root,r=We(e);for(;r&&r!==n;){let o=He(r,"package.json");if(Te(o))try{if(JSON.parse(_e(o,"utf8")).name===t)return o}catch{return}r=We(r)}}function $s(e,t){if(e.includes(Sr))return e;let n=zs(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Xa(e,t=We(yr(import.meta.url)),n=Te){return Er(e,t,n)?.path??null}function Er(e,t=We(yr(import.meta.url)),n=Te){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(pt))return null;let o=r.slice(pt.length);if(!Ns.has(o))return null;let i=qt(sa(t),o);if(gr(t)!=="src")return{path:i,requiresTranspile:!1};let s=qt(t,o.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function qs(e,t){let n=Er(e.url);if(!n)return!1;if(!Te(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Ks(_e(n.path,"utf8")):_e(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Ks(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Us({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:i,request:s,response:c}){if(js(s,c,n,o)||await qs(s,c))return;let a=Ys(s),u=Xs(s),l=a||u?Qs(c,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await i(s,c)}catch(d){throw l(),d}}function js(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let i=r();return t.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(i)),!0}function Gs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ys(e){return Js(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Xs(e){return Ls(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Js(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(pt)||t===dt||t===br)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Ls(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Qs(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),i=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(c,a,u)=>(c!==void 0&&n.push(pr(c,hr(a))),fr(a),fr(u),!0),r.end=(c,a,u)=>{let l=typeof c=="function"?void 0:c;l!==void 0&&n.push(pr(l,hr(a))),r.write=i,r.end=s,r.flushHeaders=o;let d=Buffer.concat(n),h=Zs(e,d,t);h!==d&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof a=="function"?a:typeof u=="function"?u:void 0;return m?s(h,m):s(h)},()=>{r.write=i,r.end=s,r.flushHeaders=o}}function Zs(e,t,n){if(ta(e,t))return Buffer.from($s(t.toString("utf8"),n));if(n.patchNextDevChunk&&na(e)){let r=t.toString("utf8"),o=ra(r);if(o!==r)return Buffer.from(o)}return t}function ea(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ta(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function na(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function ra(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
34
|
+
`),s.destroy();return}a.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,s,c,u=>{t.emit("connection",u,i)})};return e.server.on("upgrade",o),t.on("connection",(i,s)=>{if(n.has(s)){r(i);return}ys(i,e.sessionKey,()=>{r(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var Wt=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===or.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ds){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ms(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function gs(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Vt(e.headers["x-vcp-site-edit-key"]),o=lr(r,t.sessionKey),i=Vt(e.headers.host),s=Vt(e.headers.origin);return i&&!bs(i,t.host,s)?null:s?Es(s,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ys(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ps),o,i=()=>{clearTimeout(r),e.off("message",o),e.off("close",i)},s=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let a=oe.parseMessage(c.toString());if(a.type!=="auth"||!lr(a.payload.key,t)){s();return}i(),e.readyState===or.OPEN&&e.send(oe.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",o),e.on("close",i)}function lr(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&es(n,r)}function bs(e,t,n){let r=nr(e),o=nr(t);return r===o||tr(o)&&tr(r)&&(!n||Ht(n,e))||Ss(o)&&(!n||Ht(n,e))}function Ss(e){return e==="0.0.0.0"||e==="::"}function tr(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Es(e,t,n){return n.includes(e)||(t?Ht(e,t):!1)}function Ht(e,t){try{return new URL(e).host===dr(t)}catch{return!1}}function nr(e){let t=dr(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function dr(e){return e.trim().toLowerCase()}function Vt(e){return Array.isArray(e)?e[0]:e}function vs(){return Zi(32).toString("base64url")}import Is from"node:http";import{existsSync as Te,readFileSync as _e}from"node:fs";import{createRequire as mr}from"node:module";import ze from"node:path";import{basename as gr,dirname as We,join as He}from"node:path";import{fileURLToPath as yr}from"node:url";var Rs="next",xs="127.0.0.1",Cs=3e3,dt="/__vcp/site-edit/bridge",br="/__vcp/site-edit/health",pt="/__vcp/site-edit/client/",_s=`${pt}auto-bootstrap.js`,Sr='data-vcp-site-edit-bootstrap="true"',Ts=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ps="@vcp-dev/site-edit-engine/webpack-loader",As=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ks=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ns=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ya(e={},t={}){let n=t.process??process,r=t.createServer??Is.createServer,o=t.attachBridgeServer??sr,i=t.loadNext??ia,s=ze.resolve(e.projectRoot??process.cwd()),c=e.host??xs,a=e.port??ua(n.env.PORT)??Cs,u=e.bridgePath??dt,l=Vs(u),d=ea(),h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",m=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,P=await i(s),x=Bs(s),T=P({dev:!0,dir:s,hostname:c,port:a,...Ds(x)}),B=T.getRequestHandler(),O=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",J=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ca(s),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,L=b?.trim()?ze.resolve(b):void 0,H=null,$=r((A,C)=>{Us({basePath:h,bridgePath:u,bridgeHealthPath:l,bridgeSessionKey:d,getBridgeHealth:()=>H?.getHealth()??Gs(u),handle:B,request:A,response:C}).catch(f=>{console.error(f),C.headersSent||(C.statusCode=500),C.end("site edit preview request failed")})}),U=null,z=null,Y=()=>z||(lt(()=>n.off("SIGINT",_)),lt(()=>n.off("SIGTERM",_)),lt(()=>U?.()),U=null,lt(()=>H?.stop()),H=null,z=Promise.allSettled([da($),pa(()=>T.close())]).then(()=>{}),z),_=()=>{Y()};try{return await T.prepare(),H=o($,{...m?{tenantId:m}:{},siteId:O,snapshotId:J,projectRoot:s,basePath:h,host:c,port:a,path:u,sessionKey:d,...L?{historyRoot:L}:{}}),U=Os({server:$,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",_),n.on("SIGTERM",_),await la($,a,c),{bundler:x,close:Y,host:c,port:ha($,a),server:$}}catch(A){throw await Y(),A}}function Bs(e){let t=Fs(e);return t&&ws(t)?"webpack":"turbopack"}function Ds(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Fs(e){for(let t of Ts){let n=He(e,t);if(Te(n))return _e(n,"utf8")}return null}function ws(e){return e.includes(Ps)?!0:As.test(e)&&ks.some(t=>t.test(e))}function Os(e){let t=(n,r,o)=>{Ms(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(i=>{console.error(i),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function Ms(e,t){return new URL(e??"/","http://localhost").pathname===t}function Vs(e=dt){if(e===dt)return br;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function zs(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ws()});return`<script type="module" ${Sr}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(_s)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ws(){return{bridge:$t("@vcp-dev/site-edit-bridge"),contracts:$t("@vcp-dev/contracts"),engine:$t("@vcp-dev/site-edit-engine")}}function $t(e){let t=mr(import.meta.url);try{let n=t.resolve(e),r=Hs(n,e);if(!r)return;let o=JSON.parse(_e(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Hs(e,t){let n=ze.parse(e).root,r=We(e);for(;r&&r!==n;){let o=He(r,"package.json");if(Te(o))try{if(JSON.parse(_e(o,"utf8")).name===t)return o}catch{return}r=We(r)}}function $s(e,t){if(e.includes(Sr))return e;let n=zs(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Xa(e,t=We(yr(import.meta.url)),n=Te){return Er(e,t,n)?.path??null}function Er(e,t=We(yr(import.meta.url)),n=Te){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(pt))return null;let o=r.slice(pt.length);if(!Ns.has(o))return null;let i=qt(sa(t),o);if(gr(t)!=="src")return{path:i,requiresTranspile:!1};let s=qt(t,o.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function qs(e,t){let n=Er(e.url);if(!n)return!1;if(!Te(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Ks(_e(n.path,"utf8")):_e(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Ks(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Us({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:o,handle:i,request:s,response:c}){if(js(s,c,n,o)||await qs(s,c))return;let a=Ys(s),u=Xs(s),l=a||u?Qs(c,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await i(s,c)}catch(d){throw l(),d}}function js(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let i=r();return t.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(i)),!0}function Gs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ys(e){return Js(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Xs(e){return Ls(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Js(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(pt)||t===dt||t===br)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Ls(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function Qs(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),i=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(c,a,u)=>(c!==void 0&&n.push(pr(c,hr(a))),fr(a),fr(u),!0),r.end=(c,a,u)=>{let l=typeof c=="function"?void 0:c;l!==void 0&&n.push(pr(l,hr(a))),r.write=i,r.end=s,r.flushHeaders=o;let d=Buffer.concat(n),h=Zs(e,d,t);h!==d&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof a=="function"?a:typeof u=="function"?u:void 0;return m?s(h,m):s(h)},()=>{r.write=i,r.end=s,r.flushHeaders=o}}function Zs(e,t,n){if(ta(e,t))return Buffer.from($s(t.toString("utf8"),n));if(n.patchNextDevChunk&&na(e)){let r=t.toString("utf8"),o=ra(r);if(o!==r)return Buffer.from(o)}return t}function ea(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ta(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function na(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function ra(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
35
35
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
36
36
|
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,o])=>oa(n,r,o),e)}function oa(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function pr(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function hr(e){return typeof e=="string"?e:void 0}function fr(e){typeof e=="function"&&e()}async function ia(e){let n=mr(He(e,"package.json"))(Rs);return n.default??n}function sa(e){return gr(e)!=="src"?e:qt(aa(e),"dist")}function aa(e){return vr(e)?ze.posix.dirname(e):We(e)}function qt(e,t){return vr(e)?ze.posix.join(e,t):He(e,t)}function vr(e){return e.includes("/")&&!e.includes("\\")}function ca(e){let t=He(e,".vcp/current-snapshot.json");if(!Te(t))return"sandbox_worktree";try{let n=JSON.parse(_e(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function ua(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function la(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}function da(e){return new Promise(t=>{e.close(()=>t())})}function lt(e){try{e()}catch{}}function pa(e){try{return e()}catch(t){return Promise.reject(t)}}function ha(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{ds as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,ir as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,dn as SITE_EDIT_FRAME_RUNTIME_CHANNEL,xt as SITE_EDIT_FRAME_RUNTIME_LAYOUT_SNAPSHOT_VERSION,Ne as SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION,ke as SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION,pn as SITE_EDIT_FRAME_SECTION_GAP_RADIUS_PX,ln as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,ut as SiteEditBridgeServer,Ke as SiteEditBridgeSocketServer,oe as SiteEditBridgeTransport,Ue as SiteEditWebSocketClient,Pt as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Tt as VCP_SITE_EDIT_ROUTE_READY_EVENT,un as VCP_WINDOW_MESSAGE_SOURCE,Ia as VCP_WINDOW_MESSAGE_VERSION,Os as attachNextDevUpgradeHandler,sr as attachSiteEditBridgeServer,fs as attachSiteEditWebSocketServer,zs as createSiteEditAutoBootstrapHtmlSnippet,cn as createSiteEditBridge,De as createSiteEditFrameRuntimeMessage,$r as createVcpWindowMessageEnvelope,gt as decodeRenderDocument,mt as encodeRenderDocument,za as ensureSiteEditBridgeServerStarted,$s as injectSiteEditAutoBootstrap,Cr as isCompactRenderDocument,Dr as isDesignerTraceEnabled,mn as isSiteEditFrameRuntimeLayoutSnapshot,hn as isSiteEditFrameRuntimeMessage,qr as isVcpWindowMessageEnvelope,ra as patchNextFirefoxDevChunk,Xs as prepareFirefoxNextDevChunkPatchRequest,Ys as prepareSiteEditHtmlInjectionRequest,Vs as resolveSiteEditBridgeHealthPath,Er as resolveSiteEditClientAsset,Xa as resolveSiteEditClientAssetPath,Bs as resolveSiteEditNextDevBundler,vo as resolveSiteEditRouteId,Ro as resolveSiteEditWebSocketUrl,Fr as sanitizeTracePayload,_a as startSiteEditAutoBootstrap,ko as startSiteEditFrameRuntime,Ya as startSiteEditNextDevServer,me as traceDesignerEvent,Ks as transpileSiteEditClientSource};
|
package/dist/next-dev-server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import st from"node:http";import{existsSync as w,readFileSync as S}from"node:fs";import{createRequire as pe}from"node:module";import R from"node:path";import{basename as ge,dirname as x,join as b}from"node:path";import{fileURLToPath as me}from"node:url";import Te from"node:http";import{createHash as ie,randomBytes as He,timingSafeEqual as Be}from"node:crypto";import L from"node:path";import{WebSocket as oe,WebSocketServer as je}from"ws";import{createPreviewSiteEditEngineRuntime as Ae,openFileHistoryStore as De}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Me,scanNextAppRouterRoutes as Ue}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ne}from"@vcp-dev/site-edit-engine/source-watcher";function U(t){let e=new Map,n=[],s=new Map,r=[],i=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],o=new Map(i.map((a,u)=>[a,u])),c=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(a=>({placementKey:a.placementKey,placementUnitKey:a.placementUnitKey,relation:a.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},d=t.entries.flatMap((a,u)=>a.dynamicDataSummary?[[u,a.dynamicDataSummary]]:[]),h=a=>{let u=e.get(a);if(typeof u=="number")return u;let l=n.length;return n.push(a),e.set(a,l),l},g=a=>{let u=null;for(let l of Ce(a)){let v=`${u??"root"}\0${l}`,I=s.get(v);if(typeof I=="number"){u=I;continue}let m=r.length;r.push([u,h(l)]),s.set(v,m),u=m}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,pageComposition:c,tokens:n,nodes:r,entries:t.entries.map(a=>{let u=a.pageCompositionUnitKey?o.get(a.pageCompositionUnitKey)??-1:-1;if(a.pageCompositionUnitKey&&u<0)throw new Error(`Render entry ${a.key} references unknown page composition unit ${a.pageCompositionUnitKey}`);return[g(a.key),ke(a.operationSummary),...u>=0?[u]:[]]}),...d.length>0?{dynamicDataSummaries:d}:{}}}function ke(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function Ce(t){if(!t)return[];let e=[],n=0,s=Y(t,n);if(s<0)return e.push(t),e;for(e.push(t.slice(0,s)),n=s;n<t.length;){if(s=Y(t,n+(t.startsWith("::",n)?2:1)),s<0){e.push(t.slice(n));break}e.push(t.slice(n,s)),n=s}return e}function Y(t,e){let n=t.indexOf("/",e),s=t.indexOf("::",e);return n<0?s:s<0?n:Math.min(n,s)}var p=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let n=e.payload,s=typeof n.id=="string"?n.id:"unknown",r=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:s,kind:r}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!f(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?f(e.payload)&&typeof e.payload.id=="string":e.type==="event"?f(e.payload)&&f(e.payload.event):e.type==="auth"?f(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?f(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,n={}){if(!f(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"initialize-session":return typeof e.routeId=="string"&&(e.mutationContext===void 0||N(e.mutationContext));case"get-document":case"get-style-context":return typeof e.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-history-status":return e.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return Ee(e.request)&&(e.request.mutationContext===void 0||N(e.request.mutationContext))&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return e.mutationContext===void 0||N(e.mutationContext)}}},P=class{constructor(e){this.options=e,this.messageQueue=new V,this.eventDispatcher=new O(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.eventDispatcher.push(n)}),e.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(s){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:s instanceof Error?s.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let s=n.payload,{id:r}=s;switch(s.kind){case"initialize-session":{let i=await this.options.engine.initializeSession({routeId:s.routeId,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:{document:U(i.data.document),historyStatus:i.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:U((await this.options.engine.getDocument(s.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getStyleContext(s.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getObjectEditContext(s.key,s.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getClassNameSource(s.key,s.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceFile({path:s.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.resolveSourceLocation({key:s.key,routeId:s.routeId})}});return;case"execute":{await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.execute(s.request));return}case"undo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.redo());return}}catch(n){let s=p.extractRequestInfo(e);this.sendJson({type:"error",payload:{...s,message:X(n),code:Z(n)}})}}async handleRawMessage(e){try{await this.handleMessage(p.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=n instanceof Error?n.message:"Invalid websocket message",r=Pe(e);this.sendJson({type:"error",payload:{...r,message:s}})}}sendJson(e){this.options.socket.send(p.stringifyMessage(e))}async handleBufferedOperation(e,n,s){this.eventDispatcher.beginBuffering();try{let r=await s();this.sendJson({type:"response",payload:{id:e,kind:n,result:r}}),this.eventDispatcher.flush()}catch(r){this.sendJson({type:"error",payload:{id:e,kind:n,message:X(r),code:Z(r)}}),this.eventDispatcher.flush()}}},O=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},V=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function f(t){return typeof t=="object"&&t!==null}function Ee(t){return f(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&f(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&f(t.params)}function N(t){return _e(t)}function Z(t){if(!t||typeof t!="object")return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function X(t){if(t instanceof Error)return t.message;if(!t||typeof t!="object")return"Unknown websocket operation failure";let e=t.message;return typeof e=="string"&&e.length>0?e:"Unknown websocket operation failure"}function _e(t){return f(t)?typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0:!1}function Pe(t){try{return p.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var T=class{constructor(){this.tail=Promise.resolve()}run(e){let n=this.tail.then(e,e);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Oe}from"@vcp-dev/contracts";var Ve="127.0.0.1",Fe=30218,Ke="/__vcp/site-edit/bridge",ae=6*1024*1024,Le=ae*2,qe=3e3,ee=50,te="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function ue(t,e,n={}){let s=new q($e(e),t,!1,n);return s.start({listen:!1}),s}var q=class{constructor(e,n=Te.createServer((i,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),s=!0,r={}){this.options=e,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=r,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new T,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=Ge({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new Ne({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??ee,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let e=!!this.runtime;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=We(),n=ze(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createRuntime(e,n=null){let s=this.runtime;this.activeHistoryStore=e??null;let r=(this.dependencies.createRuntime??Ae)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let o of this.eventListeners)o(i)},...e?{historyStore:e}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=r,this.activeHistorySessionId=n,s?.dispose()}createBridgeEngine(){return{initializeSession:e=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:s,resolvedRouteId:r}=await this.activateRoute(e.routeId),i=s.getDocument(r).data;await this.recordRuntimeVersion(i.version);let o=(await s.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:o}}}),getDocument:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e),r=n.getDocument(s);return await this.recordRuntimeVersion(r.data.version),r},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e);return n.getStyleContext(s)},getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let s=this.getRuntime(),r=n?this.resolveRouteId(n):void 0;return s.getClassNameSource(e,r)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute:(e,n)=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return F(s,e);let r=await this.getRuntime().executeOperation(this.normalizeRequest(e));return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion),r}),undo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let s=await(this.dependencies.openHistoryStore??De)(Je({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let r=s.readDocumentVersion?await s.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,r),this.createRuntime(s,e)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,e);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(e){let n=this.getRuntime(),s=this.resolveRouteId(e);return await n.setActiveRoute(s),{runtime:n,resolvedRouteId:s}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let s of e)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??ee;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((n,s)=>n.localeCompare(s));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of e)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:Ue(this.options.projectRoot),n=new Map(this.routes.map(r=>[r.routeId,r.entryFile])),s=new Set(e.map(r=>r.routeId));this.routes=e;for(let r of e)n.get(r.routeId)!==r.entryFile&&this.runtime?.registerRoute(r.routeId,r.entryFile);for(let r of n.keys())s.has(r)||this.runtime?.unregisterRoute(r)}resolveRouteId(e){let n=Me(e,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function $e(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:L.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??Ve,port:t.port??Fe,path:t.path??Ke,sessionKey:t.sessionKey??nt(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function Je(t){return L.join(L.resolve(t.root),ne(t.siteId),ne(t.snapshotId),ie("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function ne(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:ie("sha256").update(t).digest("hex").slice(0,32)}function We(){let t=globalThis;return t[te]??=new Map,t[te]}function ze(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function F(t,e){return{ok:!1,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ge(t){let e=new je({maxPayload:ae,noServer:!0}),n=new WeakSet,s=i=>{new P({socket:new $(i),engine:t.engine,validateOperationRequest:o=>Oe.safeParse(o).success})},r=(i,o,c)=>{if(!Qe(i,t))return;let d=Ye(i,t);if(!d){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),o.destroy();return}d.authenticatedByHeader&&n.add(i),e.handleUpgrade(i,o,c,h=>{e.emit("connection",h,i)})};return t.server.on("upgrade",r),e.on("connection",(i,o)=>{if(n.has(o)){s(i);return}Ze(i,t.sessionKey,()=>{s(i)})}),e.stop=()=>{t.server.off("upgrade",r);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var $=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===oe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Le){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Qe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ye(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=K(t.headers["x-vcp-site-edit-key"]),r=ce(s,e.sessionKey),i=K(t.headers.host),o=K(t.headers.origin);return i&&!Xe(i,e.host,o)?null:o?tt(o,i,e.allowedOrigins)?{authenticatedByHeader:r}:null:r?{authenticatedByHeader:!0}:null}function Ze(t,e,n){let s=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},qe),r,i=()=>{clearTimeout(s),t.off("message",r),t.off("close",i)},o=()=>{i(),t.close(1008,"bridge authentication failed")};r=c=>{try{let d=p.parseMessage(c.toString());if(d.type!=="auth"||!ce(d.payload.key,e)){o();return}i(),t.readyState===oe.OPEN&&t.send(p.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{o()}},t.on("message",r),t.on("close",i)}function ce(t,e){if(!t)return!1;let n=Buffer.from(t),s=Buffer.from(e);return n.length===s.length&&Be(n,s)}function Xe(t,e,n){let s=re(t),r=re(e);return s===r||se(r)&&se(s)&&(!n||J(n,t))||et(r)&&(!n||J(n,t))}function et(t){return t==="0.0.0.0"||t==="::"}function se(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function tt(t,e,n){return n.includes(t)||(e?J(t,e):!1)}function J(t,e){try{return new URL(t).host===de(e)}catch{return!1}}function re(t){let e=de(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function de(t){return t.trim().toLowerCase()}function K(t){return Array.isArray(t)?t[0]:t}function nt(){return He(32).toString("base64url")}var rt="next",it="127.0.0.1",ot=3e3,B="/__vcp/site-edit/bridge",ye="/__vcp/site-edit/health",j="/__vcp/site-edit/client/",at=`${j}auto-bootstrap.js`,Se='data-vcp-site-edit-bootstrap="true"',ut=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ct="@vcp-dev/site-edit-engine/webpack-loader",dt=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ht=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],lt=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Sn(t={},e={}){let n=e.process??process,s=e.createServer??st.createServer,r=e.attachBridgeServer??ue,i=e.loadNext??Vt,o=R.resolve(t.projectRoot??process.cwd()),c=t.host??it,d=t.port??qt(n.env.PORT)??ot,h=t.bridgePath??B,g=wt(h),a=Dt(),u=t.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",l=(t.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,v=await i(o),I=ft(o),m=v({dev:!0,dir:o,hostname:c,port:d,...pt(I)}),Re=m.getRequestHandler(),xe=t.siteId??n.env.VCP_SITE_ID??"site_preview",be=t.snapshotId??n.env.VCP_SNAPSHOT_ID??Lt(o),G=t.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,Q=G?.trim()?R.resolve(G):void 0,k=null,y=s((M,_)=>{Ct({basePath:u,bridgePath:h,bridgeHealthPath:g,bridgeSessionKey:a,getBridgeHealth:()=>k?.getHealth()??_t(h),handle:Re,request:M,response:_}).catch(ve=>{console.error(ve),_.headersSent||(_.statusCode=500),_.end("site edit preview request failed")})}),A=null,C=null,D=()=>C||(H(()=>n.off("SIGINT",E)),H(()=>n.off("SIGTERM",E)),H(()=>A?.()),A=null,H(()=>k?.stop()),k=null,C=Promise.allSettled([Jt(y),Wt(()=>m.close())]).then(()=>{}),C),E=()=>{D()};try{return await m.prepare(),k=r(y,{...l?{tenantId:l}:{},siteId:xe,snapshotId:be,projectRoot:o,basePath:u,host:c,port:d,path:h,sessionKey:a,...Q?{historyRoot:Q}:{}}),A=yt({server:y,bridgePath:h,handleUpgrade:m.getUpgradeHandler()}),n.on("SIGINT",E),n.on("SIGTERM",E),await $t(y,d,c),{bundler:I,close:D,host:c,port:zt(y,d),server:y}}catch(M){throw await D(),M}}function ft(t){let e=gt(t);return e&&mt(e)?"webpack":"turbopack"}function pt(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function gt(t){for(let e of ut){let n=b(t,e);if(w(n))return S(n,"utf8")}return null}function mt(t){return t.includes(ct)?!0:dt.test(t)&&ht.some(e=>e.test(t))}function yt(t){let e=(n,s,r)=>{St(n.url,t.bridgePath)||t.handleUpgrade(n,s,r).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function St(t,e){return new URL(t??"/","http://localhost").pathname===e}function wt(t=B){if(t===B)return ye;let e=(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"");return e.endsWith("/bridge")?`${e.slice(0,-7)}/health`:e?`${e}/health`:"/health"}function It(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??Rt()});return`<script type="module" ${Se}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(at)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function Rt(){return{bridge:W("@vcp-dev/site-edit-bridge"),contracts:W("@vcp-dev/contracts"),engine:W("@vcp-dev/site-edit-engine")}}function W(t){let e=pe(import.meta.url);try{let n=e.resolve(t),s=xt(n,t);if(!s)return;let r=JSON.parse(S(s,"utf8"));return typeof r.version=="string"?r.version:void 0}catch{return}}function xt(t,e){let n=R.parse(t).root,s=x(t);for(;s&&s!==n;){let r=b(s,"package.json");if(w(r))try{if(JSON.parse(S(r,"utf8")).name===e)return r}catch{return}s=x(s)}}function bt(t,e){if(t.includes(Se))return t;let n=It(e),s=/<\/body\s*>/i.exec(t);return s?`${t.slice(0,s.index)}${n}${t.slice(s.index)}`:`${t}${n}`}function wn(t,e=x(me(import.meta.url)),n=w){return we(t,e,n)?.path??null}function we(t,e=x(me(import.meta.url)),n=w){let s=new URL(t??"/","http://localhost").pathname;if(!s.startsWith(j))return null;let r=s.slice(j.length);if(!lt.has(r))return null;let i=z(Ft(e),r);if(ge(e)!=="src")return{path:i,requiresTranspile:!1};let o=z(e,r.replace(/\.js$/,".ts"));return n(o)?{path:o,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function vt(t,e){let n=we(t.url);if(!n)return!1;if(!w(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await kt(S(n.path,"utf8")):S(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(s),!0}async function kt(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ct({basePath:t,bridgePath:e,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:r,handle:i,request:o,response:c}){if(Et(o,c,n,r)||await vt(o,c))return;let d=Pt(o),h=Tt(o),g=d||h?jt(c,{basePath:t,bridgePath:e,bridgeSessionKey:s,patchNextDevChunk:h}):()=>{};try{await i(o,c)}catch(a){throw g(),a}}function Et(t,e,n,s){if(t.method!=="GET"||new URL(t.url??"/","http://localhost").pathname!==n)return!1;let i=s();return e.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(i)),!0}function _t(t){return{ok:!1,bridgePath:t,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Pt(t){return Ht(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Tt(t){return Bt(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ht(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(j)||e===B||e===ye)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Bt(t){if(t.method!=="GET"||!String(t.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(t.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function jt(t,e){let n=[],s=t,r=s.flushHeaders.bind(t),i=s.write.bind(t),o=s.end.bind(t);return s.flushHeaders=()=>{},s.write=(c,d,h)=>(c!==void 0&&n.push(he(c,le(d))),fe(d),fe(h),!0),s.end=(c,d,h)=>{let g=typeof c=="function"?void 0:c;g!==void 0&&n.push(he(g,le(d))),s.write=i,s.end=o,s.flushHeaders=r;let a=Buffer.concat(n),u=At(t,a,e);u!==a&&!t.headersSent&&t.removeHeader("content-length");let l=typeof c=="function"?c:typeof d=="function"?d:typeof h=="function"?h:void 0;return l?o(u,l):o(u)},()=>{s.write=i,s.end=o,s.flushHeaders=r}}function At(t,e,n){if(Mt(t,e))return Buffer.from(bt(e.toString("utf8"),n));if(n.patchNextDevChunk&&Ut(t)){let s=e.toString("utf8"),r=Nt(s);if(r!==s)return Buffer.from(r)}return e}function Dt(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function Mt(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function Ut(t){if(t.statusCode<200||t.statusCode>=300)return!1;let e=t.getHeader("content-type"),n=Array.isArray(e)?e.join(";"):String(e??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Nt(t){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
4
|
+
`),o.destroy();return}d.authenticatedByHeader&&n.add(i),e.handleUpgrade(i,o,c,h=>{e.emit("connection",h,i)})};return t.server.on("upgrade",r),e.on("connection",(i,o)=>{if(n.has(o)){s(i);return}Ze(i,t.sessionKey,()=>{s(i)})}),e.stop=()=>{t.server.off("upgrade",r);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var $=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===oe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Le){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Qe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ye(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=K(t.headers["x-vcp-site-edit-key"]),r=ce(s,e.sessionKey),i=K(t.headers.host),o=K(t.headers.origin);return i&&!Xe(i,e.host,o)?null:o?tt(o,i,e.allowedOrigins)?{authenticatedByHeader:r}:null:r?{authenticatedByHeader:!0}:null}function Ze(t,e,n){let s=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},qe),r,i=()=>{clearTimeout(s),t.off("message",r),t.off("close",i)},o=()=>{i(),t.close(1008,"bridge authentication failed")};r=c=>{try{let d=p.parseMessage(c.toString());if(d.type!=="auth"||!ce(d.payload.key,e)){o();return}i(),t.readyState===oe.OPEN&&t.send(p.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{o()}},t.on("message",r),t.on("close",i)}function ce(t,e){if(!t)return!1;let n=Buffer.from(t),s=Buffer.from(e);return n.length===s.length&&Be(n,s)}function Xe(t,e,n){let s=re(t),r=re(e);return s===r||se(r)&&se(s)&&(!n||J(n,t))||et(r)&&(!n||J(n,t))}function et(t){return t==="0.0.0.0"||t==="::"}function se(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function tt(t,e,n){return n.includes(t)||(e?J(t,e):!1)}function J(t,e){try{return new URL(t).host===de(e)}catch{return!1}}function re(t){let e=de(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function de(t){return t.trim().toLowerCase()}function K(t){return Array.isArray(t)?t[0]:t}function nt(){return He(32).toString("base64url")}var rt="next",it="127.0.0.1",ot=3e3,B="/__vcp/site-edit/bridge",ye="/__vcp/site-edit/health",j="/__vcp/site-edit/client/",at=`${j}auto-bootstrap.js`,Se='data-vcp-site-edit-bootstrap="true"',ut=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ct="@vcp-dev/site-edit-engine/webpack-loader",dt=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ht=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],lt=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Sn(t={},e={}){let n=e.process??process,s=e.createServer??st.createServer,r=e.attachBridgeServer??ue,i=e.loadNext??Vt,o=R.resolve(t.projectRoot??process.cwd()),c=t.host??it,d=t.port??qt(n.env.PORT)??ot,h=t.bridgePath??B,g=wt(h),a=Dt(),u=t.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",l=(t.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,v=await i(o),I=ft(o),m=v({dev:!0,dir:o,hostname:c,port:d,...pt(I)}),Re=m.getRequestHandler(),xe=t.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",be=t.snapshotId??n.env.VCP_SNAPSHOT_ID??Lt(o),G=t.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,Q=G?.trim()?R.resolve(G):void 0,k=null,y=s((M,_)=>{Ct({basePath:u,bridgePath:h,bridgeHealthPath:g,bridgeSessionKey:a,getBridgeHealth:()=>k?.getHealth()??_t(h),handle:Re,request:M,response:_}).catch(ve=>{console.error(ve),_.headersSent||(_.statusCode=500),_.end("site edit preview request failed")})}),A=null,C=null,D=()=>C||(H(()=>n.off("SIGINT",E)),H(()=>n.off("SIGTERM",E)),H(()=>A?.()),A=null,H(()=>k?.stop()),k=null,C=Promise.allSettled([Jt(y),Wt(()=>m.close())]).then(()=>{}),C),E=()=>{D()};try{return await m.prepare(),k=r(y,{...l?{tenantId:l}:{},siteId:xe,snapshotId:be,projectRoot:o,basePath:u,host:c,port:d,path:h,sessionKey:a,...Q?{historyRoot:Q}:{}}),A=yt({server:y,bridgePath:h,handleUpgrade:m.getUpgradeHandler()}),n.on("SIGINT",E),n.on("SIGTERM",E),await $t(y,d,c),{bundler:I,close:D,host:c,port:zt(y,d),server:y}}catch(M){throw await D(),M}}function ft(t){let e=gt(t);return e&&mt(e)?"webpack":"turbopack"}function pt(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function gt(t){for(let e of ut){let n=b(t,e);if(w(n))return S(n,"utf8")}return null}function mt(t){return t.includes(ct)?!0:dt.test(t)&&ht.some(e=>e.test(t))}function yt(t){let e=(n,s,r)=>{St(n.url,t.bridgePath)||t.handleUpgrade(n,s,r).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function St(t,e){return new URL(t??"/","http://localhost").pathname===e}function wt(t=B){if(t===B)return ye;let e=(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"");return e.endsWith("/bridge")?`${e.slice(0,-7)}/health`:e?`${e}/health`:"/health"}function It(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??Rt()});return`<script type="module" ${Se}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(at)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function Rt(){return{bridge:W("@vcp-dev/site-edit-bridge"),contracts:W("@vcp-dev/contracts"),engine:W("@vcp-dev/site-edit-engine")}}function W(t){let e=pe(import.meta.url);try{let n=e.resolve(t),s=xt(n,t);if(!s)return;let r=JSON.parse(S(s,"utf8"));return typeof r.version=="string"?r.version:void 0}catch{return}}function xt(t,e){let n=R.parse(t).root,s=x(t);for(;s&&s!==n;){let r=b(s,"package.json");if(w(r))try{if(JSON.parse(S(r,"utf8")).name===e)return r}catch{return}s=x(s)}}function bt(t,e){if(t.includes(Se))return t;let n=It(e),s=/<\/body\s*>/i.exec(t);return s?`${t.slice(0,s.index)}${n}${t.slice(s.index)}`:`${t}${n}`}function wn(t,e=x(me(import.meta.url)),n=w){return we(t,e,n)?.path??null}function we(t,e=x(me(import.meta.url)),n=w){let s=new URL(t??"/","http://localhost").pathname;if(!s.startsWith(j))return null;let r=s.slice(j.length);if(!lt.has(r))return null;let i=z(Ft(e),r);if(ge(e)!=="src")return{path:i,requiresTranspile:!1};let o=z(e,r.replace(/\.js$/,".ts"));return n(o)?{path:o,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function vt(t,e){let n=we(t.url);if(!n)return!1;if(!w(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await kt(S(n.path,"utf8")):S(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(s),!0}async function kt(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ct({basePath:t,bridgePath:e,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:r,handle:i,request:o,response:c}){if(Et(o,c,n,r)||await vt(o,c))return;let d=Pt(o),h=Tt(o),g=d||h?jt(c,{basePath:t,bridgePath:e,bridgeSessionKey:s,patchNextDevChunk:h}):()=>{};try{await i(o,c)}catch(a){throw g(),a}}function Et(t,e,n,s){if(t.method!=="GET"||new URL(t.url??"/","http://localhost").pathname!==n)return!1;let i=s();return e.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(i)),!0}function _t(t){return{ok:!1,bridgePath:t,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Pt(t){return Ht(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Tt(t){return Bt(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ht(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(j)||e===B||e===ye)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Bt(t){if(t.method!=="GET"||!String(t.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(t.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function jt(t,e){let n=[],s=t,r=s.flushHeaders.bind(t),i=s.write.bind(t),o=s.end.bind(t);return s.flushHeaders=()=>{},s.write=(c,d,h)=>(c!==void 0&&n.push(he(c,le(d))),fe(d),fe(h),!0),s.end=(c,d,h)=>{let g=typeof c=="function"?void 0:c;g!==void 0&&n.push(he(g,le(d))),s.write=i,s.end=o,s.flushHeaders=r;let a=Buffer.concat(n),u=At(t,a,e);u!==a&&!t.headersSent&&t.removeHeader("content-length");let l=typeof c=="function"?c:typeof d=="function"?d:typeof h=="function"?h:void 0;return l?o(u,l):o(u)},()=>{s.write=i,s.end=o,s.flushHeaders=r}}function At(t,e,n){if(Mt(t,e))return Buffer.from(bt(e.toString("utf8"),n));if(n.patchNextDevChunk&&Ut(t)){let s=e.toString("utf8"),r=Nt(s);if(r!==s)return Buffer.from(r)}return e}function Dt(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function Mt(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function Ut(t){if(t.statusCode<200||t.statusCode>=300)return!1;let e=t.getHeader("content-type"),n=Array.isArray(e)?e.join(";"):String(e??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Nt(t){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
5
5
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
6
6
|
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[s,r])=>Ot(n,s,r),t)}function Ot(t,e,n){if(n.length>e.length)throw new Error("Replacement must not be longer than the search string.");return t.replaceAll(e,n.padEnd(e.length," "))}function he(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function le(t){return typeof t=="string"?t:void 0}function fe(t){typeof t=="function"&&t()}async function Vt(t){let n=pe(b(t,"package.json"))(rt);return n.default??n}function Ft(t){return ge(t)!=="src"?t:z(Kt(t),"dist")}function Kt(t){return Ie(t)?R.posix.dirname(t):x(t)}function z(t,e){return Ie(t)?R.posix.join(t,e):b(t,e)}function Ie(t){return t.includes("/")&&!t.includes("\\")}function Lt(t){let e=b(t,".vcp/current-snapshot.json");if(!w(e))return"sandbox_worktree";try{let n=JSON.parse(S(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function qt(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function $t(t,e,n){return new Promise((s,r)=>{t.once("error",r),t.listen(e,n,()=>{t.off("error",r),s()})})}function Jt(t){return new Promise(e=>{t.close(()=>e())})}function H(t){try{t()}catch{}}function Wt(t){try{return t()}catch(e){return Promise.reject(e)}}function zt(t,e){let n=t.address();return typeof n=="object"&&n?n.port:e}export{yt as attachNextDevUpgradeHandler,It as createSiteEditAutoBootstrapHtmlSnippet,bt as injectSiteEditAutoBootstrap,Nt as patchNextFirefoxDevChunk,Tt as prepareFirefoxNextDevChunkPatchRequest,Pt as prepareSiteEditHtmlInjectionRequest,wt as resolveSiteEditBridgeHealthPath,we as resolveSiteEditClientAsset,wn as resolveSiteEditClientAssetPath,ft as resolveSiteEditNextDevBundler,Sn as startSiteEditNextDevServer,kt as transpileSiteEditClientSource};
|
|
@@ -9,7 +9,7 @@ export async function runStartNextDevServerCli(argv, dependencies = {}) {
|
|
|
9
9
|
host,
|
|
10
10
|
port,
|
|
11
11
|
projectRoot,
|
|
12
|
-
siteId: env.VCP_SITE_ID ?? "
|
|
12
|
+
siteId: env.VCP_SITE_ID ?? "018f6f4d-a9b8-7120-8000-000000000120",
|
|
13
13
|
snapshotId: env.VCP_SNAPSHOT_ID,
|
|
14
14
|
});
|
|
15
15
|
(dependencies.log ?? console.log)(JSON.stringify({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vcp-dev/site-edit-bridge",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -74,8 +74,8 @@
|
|
|
74
74
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@vcp-dev/contracts": "0.6.
|
|
78
|
-
"@vcp-dev/site-edit-engine": "0.6.
|
|
77
|
+
"@vcp-dev/contracts": "0.6.10",
|
|
78
|
+
"@vcp-dev/site-edit-engine": "0.6.10",
|
|
79
79
|
"@types/ws": "^8.18.1",
|
|
80
80
|
"ws": "^8.20.1"
|
|
81
81
|
},
|