@vcp-dev/site-edit-bridge 0.3.14 → 0.3.15

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.
@@ -1 +1 @@
1
- function de(e){if(!Ve(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let u=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,u),u};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function Ve(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}var U=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!M(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?M(t.payload)&&typeof t.payload.id=="string":t.type==="event"?M(t.payload)&&M(t.payload.event):!1}static isRequestPayload(t,n={}){if(!M(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return We(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}};function M(e){return typeof e=="object"&&e!==null}function We(e){return M(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&M(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&M(e.params)}var je="vcp:designer:trace",Ue="designer_trace",pe="__VCP_DESIGNER_TRACE__";var $e=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ye(e=globalThis){let t=e;try{if(t.localStorage?.getItem(je)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Ue)==="1"}catch{return!1}}function K(e,t={},n=globalThis){if(!Ye(n))return;let r={type:e,timestamp:Date.now(),payload:Ge(t)},o=n,s=o[pe]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[pe]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Ge(e){return L(e,0)}function L(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>L(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if($e.test(r)){n[r]="[redacted]";continue}n[r]=L(o,t+1)}return n}var H=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}getDocument(t){return this.request("get-document",{routeId:t})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}execute(t){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=we(o,t,n);return K("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:fe(n.request,"kind"),documentVersion:fe(n.request,"documentVersion")}),new Promise((i,u)=>{this.pending.set(o,{kind:t,resolve:d=>i(d),reject:u}),r.send(U.stringifyMessage(s))})}handleMessage(t){let n=U.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.pending.delete(n.payload.id),n.type==="error"){K("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}K("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Xe(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:de(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}};function fe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Xe(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function me(e){return new ee(e)}var ee=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,ze(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Je(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return He(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}async execute(t){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId){this.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function He(e){return e.version===0&&e.rootKeys.length===0}function we(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t}}}}function ze(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Je(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var he="vcp-window-message";function Qe(e){return{source:he,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ze(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===he&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var ye="site-edit",ge="frame-runtime";function $(e,t={}){return Qe({namespace:ye,channel:ge,sessionKey:t.sessionKey,body:e})}function be(e){return!Ze(e)||e.namespace!==ye||e.channel!==ge?!1:typeof e.body?.type=="string"}var re="vcp-site-edit:route-ready",Le=1e3,et="data-vcp-ui-component",xe="data-vcp-theme-preview",Ee="::repeat-item#",w="components/ui",tt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),nt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function rt(e,t=""){let n=mt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function ot(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function st(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function pn(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:a=>n.currentEntriesByKey.get(a)??null});let r=t.create_client??(a=>new H({url:a})),o=t.schedule_after_navigation??pt,s=st(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},u=a=>{n.currentDocument=a,n.currentEntriesByKey=new Map((a?.entries??[]).map(R=>[R.key,R]))},d=async(a,R)=>{let E=e.__VCP_SITE_EDIT__;if(!E)return null;let b=await E.getDocument(a);return R!==n.routeSequence||a!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||u(b.data),b.data},y=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,u(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},m=async()=>{let a=rt(e.location.pathname,t.basePath||"");if(a===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),y();let E=r(s);try{if(await E.connect(),R!==n.routeSequence){E.disconnect();return}e.__VCP_SITE_EDIT__=me({routeId:a,client:E,initialDocument:it(a)}),n.activeClient=E,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===a&&d(a,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=a;let b=await d(a,R);ot(e,{documentVersion:b?.version??0,routeId:a,versions:t.runtime_versions}),ft(e,{routeId:a,version:b?.version??0})}catch(b){throw E.disconnect(),b}},v=()=>{i(),n.retryTimer=e.setTimeout(()=>{m().catch(()=>v())},Le)},_=()=>{o(()=>{m().catch(()=>v())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:m,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),y(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=dt(e,_),t.defer_initial_sync){_();return}await m()}function it(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,u=null,d=new Map,y=()=>{n?.(),n=null},m=()=>{r?.(),r=null,o?.(),o=null},v=(I,l,c)=>{let T=s?.sessionKey!==I||s?.sourceWindow!==l||s?.targetOrigin!==c;s={sessionKey:I,sourceWindow:l,targetOrigin:c},T&&(u=null)},_=()=>{for(let I of d.values())I();d.clear()},a=I=>{i=I.routeId==="/"?null:I;let l=`${I.routeId}:${I.version}`;u!==l&&(o?.(),o=null,E({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(u=l))},R=()=>{i&&a(i)},E=I=>{s&&s.sourceWindow.postMessage($({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},b=(I,l,c,T)=>{let S=Q(e.document,l.clientX,l.clientY),x=S?D(S,c==="full"?A(e.document,S,t.getCurrentDocument?.()??null):ve(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,c):null;T&&x&&(I==="pointer-click"||I==="pointer-double-click")&&(T.preventDefault(),T.stopPropagation(),typeof T.stopImmediatePropagation=="function"&&T.stopImmediatePropagation()),E({kind:I,payload:{clientX:l.clientX,clientY:l.clientY,buttons:Number(l.buttons??0),hit:x}})},N=(I,l,c)=>{m(),s={sessionKey:I,sourceWindow:l,targetOrigin:c};let T=Jt(e.document),S=null,x=null,f=()=>{x=null;let p=S;S=null,p&&b("pointer-move",p,"summary")},k=p=>{S={clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},x===null&&(x=Ce(e,f))},F=p=>{b("pointer-down",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},B=p=>{b("pointer-up",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"summary",p)},P=p=>{b("pointer-cancel",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"summary",p)},q=p=>{b("pointer-click",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},W=p=>{b("pointer-double-click",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},j=()=>{E({kind:"scroll",payload:{metrics:J(e)}})};e.document.addEventListener("pointerdown",F,!0),e.document.addEventListener("pointermove",k,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",B,!0),e.document.addEventListener("pointercancel",P,!0),e.document.addEventListener("click",q,!0),e.document.addEventListener("dblclick",W,!0),e.addEventListener("scroll",j,{passive:!0}),r=()=>{x!==null&&(Ne(e,x),x=null),S=null,T(),e.document.removeEventListener("pointerdown",F,!0),e.document.removeEventListener("pointermove",k,!0),e.document.removeEventListener("pointerup",B,!0),e.document.removeEventListener("pointercancel",P,!0),e.document.removeEventListener("click",q,!0),e.document.removeEventListener("dblclick",W,!0),e.removeEventListener("scroll",j)}},ae=I=>{let l=I.detail;l?.routeId&&a(l)},le=I=>{let l=I.data;if(!be(l)||l.body.type!=="request"||l.body.kind!=="apply-node-patch"&&l.body.kind!=="get-hit-by-ref"&&l.body.kind!=="get-path-by-ref"&&l.body.kind!=="get-scroll-metrics"&&l.body.kind!=="scroll-to"&&l.body.kind!=="scroll-by"&&l.body.kind!=="set-interaction-mode"&&l.body.kind!=="set-theme-override"&&l.body.kind!=="clear-theme-override"&&l.body.kind!=="get-theme-variables"&&l.body.kind!=="compute-drop-target-at-point"&&l.body.kind!=="observe-node-bounds"&&l.body.kind!=="clear-node-bounds-observer"&&l.body.kind!=="start-text-edit-at-point"&&l.body.kind!=="hit-test-at-point"&&!Ie(l.body))return;let c=l.body,T=typeof l.sessionKey=="string"?l.sessionKey:null,S=I.source,x=I.origin;if(!T||!x||!S||typeof S.postMessage!="function"||s&&(s.sessionKey!==T||s.sourceWindow!==S||s.targetOrigin!==x))return;v(T,S,x),R();let f=k=>{let F=typeof c.id=="string"?c.id:"unknown";S.postMessage($({id:F,...k},{sessionKey:T}),x)};try{if(Ie(c)){ct({message:c,sendEvent:h=>{S.postMessage($({type:"event",...h},{sessionKey:T}),x)},sendResponse:f,subscriptions:d,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(c.kind==="apply-node-patch"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for patch target"});return}let g=c.payload.preview,C=g?qt(g.sessionId,c.payload.ref):null;if(C&&g){let X=Y.get(C)??-1;if(g.revision<X){f({type:"response",ok:!0,result:{applied:!1,appliedRevision:g.revision,stale:!0,latestRevision:X}});return}if(g.revision===X){f({type:"response",ok:!0,result:{applied:!1,appliedRevision:g.revision,duplicate:!0,latestRevision:X}});return}}if(Ft(h,c.payload.patch),C&&g&&Kt(C,g.revision),g?.responseDetail==="none"){f({type:"response",ok:!0,result:{applied:!0,appliedRevision:g.revision}});return}f({type:"response",ok:!0,result:D(h,A(e.document,h,t.getCurrentDocument?.()??null),t.getDocumentEntry,g?.responseDetail??"full")});return}if(c.kind==="get-hit-by-ref"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for hit target"});return}f({type:"response",ok:!0,result:D(h,A(e.document,h,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(c.kind==="get-path-by-ref"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for path target"});return}let g=[],C=h;for(;C;)C.getAttribute("data-vcp-edit-key")&&g.push(D(C,A(e.document,C,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),C=C.parentElement;f({type:"response",ok:!0,result:g.reverse()});return}if(c.kind==="get-scroll-metrics"){f({type:"response",ok:!0,result:J(e)});return}if(c.kind==="scroll-to"){let h=Number(c.payload.x),g=Number(c.payload.y);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:h,top:g}),f({type:"response",ok:!0,result:J(e)});return}if(c.kind==="scroll-by"){let h=Number(c.payload.deltaX),g=Number(c.payload.deltaY);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:h,top:g}),f({type:"response",ok:!0,result:{...J(e),scrolled:!0}});return}if(c.kind==="set-interaction-mode"){c.payload.enabled?N(T,S,x):s?.sourceWindow===S&&s.targetOrigin===x&&s.sessionKey===T&&m(),f({type:"response",ok:!0,result:{interactionEnabled:c.payload.enabled}});return}if(c.kind==="set-theme-override"){Bt(e.document,c.payload),f({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(c.kind==="clear-theme-override"){Vt(e.document),f({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(c.kind==="get-theme-variables"){f({type:"response",ok:!0,result:Wt(e.document,c.payload.names)});return}if(c.kind==="compute-drop-target-at-point"){let h=Number(c.payload?.x),g=Number(c.payload?.y);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid drop target point"});return}f({type:"response",ok:!0,result:Dt(e,h,g,c.payload.dragKind,c.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(c.kind==="observe-node-bounds"){let h=c.payload.ref;if(!h){f({type:"response",ok:!1,error:"Missing bounds observer target"});return}let g=V(e.document,h,t.getCurrentDocument?.()??null);if(!g){f({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=Nt(e,g,h,t.getDocumentEntry,C=>E({kind:"node-bounds-change",payload:{hit:C}})),f({type:"response",ok:!0,result:{observing:!0}}),E({kind:"node-bounds-change",payload:{hit:D(g,h,t.getDocumentEntry,"summary")}});return}if(c.kind==="clear-node-bounds-observer"){o?.(),o=null,f({type:"response",ok:!0,result:{cleared:!0}});return}if(c.kind!=="hit-test-at-point"&&c.kind!=="start-text-edit-at-point")return;let k=Number(c.payload?.x),F=Number(c.payload?.y);if(!Number.isFinite(k)||!Number.isFinite(F)){f({type:"response",ok:!1,error:"Invalid text edit point"});return}let B=c.kind==="hit-test-at-point"?Q(e.document,k,F):yt(e.document,k,F,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!B){f({type:"response",ok:!1,error:c.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let P=c.kind==="start-text-edit-at-point"?B:null,q=c.kind==="hit-test-at-point"?B:P.element,W=c.payload.detailLevel??"full",j=W==="full"?A(e.document,q,t.getCurrentDocument?.()??null):ve(e.document,q,t.getCurrentDocument?.()??null),p=P&&typeof P.textSegmentIndex=="number"?{...j,textSegmentIndex:P.textSegmentIndex}:j,Be=D(q,p,t.getDocumentEntry,W);if(c.kind==="hit-test-at-point"){f({type:"response",ok:!0,result:Be});return}y(),n=Yt(e,q,p,h=>{S.postMessage($({type:"event",...h},{sessionKey:T}),x)},P?{textNode:P.textNode}:void 0),f({type:"response",ok:!0,result:{ref:p}})}catch(k){f({type:"response",ok:!1,error:k instanceof Error?k.message:"Failed to start text edit"})}};return e.addEventListener("message",le),e.addEventListener(re,ae),()=>{y(),m(),s=null,_(),e.removeEventListener("message",le),e.removeEventListener(re,ae)}}function Ie(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function ct({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await i.getDocument(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}n({type:"response",ok:!0,result:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:at(u,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let d=i.subscribe(y=>{t({kind:"bridge-event",payload:{event:y,subscriptionId:u}})});r.set(u,d),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){n({type:"response",ok:!1,error:u instanceof Error?u.message:"Site edit bridge request failed"})}}function at(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=V(n,{key:t},r),s=o?lt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function lt(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 dt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let u=n.apply(this,i);return t(),u},e.history.replaceState=function(...i){let u=r.apply(this,i);return t(),u},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function pt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ce(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function Ne(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function ft(e,t){e.dispatchEvent(new CustomEvent(re,{detail:t}))}function mt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ie(e){return tt.has(De(e))}function ht(e){return nt.has(De(e))}function ke(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:ht(e.tagName),canInsertChild:ie(e.tagName),canMove:!1,canRemove:!1}}function De(e){return e?.trim().toLowerCase()??""}function yt(e,t,n,r,o){let s=Q(e,t,n),i=Oe(s);if(!i)return null;let u=i.getAttribute("data-vcp-edit-key")??"",d=A(e,i,r),y=o?.(d.key)??o?.(u);if(!ke({operationSummary:y?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((y?.childKeys.length??0)===0)return{element:i};let v=gt(e,t,n,i);if(!v)return null;let _=Et(i,v);return _===null?null:{element:i,textNode:v,textSegmentIndex:_}}function gt(e,t,n,r){let o=bt(e,t,n);return!o||o.parentElement!==r?null:o}function bt(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(oe(s))return s;let u=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return oe(u)?u:null}function Et(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!oe(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function oe(e){return e?.nodeType===3}function Q(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=Oe(o);if(s)return s}return null}function Oe(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(ue(t))return n??t;!It(r)&&!n&&(n=t)}t=t.parentElement}return n}function ue(e){return e.getAttribute(et)!==null}function It(e){return vt(e.split("::")[0]??"")}function vt(e){if(!e)return!1;let t=St(e);return t===w||t.startsWith(`${w}/`)||t.includes(`/${w}/`)||t.endsWith(`/${w}`)}function St(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 A(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=Pe(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ke(r)}"]`)));if(o.length<=1)return{key:Se(n,r,0)};let s=o.indexOf(t);return s>=0?{key:Se(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function ve(e,t,n){return A(e,t,n)}function V(e,t,n){let r=ce(t.key)??t.key,o=Pe(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ke(r)}"]`)));if(o.length===0)return null;let s=_t(n,t.key);return s!==null&&s>=0&&s<o.length?o[s]??null:typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?o[t.instanceIndex]??null:o[0]??null}function Se(e,t,n){return Ae(e,t)[n]?.key??t}function _t(e,t){let n=ce(t);if(!n)return null;let o=Ae(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function Ae(e,t){return(e?.entries??[]).filter(n=>(ce(n.key)??n.key)===t)}var Rt=2,Tt=4;function Pe(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&Tt)!==0?-1:(r&Rt)!==0?1:0})}function ce(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Ee);if(n<0)break;let r=Number(t.slice(n+Ee.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function xt(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function Ct(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>se(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function D(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),u=Z(e),d=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([a,R])=>[a,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(a=>[a,e.getAttribute(a)??""]))}:{},y=ke({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),m=ue(e),v=!!(s&&/^[A-Z]/.test(s.tag)),_=!s||!v;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:v?"component-call":"jsx"}:{},...v&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...d,runtimeFlags:{selectable:!0,movable:y.canMove,removable:y.canRemove,textEditable:y.canUpdateText,container:m?!1:(s?.childKeys.length??0)>0||y.canInsertChild||_&&ie(i)},layout:u,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:Ct(e),spacing:xt(e)}}function Nt(e,t,n,r,o){let s=se(t.getBoundingClientRect()),i=null,u=()=>{i===null&&(i=Ce(e,d))},d=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let a=se(t.getBoundingClientRect());kt(s,a)&&(s=a,o(D(t,n,r,"summary")))},y=e.ResizeObserver,m=typeof y=="function"?new y(u):null;m?.observe(t);let v=e.MutationObserver,_=typeof v=="function"?new v(u):null;return _?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",u,!0),()=>{i!==null&&(Ne(e,i),i=null),m?.disconnect(),_?.disconnect(),e.document.removeEventListener("load",u,!0)}}function se(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function kt(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 Dt(e,t,n,r,o,s,i){let u=e.document,d=Q(u,t,n);if(!d)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let y=o?V(u,o,s):null;if(y&&Te(d,y))return z(u,d,"self-or-descendant",s,i);let m=null,v=!1,_=d,a=d.parentElement;for(;a;){if(a.getAttribute("data-vcp-edit-key")){if(y&&Te(a,y))return z(u,d,"self-or-descendant",s,i);let E=_e(a,r,i);if(E==="accept"){m={child:_,targetParent:a};break}E==="blocked"&&(v=!0),_=a}a=a.parentElement}let R=_e(d,r,i);if(R==="accept"){if(m){let E=Re(m.child,m.targetParent,t,n,"edge");if(E)return te(u,m.child,m.targetParent,E,s,i)}return te(u,d,d,Ot(d,t,n),s,i)}if(m){let E=Re(m.child,m.targetParent,t,n,"nearest");return te(u,m.child,m.targetParent,E??"after",s,i)}return R==="blocked"||v?z(u,d,"operation-boundary-blocked",s,i):z(u,d,"no-accepting-parent",s,i)}function z(e,t,n,r,o){return{anchorHit:D(t,A(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function te(e,t,n,r,o,s){let i=D(t,A(e,t,o),s,"summary"),u=D(n,A(e,n,o),s,"summary"),d=Z(n).indicatorOrientation,y=r==="append"||r==="prepend"?At(n.getBoundingClientRect(),d,r):Pt(t.getBoundingClientRect(),d,r);return{anchorHit:i,targetParentHit:u,relation:r,indicatorOrientation:d,indicatorBounds:y}}function _e(e,t,n){if(ue(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return ie(s)?"accept":"not-container"}function Re(e,t,n,r,o){let s=Z(t).indicatorOrientation,i=e.getBoundingClientRect(),u=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&u>=.25&&u<=.75?null:u<.5?"before":"after"}function Ot(e,t,n){let r=Z(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 Z(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function At(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 Pt(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 Te(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function J(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:O(e.scrollX),scrollY:O(e.scrollY),scrollWidth:Math.max(O(t?.scrollWidth),O(n?.scrollWidth),O(e.innerWidth)),scrollHeight:Math.max(O(t?.scrollHeight),O(n?.scrollHeight),O(e.innerHeight)),viewportWidth:O(e.innerWidth),viewportHeight:O(e.innerHeight)}}function Ft(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var Mt=500,Y=new Map;function qt(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Kt(e,t){if(Y.size>=Mt){let n=Y.keys().next().value;n&&Y.delete(n)}Y.set(e,t)}var G=new Set;function Bt(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of G)r.has(o)||n?.removeProperty(o);G.clear();for(let o of r)G.add(o);$t(e,t.stylesheets??[])}function Vt(e){let t=e.documentElement?.style;for(let n of G)t?.removeProperty(n);G.clear();for(let n of qe(e))n.remove()}function Wt(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let u=Fe(o,i);u&&(s[i]=u)}return s}function Fe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Me(e,r,n)}function Me(e,t,n){if(!t)return null;let r=jt(t);if(!r)return t;let o=Fe(e,r.name,n);return o||(r.fallback?Me(e,r.fallback,n)??r.fallback:null)}function jt(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Ut(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function Ut(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 $t(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of qe(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(xe,"true"),i.setAttribute("href",s),o.appendChild(i)}}function qe(e){return Array.from(e.querySelectorAll(`link[${xe}]`))}function Yt(e,t,n,r,o={}){let s=o.textNode?Gt(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,u=i.textContent??"",d=Xt(i),y=!1,m=()=>{e.document.removeEventListener("pointerdown",_,!0),i.removeEventListener("keydown",a),i.removeEventListener("blur",R),i.removeEventListener("input",E),wt(i,d)},v=b=>{if(y)return;y=!0;let N=i.textContent??"";if(m(),b==="cancel"){s?.restore(u),s||(t.textContent=u),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(N),b==="commit"&&N!==u){r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function _(b){let N=b.target;N&&i.contains(N)||v("commit")}function a(b){if(b.key==="Escape"){b.preventDefault(),v("cancel");return}b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),v("commit"))}function R(){v("commit")}function E(){r({kind:"text-edit-input",payload:{ref:n,hit:D(t,n,void 0,"full")}})}return Ht(i),e.document.addEventListener("pointerdown",_,!0),i.addEventListener("keydown",a),i.addEventListener("blur",R),i.addEventListener("input",E),Qt(i),Zt(i,e.document),m}function Gt(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 Xt(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 Ht(e){zt(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 wt(e,t){ne(e,"contenteditable",t.contentEditable),ne(e,"spellcheck",t.spellcheck),ne(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function zt(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 ne(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Jt(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 Qt(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Zt(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ke(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function O(e){let t=Number(e);return Number.isFinite(t)?t:0}export{re as VCP_SITE_EDIT_ROUTE_READY_EVENT,rt as resolveSiteEditRouteId,st as resolveSiteEditWebSocketUrl,pn as startSiteEditAutoBootstrap,ut as startSiteEditFrameRuntime};
1
+ function de(e){if(!Ve(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let u=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,u),u};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function Ve(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}var U=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!M(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?M(t.payload)&&typeof t.payload.id=="string":t.type==="event"?M(t.payload)&&M(t.payload.event):!1}static isRequestPayload(t,n={}){if(!M(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return je(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}};function M(e){return typeof e=="object"&&e!==null}function je(e){return M(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&M(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&M(e.params)}var We="vcp:designer:trace",Ue="designer_trace",pe="__VCP_DESIGNER_TRACE__";var $e=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ye(e=globalThis){let t=e;try{if(t.localStorage?.getItem(We)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Ue)==="1"}catch{return!1}}function K(e,t={},n=globalThis){if(!Ye(n))return;let r={type:e,timestamp:Date.now(),payload:Ge(t)},o=n,s=o[pe]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[pe]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Ge(e){return ee(e,0)}function ee(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>ee(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if($e.test(r)){n[r]="[redacted]";continue}n[r]=ee(o,t+1)}return n}var H=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}getDocument(t){return this.request("get-document",{routeId:t})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}execute(t){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=we(o,t,n);return K("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:fe(n.request,"kind"),documentVersion:fe(n.request,"documentVersion")}),new Promise((i,u)=>{this.pending.set(o,{kind:t,resolve:d=>i(d),reject:u}),r.send(U.stringifyMessage(s))})}handleMessage(t){let n=U.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.pending.delete(n.payload.id),n.type==="error"){K("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}K("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Xe(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:de(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}};function fe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Xe(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function me(e){return new te(e)}var te=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,ze(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Je(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return He(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}async execute(t){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId){this.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}K("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function He(e){return e.version===0&&e.rootKeys.length===0}function we(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t}}}}function ze(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Je(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var he="vcp-window-message";function Qe(e){return{source:he,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ze(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===he&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var ye="site-edit",ge="frame-runtime";function $(e,t={}){return Qe({namespace:ye,channel:ge,sessionKey:t.sessionKey,body:e})}function be(e){return!Ze(e)||e.namespace!==ye||e.channel!==ge?!1:typeof e.body?.type=="string"}var oe="vcp-site-edit:route-ready",Le=1e3,et="data-vcp-ui-component",Te="data-vcp-theme-preview",Ee="::repeat-item#",w="components/ui",tt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),nt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function rt(e,t=""){let n=mt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function ot(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function st(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function pn(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:a=>n.currentEntriesByKey.get(a)??null});let r=t.create_client??(a=>new H({url:a})),o=t.schedule_after_navigation??pt,s=st(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},u=a=>{n.currentDocument=a,n.currentEntriesByKey=new Map((a?.entries??[]).map(R=>[R.key,R]))},d=async(a,R)=>{let E=e.__VCP_SITE_EDIT__;if(!E)return null;let b=await E.getDocument(a);return R!==n.routeSequence||a!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||u(b.data),b.data},y=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,u(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},m=async()=>{let a=rt(e.location.pathname,t.basePath||"");if(a===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),y();let E=r(s);try{if(await E.connect(),R!==n.routeSequence){E.disconnect();return}e.__VCP_SITE_EDIT__=me({routeId:a,client:E,initialDocument:it(a)}),n.activeClient=E,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===a&&d(a,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=a;let b=await d(a,R);ot(e,{documentVersion:b?.version??0,routeId:a,versions:t.runtime_versions}),ft(e,{routeId:a,version:b?.version??0})}catch(b){throw E.disconnect(),b}},v=()=>{i(),n.retryTimer=e.setTimeout(()=>{m().catch(()=>v())},Le)},_=()=>{o(()=>{m().catch(()=>v())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:m,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),y(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=dt(e,_),t.defer_initial_sync){_();return}await m()}function it(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,u=null,d=new Map,y=()=>{n?.(),n=null},m=()=>{r?.(),r=null,o?.(),o=null},v=(I,l,c)=>{let x=s?.sessionKey!==I||s?.sourceWindow!==l||s?.targetOrigin!==c;s={sessionKey:I,sourceWindow:l,targetOrigin:c},x&&(u=null)},_=()=>{for(let I of d.values())I();d.clear()},a=I=>{i=I.routeId==="/"?null:I;let l=`${I.routeId}:${I.version}`;u!==l&&(o?.(),o=null,E({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(u=l))},R=()=>{i&&a(i)},E=I=>{s&&s.sourceWindow.postMessage($({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},b=(I,l,c,x)=>{let S=Q(e.document,l.clientX,l.clientY),T=S?D(S,c==="full"?P(e.document,S,t.getCurrentDocument?.()??null):ve(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,c):null;x&&T&&(I==="pointer-click"||I==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),E({kind:I,payload:{clientX:l.clientX,clientY:l.clientY,buttons:Number(l.buttons??0),hit:T}})},N=(I,l,c)=>{m(),s={sessionKey:I,sourceWindow:l,targetOrigin:c};let x=Jt(e.document),S=null,T=null,f=()=>{T=null;let p=S;S=null,p&&b("pointer-move",p,"summary")},k=p=>{S={clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},T===null&&(T=Ce(e,f))},F=p=>{b("pointer-down",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},B=p=>{b("pointer-up",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"summary",p)},A=p=>{b("pointer-cancel",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"summary",p)},q=p=>{b("pointer-click",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},j=p=>{b("pointer-double-click",{clientX:Number(p.clientX),clientY:Number(p.clientY),buttons:Number(p.buttons)},"full",p)},W=()=>{E({kind:"scroll",payload:{metrics:J(e)}})};e.document.addEventListener("pointerdown",F,!0),e.document.addEventListener("pointermove",k,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",B,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",q,!0),e.document.addEventListener("dblclick",j,!0),e.addEventListener("scroll",W,{passive:!0}),r=()=>{T!==null&&(Ne(e,T),T=null),S=null,x(),e.document.removeEventListener("pointerdown",F,!0),e.document.removeEventListener("pointermove",k,!0),e.document.removeEventListener("pointerup",B,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",q,!0),e.document.removeEventListener("dblclick",j,!0),e.removeEventListener("scroll",W)}},ae=I=>{let l=I.detail;l?.routeId&&a(l)},le=I=>{let l=I.data;if(!be(l)||l.body.type!=="request"||l.body.kind!=="apply-node-patch"&&l.body.kind!=="get-hit-by-ref"&&l.body.kind!=="get-path-by-ref"&&l.body.kind!=="get-scroll-metrics"&&l.body.kind!=="scroll-to"&&l.body.kind!=="scroll-by"&&l.body.kind!=="set-interaction-mode"&&l.body.kind!=="set-theme-override"&&l.body.kind!=="clear-theme-override"&&l.body.kind!=="get-theme-variables"&&l.body.kind!=="compute-drop-target-at-point"&&l.body.kind!=="observe-node-bounds"&&l.body.kind!=="clear-node-bounds-observer"&&l.body.kind!=="start-text-edit-at-point"&&l.body.kind!=="hit-test-at-point"&&!Ie(l.body))return;let c=l.body,x=typeof l.sessionKey=="string"?l.sessionKey:null,S=I.source,T=I.origin;if(!x||!T||!S||typeof S.postMessage!="function"||s&&(s.sessionKey!==x||s.sourceWindow!==S||s.targetOrigin!==T))return;v(x,S,T),R();let f=k=>{let F=typeof c.id=="string"?c.id:"unknown";S.postMessage($({id:F,...k},{sessionKey:x}),T)};try{if(Ie(c)){ct({message:c,sendEvent:h=>{S.postMessage($({type:"event",...h},{sessionKey:x}),T)},sendResponse:f,subscriptions:d,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(c.kind==="apply-node-patch"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for patch target"});return}let g=c.payload.preview,C=g?qt(g.sessionId,c.payload.ref):null;if(C&&g){let X=Y.get(C)??-1;if(g.revision<X){f({type:"response",ok:!0,result:{applied:!1,appliedRevision:g.revision,stale:!0,latestRevision:X}});return}if(g.revision===X){f({type:"response",ok:!0,result:{applied:!1,appliedRevision:g.revision,duplicate:!0,latestRevision:X}});return}}if(Ft(h,c.payload.patch),C&&g&&Kt(C,g.revision),g?.responseDetail==="none"){f({type:"response",ok:!0,result:{applied:!0,appliedRevision:g.revision}});return}f({type:"response",ok:!0,result:D(h,P(e.document,h,t.getCurrentDocument?.()??null),t.getDocumentEntry,g?.responseDetail??"full")});return}if(c.kind==="get-hit-by-ref"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for hit target"});return}f({type:"response",ok:!0,result:D(h,P(e.document,h,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(c.kind==="get-path-by-ref"){let h=V(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!h){f({type:"response",ok:!1,error:"No editable element found for path target"});return}let g=[],C=h;for(;C;)C.getAttribute("data-vcp-edit-key")&&g.push(D(C,P(e.document,C,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),C=C.parentElement;f({type:"response",ok:!0,result:g.reverse()});return}if(c.kind==="get-scroll-metrics"){f({type:"response",ok:!0,result:J(e)});return}if(c.kind==="scroll-to"){let h=Number(c.payload.x),g=Number(c.payload.y);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:h,top:g}),f({type:"response",ok:!0,result:J(e)});return}if(c.kind==="scroll-by"){let h=Number(c.payload.deltaX),g=Number(c.payload.deltaY);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:h,top:g}),f({type:"response",ok:!0,result:{...J(e),scrolled:!0}});return}if(c.kind==="set-interaction-mode"){c.payload.enabled?N(x,S,T):s?.sourceWindow===S&&s.targetOrigin===T&&s.sessionKey===x&&m(),f({type:"response",ok:!0,result:{interactionEnabled:c.payload.enabled}});return}if(c.kind==="set-theme-override"){Bt(e.document,c.payload),f({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(c.kind==="clear-theme-override"){Vt(e.document),f({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(c.kind==="get-theme-variables"){f({type:"response",ok:!0,result:jt(e.document,c.payload.names)});return}if(c.kind==="compute-drop-target-at-point"){let h=Number(c.payload?.x),g=Number(c.payload?.y);if(!Number.isFinite(h)||!Number.isFinite(g)){f({type:"response",ok:!1,error:"Invalid drop target point"});return}f({type:"response",ok:!0,result:Dt(e,h,g,c.payload.dragKind,c.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(c.kind==="observe-node-bounds"){let h=c.payload.ref;if(!h){f({type:"response",ok:!1,error:"Missing bounds observer target"});return}let g=V(e.document,h,t.getCurrentDocument?.()??null);if(!g){f({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=Nt(e,g,h,t.getDocumentEntry,C=>E({kind:"node-bounds-change",payload:{hit:C}})),f({type:"response",ok:!0,result:{observing:!0}}),E({kind:"node-bounds-change",payload:{hit:D(g,h,t.getDocumentEntry,"summary")}});return}if(c.kind==="clear-node-bounds-observer"){o?.(),o=null,f({type:"response",ok:!0,result:{cleared:!0}});return}if(c.kind!=="hit-test-at-point"&&c.kind!=="start-text-edit-at-point")return;let k=Number(c.payload?.x),F=Number(c.payload?.y);if(!Number.isFinite(k)||!Number.isFinite(F)){f({type:"response",ok:!1,error:"Invalid text edit point"});return}let B=c.kind==="hit-test-at-point"?Q(e.document,k,F):yt(e.document,k,F,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!B){f({type:"response",ok:!1,error:c.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=c.kind==="start-text-edit-at-point"?B:null,q=c.kind==="hit-test-at-point"?B:A.element,j=c.payload.detailLevel??"full",W=j==="full"?P(e.document,q,t.getCurrentDocument?.()??null):ve(e.document,q,t.getCurrentDocument?.()??null),p=A&&typeof A.textSegmentIndex=="number"?{...W,textSegmentIndex:A.textSegmentIndex}:W,Be=D(q,p,t.getDocumentEntry,j);if(c.kind==="hit-test-at-point"){f({type:"response",ok:!0,result:Be});return}y(),n=Yt(e,q,p,h=>{S.postMessage($({type:"event",...h},{sessionKey:x}),T)},A?{textNode:A.textNode}:void 0),f({type:"response",ok:!0,result:{ref:p}})}catch(k){f({type:"response",ok:!1,error:k instanceof Error?k.message:"Failed to start text edit"})}};return e.addEventListener("message",le),e.addEventListener(oe,ae),()=>{y(),m(),s=null,_(),e.removeEventListener("message",le),e.removeEventListener(oe,ae)}}function Ie(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function ct({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await i.getDocument(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}n({type:"response",ok:!0,result:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:at(u,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let d=i.subscribe(y=>{t({kind:"bridge-event",payload:{event:y,subscriptionId:u}})});r.set(u,d),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){n({type:"response",ok:!1,error:u instanceof Error?u.message:"Site edit bridge request failed"})}}function at(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=V(n,{key:t},r),s=o?lt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function lt(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 dt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let u=n.apply(this,i);return t(),u},e.history.replaceState=function(...i){let u=r.apply(this,i);return t(),u},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function pt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ce(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function Ne(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function ft(e,t){e.dispatchEvent(new CustomEvent(oe,{detail:t}))}function mt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ue(e){return tt.has(De(e))}function ht(e){return nt.has(De(e))}function ke(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:ht(e.tagName),canInsertChild:ue(e.tagName),canMove:!1,canRemove:!1}}function De(e){return e?.trim().toLowerCase()??""}function yt(e,t,n,r,o){let s=Q(e,t,n),i=Oe(s);if(!i)return null;let u=i.getAttribute("data-vcp-edit-key")??"",d=P(e,i,r),y=o?.(d.key)??o?.(u);if(!ke({operationSummary:y?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((y?.childKeys.length??0)===0)return{element:i};let v=gt(e,t,n,i);if(!v)return null;let _=Et(i,v);return _===null?null:{element:i,textNode:v,textSegmentIndex:_}}function gt(e,t,n,r){let o=bt(e,t,n);return!o||o.parentElement!==r?null:o}function bt(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(se(s))return s;let u=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return se(u)?u:null}function Et(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!se(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function se(e){return e?.nodeType===3}function Q(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=Oe(o);if(s)return s}return null}function Oe(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(ce(t))return n??t;!It(r)&&!n&&(n=t)}t=t.parentElement}return n}function ce(e){return e.getAttribute(et)!==null}function It(e){return vt(e.split("::")[0]??"")}function vt(e){if(!e)return!1;let t=St(e);return t===w||t.startsWith(`${w}/`)||t.includes(`/${w}/`)||t.endsWith(`/${w}`)}function St(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 P(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=Ae(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ke(r)}"]`)));if(o.length<=1)return{key:Se(n,r,0)};let s=o.indexOf(t);return s>=0?{key:Se(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function ve(e,t,n){return P(e,t,n)}function V(e,t,n){let r=Z(t.key)??t.key,o=Ae(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ke(r)}"]`)));if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(Z(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let u=_t(n,t.key);return u!==null&&u>=0&&u<o.length?o[u]??null:s!==null?o[s]??null:o[0]??null}function Se(e,t,n){return Pe(e,t)[n]?.key??t}function _t(e,t){let n=Z(t);if(!n)return null;let o=Pe(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function Pe(e,t){return(e?.entries??[]).filter(n=>(Z(n.key)??n.key)===t)}var Rt=2,xt=4;function Ae(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&xt)!==0?-1:(r&Rt)!==0?1:0})}function Z(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Ee);if(n<0)break;let r=Number(t.slice(n+Ee.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Tt(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function Ct(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>ie(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function D(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),u=L(e),d=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([a,R])=>[a,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(a=>[a,e.getAttribute(a)??""]))}:{},y=ke({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),m=ce(e),v=!!(s&&/^[A-Z]/.test(s.tag)),_=!s||!v;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:v?"component-call":"jsx"}:{},...v&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...d,runtimeFlags:{selectable:!0,movable:y.canMove,removable:y.canRemove,textEditable:y.canUpdateText,container:m?!1:(s?.childKeys.length??0)>0||y.canInsertChild||_&&ue(i)},layout:u,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:Ct(e),spacing:Tt(e)}}function Nt(e,t,n,r,o){let s=ie(t.getBoundingClientRect()),i=null,u=()=>{i===null&&(i=Ce(e,d))},d=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let a=ie(t.getBoundingClientRect());kt(s,a)&&(s=a,o(D(t,n,r,"summary")))},y=e.ResizeObserver,m=typeof y=="function"?new y(u):null;m?.observe(t);let v=e.MutationObserver,_=typeof v=="function"?new v(u):null;return _?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",u,!0),()=>{i!==null&&(Ne(e,i),i=null),m?.disconnect(),_?.disconnect(),e.document.removeEventListener("load",u,!0)}}function ie(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function kt(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 Dt(e,t,n,r,o,s,i){let u=e.document,d=Q(u,t,n);if(!d)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let y=o?V(u,o,s):null;if(y&&xe(d,y))return z(u,d,"self-or-descendant",s,i);let m=null,v=!1,_=d,a=d.parentElement;for(;a;){if(a.getAttribute("data-vcp-edit-key")){if(y&&xe(a,y))return z(u,d,"self-or-descendant",s,i);let E=_e(a,r,i);if(E==="accept"){m={child:_,targetParent:a};break}E==="blocked"&&(v=!0),_=a}a=a.parentElement}let R=_e(d,r,i);if(R==="accept"){if(m){let E=Re(m.child,m.targetParent,t,n,"edge");if(E)return ne(u,m.child,m.targetParent,E,s,i)}return ne(u,d,d,Ot(d,t,n),s,i)}if(m){let E=Re(m.child,m.targetParent,t,n,"nearest");return ne(u,m.child,m.targetParent,E??"after",s,i)}return R==="blocked"||v?z(u,d,"operation-boundary-blocked",s,i):z(u,d,"no-accepting-parent",s,i)}function z(e,t,n,r,o){return{anchorHit:D(t,P(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function ne(e,t,n,r,o,s){let i=D(t,P(e,t,o),s,"summary"),u=D(n,P(e,n,o),s,"summary"),d=L(n).indicatorOrientation,y=r==="append"||r==="prepend"?Pt(n.getBoundingClientRect(),d,r):At(t.getBoundingClientRect(),d,r);return{anchorHit:i,targetParentHit:u,relation:r,indicatorOrientation:d,indicatorBounds:y}}function _e(e,t,n){if(ce(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return ue(s)?"accept":"not-container"}function Re(e,t,n,r,o){let s=L(t).indicatorOrientation,i=e.getBoundingClientRect(),u=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&u>=.25&&u<=.75?null:u<.5?"before":"after"}function Ot(e,t,n){let r=L(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 L(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function Pt(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 At(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 xe(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function J(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:O(e.scrollX),scrollY:O(e.scrollY),scrollWidth:Math.max(O(t?.scrollWidth),O(n?.scrollWidth),O(e.innerWidth)),scrollHeight:Math.max(O(t?.scrollHeight),O(n?.scrollHeight),O(e.innerHeight)),viewportWidth:O(e.innerWidth),viewportHeight:O(e.innerHeight)}}function Ft(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var Mt=500,Y=new Map;function qt(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Kt(e,t){if(Y.size>=Mt){let n=Y.keys().next().value;n&&Y.delete(n)}Y.set(e,t)}var G=new Set;function Bt(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of G)r.has(o)||n?.removeProperty(o);G.clear();for(let o of r)G.add(o);$t(e,t.stylesheets??[])}function Vt(e){let t=e.documentElement?.style;for(let n of G)t?.removeProperty(n);G.clear();for(let n of qe(e))n.remove()}function jt(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let u=Fe(o,i);u&&(s[i]=u)}return s}function Fe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Me(e,r,n)}function Me(e,t,n){if(!t)return null;let r=Wt(t);if(!r)return t;let o=Fe(e,r.name,n);return o||(r.fallback?Me(e,r.fallback,n)??r.fallback:null)}function Wt(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Ut(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function Ut(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 $t(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of qe(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(Te,"true"),i.setAttribute("href",s),o.appendChild(i)}}function qe(e){return Array.from(e.querySelectorAll(`link[${Te}]`))}function Yt(e,t,n,r,o={}){let s=o.textNode?Gt(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,u=i.textContent??"",d=Xt(i),y=!1,m=()=>{e.document.removeEventListener("pointerdown",_,!0),i.removeEventListener("keydown",a),i.removeEventListener("blur",R),i.removeEventListener("input",E),wt(i,d)},v=b=>{if(y)return;y=!0;let N=i.textContent??"";if(m(),b==="cancel"){s?.restore(u),s||(t.textContent=u),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(N),b==="commit"&&N!==u){r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function _(b){let N=b.target;N&&i.contains(N)||v("commit")}function a(b){if(b.key==="Escape"){b.preventDefault(),v("cancel");return}b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),v("commit"))}function R(){v("commit")}function E(){r({kind:"text-edit-input",payload:{ref:n,hit:D(t,n,void 0,"full")}})}return Ht(i),e.document.addEventListener("pointerdown",_,!0),i.addEventListener("keydown",a),i.addEventListener("blur",R),i.addEventListener("input",E),Qt(i),Zt(i,e.document),m}function Gt(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 Xt(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 Ht(e){zt(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 wt(e,t){re(e,"contenteditable",t.contentEditable),re(e,"spellcheck",t.spellcheck),re(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function zt(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 re(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Jt(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 Qt(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Zt(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ke(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function O(e){let t=Number(e);return Number.isFinite(t)?t:0}export{oe as VCP_SITE_EDIT_ROUTE_READY_EVENT,rt as resolveSiteEditRouteId,st as resolveSiteEditWebSocketUrl,pn as startSiteEditAutoBootstrap,ut as startSiteEditFrameRuntime};
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- function Ce(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let u=t.get(a);if(typeof u=="number")return u;let d=n.length;return n.push(a),t.set(a,d),d},i=a=>{let u=null;for(let d of Et(a)){let f=`${u??"root"}\0${d}`,g=r.get(f);if(typeof g=="number"){u=g;continue}let y=o.length;o.push({parent:u,token:s(d)}),r.set(f,y),u=y}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,tokens:n,nodes:o,rootKeyNodeIds:e.rootKeys.map(i),entries:e.entries.map(a=>({keyNodeId:i(a.key),tag:a.tag,label:a.label,parentKeyNodeId:a.parentKey?i(a.parentKey):null,childKeyNodeIds:a.childKeys.map(i),operationSummary:a.operationSummary}))}}function Te(e){if(!St(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let a=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,a),a};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function St(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Et(e){if(!e)return[];let t=[],n=0,r=xe(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=xe(e,n+(e.startsWith("::",n)?2:1)),r<0){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r}return t}function xe(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var F=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!B(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?B(t.payload)&&typeof t.payload.id=="string":t.type==="event"?B(t.payload)&&B(t.payload.event):!1}static isRequestPayload(t,n={}){if(!B(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return vt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},X=class{constructor(t){this.options=t,this.messageQueue=new ue,this.eventDispatcher=new ae(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Ce((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"execute":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=F.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(t){try{await this.handleMessage(F.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=It(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(F.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ae=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},ue=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function B(e){return typeof e=="object"&&e!==null}function vt(e){return B(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&B(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&B(e.params)}function It(e){try{return F.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Rt="vcp:designer:trace",_t="designer_trace",Ne="__VCP_DESIGNER_TRACE__";var xt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ct(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Rt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(_t)==="1"}catch{return!1}}function w(e,t={},n=globalThis){if(!Ct(n))return;let r={type:e,timestamp:Date.now(),payload:Tt(t)},o=n,s=o[Ne]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Ne]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Tt(e){return ce(e,0)}function ce(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>ce(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(xt.test(r)){n[r]="[redacted]";continue}n[r]=ce(o,t+1)}return n}var Q=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}getDocument(t){return this.request("get-document",{routeId:t})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}execute(t){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=kt(o,t,n);return w("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Pe(n.request,"kind"),documentVersion:Pe(n.request,"documentVersion")}),new Promise((i,a)=>{this.pending.set(o,{kind:t,resolve:u=>i(u),reject:a}),r.send(F.stringifyMessage(s))})}handleMessage(t){let n=F.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.pending.delete(n.payload.id),n.type==="error"){w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Nt(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Te(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}};function Pe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Nt(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function ke(e){return new le(e)}var le=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Dt(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ot(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return Pt(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}async execute(t){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId){this.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function Pt(e){return e.version===0&&e.rootKeys.length===0}function kt(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t}}}}function Dt(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Ot(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var De="vcp-window-message",$r=1;function At(e){return{source:De,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===De&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Oe="site-edit",Ae="frame-runtime";function U(e,t={}){return At({namespace:Oe,channel:Ae,sessionKey:t.sessionKey,body:e})}function Fe(e){return!Ft(e)||e.namespace!==Oe||e.channel!==Ae?!1:typeof e.body?.type=="string"}var pe="vcp-site-edit:route-ready",Mt=1e3,Bt="data-vcp-ui-component",Ve="data-vcp-theme-preview",Me="::repeat-item#",Z="components/ui",jt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),wt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Kt(e,t=""){let n=Xt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function qt(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function Wt(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function Jr(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=Ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:l=>n.currentEntriesByKey.get(l)??null});let r=t.create_client??(l=>new Q({url:l})),o=t.schedule_after_navigation??zt,s=Wt(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},a=l=>{n.currentDocument=l,n.currentEntriesByKey=new Map((l?.entries??[]).map(R=>[R.key,R]))},u=async(l,R)=>{let E=e.__VCP_SITE_EDIT__;if(!E)return null;let v=await E.getDocument(l);return R!==n.routeSequence||l!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||a(v.data),v.data},d=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,a(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},f=async()=>{let l=Kt(e.location.pathname,t.basePath||"");if(l===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),d();let E=r(s);try{if(await E.connect(),R!==n.routeSequence){E.disconnect();return}e.__VCP_SITE_EDIT__=ke({routeId:l,client:E,initialDocument:Vt(l)}),n.activeClient=E,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===l&&u(l,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=l;let v=await u(l,R);qt(e,{documentVersion:v?.version??0,routeId:l,versions:t.runtime_versions}),Jt(e,{routeId:l,version:v?.version??0})}catch(v){throw E.disconnect(),v}},g=()=>{i(),n.retryTimer=e.setTimeout(()=>{f().catch(()=>g())},Mt)},y=()=>{o(()=>{f().catch(()=>g())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:f,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),d(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=Yt(e,y),t.defer_initial_sync){y();return}await f()}function Vt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,u=new Map,d=()=>{n?.(),n=null},f=()=>{r?.(),r=null,o?.(),o=null},g=(I,p,c)=>{let x=s?.sessionKey!==I||s?.sourceWindow!==p||s?.targetOrigin!==c;s={sessionKey:I,sourceWindow:p,targetOrigin:c},x&&(a=null)},y=()=>{for(let I of u.values())I();u.clear()},l=I=>{i=I.routeId==="/"?null:I;let p=`${I.routeId}:${I.version}`;a!==p&&(o?.(),o=null,E({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(a=p))},R=()=>{i&&l(i)},E=I=>{s&&s.sourceWindow.postMessage(U({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},v=(I,p,c,x)=>{let _=te(e.document,p.clientX,p.clientY),C=_?k(_,c==="full"?O(e.document,_,t.getCurrentDocument?.()??null):je(e.document,_,t.getCurrentDocument?.()??null),t.getDocumentEntry,c):null;x&&C&&(I==="pointer-click"||I==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),E({kind:I,payload:{clientX:p.clientX,clientY:p.clientY,buttons:Number(p.buttons??0),hit:C}})},N=(I,p,c)=>{f(),s={sessionKey:I,sourceWindow:p,targetOrigin:c};let x=An(e.document),_=null,C=null,m=()=>{C=null;let h=_;_=null,h&&v("pointer-move",h,"summary")},P=h=>{_={clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},C===null&&(C=Ue(e,m))},M=h=>{v("pointer-down",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},K=h=>{v("pointer-up",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},A=h=>{v("pointer-cancel",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},j=h=>{v("pointer-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},W=h=>{v("pointer-double-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},V=()=>{E({kind:"scroll",payload:{metrics:ee(e)}})};e.document.addEventListener("pointerdown",M,!0),e.document.addEventListener("pointermove",P,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",K,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",j,!0),e.document.addEventListener("dblclick",W,!0),e.addEventListener("scroll",V,{passive:!0}),r=()=>{C!==null&&(He(e,C),C=null),_=null,x(),e.document.removeEventListener("pointerdown",M,!0),e.document.removeEventListener("pointermove",P,!0),e.document.removeEventListener("pointerup",K,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",j,!0),e.document.removeEventListener("dblclick",W,!0),e.removeEventListener("scroll",V)}},Re=I=>{let p=I.detail;p?.routeId&&l(p)},_e=I=>{let p=I.data;if(!Fe(p)||p.body.type!=="request"||p.body.kind!=="apply-node-patch"&&p.body.kind!=="get-hit-by-ref"&&p.body.kind!=="get-path-by-ref"&&p.body.kind!=="get-scroll-metrics"&&p.body.kind!=="scroll-to"&&p.body.kind!=="scroll-by"&&p.body.kind!=="set-interaction-mode"&&p.body.kind!=="set-theme-override"&&p.body.kind!=="clear-theme-override"&&p.body.kind!=="get-theme-variables"&&p.body.kind!=="compute-drop-target-at-point"&&p.body.kind!=="observe-node-bounds"&&p.body.kind!=="clear-node-bounds-observer"&&p.body.kind!=="start-text-edit-at-point"&&p.body.kind!=="hit-test-at-point"&&!Be(p.body))return;let c=p.body,x=typeof p.sessionKey=="string"?p.sessionKey:null,_=I.source,C=I.origin;if(!x||!C||!_||typeof _.postMessage!="function"||s&&(s.sessionKey!==x||s.sourceWindow!==_||s.targetOrigin!==C))return;g(x,_,C),R();let m=P=>{let M=typeof c.id=="string"?c.id:"unknown";_.postMessage(U({id:M,...P},{sessionKey:x}),C)};try{if(Be(c)){Ht({message:c,sendEvent:b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},sendResponse:m,subscriptions:u,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(c.kind==="apply-node-patch"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for patch target"});return}let S=c.payload.preview,T=S?Sn(S.sessionId,c.payload.ref):null;if(T&&S){let J=H.get(T)??-1;if(S.revision<J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,stale:!0,latestRevision:J}});return}if(S.revision===J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,duplicate:!0,latestRevision:J}});return}}if(yn(b,c.payload.patch),T&&S&&En(T,S.revision),S?.responseDetail==="none"){m({type:"response",ok:!0,result:{applied:!0,appliedRevision:S.revision}});return}m({type:"response",ok:!0,result:k(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,S?.responseDetail??"full")});return}if(c.kind==="get-hit-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for hit target"});return}m({type:"response",ok:!0,result:k(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(c.kind==="get-path-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for path target"});return}let S=[],T=b;for(;T;)T.getAttribute("data-vcp-edit-key")&&S.push(k(T,O(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),T=T.parentElement;m({type:"response",ok:!0,result:S.reverse()});return}if(c.kind==="get-scroll-metrics"){m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-to"){let b=Number(c.payload.x),S=Number(c.payload.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:b,top:S}),m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-by"){let b=Number(c.payload.deltaX),S=Number(c.payload.deltaY);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:b,top:S}),m({type:"response",ok:!0,result:{...ee(e),scrolled:!0}});return}if(c.kind==="set-interaction-mode"){c.payload.enabled?N(x,_,C):s?.sourceWindow===_&&s.targetOrigin===C&&s.sessionKey===x&&f(),m({type:"response",ok:!0,result:{interactionEnabled:c.payload.enabled}});return}if(c.kind==="set-theme-override"){vn(e.document,c.payload),m({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(c.kind==="clear-theme-override"){In(e.document),m({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(c.kind==="get-theme-variables"){m({type:"response",ok:!0,result:Rn(e.document,c.payload.names)});return}if(c.kind==="compute-drop-target-at-point"){let b=Number(c.payload?.x),S=Number(c.payload?.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid drop target point"});return}m({type:"response",ok:!0,result:pn(e,b,S,c.payload.dragKind,c.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(c.kind==="observe-node-bounds"){let b=c.payload.ref;if(!b){m({type:"response",ok:!1,error:"Missing bounds observer target"});return}let S=q(e.document,b,t.getCurrentDocument?.()??null);if(!S){m({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=dn(e,S,b,t.getDocumentEntry,T=>E({kind:"node-bounds-change",payload:{hit:T}})),m({type:"response",ok:!0,result:{observing:!0}}),E({kind:"node-bounds-change",payload:{hit:k(S,b,t.getDocumentEntry,"summary")}});return}if(c.kind==="clear-node-bounds-observer"){o?.(),o=null,m({type:"response",ok:!0,result:{cleared:!0}});return}if(c.kind!=="hit-test-at-point"&&c.kind!=="start-text-edit-at-point")return;let P=Number(c.payload?.x),M=Number(c.payload?.y);if(!Number.isFinite(P)||!Number.isFinite(M)){m({type:"response",ok:!1,error:"Invalid text edit point"});return}let K=c.kind==="hit-test-at-point"?te(e.document,P,M):Zt(e.document,P,M,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!K){m({type:"response",ok:!1,error:c.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=c.kind==="start-text-edit-at-point"?K:null,j=c.kind==="hit-test-at-point"?K:A.element,W=c.payload.detailLevel??"full",V=W==="full"?O(e.document,j,t.getCurrentDocument?.()??null):je(e.document,j,t.getCurrentDocument?.()??null),h=A&&typeof A.textSegmentIndex=="number"?{...V,textSegmentIndex:A.textSegmentIndex}:V,bt=k(j,h,t.getDocumentEntry,W);if(c.kind==="hit-test-at-point"){m({type:"response",ok:!0,result:bt});return}d(),n=Tn(e,j,h,b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},A?{textNode:A.textNode}:void 0),m({type:"response",ok:!0,result:{ref:h}})}catch(P){m({type:"response",ok:!1,error:P instanceof Error?P.message:"Failed to start text edit"})}};return e.addEventListener("message",_e),e.addEventListener(pe,Re),()=>{d(),f(),s=null,y(),e.removeEventListener("message",_e),e.removeEventListener(pe,Re)}}function Be(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function Ht({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await i.getDocument(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}n({type:"response",ok:!0,result:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let a=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:$t(a,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let a=e.payload.subscriptionId;r.get(a)?.();let u=i.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:a}})});r.set(a,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let a=e.payload.subscriptionId;r.get(a)?.(),r.delete(a),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(a){n({type:"response",ok:!1,error:a instanceof Error?a.message:"Site edit bridge request failed"})}}function $t(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=q(n,{key:t},r),s=o?Gt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Gt(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 Yt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let a=n.apply(this,i);return t(),a},e.history.replaceState=function(...i){let a=r.apply(this,i);return t(),a},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function zt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ue(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function He(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Jt(e,t){e.dispatchEvent(new CustomEvent(pe,{detail:t}))}function Xt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ge(e){return jt.has(Ge(e))}function Qt(e){return wt.has(Ge(e))}function $e(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:Qt(e.tagName),canInsertChild:ge(e.tagName),canMove:!1,canRemove:!1}}function Ge(e){return e?.trim().toLowerCase()??""}function Zt(e,t,n,r,o){let s=te(e,t,n),i=Ye(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",u=O(e,i,r),d=o?.(u.key)??o?.(a);if(!$e({operationSummary:d?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((d?.childKeys.length??0)===0)return{element:i};let g=Lt(e,t,n,i);if(!g)return null;let y=tn(i,g);return y===null?null:{element:i,textNode:g,textSegmentIndex:y}}function Lt(e,t,n,r){let o=en(e,t,n);return!o||o.parentElement!==r?null:o}function en(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(he(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return he(a)?a:null}function tn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!he(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function he(e){return e?.nodeType===3}function te(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=Ye(o);if(s)return s}return null}function Ye(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(ye(t))return n??t;!nn(r)&&!n&&(n=t)}t=t.parentElement}return n}function ye(e){return e.getAttribute(Bt)!==null}function nn(e){return rn(e.split("::")[0]??"")}function rn(e){if(!e)return!1;let t=on(e);return t===Z||t.startsWith(`${Z}/`)||t.includes(`/${Z}/`)||t.endsWith(`/${Z}`)}function on(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 O(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length<=1)return{key:we(n,r,0)};let s=o.indexOf(t);return s>=0?{key:we(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function je(e,t,n){return O(e,t,n)}function q(e,t,n){let r=be(t.key)??t.key,o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length===0)return null;let s=sn(n,t.key);return s!==null&&s>=0&&s<o.length?o[s]??null:typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?o[t.instanceIndex]??null:o[0]??null}function we(e,t,n){return ze(e,t)[n]?.key??t}function sn(e,t){let n=be(t);if(!n)return null;let o=ze(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function ze(e,t){return(e?.entries??[]).filter(n=>(be(n.key)??n.key)===t)}var an=2,un=4;function Je(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&un)!==0?-1:(r&an)!==0?1:0})}function be(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Me);if(n<0)break;let r=Number(t.slice(n+Me.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function cn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function ln(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>me(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function k(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=ne(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([l,R])=>[l,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(l=>[l,e.getAttribute(l)??""]))}:{},d=$e({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),f=ye(e),g=!!(s&&/^[A-Z]/.test(s.tag)),y=!s||!g;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:g?"component-call":"jsx"}:{},...g&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...u,runtimeFlags:{selectable:!0,movable:d.canMove,removable:d.canRemove,textEditable:d.canUpdateText,container:f?!1:(s?.childKeys.length??0)>0||d.canInsertChild||y&&ge(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:ln(e),spacing:cn(e)}}function dn(e,t,n,r,o){let s=me(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=Ue(e,u))},u=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let l=me(t.getBoundingClientRect());fn(s,l)&&(s=l,o(k(t,n,r,"summary")))},d=e.ResizeObserver,f=typeof d=="function"?new d(a):null;f?.observe(t);let g=e.MutationObserver,y=typeof g=="function"?new g(a):null;return y?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(He(e,i),i=null),f?.disconnect(),y?.disconnect(),e.document.removeEventListener("load",a,!0)}}function me(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function fn(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 pn(e,t,n,r,o,s,i){let a=e.document,u=te(a,t,n);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let d=o?q(a,o,s):null;if(d&&We(u,d))return L(a,u,"self-or-descendant",s,i);let f=null,g=!1,y=u,l=u.parentElement;for(;l;){if(l.getAttribute("data-vcp-edit-key")){if(d&&We(l,d))return L(a,u,"self-or-descendant",s,i);let E=Ke(l,r,i);if(E==="accept"){f={child:y,targetParent:l};break}E==="blocked"&&(g=!0),y=l}l=l.parentElement}let R=Ke(u,r,i);if(R==="accept"){if(f){let E=qe(f.child,f.targetParent,t,n,"edge");if(E)return de(a,f.child,f.targetParent,E,s,i)}return de(a,u,u,hn(u,t,n),s,i)}if(f){let E=qe(f.child,f.targetParent,t,n,"nearest");return de(a,f.child,f.targetParent,E??"after",s,i)}return R==="blocked"||g?L(a,u,"operation-boundary-blocked",s,i):L(a,u,"no-accepting-parent",s,i)}function L(e,t,n,r,o){return{anchorHit:k(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function de(e,t,n,r,o,s){let i=k(t,O(e,t,o),s,"summary"),a=k(n,O(e,n,o),s,"summary"),u=ne(n).indicatorOrientation,d=r==="append"||r==="prepend"?mn(n.getBoundingClientRect(),u,r):gn(t.getBoundingClientRect(),u,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:u,indicatorBounds:d}}function Ke(e,t,n){if(ye(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return ge(s)?"accept":"not-container"}function qe(e,t,n,r,o){let s=ne(t).indicatorOrientation,i=e.getBoundingClientRect(),a=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function hn(e,t,n){let r=ne(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 ne(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function mn(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 gn(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 We(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ee(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:D(e.scrollX),scrollY:D(e.scrollY),scrollWidth:Math.max(D(t?.scrollWidth),D(n?.scrollWidth),D(e.innerWidth)),scrollHeight:Math.max(D(t?.scrollHeight),D(n?.scrollHeight),D(e.innerHeight)),viewportWidth:D(e.innerWidth),viewportHeight:D(e.innerHeight)}}function yn(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var bn=500,H=new Map;function Sn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function En(e,t){if(H.size>=bn){let n=H.keys().next().value;n&&H.delete(n)}H.set(e,t)}var $=new Set;function vn(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of $)r.has(o)||n?.removeProperty(o);$.clear();for(let o of r)$.add(o);Cn(e,t.stylesheets??[])}function In(e){let t=e.documentElement?.style;for(let n of $)t?.removeProperty(n);$.clear();for(let n of Ze(e))n.remove()}function Rn(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let a=Xe(o,i);a&&(s[i]=a)}return s}function Xe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Qe(e,r,n)}function Qe(e,t,n){if(!t)return null;let r=_n(t);if(!r)return t;let o=Xe(e,r.name,n);return o||(r.fallback?Qe(e,r.fallback,n)??r.fallback:null)}function _n(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=xn(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function xn(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 Cn(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Ze(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(Ve,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Ze(e){return Array.from(e.querySelectorAll(`link[${Ve}]`))}function Tn(e,t,n,r,o={}){let s=o.textNode?Nn(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,a=i.textContent??"",u=Pn(i),d=!1,f=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",l),i.removeEventListener("blur",R),i.removeEventListener("input",E),Dn(i,u)},g=v=>{if(d)return;d=!0;let N=i.textContent??"";if(f(),v==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(N),v==="commit"&&N!==a){r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(v){let N=v.target;N&&i.contains(N)||g("commit")}function l(v){if(v.key==="Escape"){v.preventDefault(),g("cancel");return}v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),g("commit"))}function R(){g("commit")}function E(){r({kind:"text-edit-input",payload:{ref:n,hit:k(t,n,void 0,"full")}})}return kn(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",l),i.addEventListener("blur",R),i.addEventListener("input",E),Fn(i),Mn(i,e.document),f}function Nn(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 Pn(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 kn(e){On(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 Dn(e,t){fe(e,"contenteditable",t.contentEditable),fe(e,"spellcheck",t.spellcheck),fe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function On(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 fe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function An(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 Fn(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Mn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function D(e){let t=Number(e);return Number.isFinite(t)?t:0}import Bn from"node:http";import{randomBytes as jn,timingSafeEqual as wn}from"node:crypto";import Kn from"node:path";import{WebSocket as qn,WebSocketServer as Wn}from"ws";import{createPreviewSiteEditEngineRuntime as Vn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Un,scanNextAppRouterRoutes as Hn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as $n}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as Gn}from"@vcp-dev/contracts";var Yn="127.0.0.1",zn=30218,Jn="/__vcp/site-edit/bridge",Xn=128*1024,et="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function io(e){let t=rt(e),n=st(t),r=ot(),o=r.get(n);if(o)return o;let s=new re(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function nt(e,t){let n=new re(rt(t),e,!1);return n.start({listen:!1}),n}var re=class{constructor(t,n=Bn.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Vn({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Qn({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 $n({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=ot(),n=st(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getDocument(r)},getObjectSummary:async(t,n)=>this.getRuntime().getObjectSummary(t,n?this.resolveRouteId(n):void 0),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 await r.refreshSourceForKey(t,o),r.getClassNameSource(t,o)},execute:async t=>this.getRuntime().executeOperation(this.normalizeRequest(t)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:t=>this.getRuntime().subscribe(t)}}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.refreshRoutes(),this.runtime?.notifyFileChanged(t)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:Hn(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=Un(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 rt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Kn.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Yn,port:e.port??zn,path:e.path??Jn,sessionKey:e.sessionKey??or(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function ot(){let e=globalThis;return e[et]??=new Map,e[et]}function st(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Qn(e){let t=new Wn({maxPayload:Xn,noServer:!0}),n=(r,o,s)=>{if(Zn(r,e)){if(!Ln(r,e)){o.write(`HTTP/1.1 401 Unauthorized\r
1
+ function Ce(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let u=t.get(a);if(typeof u=="number")return u;let d=n.length;return n.push(a),t.set(a,d),d},i=a=>{let u=null;for(let d of Et(a)){let p=`${u??"root"}\0${d}`,g=r.get(p);if(typeof g=="number"){u=g;continue}let y=o.length;o.push({parent:u,token:s(d)}),r.set(p,y),u=y}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,tokens:n,nodes:o,rootKeyNodeIds:e.rootKeys.map(i),entries:e.entries.map(a=>({keyNodeId:i(a.key),tag:a.tag,label:a.label,parentKeyNodeId:a.parentKey?i(a.parentKey):null,childKeyNodeIds:a.childKeys.map(i),operationSummary:a.operationSummary}))}}function Te(e){if(!St(e))return e;let t=new Map,n=r=>{let o=t.get(r);if(o)return o;let s=e.nodes[r];if(!s)throw new Error(`Missing compact document node ${r}`);let i=e.tokens[s.token];if(typeof i!="string")throw new Error(`Missing compact document token ${s.token}`);let a=`${s.parent===null?"":n(s.parent)}${i}`;return t.set(r,a),a};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,rootKeys:e.rootKeyNodeIds.map(n),entries:e.entries.map(r=>({key:n(r.keyNodeId),tag:r.tag,label:r.label,parentKey:r.parentKeyNodeId===null?null:n(r.parentKeyNodeId),childKeys:r.childKeyNodeIds.map(n),operationSummary:r.operationSummary}))}}function St(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Et(e){if(!e)return[];let t=[],n=0,r=xe(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=xe(e,n+(e.startsWith("::",n)?2:1)),r<0){t.push(e.slice(n));break}t.push(e.slice(n,r)),n=r}return t}function xe(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var F=class e{constructor(){}static parseMessage(t,n={}){let r=JSON.parse(t);if(!e.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(typeof t=="object"&&t!==null&&"payload"in t&&typeof t.payload=="object"&&t.payload!==null){let n=t.payload,r=typeof n.id=="string"?n.id:"unknown",o=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:o}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="get-document"||t==="get-object-summary"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!B(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?B(t.payload)&&typeof t.payload.id=="string":t.type==="event"?B(t.payload)&&B(t.payload.event):!1}static isRequestPayload(t,n={}){if(!B(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"get-document":return typeof t.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"execute":return vt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},X=class{constructor(t){this.options=t,this.messageQueue=new ce,this.eventDispatcher=new ue(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.eventDispatcher.push(n)}),t.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let r=n.payload,{id:o}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:{ok:!0,data:Ce((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"execute":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(o,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=F.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(t){try{await this.handleMessage(F.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=It(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(F.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let o=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:o}}),this.eventDispatcher.flush()}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:o instanceof Error?o.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},ue=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>{this.send(n)})}},ce=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function B(e){return typeof e=="object"&&e!==null}function vt(e){return B(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&(e.routeId===void 0||typeof e.routeId=="string")&&typeof e.kind=="string"&&B(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&B(e.params)}function It(e){try{return F.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Rt="vcp:designer:trace",_t="designer_trace",Ne="__VCP_DESIGNER_TRACE__";var xt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ct(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Rt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(_t)==="1"}catch{return!1}}function w(e,t={},n=globalThis){if(!Ct(n))return;let r={type:e,timestamp:Date.now(),payload:Tt(t)},o=n,s=o[Ne]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Ne]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Tt(e){return le(e,0)}function le(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>le(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(xt.test(r)){n[r]="[redacted]";continue}n[r]=le(o,t+1)}return n}var Q=class{constructor(t){this.options=t,this.socket=null,this.sequence=0,this.pending=new Map,this.listeners=new Set}connect(){return this.socket?Promise.resolve():new Promise((t,n)=>{let r=this.createSocket(this.options.url);this.socket=r,r.onopen=()=>t(),r.onerror=o=>{n(o instanceof Error?o:new Error("WebSocket failed"))},r.onmessage=o=>this.handleMessage(o.data),r.onclose=()=>{this.rejectAll(new Error("WebSocket closed")),this.socket=null}})}disconnect(){this.socket?.close(),this.socket=null,this.rejectAll(new Error("WebSocket disconnected"))}getDocument(t){return this.request("get-document",{routeId:t})}getObjectSummary(t,n){return this.request("get-object-summary",{key:t,routeId:n})}getObjectEditContext(t,n){return this.request("get-object-edit-context",{key:t,routeId:n})}getClassNameSource(t,n){return this.request("get-class-name-source",{key:t,routeId:n})}execute(t){return this.request("execute",{request:t})}undo(){return this.request("undo",{})}redo(){return this.request("redo",{})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}request(t,n){let r=this.socket;if(!r)return Promise.reject(new Error("WebSocket is not connected"));let o=`${t}-${this.sequence+=1}`,s=Pt(o,t,n);return w("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:ke(n.request,"kind"),documentVersion:ke(n.request,"documentVersion")}),new Promise((i,a)=>{this.pending.set(o,{kind:t,resolve:u=>i(u),reject:a}),r.send(F.stringifyMessage(s))})}handleMessage(t){let n=F.parseMessage(t);if(n.type==="event"){for(let o of this.listeners)o(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let r=this.pending.get(n.payload.id);if(r){if(this.pending.delete(n.payload.id),n.type==="error"){w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}w("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Nt(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Te(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let n of this.pending.values())n.reject(t);this.pending.clear()}createSocket(t){if(this.options.createSocket)return this.options.createSocket(t);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(t)}};function ke(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Nt(e){if(!e||typeof e!="object")return null;let t=e,n=t.data?.resultVersion??t.data?.version??null;return typeof n=="number"?n:null}function Pe(e){return new de(e)}var de=class{constructor(t){this.params=t,this.refreshInFlight=null,this.currentDocument=t.initialDocument,this.summaryCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Dt(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,Ot(r)]))}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return kt(this.currentDocument)&&(this.currentDocument=await this.refreshSnapshot(void 0,"get-document")),{ok:!0,data:this.currentDocument}}async ensureDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let r=await this.refreshSnapshot(n,"ensure-version");if(r.version<n)throw new Error(`Document refresh returned version ${r.version}, expected at least ${n}`);return{ok:!0,data:r}}async getObjectSummary(t,n){let r=this.summaryCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectSummary(t,n??this.params.routeId);return this.summaryCache.set(t,o.data),o}async getObjectEditContext(t,n){let r=this.editContextCache.get(t);if(r)return{ok:!0,data:r};let o=await this.params.client.getObjectEditContext(t,n??this.params.routeId);return this.editContextCache.set(t,o.data),o}async getClassNameSource(t,n){return this.params.client.getClassNameSource(t,n??this.params.routeId)}async execute(t){return this.params.client.execute(t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t)}async undo(){return this.params.client.undo()}async redo(){return this.params.client.redo()}subscribe(t){return this.params.client.subscribe(n=>{if(n.type==="site-edit.document.changed"&&n.routeId===this.params.routeId){this.refreshSnapshot(n.version,"event").catch(()=>{}).finally(()=>t(n));return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let o=await this.refreshInFlight;if(typeof t!="number"||o.version>=t||this.currentDocument.version>=t)return this.currentDocument}w("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(o=>(this.currentDocument=o.data,this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(){this.summaryCache.clear(),this.editContextCache.clear()}};function kt(e){return e.version===0&&e.rootKeys.length===0}function Pt(e,t,n){switch(t){case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-object-summary":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-object-edit-context":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"get-class-name-source":return{type:"request",payload:{id:e,kind:t,key:String(n.key),routeId:typeof n.routeId=="string"?n.routeId:void 0}};case"execute":return{type:"request",payload:{id:e,kind:t,request:n.request}};case"undo":case"redo":return{type:"request",payload:{id:e,kind:t}}}}function Dt(e){return{key:e.key,tag:e.tag,label:e.label,capabilities:{constraints:e.capabilities.constraints},isOpaque:e.isOpaque,provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,ancestors:e.ancestors}}function Ot(e){return{key:e.key,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:e.capabilities,writeTarget:e.writeTarget,effectiveWriteTarget:e.effectiveWriteTarget,provenanceChain:e.provenanceChain,componentSemantic:e.componentSemantic,textSegments:e.textSegments,boundaryKind:e.boundaryKind,children:e.children,siblings:e.siblings}}var De="vcp-window-message",$r=1;function At(e){return{source:De,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===De&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Oe="site-edit",Ae="frame-runtime";function U(e,t={}){return At({namespace:Oe,channel:Ae,sessionKey:t.sessionKey,body:e})}function Fe(e){return!Ft(e)||e.namespace!==Oe||e.channel!==Ae?!1:typeof e.body?.type=="string"}var he="vcp-site-edit:route-ready",Mt=1e3,Bt="data-vcp-ui-component",Ve="data-vcp-theme-preview",Me="::repeat-item#",Z="components/ui",jt=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),wt=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Kt(e,t=""){let n=Xt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function qt(e,t){if(e.__VCP_SITE_EDIT_VERSION_LOGGED__)return;let n=e.console?.info;typeof n=="function"&&(e.__VCP_SITE_EDIT_VERSION_LOGGED__=!0,n.call(e.console,"[VCP Site Edit] runtime loaded",{bridge:t.versions?.bridge??"unknown",contracts:t.versions?.contracts??"unknown",documentVersion:t.documentVersion,engine:t.versions?.engine??"unknown",routeId:t.routeId}))}function Wt(e,t={}){let n=s=>{if(!t.bridge_session_key)return s;let i=new URL(s,e.location.href);return i.searchParams.set("vcp_bridge_key",t.bridge_session_key),i.toString()};if(t.explicit_ws_url){if(t.explicit_ws_url.startsWith("/")){let s=e.location.protocol==="https:"?"wss:":"ws:";return n(`${s}//${e.location.host}${t.explicit_ws_url}`)}return n(t.explicit_ws_url)}let r=e.location.protocol==="https:"?"wss:":"ws:",o=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return n(`${r}//${o}${t.path??"/__vcp/site-edit/bridge"}`)}async function Jr(e=window,t={}){if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.started)return;let n={activeClient:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unbindRouteChange:void 0};n.cleanupFrameRuntime=Ut(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:l=>n.currentEntriesByKey.get(l)??null});let r=t.create_client??(l=>new Q({url:l})),o=t.schedule_after_navigation??zt,s=Wt(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge",bridge_session_key:t.bridge_session_key}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},a=l=>{n.currentDocument=l,n.currentEntriesByKey=new Map((l?.entries??[]).map(R=>[R.key,R]))},u=async(l,R)=>{let E=e.__VCP_SITE_EDIT__;if(!E)return null;let v=await E.getDocument(l);return R!==n.routeSequence||l!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||a(v.data),v.data},d=()=>{n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0,a(null),delete e.__VCP_SITE_EDIT__,n.activeClient?.disconnect(),n.activeClient=null},p=async()=>{let l=Kt(e.location.pathname,t.basePath||"");if(l===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&e.__VCP_SITE_EDIT__)return;let R=n.routeSequence+=1;i(),d();let E=r(s);try{if(await E.connect(),R!==n.routeSequence){E.disconnect();return}e.__VCP_SITE_EDIT__=Pe({routeId:l,client:E,initialDocument:Vt(l)}),n.activeClient=E,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===l&&u(l,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=l;let v=await u(l,R);qt(e,{documentVersion:v?.version??0,routeId:l,versions:t.runtime_versions}),Jt(e,{routeId:l,version:v?.version??0})}catch(v){throw E.disconnect(),v}},g=()=>{i(),n.retryTimer=e.setTimeout(()=>{p().catch(()=>g())},Mt)},y=()=>{o(()=>{p().catch(()=>g())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:p,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),d(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=Yt(e,y),t.defer_initial_sync){y();return}await p()}function Vt(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function Ut(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,u=new Map,d=()=>{n?.(),n=null},p=()=>{r?.(),r=null,o?.(),o=null},g=(I,f,c)=>{let x=s?.sessionKey!==I||s?.sourceWindow!==f||s?.targetOrigin!==c;s={sessionKey:I,sourceWindow:f,targetOrigin:c},x&&(a=null)},y=()=>{for(let I of u.values())I();u.clear()},l=I=>{i=I.routeId==="/"?null:I;let f=`${I.routeId}:${I.version}`;a!==f&&(o?.(),o=null,E({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(a=f))},R=()=>{i&&l(i)},E=I=>{s&&s.sourceWindow.postMessage(U({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},v=(I,f,c,x)=>{let _=te(e.document,f.clientX,f.clientY),C=_?P(_,c==="full"?O(e.document,_,t.getCurrentDocument?.()??null):je(e.document,_,t.getCurrentDocument?.()??null),t.getDocumentEntry,c):null;x&&C&&(I==="pointer-click"||I==="pointer-double-click")&&(x.preventDefault(),x.stopPropagation(),typeof x.stopImmediatePropagation=="function"&&x.stopImmediatePropagation()),E({kind:I,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:C}})},N=(I,f,c)=>{p(),s={sessionKey:I,sourceWindow:f,targetOrigin:c};let x=An(e.document),_=null,C=null,m=()=>{C=null;let h=_;_=null,h&&v("pointer-move",h,"summary")},k=h=>{_={clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},C===null&&(C=Ue(e,m))},M=h=>{v("pointer-down",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},K=h=>{v("pointer-up",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},A=h=>{v("pointer-cancel",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"summary",h)},j=h=>{v("pointer-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},W=h=>{v("pointer-double-click",{clientX:Number(h.clientX),clientY:Number(h.clientY),buttons:Number(h.buttons)},"full",h)},V=()=>{E({kind:"scroll",payload:{metrics:ee(e)}})};e.document.addEventListener("pointerdown",M,!0),e.document.addEventListener("pointermove",k,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",K,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",j,!0),e.document.addEventListener("dblclick",W,!0),e.addEventListener("scroll",V,{passive:!0}),r=()=>{C!==null&&(He(e,C),C=null),_=null,x(),e.document.removeEventListener("pointerdown",M,!0),e.document.removeEventListener("pointermove",k,!0),e.document.removeEventListener("pointerup",K,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",j,!0),e.document.removeEventListener("dblclick",W,!0),e.removeEventListener("scroll",V)}},Re=I=>{let f=I.detail;f?.routeId&&l(f)},_e=I=>{let f=I.data;if(!Fe(f)||f.body.type!=="request"||f.body.kind!=="apply-node-patch"&&f.body.kind!=="get-hit-by-ref"&&f.body.kind!=="get-path-by-ref"&&f.body.kind!=="get-scroll-metrics"&&f.body.kind!=="scroll-to"&&f.body.kind!=="scroll-by"&&f.body.kind!=="set-interaction-mode"&&f.body.kind!=="set-theme-override"&&f.body.kind!=="clear-theme-override"&&f.body.kind!=="get-theme-variables"&&f.body.kind!=="compute-drop-target-at-point"&&f.body.kind!=="observe-node-bounds"&&f.body.kind!=="clear-node-bounds-observer"&&f.body.kind!=="start-text-edit-at-point"&&f.body.kind!=="hit-test-at-point"&&!Be(f.body))return;let c=f.body,x=typeof f.sessionKey=="string"?f.sessionKey:null,_=I.source,C=I.origin;if(!x||!C||!_||typeof _.postMessage!="function"||s&&(s.sessionKey!==x||s.sourceWindow!==_||s.targetOrigin!==C))return;g(x,_,C),R();let m=k=>{let M=typeof c.id=="string"?c.id:"unknown";_.postMessage(U({id:M,...k},{sessionKey:x}),C)};try{if(Be(c)){Ht({message:c,sendEvent:b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},sendResponse:m,subscriptions:u,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(c.kind==="apply-node-patch"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for patch target"});return}let S=c.payload.preview,T=S?Sn(S.sessionId,c.payload.ref):null;if(T&&S){let J=H.get(T)??-1;if(S.revision<J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,stale:!0,latestRevision:J}});return}if(S.revision===J){m({type:"response",ok:!0,result:{applied:!1,appliedRevision:S.revision,duplicate:!0,latestRevision:J}});return}}if(yn(b,c.payload.patch),T&&S&&En(T,S.revision),S?.responseDetail==="none"){m({type:"response",ok:!0,result:{applied:!0,appliedRevision:S.revision}});return}m({type:"response",ok:!0,result:P(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,S?.responseDetail??"full")});return}if(c.kind==="get-hit-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for hit target"});return}m({type:"response",ok:!0,result:P(b,O(e.document,b,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(c.kind==="get-path-by-ref"){let b=q(e.document,c.payload.ref,t.getCurrentDocument?.()??null);if(!b){m({type:"response",ok:!1,error:"No editable element found for path target"});return}let S=[],T=b;for(;T;)T.getAttribute("data-vcp-edit-key")&&S.push(P(T,O(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),T=T.parentElement;m({type:"response",ok:!0,result:S.reverse()});return}if(c.kind==="get-scroll-metrics"){m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-to"){let b=Number(c.payload.x),S=Number(c.payload.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:b,top:S}),m({type:"response",ok:!0,result:ee(e)});return}if(c.kind==="scroll-by"){let b=Number(c.payload.deltaX),S=Number(c.payload.deltaY);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:b,top:S}),m({type:"response",ok:!0,result:{...ee(e),scrolled:!0}});return}if(c.kind==="set-interaction-mode"){c.payload.enabled?N(x,_,C):s?.sourceWindow===_&&s.targetOrigin===C&&s.sessionKey===x&&p(),m({type:"response",ok:!0,result:{interactionEnabled:c.payload.enabled}});return}if(c.kind==="set-theme-override"){vn(e.document,c.payload),m({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(c.kind==="clear-theme-override"){In(e.document),m({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(c.kind==="get-theme-variables"){m({type:"response",ok:!0,result:Rn(e.document,c.payload.names)});return}if(c.kind==="compute-drop-target-at-point"){let b=Number(c.payload?.x),S=Number(c.payload?.y);if(!Number.isFinite(b)||!Number.isFinite(S)){m({type:"response",ok:!1,error:"Invalid drop target point"});return}m({type:"response",ok:!0,result:fn(e,b,S,c.payload.dragKind,c.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(c.kind==="observe-node-bounds"){let b=c.payload.ref;if(!b){m({type:"response",ok:!1,error:"Missing bounds observer target"});return}let S=q(e.document,b,t.getCurrentDocument?.()??null);if(!S){m({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=dn(e,S,b,t.getDocumentEntry,T=>E({kind:"node-bounds-change",payload:{hit:T}})),m({type:"response",ok:!0,result:{observing:!0}}),E({kind:"node-bounds-change",payload:{hit:P(S,b,t.getDocumentEntry,"summary")}});return}if(c.kind==="clear-node-bounds-observer"){o?.(),o=null,m({type:"response",ok:!0,result:{cleared:!0}});return}if(c.kind!=="hit-test-at-point"&&c.kind!=="start-text-edit-at-point")return;let k=Number(c.payload?.x),M=Number(c.payload?.y);if(!Number.isFinite(k)||!Number.isFinite(M)){m({type:"response",ok:!1,error:"Invalid text edit point"});return}let K=c.kind==="hit-test-at-point"?te(e.document,k,M):Zt(e.document,k,M,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!K){m({type:"response",ok:!1,error:c.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=c.kind==="start-text-edit-at-point"?K:null,j=c.kind==="hit-test-at-point"?K:A.element,W=c.payload.detailLevel??"full",V=W==="full"?O(e.document,j,t.getCurrentDocument?.()??null):je(e.document,j,t.getCurrentDocument?.()??null),h=A&&typeof A.textSegmentIndex=="number"?{...V,textSegmentIndex:A.textSegmentIndex}:V,bt=P(j,h,t.getDocumentEntry,W);if(c.kind==="hit-test-at-point"){m({type:"response",ok:!0,result:bt});return}d(),n=Tn(e,j,h,b=>{_.postMessage(U({type:"event",...b},{sessionKey:x}),C)},A?{textNode:A.textNode}:void 0),m({type:"response",ok:!0,result:{ref:h}})}catch(k){m({type:"response",ok:!1,error:k instanceof Error?k.message:"Failed to start text edit"})}};return e.addEventListener("message",_e),e.addEventListener(he,Re),()=>{d(),p(),s=null,y(),e.removeEventListener("message",_e),e.removeEventListener(he,Re)}}function Be(e){let t=e.kind;return t==="bridge-get-document"||t==="bridge-ensure-document-version"||t==="bridge-get-object-summary"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function Ht({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,windowLike:s}){let i=s.__VCP_SITE_EDIT__;if(!i){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await i.getDocument(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}n({type:"response",ok:!0,result:i.ensureDocumentVersion?await i.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await i.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await i.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await i.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let a=await i.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:$t(a,e.payload.key,s.document,o?.()??null)});return}case"bridge-execute":n({type:"response",ok:!0,result:await i.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await i.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await i.redo()});return;case"bridge-subscribe":{let a=e.payload.subscriptionId;r.get(a)?.();let u=i.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:a}})});r.set(a,u),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let a=e.payload.subscriptionId;r.get(a)?.(),r.delete(a),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(a){n({type:"response",ok:!1,error:a instanceof Error?a.message:"Site edit bridge request failed"})}}function $t(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=q(n,{key:t},r),s=o?Gt(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function Gt(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 Yt(e,t){let n=e.history.pushState,r=e.history.replaceState,o=()=>t();return e.history.pushState=function(...i){let a=n.apply(this,i);return t(),a},e.history.replaceState=function(...i){let a=r.apply(this,i);return t(),a},e.addEventListener("popstate",o),()=>{e.history.pushState=n,e.history.replaceState=r,e.removeEventListener("popstate",o)}}function zt(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Ue(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function He(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Jt(e,t){e.dispatchEvent(new CustomEvent(he,{detail:t}))}function Xt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ye(e){return jt.has(Ge(e))}function Qt(e){return wt.has(Ge(e))}function $e(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:Qt(e.tagName),canInsertChild:ye(e.tagName),canMove:!1,canRemove:!1}}function Ge(e){return e?.trim().toLowerCase()??""}function Zt(e,t,n,r,o){let s=te(e,t,n),i=Ye(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",u=O(e,i,r),d=o?.(u.key)??o?.(a);if(!$e({operationSummary:d?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((d?.childKeys.length??0)===0)return{element:i};let g=Lt(e,t,n,i);if(!g)return null;let y=tn(i,g);return y===null?null:{element:i,textNode:g,textSegmentIndex:y}}function Lt(e,t,n,r){let o=en(e,t,n);return!o||o.parentElement!==r?null:o}function en(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(me(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return me(a)?a:null}function tn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!me(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function me(e){return e?.nodeType===3}function te(e,t,n){let r=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of r){let s=Ye(o);if(s)return s}return null}function Ye(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(be(t))return n??t;!nn(r)&&!n&&(n=t)}t=t.parentElement}return n}function be(e){return e.getAttribute(Bt)!==null}function nn(e){return rn(e.split("::")[0]??"")}function rn(e){if(!e)return!1;let t=on(e);return t===Z||t.startsWith(`${Z}/`)||t.includes(`/${Z}/`)||t.endsWith(`/${Z}`)}function on(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 O(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length<=1)return{key:we(n,r,0)};let s=o.indexOf(t);return s>=0?{key:we(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function je(e,t,n){return O(e,t,n)}function q(e,t,n){let r=ne(t.key)??t.key,o=Je(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Le(r)}"]`)));if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(ne(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=sn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function we(e,t,n){return ze(e,t)[n]?.key??t}function sn(e,t){let n=ne(t);if(!n)return null;let o=ze(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function ze(e,t){return(e?.entries??[]).filter(n=>(ne(n.key)??n.key)===t)}var an=2,un=4;function Je(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&un)!==0?-1:(r&an)!==0?1:0})}function ne(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Me);if(n<0)break;let r=Number(t.slice(n+Me.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function cn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=o=>{let s=Number.parseFloat(o??"");return Number.isFinite(s)&&s>0?s:0};return{marginTop:r(n?.marginTop),marginRight:r(n?.marginRight),marginBottom:r(n?.marginBottom),marginLeft:r(n?.marginLeft),paddingTop:r(n?.paddingTop),paddingRight:r(n?.paddingRight),paddingBottom:r(n?.paddingBottom),paddingLeft:r(n?.paddingLeft),borderTopWidth:r(n?.borderTopWidth),borderRightWidth:r(n?.borderRightWidth),borderBottomWidth:r(n?.borderBottomWidth),borderLeftWidth:r(n?.borderLeftWidth),columnGap:r(n?.columnGap),rowGap:r(n?.rowGap)}}function ln(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>ge(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function P(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=re(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([l,R])=>[l,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(l=>[l,e.getAttribute(l)??""]))}:{},d=$e({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),p=be(e),g=!!(s&&/^[A-Z]/.test(s.tag)),y=!s||!g;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:g?"component-call":"jsx"}:{},...g&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...u,runtimeFlags:{selectable:!0,movable:d.canMove,removable:d.canRemove,textEditable:d.canUpdateText,container:p?!1:(s?.childKeys.length??0)>0||d.canInsertChild||y&&ye(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:ln(e),spacing:cn(e)}}function dn(e,t,n,r,o){let s=ge(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=Ue(e,u))},u=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let l=ge(t.getBoundingClientRect());pn(s,l)&&(s=l,o(P(t,n,r,"summary")))},d=e.ResizeObserver,p=typeof d=="function"?new d(a):null;p?.observe(t);let g=e.MutationObserver,y=typeof g=="function"?new g(a):null;return y?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(He(e,i),i=null),p?.disconnect(),y?.disconnect(),e.document.removeEventListener("load",a,!0)}}function ge(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function pn(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 fn(e,t,n,r,o,s,i){let a=e.document,u=te(a,t,n);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let d=o?q(a,o,s):null;if(d&&We(u,d))return L(a,u,"self-or-descendant",s,i);let p=null,g=!1,y=u,l=u.parentElement;for(;l;){if(l.getAttribute("data-vcp-edit-key")){if(d&&We(l,d))return L(a,u,"self-or-descendant",s,i);let E=Ke(l,r,i);if(E==="accept"){p={child:y,targetParent:l};break}E==="blocked"&&(g=!0),y=l}l=l.parentElement}let R=Ke(u,r,i);if(R==="accept"){if(p){let E=qe(p.child,p.targetParent,t,n,"edge");if(E)return pe(a,p.child,p.targetParent,E,s,i)}return pe(a,u,u,hn(u,t,n),s,i)}if(p){let E=qe(p.child,p.targetParent,t,n,"nearest");return pe(a,p.child,p.targetParent,E??"after",s,i)}return R==="blocked"||g?L(a,u,"operation-boundary-blocked",s,i):L(a,u,"no-accepting-parent",s,i)}function L(e,t,n,r,o){return{anchorHit:P(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function pe(e,t,n,r,o,s){let i=P(t,O(e,t,o),s,"summary"),a=P(n,O(e,n,o),s,"summary"),u=re(n).indicatorOrientation,d=r==="append"||r==="prepend"?mn(n.getBoundingClientRect(),u,r):gn(t.getBoundingClientRect(),u,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:u,indicatorBounds:d}}function Ke(e,t,n){if(be(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":o.childKeys.length>0?"blocked":"not-container";let s=e.tagName.toLowerCase();return ye(s)?"accept":"not-container"}function qe(e,t,n,r,o){let s=re(t).indicatorOrientation,i=e.getBoundingClientRect(),a=s==="vertical"?i.width>0?(n-i.left)/i.width:.5:i.height>0?(r-i.top)/i.height:.5;return o==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function hn(e,t,n){let r=re(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 re(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",o=n?.flexDirection,s=n?.gridAutoFlow,i="horizontal";return r==="flex"||r==="inline-flex"?i=(o??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(i=(s??"row").includes("column")?"vertical":"horizontal"),{display:r,...o?{flexDirection:o}:{},...s?{gridAutoFlow:s}:{},indicatorOrientation:i}}function mn(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 gn(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 We(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ee(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:D(e.scrollX),scrollY:D(e.scrollY),scrollWidth:Math.max(D(t?.scrollWidth),D(n?.scrollWidth),D(e.innerWidth)),scrollHeight:Math.max(D(t?.scrollHeight),D(n?.scrollHeight),D(e.innerHeight)),viewportWidth:D(e.innerWidth),viewportHeight:D(e.innerHeight)}}function yn(e,t){Object.entries(t.attributes??{}).forEach(([n,r])=>{if(r===null){e.removeAttribute(n);return}e.setAttribute(n,r)}),typeof t.className=="string"&&(e.className=t.className),Object.entries(t.style??{}).forEach(([n,r])=>{let o=e.style,s=n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);if(r==null||r===""){o.removeProperty(s);return}o.setProperty(s,String(r))})}var bn=500,H=new Map;function Sn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function En(e,t){if(H.size>=bn){let n=H.keys().next().value;n&&H.delete(n)}H.set(e,t)}var $=new Set;function vn(e,t){let n=e.documentElement?.style,r=new Set;for(let[o,s]of Object.entries(t.variables??{}))o.startsWith("--")&&(r.add(o),n?.setProperty(o,s));for(let o of $)r.has(o)||n?.removeProperty(o);$.clear();for(let o of r)$.add(o);Cn(e,t.stylesheets??[])}function In(e){let t=e.documentElement?.style;for(let n of $)t?.removeProperty(n);$.clear();for(let n of Ze(e))n.remove()}function Rn(e,t){let n=Array.from(new Set(t.filter(i=>typeof i=="string"&&i.startsWith("--"))));if(n.length===0)return{};let r=e.documentElement,o=r?e.defaultView?.getComputedStyle(r):null,s={};for(let i of n){let a=Xe(o,i);a&&(s[i]=a)}return s}function Xe(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Qe(e,r,n)}function Qe(e,t,n){if(!t)return null;let r=_n(t);if(!r)return t;let o=Xe(e,r.name,n);return o||(r.fallback?Qe(e,r.fallback,n)??r.fallback:null)}function _n(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=xn(n),o=r>=0?n.slice(0,r).trim():n;if(!o.startsWith("--"))return null;let s=r>=0?n.slice(r+1).trim():null;return{name:o,fallback:s||null}}function xn(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 Cn(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of Ze(e)){let i=s.getAttribute("href")??"";if(!n.has(i)||r.has(i)){s.remove();continue}r.set(i,s)}let o=e.head;if(o)for(let s of n){if(r.has(s))continue;let i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute(Ve,"true"),i.setAttribute("href",s),o.appendChild(i)}}function Ze(e){return Array.from(e.querySelectorAll(`link[${Ve}]`))}function Tn(e,t,n,r,o={}){let s=o.textNode?Nn(e.document,o.textNode):null;if(o.textNode&&!s)throw new Error("Failed to prepare text segment editor");let i=s?.element??t,a=i.textContent??"",u=kn(i),d=!1,p=()=>{e.document.removeEventListener("pointerdown",y,!0),i.removeEventListener("keydown",l),i.removeEventListener("blur",R),i.removeEventListener("input",E),Dn(i,u)},g=v=>{if(d)return;d=!0;let N=i.textContent??"";if(p(),v==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(N),v==="commit"&&N!==a){r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(v){let N=v.target;N&&i.contains(N)||g("commit")}function l(v){if(v.key==="Escape"){v.preventDefault(),g("cancel");return}v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),g("commit"))}function R(){g("commit")}function E(){r({kind:"text-edit-input",payload:{ref:n,hit:P(t,n,void 0,"full")}})}return Pn(i),e.document.addEventListener("pointerdown",y,!0),i.addEventListener("keydown",l),i.addEventListener("blur",R),i.addEventListener("input",E),Fn(i),Mn(i,e.document),p}function Nn(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 kn(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 Pn(e){On(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 Dn(e,t){fe(e,"contenteditable",t.contentEditable),fe(e,"spellcheck",t.spellcheck),fe(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function On(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 fe(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function An(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 Fn(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function Mn(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function D(e){let t=Number(e);return Number.isFinite(t)?t:0}import Bn from"node:http";import{randomBytes as jn,timingSafeEqual as wn}from"node:crypto";import Kn from"node:path";import{WebSocket as qn,WebSocketServer as Wn}from"ws";import{createPreviewSiteEditEngineRuntime as Vn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Un,scanNextAppRouterRoutes as Hn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as $n}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as Gn}from"@vcp-dev/contracts";var Yn="127.0.0.1",zn=30218,Jn="/__vcp/site-edit/bridge",Xn=128*1024,et="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function io(e){let t=rt(e),n=st(t),r=ot(),o=r.get(n);if(o)return o;let s=new oe(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function nt(e,t){let n=new oe(rt(t),e,!1);return n.start({listen:!1}),n}var oe=class{constructor(t,n=Bn.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Vn({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Qn({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 $n({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=ot(),n=st(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getDocument(r)},getObjectSummary:async(t,n)=>this.getRuntime().getObjectSummary(t,n?this.resolveRouteId(n):void 0),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 await r.refreshSourceForKey(t,o),r.getClassNameSource(t,o)},execute:async t=>this.getRuntime().executeOperation(this.normalizeRequest(t)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:t=>this.getRuntime().subscribe(t)}}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.refreshRoutes(),this.runtime?.notifyFileChanged(t)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:Hn(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=Un(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 rt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Kn.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Yn,port:e.port??zn,path:e.path??Jn,sessionKey:e.sessionKey??or(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function ot(){let e=globalThis;return e[et]??=new Map,e[et]}function st(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Qn(e){let t=new Wn({maxPayload:Xn,noServer:!0}),n=(r,o,s)=>{if(Zn(r,e)){if(!Ln(r,e)){o.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),o.destroy();return}t.handleUpgrade(r,o,s,i=>{t.emit("connection",i,r)})}};return e.server.on("upgrade",n),t.on("connection",r=>{new X({socket:new Ee(r),engine:e.engine,validateOperationRequest:o=>Gn.safeParse(o).success})}),t.stop=()=>{e.server.off("upgrade",n);for(let r of t.clients)r.close(1001,"bridge stopped");t.close()},t}var Ee=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){this.socket.readyState===qn.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function Zn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Ln(e,t){let r=new URL(e.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??Se(e.headers["x-vcp-site-edit-key"]);if(!er(r,t.sessionKey))return!1;let o=Se(e.headers.host),s=Se(e.headers.origin);return o&&!tr(o,t.host,s)?!1:s?t.allowedOrigins.includes(s)||rr(s)||(o?it(s,o):!1):!0}function er(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&wn(n,r)}function tr(e,t,n){let r=tt(e),o=tt(t);return r===o||r==="localhost"||r==="127.0.0.1"||r==="::1"||nr(o)&&!!(n&&it(n,e))}function nr(e){return e==="0.0.0.0"||e==="::"}function rr(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}}function it(e,t){try{return new URL(e).host===at(t)}catch{return!1}}function tt(e){let t=at(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function at(e){return e.trim().toLowerCase()}function Se(e){return Array.isArray(e)?e[0]:e}function or(){return jn(32).toString("base64url")}import sr from"node:http";import{existsSync as z,readFileSync as G}from"node:fs";import{createRequire as dt}from"node:module";import se from"node:path";import{basename as ft,dirname as Y,join as ie}from"node:path";import{fileURLToPath as pt}from"node:url";var ir="next",ar="127.0.0.1",ur=3e3,ht="/__vcp/site-edit/bridge",oe="/__vcp/site-edit/client/",cr=`${oe}auto-bootstrap.js`,mt='data-vcp-site-edit-bootstrap="true"',lr=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function go(e={}){let t=se.resolve(e.projectRoot??process.cwd()),n=e.host??ar,r=e.port??Mr(process.env.PORT)??ur,o=e.bridgePath??ht,s=Cr(),i=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",u=(await Dr(t))({dev:!0,dir:t,hostname:n,port:r,webpack:!0}),d=u.getRequestHandler();await u.prepare();let f=sr.createServer((l,R)=>{Sr({basePath:i,bridgePath:o,bridgeSessionKey:s,handle:d,request:l,response:R}).catch(E=>{console.error(E),R.headersSent||(R.statusCode=500),R.end("site edit preview request failed")})}),g=nt(f,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??Fr(t),projectRoot:t,basePath:i,host:n,port:r,path:o,sessionKey:s});dr({server:f,bridgePath:o,handleUpgrade:u.getUpgradeHandler()});let y=()=>{g.stop(),u.close().catch(()=>{}),f.close()};return process.on("SIGINT",y),process.on("SIGTERM",y),await Br(f,r,n),{close:y,server:f}}function dr(e){let t=(n,r,o)=>{fr(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(s=>{console.error(s),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function fr(e,t){return new URL(e??"/","http://localhost").pathname===t}function pr(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??hr()});return`<script type="module" ${mt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(cr)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function hr(){return{bridge:ve("@vcp-dev/site-edit-bridge"),contracts:ve("@vcp-dev/contracts"),engine:ve("@vcp-dev/site-edit-engine")}}function ve(e){let t=dt(import.meta.url);try{let n=t.resolve(e),r=mr(n,e);if(!r)return;let o=JSON.parse(G(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function mr(e,t){let n=se.parse(e).root,r=Y(e);for(;r&&r!==n;){let o=ie(r,"package.json");if(z(o))try{if(JSON.parse(G(o,"utf8")).name===t)return o}catch{return}r=Y(r)}}function gr(e,t){if(e.includes(mt))return e;let n=pr(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function yo(e,t=Y(pt(import.meta.url)),n=z){return gt(e,t,n)?.path??null}function gt(e,t=Y(pt(import.meta.url)),n=z){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(oe))return null;let o=r.slice(oe.length);if(!lr.has(o))return null;let s=Ie(Or(t),o);if(ft(t)!=="src")return{path:s,requiresTranspile:!1};let i=Ie(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function yr(e,t){let n=gt(e.url);if(!n)return!1;if(!z(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await br(G(n.path,"utf8")):G(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function br(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Sr({basePath:e,bridgePath:t,bridgeSessionKey:n,handle:r,request:o,response:s}){if(await yr(o,s))return;let i=Er(o),a=vr(o),u=i||a?_r(s,{basePath:e,bridgePath:t,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(o,s)}catch(d){throw u(),d}}function Er(e){return Ir(e)?(e.headers["accept-encoding"]="identity",!0):!1}function vr(e){return Rr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ir(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(oe)||t===ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Rr(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 _r(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),s=r.write.bind(e),i=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,u,d)=>(a!==void 0&&n.push(ut(a,ct(u))),lt(u),lt(d),!0),r.end=(a,u,d)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(ut(f,ct(u))),r.write=s,r.end=i,r.flushHeaders=o;let g=Buffer.concat(n),y=xr(e,g,t);y!==g&&!e.headersSent&&e.removeHeader("content-length");let l=typeof a=="function"?a:typeof u=="function"?u:typeof d=="function"?d:void 0;return l?i(y,l):i(y)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function xr(e,t,n){if(Tr(e,t))return Buffer.from(gr(t.toString("utf8"),n));if(n.patchNextDevChunk&&Nr(e)){let r=t.toString("utf8"),o=Pr(r);if(o!==r)return Buffer.from(o)}return t}function Cr(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Tr(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 Nr(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 Pr(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(`
4
+ `),o.destroy();return}t.handleUpgrade(r,o,s,i=>{t.emit("connection",i,r)})}};return e.server.on("upgrade",n),t.on("connection",r=>{new X({socket:new Ee(r),engine:e.engine,validateOperationRequest:o=>Gn.safeParse(o).success})}),t.stop=()=>{e.server.off("upgrade",n);for(let r of t.clients)r.close(1001,"bridge stopped");t.close()},t}var Ee=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){this.socket.readyState===qn.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function Zn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Ln(e,t){let r=new URL(e.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??Se(e.headers["x-vcp-site-edit-key"]);if(!er(r,t.sessionKey))return!1;let o=Se(e.headers.host),s=Se(e.headers.origin);return o&&!tr(o,t.host,s)?!1:s?t.allowedOrigins.includes(s)||rr(s)||(o?it(s,o):!1):!0}function er(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&wn(n,r)}function tr(e,t,n){let r=tt(e),o=tt(t);return r===o||r==="localhost"||r==="127.0.0.1"||r==="::1"||nr(o)&&!!(n&&it(n,e))}function nr(e){return e==="0.0.0.0"||e==="::"}function rr(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}}function it(e,t){try{return new URL(e).host===at(t)}catch{return!1}}function tt(e){let t=at(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function at(e){return e.trim().toLowerCase()}function Se(e){return Array.isArray(e)?e[0]:e}function or(){return jn(32).toString("base64url")}import sr from"node:http";import{existsSync as z,readFileSync as G}from"node:fs";import{createRequire as dt}from"node:module";import ie from"node:path";import{basename as pt,dirname as Y,join as ae}from"node:path";import{fileURLToPath as ft}from"node:url";var ir="next",ar="127.0.0.1",ur=3e3,ht="/__vcp/site-edit/bridge",se="/__vcp/site-edit/client/",cr=`${se}auto-bootstrap.js`,mt='data-vcp-site-edit-bootstrap="true"',lr=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function go(e={}){let t=ie.resolve(e.projectRoot??process.cwd()),n=e.host??ar,r=e.port??Mr(process.env.PORT)??ur,o=e.bridgePath??ht,s=Cr(),i=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",u=(await Dr(t))({dev:!0,dir:t,hostname:n,port:r,turbopack:!0}),d=u.getRequestHandler();await u.prepare();let p=sr.createServer((l,R)=>{Sr({basePath:i,bridgePath:o,bridgeSessionKey:s,handle:d,request:l,response:R}).catch(E=>{console.error(E),R.headersSent||(R.statusCode=500),R.end("site edit preview request failed")})}),g=nt(p,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??Fr(t),projectRoot:t,basePath:i,host:n,port:r,path:o,sessionKey:s});dr({server:p,bridgePath:o,handleUpgrade:u.getUpgradeHandler()});let y=()=>{g.stop(),u.close().catch(()=>{}),p.close()};return process.on("SIGINT",y),process.on("SIGTERM",y),await Br(p,r,n),{close:y,server:p}}function dr(e){let t=(n,r,o)=>{pr(n.url,e.bridgePath)||e.handleUpgrade(n,r,o).catch(s=>{console.error(s),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function pr(e,t){return new URL(e??"/","http://localhost").pathname===t}function fr(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??hr()});return`<script type="module" ${mt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(cr)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function hr(){return{bridge:ve("@vcp-dev/site-edit-bridge"),contracts:ve("@vcp-dev/contracts"),engine:ve("@vcp-dev/site-edit-engine")}}function ve(e){let t=dt(import.meta.url);try{let n=t.resolve(e),r=mr(n,e);if(!r)return;let o=JSON.parse(G(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function mr(e,t){let n=ie.parse(e).root,r=Y(e);for(;r&&r!==n;){let o=ae(r,"package.json");if(z(o))try{if(JSON.parse(G(o,"utf8")).name===t)return o}catch{return}r=Y(r)}}function gr(e,t){if(e.includes(mt))return e;let n=fr(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function yo(e,t=Y(ft(import.meta.url)),n=z){return gt(e,t,n)?.path??null}function gt(e,t=Y(ft(import.meta.url)),n=z){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(se))return null;let o=r.slice(se.length);if(!lr.has(o))return null;let s=Ie(Or(t),o);if(pt(t)!=="src")return{path:s,requiresTranspile:!1};let i=Ie(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function yr(e,t){let n=gt(e.url);if(!n)return!1;if(!z(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await br(G(n.path,"utf8")):G(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function br(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Sr({basePath:e,bridgePath:t,bridgeSessionKey:n,handle:r,request:o,response:s}){if(await yr(o,s))return;let i=Er(o),a=vr(o),u=i||a?_r(s,{basePath:e,bridgePath:t,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(o,s)}catch(d){throw u(),d}}function Er(e){return Ir(e)?(e.headers["accept-encoding"]="identity",!0):!1}function vr(e){return Rr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ir(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(se)||t===ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Rr(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 _r(e,t){let n=[],r=e,o=r.flushHeaders.bind(e),s=r.write.bind(e),i=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,u,d)=>(a!==void 0&&n.push(ut(a,ct(u))),lt(u),lt(d),!0),r.end=(a,u,d)=>{let p=typeof a=="function"?void 0:a;p!==void 0&&n.push(ut(p,ct(u))),r.write=s,r.end=i,r.flushHeaders=o;let g=Buffer.concat(n),y=xr(e,g,t);y!==g&&!e.headersSent&&e.removeHeader("content-length");let l=typeof a=="function"?a:typeof u=="function"?u:typeof d=="function"?d:void 0;return l?i(y,l):i(y)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function xr(e,t,n){if(Tr(e,t))return Buffer.from(gr(t.toString("utf8"),n));if(n.patchNextDevChunk&&Nr(e)){let r=t.toString("utf8"),o=kr(r);if(o!==r)return Buffer.from(o)}return t}function Cr(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Tr(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 Nr(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 kr(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(`
5
5
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
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,[r,o])=>kr(n,r,o),e)}function kr(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 ut(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function ct(e){return typeof e=="string"?e:void 0}function lt(e){typeof e=="function"&&e()}async function Dr(e){let n=dt(ie(e,"package.json"))(ir);return n.default??n}function Or(e){return ft(e)!=="src"?e:Ie(Ar(e),"dist")}function Ar(e){return yt(e)?se.posix.dirname(e):Y(e)}function Ie(e,t){return yt(e)?se.posix.join(e,t):ie(e,t)}function yt(e){return e.includes("/")&&!e.includes("\\")}function Fr(e){let t=ie(e,".vcp/current-snapshot.json");if(!z(t))return"sandbox_worktree";try{let n=JSON.parse(G(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Mr(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Br(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Ae as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Oe as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,re as SiteEditBridgeServer,X as SiteEditBridgeSocketServer,F as SiteEditBridgeTransport,Q as SiteEditWebSocketClient,pe as VCP_SITE_EDIT_ROUTE_READY_EVENT,De as VCP_WINDOW_MESSAGE_SOURCE,$r as VCP_WINDOW_MESSAGE_VERSION,dr as attachNextDevUpgradeHandler,nt as attachSiteEditBridgeServer,Qn as attachSiteEditWebSocketServer,pr as createSiteEditAutoBootstrapHtmlSnippet,ke as createSiteEditBridge,U as createSiteEditFrameRuntimeMessage,At as createVcpWindowMessageEnvelope,Te as decodeRenderDocument,Ce as encodeRenderDocument,io as ensureSiteEditBridgeServerStarted,gr as injectSiteEditAutoBootstrap,St as isCompactRenderDocument,Ct as isDesignerTraceEnabled,Fe as isSiteEditFrameRuntimeMessage,Ft as isVcpWindowMessageEnvelope,Pr as patchNextFirefoxDevChunk,vr as prepareFirefoxNextDevChunkPatchRequest,Er as prepareSiteEditHtmlInjectionRequest,gt as resolveSiteEditClientAsset,yo as resolveSiteEditClientAssetPath,Kt as resolveSiteEditRouteId,Wt as resolveSiteEditWebSocketUrl,Tt as sanitizeTracePayload,Jr as startSiteEditAutoBootstrap,Ut as startSiteEditFrameRuntime,go as startSiteEditNextDevServer,w as traceDesignerEvent,br as transpileSiteEditClientSource};
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,[r,o])=>Pr(n,r,o),e)}function Pr(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 ut(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function ct(e){return typeof e=="string"?e:void 0}function lt(e){typeof e=="function"&&e()}async function Dr(e){let n=dt(ae(e,"package.json"))(ir);return n.default??n}function Or(e){return pt(e)!=="src"?e:Ie(Ar(e),"dist")}function Ar(e){return yt(e)?ie.posix.dirname(e):Y(e)}function Ie(e,t){return yt(e)?ie.posix.join(e,t):ae(e,t)}function yt(e){return e.includes("/")&&!e.includes("\\")}function Fr(e){let t=ae(e,".vcp/current-snapshot.json");if(!z(t))return"sandbox_worktree";try{let n=JSON.parse(G(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Mr(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Br(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Ae as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Oe as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,oe as SiteEditBridgeServer,X as SiteEditBridgeSocketServer,F as SiteEditBridgeTransport,Q as SiteEditWebSocketClient,he as VCP_SITE_EDIT_ROUTE_READY_EVENT,De as VCP_WINDOW_MESSAGE_SOURCE,$r as VCP_WINDOW_MESSAGE_VERSION,dr as attachNextDevUpgradeHandler,nt as attachSiteEditBridgeServer,Qn as attachSiteEditWebSocketServer,fr as createSiteEditAutoBootstrapHtmlSnippet,Pe as createSiteEditBridge,U as createSiteEditFrameRuntimeMessage,At as createVcpWindowMessageEnvelope,Te as decodeRenderDocument,Ce as encodeRenderDocument,io as ensureSiteEditBridgeServerStarted,gr as injectSiteEditAutoBootstrap,St as isCompactRenderDocument,Ct as isDesignerTraceEnabled,Fe as isSiteEditFrameRuntimeMessage,Ft as isVcpWindowMessageEnvelope,kr as patchNextFirefoxDevChunk,vr as prepareFirefoxNextDevChunkPatchRequest,Er as prepareSiteEditHtmlInjectionRequest,gt as resolveSiteEditClientAsset,yo as resolveSiteEditClientAssetPath,Kt as resolveSiteEditRouteId,Wt as resolveSiteEditWebSocketUrl,Tt as sanitizeTracePayload,Jr as startSiteEditAutoBootstrap,Ut as startSiteEditFrameRuntime,go as startSiteEditNextDevServer,w as traceDesignerEvent,br as transpileSiteEditClientSource};
@@ -1,6 +1,6 @@
1
1
  import ve from"node:http";import{existsSync as y,readFileSync as g}from"node:fs";import{createRequire as D}from"node:module";import x from"node:path";import{basename as J,dirname as m,join as I}from"node:path";import{fileURLToPath as W}from"node:url";import Y from"node:http";import{randomBytes as Z,timingSafeEqual as ee}from"node:crypto";import te from"node:path";import{WebSocket as ne,WebSocketServer as re}from"ws";import{createPreviewSiteEditEngineRuntime as se}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as oe,scanNextAppRouterRoutes as ie}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ae}from"@vcp-dev/site-edit-engine/source-watcher";function _(t){let e=new Map,n=[],r=new Map,s=[],o=i=>{let a=e.get(i);if(typeof a=="number")return a;let c=n.length;return n.push(i),e.set(i,c),c},u=i=>{let a=null;for(let c of G(i)){let d=`${a??"root"}\0${c}`,l=r.get(d);if(typeof l=="number"){a=l;continue}let h=s.length;s.push({parent:a,token:o(c)}),r.set(d,h),a=h}if(a===null)throw new Error("Document key must not be empty");return a};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,tokens:n,nodes:s,rootKeyNodeIds:t.rootKeys.map(u),entries:t.entries.map(i=>({keyNodeId:u(i.key),tag:i.tag,label:i.label,parentKeyNodeId:i.parentKey?u(i.parentKey):null,childKeyNodeIds:i.childKeys.map(u),operationSummary:i.operationSummary}))}}function G(t){if(!t)return[];let e=[],n=0,r=N(t,n);if(r<0)return e.push(t),e;for(e.push(t.slice(0,r)),n=r;n<t.length;){if(r=N(t,n+(t.startsWith("::",n)?2:1)),r<0){e.push(t.slice(n));break}e.push(t.slice(n,r)),n=r}return e}function N(t,e){let n=t.indexOf("/",e),r=t.indexOf("::",e);return n<0?r:r<0?n:Math.min(n,r)}var p=class t{constructor(){}static parseMessage(e,n={}){let r=JSON.parse(e);if(!t.isMessage(r,n))throw new Error("Invalid site edit bridge message");return r}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,r=typeof n.id=="string"?n.id:"unknown",s=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="get-document"||e==="get-object-summary"||e==="get-object-edit-context"||e==="get-class-name-source"||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):!1}static isRequestPayload(e,n={}){if(!f(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"get-document":return typeof e.routeId=="string";case"get-object-summary":case"get-object-edit-context":case"get-class-name-source":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"execute":return Q(e.request)&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return!0}}},w=class{constructor(e){this.options=e,this.messageQueue=new k,this.eventDispatcher=new v(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(r){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:r instanceof Error?r.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 r=n.payload,{id:s}=r;switch(r.kind){case"get-document":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:{ok:!0,data:_((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-object-summary":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.getObjectSummary(r.key,r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.getObjectEditContext(r.key,r.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"execute":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.execute(r.request));return;case"undo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(s,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=p.extractRequestInfo(e);this.sendJson({type:"error",payload:{...r,message:n instanceof Error?n.message:"Unknown websocket operation failure"}})}}async handleRawMessage(e){try{await this.handleMessage(p.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",s=X(e);this.sendJson({type:"error",payload:{...s,message:r}})}}sendJson(e){this.options.socket.send(p.stringifyMessage(e))}async handleBufferedOperation(e,n,r){this.eventDispatcher.beginBuffering();try{let s=await r();this.sendJson({type:"response",payload:{id:e,kind:n,result:s}}),this.eventDispatcher.flush()}catch(s){this.sendJson({type:"error",payload:{id:e,kind:n,message:s instanceof Error?s.message:"Unknown websocket operation failure"}}),this.eventDispatcher.flush()}}},v=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)})}},k=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()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function f(t){return typeof t=="object"&&t!==null}function Q(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 X(t){try{return p.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}import{SiteEditOperationRequestSchema as ue}from"@vcp-dev/contracts";var ce="127.0.0.1",de=30218,he="/__vcp/site-edit/bridge",fe=128*1024,H="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function K(t,e){let n=new P(le(e),t,!1);return n.start({listen:!1}),n}var P=class{constructor(e,n=Y.createServer((s,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),r=!0){this.options=e,this.server=n,this.closeHttpServerOnStop=r,this.runtime=null,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.isStarted=!1}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=se({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=me({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 ae({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,on_change:r=>this.handleFileChanged(r)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=pe(),n=ge(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createBridgeEngine(){return{getDocument:async e=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(e);return n.getDocument(r)},getObjectSummary:async(e,n)=>this.getRuntime().getObjectSummary(e,n?this.resolveRouteId(n):void 0),getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let r=this.getRuntime(),s=n?this.resolveRouteId(n):void 0;return await r.refreshSourceForKey(e,s),r.getClassNameSource(e,s)},execute:async e=>this.getRuntime().executeOperation(this.normalizeRequest(e)),undo:async()=>this.getRuntime().undo(),redo:async()=>this.getRuntime().redo(),subscribe:e=>this.getRuntime().subscribe(e)}}async activateRoute(e){let n=this.getRuntime(),r=this.resolveRouteId(e);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}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.refreshRoutes(),this.runtime?.notifyFileChanged(e)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:ie(this.options.projectRoot),n=new Map(this.routes.map(s=>[s.routeId,s.entryFile])),r=new Set(e.map(s=>s.routeId));this.routes=e;for(let s of e)n.get(s.routeId)!==s.entryFile&&this.runtime?.registerRoute(s.routeId,s.entryFile);for(let s of n.keys())r.has(s)||this.runtime?.unregisterRoute(s)}resolveRouteId(e){let n=oe(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 le(t){return{siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:te.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??ce,port:t.port??de,path:t.path??he,sessionKey:t.sessionKey??Ie(),allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function pe(){let t=globalThis;return t[H]??=new Map,t[H]}function ge(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}`}function me(t){let e=new re({maxPayload:fe,noServer:!0}),n=(r,s,o)=>{if(ye(r,t)){if(!Se(r,t)){s.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),s.destroy();return}e.handleUpgrade(r,s,o,u=>{e.emit("connection",u,r)})}};return t.server.on("upgrade",n),e.on("connection",r=>{new w({socket:new j(r),engine:t.engine,validateOperationRequest:s=>ue.safeParse(s).success})}),e.stop=()=>{t.server.off("upgrade",n);for(let r of e.clients)r.close(1001,"bridge stopped");e.close()},e}var j=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){this.socket.readyState===ne.OPEN&&this.socket.send(e)}close(e,n){this.socket.close(e,n)}};function ye(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Se(t,e){let r=new URL(t.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??E(t.headers["x-vcp-site-edit-key"]);if(!be(r,e.sessionKey))return!1;let s=E(t.headers.host),o=E(t.headers.origin);return s&&!we(s,e.host,o)?!1:o?e.allowedOrigins.includes(o)||xe(o)||(s?q(o,s):!1):!0}function be(t,e){if(!t)return!1;let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&ee(n,r)}function we(t,e,n){let r=O(t),s=O(e);return r===s||r==="localhost"||r==="127.0.0.1"||r==="::1"||Re(s)&&!!(n&&q(n,t))}function Re(t){return t==="0.0.0.0"||t==="::"}function xe(t){try{let e=new URL(t);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"}catch{return!1}}function q(t,e){try{return new URL(t).host===T(e)}catch{return!1}}function O(t){let e=T(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function T(t){return t.trim().toLowerCase()}function E(t){return Array.isArray(t)?t[0]:t}function Ie(){return Z(32).toString("base64url")}var ke="next",Ee="127.0.0.1",Pe=3e3,$="/__vcp/site-edit/bridge",R="/__vcp/site-edit/client/",je=`${R}auto-bootstrap.js`,L='data-vcp-site-edit-bootstrap="true"',Ce=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function xt(t={}){let e=x.resolve(t.projectRoot??process.cwd()),n=t.host??Ee,r=t.port??et(process.env.PORT)??Pe,s=t.bridgePath??$,o=Le(),u=t.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=(await Qe(e))({dev:!0,dir:e,hostname:n,port:r,webpack:!0}),c=a.getRequestHandler();await a.prepare();let d=ve.createServer((S,b)=>{Me({basePath:u,bridgePath:s,bridgeSessionKey:o,handle:c,request:S,response:b}).catch(z=>{console.error(z),b.headersSent||(b.statusCode=500),b.end("site edit preview request failed")})}),l=K(d,{siteId:t.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:t.snapshotId??process.env.VCP_SNAPSHOT_ID??Ze(e),projectRoot:e,basePath:u,host:n,port:r,path:s,sessionKey:o});Be({server:d,bridgePath:s,handleUpgrade:a.getUpgradeHandler()});let h=()=>{l.stop(),a.close().catch(()=>{}),d.close()};return process.on("SIGINT",h),process.on("SIGTERM",h),await tt(d,r,n),{close:h,server:d}}function Be(t){let e=(n,r,s)=>{Ne(n.url,t.bridgePath)||t.handleUpgrade(n,r,s).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function Ne(t,e){return new URL(t??"/","http://localhost").pathname===e}function _e(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??He()});return`<script type="module" ${L}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(je)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function He(){return{bridge:C("@vcp-dev/site-edit-bridge"),contracts:C("@vcp-dev/contracts"),engine:C("@vcp-dev/site-edit-engine")}}function C(t){let e=D(import.meta.url);try{let n=e.resolve(t),r=Oe(n,t);if(!r)return;let s=JSON.parse(g(r,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function Oe(t,e){let n=x.parse(t).root,r=m(t);for(;r&&r!==n;){let s=I(r,"package.json");if(y(s))try{if(JSON.parse(g(s,"utf8")).name===e)return s}catch{return}r=m(r)}}function Ke(t,e){if(t.includes(L))return t;let n=_e(e),r=/<\/body\s*>/i.exec(t);return r?`${t.slice(0,r.index)}${n}${t.slice(r.index)}`:`${t}${n}`}function It(t,e=m(W(import.meta.url)),n=y){return F(t,e,n)?.path??null}function F(t,e=m(W(import.meta.url)),n=y){let r=new URL(t??"/","http://localhost").pathname;if(!r.startsWith(R))return null;let s=r.slice(R.length);if(!Ce.has(s))return null;let o=B(Xe(e),s);if(J(e)!=="src")return{path:o,requiresTranspile:!1};let u=B(e,s.replace(/\.js$/,".ts"));return n(u)?{path:u,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function qe(t,e){let n=F(t.url);if(!n)return!1;if(!y(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Te(g(n.path,"utf8")):g(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(r),!0}async function Te(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Me({basePath:t,bridgePath:e,bridgeSessionKey:n,handle:r,request:s,response:o}){if(await qe(s,o))return;let u=Ae(s),i=Ue(s),a=u||i?We(o,{basePath:t,bridgePath:e,bridgeSessionKey:n,patchNextDevChunk:i}):()=>{};try{await r(s,o)}catch(c){throw a(),c}}function Ae(t){return De(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ue(t){return Je(t)?(t.headers["accept-encoding"]="identity",!0):!1}function De(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(R)||e===$)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Je(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 We(t,e){let n=[],r=t,s=r.flushHeaders.bind(t),o=r.write.bind(t),u=r.end.bind(t);return r.flushHeaders=()=>{},r.write=(i,a,c)=>(i!==void 0&&n.push(M(i,A(a))),U(a),U(c),!0),r.end=(i,a,c)=>{let d=typeof i=="function"?void 0:i;d!==void 0&&n.push(M(d,A(a))),r.write=o,r.end=u,r.flushHeaders=s;let l=Buffer.concat(n),h=$e(t,l,e);h!==l&&!t.headersSent&&t.removeHeader("content-length");let S=typeof i=="function"?i:typeof a=="function"?a:typeof c=="function"?c:void 0;return S?u(h,S):u(h)},()=>{r.write=o,r.end=u,r.flushHeaders=s}}function $e(t,e,n){if(Fe(t,e))return Buffer.from(Ke(e.toString("utf8"),n));if(n.patchNextDevChunk&&Ve(t)){let r=e.toString("utf8"),s=ze(r);if(s!==r)return Buffer.from(s)}return e}function Le(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function Fe(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function Ve(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 ze(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
+ `),s.destroy();return}e.handleUpgrade(r,s,o,u=>{e.emit("connection",u,r)})}};return t.server.on("upgrade",n),e.on("connection",r=>{new w({socket:new j(r),engine:t.engine,validateOperationRequest:s=>ue.safeParse(s).success})}),e.stop=()=>{t.server.off("upgrade",n);for(let r of e.clients)r.close(1001,"bridge stopped");e.close()},e}var j=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){this.socket.readyState===ne.OPEN&&this.socket.send(e)}close(e,n){this.socket.close(e,n)}};function ye(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Se(t,e){let r=new URL(t.url??"/","http://localhost").searchParams.get("vcp_bridge_key")??E(t.headers["x-vcp-site-edit-key"]);if(!be(r,e.sessionKey))return!1;let s=E(t.headers.host),o=E(t.headers.origin);return s&&!we(s,e.host,o)?!1:o?e.allowedOrigins.includes(o)||xe(o)||(s?q(o,s):!1):!0}function be(t,e){if(!t)return!1;let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&ee(n,r)}function we(t,e,n){let r=O(t),s=O(e);return r===s||r==="localhost"||r==="127.0.0.1"||r==="::1"||Re(s)&&!!(n&&q(n,t))}function Re(t){return t==="0.0.0.0"||t==="::"}function xe(t){try{let e=new URL(t);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"}catch{return!1}}function q(t,e){try{return new URL(t).host===T(e)}catch{return!1}}function O(t){let e=T(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function T(t){return t.trim().toLowerCase()}function E(t){return Array.isArray(t)?t[0]:t}function Ie(){return Z(32).toString("base64url")}var ke="next",Ee="127.0.0.1",Pe=3e3,$="/__vcp/site-edit/bridge",R="/__vcp/site-edit/client/",je=`${R}auto-bootstrap.js`,L='data-vcp-site-edit-bootstrap="true"',Ce=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function xt(t={}){let e=x.resolve(t.projectRoot??process.cwd()),n=t.host??Ee,r=t.port??et(process.env.PORT)??Pe,s=t.bridgePath??$,o=Le(),u=t.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=(await Qe(e))({dev:!0,dir:e,hostname:n,port:r,turbopack:!0}),c=a.getRequestHandler();await a.prepare();let d=ve.createServer((S,b)=>{Me({basePath:u,bridgePath:s,bridgeSessionKey:o,handle:c,request:S,response:b}).catch(z=>{console.error(z),b.headersSent||(b.statusCode=500),b.end("site edit preview request failed")})}),l=K(d,{siteId:t.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:t.snapshotId??process.env.VCP_SNAPSHOT_ID??Ze(e),projectRoot:e,basePath:u,host:n,port:r,path:s,sessionKey:o});Be({server:d,bridgePath:s,handleUpgrade:a.getUpgradeHandler()});let h=()=>{l.stop(),a.close().catch(()=>{}),d.close()};return process.on("SIGINT",h),process.on("SIGTERM",h),await tt(d,r,n),{close:h,server:d}}function Be(t){let e=(n,r,s)=>{Ne(n.url,t.bridgePath)||t.handleUpgrade(n,r,s).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function Ne(t,e){return new URL(t??"/","http://localhost").pathname===e}function _e(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??He()});return`<script type="module" ${L}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(je)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function He(){return{bridge:C("@vcp-dev/site-edit-bridge"),contracts:C("@vcp-dev/contracts"),engine:C("@vcp-dev/site-edit-engine")}}function C(t){let e=D(import.meta.url);try{let n=e.resolve(t),r=Oe(n,t);if(!r)return;let s=JSON.parse(g(r,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function Oe(t,e){let n=x.parse(t).root,r=m(t);for(;r&&r!==n;){let s=I(r,"package.json");if(y(s))try{if(JSON.parse(g(s,"utf8")).name===e)return s}catch{return}r=m(r)}}function Ke(t,e){if(t.includes(L))return t;let n=_e(e),r=/<\/body\s*>/i.exec(t);return r?`${t.slice(0,r.index)}${n}${t.slice(r.index)}`:`${t}${n}`}function It(t,e=m(W(import.meta.url)),n=y){return F(t,e,n)?.path??null}function F(t,e=m(W(import.meta.url)),n=y){let r=new URL(t??"/","http://localhost").pathname;if(!r.startsWith(R))return null;let s=r.slice(R.length);if(!Ce.has(s))return null;let o=B(Xe(e),s);if(J(e)!=="src")return{path:o,requiresTranspile:!1};let u=B(e,s.replace(/\.js$/,".ts"));return n(u)?{path:u,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function qe(t,e){let n=F(t.url);if(!n)return!1;if(!y(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Te(g(n.path,"utf8")):g(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(r),!0}async function Te(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Me({basePath:t,bridgePath:e,bridgeSessionKey:n,handle:r,request:s,response:o}){if(await qe(s,o))return;let u=Ae(s),i=Ue(s),a=u||i?We(o,{basePath:t,bridgePath:e,bridgeSessionKey:n,patchNextDevChunk:i}):()=>{};try{await r(s,o)}catch(c){throw a(),c}}function Ae(t){return De(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ue(t){return Je(t)?(t.headers["accept-encoding"]="identity",!0):!1}function De(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(R)||e===$)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Je(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 We(t,e){let n=[],r=t,s=r.flushHeaders.bind(t),o=r.write.bind(t),u=r.end.bind(t);return r.flushHeaders=()=>{},r.write=(i,a,c)=>(i!==void 0&&n.push(M(i,A(a))),U(a),U(c),!0),r.end=(i,a,c)=>{let d=typeof i=="function"?void 0:i;d!==void 0&&n.push(M(d,A(a))),r.write=o,r.end=u,r.flushHeaders=s;let l=Buffer.concat(n),h=$e(t,l,e);h!==l&&!t.headersSent&&t.removeHeader("content-length");let S=typeof i=="function"?i:typeof a=="function"?a:typeof c=="function"?c:void 0;return S?u(h,S):u(h)},()=>{r.write=o,r.end=u,r.flushHeaders=s}}function $e(t,e,n){if(Fe(t,e))return Buffer.from(Ke(e.toString("utf8"),n));if(n.patchNextDevChunk&&Ve(t)){let r=e.toString("utf8"),s=ze(r);if(s!==r)return Buffer.from(s)}return e}function Le(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function Fe(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),r=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(r===""||r.includes("text/html"))}function Ve(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 ze(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,[r,s])=>Ge(n,r,s),t)}function Ge(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 M(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function A(t){return typeof t=="string"?t:void 0}function U(t){typeof t=="function"&&t()}async function Qe(t){let n=D(I(t,"package.json"))(ke);return n.default??n}function Xe(t){return J(t)!=="src"?t:B(Ye(t),"dist")}function Ye(t){return V(t)?x.posix.dirname(t):m(t)}function B(t,e){return V(t)?x.posix.join(t,e):I(t,e)}function V(t){return t.includes("/")&&!t.includes("\\")}function Ze(t){let e=I(t,".vcp/current-snapshot.json");if(!y(e))return"sandbox_worktree";try{let n=JSON.parse(g(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function et(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function tt(t,e,n){return new Promise((r,s)=>{t.once("error",s),t.listen(e,n,()=>{t.off("error",s),r()})})}export{Be as attachNextDevUpgradeHandler,_e as createSiteEditAutoBootstrapHtmlSnippet,Ke as injectSiteEditAutoBootstrap,ze as patchNextFirefoxDevChunk,Ue as prepareFirefoxNextDevChunkPatchRequest,Ae as prepareSiteEditHtmlInjectionRequest,F as resolveSiteEditClientAsset,It as resolveSiteEditClientAssetPath,xt as startSiteEditNextDevServer,Te as transpileSiteEditClientSource};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-bridge",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
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.3.14",
78
- "@vcp-dev/site-edit-engine": "0.3.14",
77
+ "@vcp-dev/contracts": "0.3.15",
78
+ "@vcp-dev/site-edit-engine": "0.3.15",
79
79
  "@types/ws": "^8.18.1",
80
80
  "ws": "^8.20.1"
81
81
  },