@vcp-dev/site-edit-bridge 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 c=t.get(a);if(typeof c=="number")return c;let d=n.length;return n.push(a),t.set(a,d),d},i=a=>{let c=null;for(let d of Et(a)){let p=`${c??"root"}\0${d}`,h=r.get(p);if(typeof h=="number"){c=h;continue}let v=o.length;o.push({parent:c,token:s(d)}),r.set(p,v),c=v}if(c===null)throw new Error("Document key must not be empty");return c};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=_e(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=_e(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 _e(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}}},Q=class{constructor(t){this.options=t,this.messageQueue=new ue,this.eventDispatcher=new ce(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()}}},ce=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",xt="designer_trace",ke="__VCP_DESIGNER_TRACE__";var _t=/(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(xt)==="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[ke]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[ke]=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(_t.test(r)){n[r]="[redacted]";continue}n[r]=le(o,t+1)}return n}var Z=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:Ne(n.request,"kind"),documentVersion:Ne(n.request,"documentVersion")}),new Promise((i,a)=>{this.pending.set(o,{kind:t,resolve:c=>i(c),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:kt(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 Ne(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function kt(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 Nt(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 Nt(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",Lr=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 $(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",jt=1e3,Bt="data-vcp-ui-component",Ve="data-vcp-theme-preview",je="::repeat-item#",L="components/ui",Mt=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 ro(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 Z({url:l})),o=t.schedule_after_navigation??Yt,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]))},c=async(l,R)=>{let y=e.__VCP_SITE_EDIT__;if(!y)return null;let b=await y.getDocument(l);return R!==n.routeSequence||l!==e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId||a(b.data),b.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 y=r(s);try{if(await y.connect(),R!==n.routeSequence){y.disconnect();return}e.__VCP_SITE_EDIT__=Pe({routeId:l,client:y,initialDocument:Vt(l)}),n.activeClient=y,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(k=>{k.type==="site-edit.document.changed"&&k.routeId===l&&c(l,R).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=l;let b=await c(l,R);qt(e,{documentVersion:b?.version??0,routeId:l,versions:t.runtime_versions}),Jt(e,{routeId:l,version:b?.version??0})}catch(b){throw y.disconnect(),b}},h=()=>{i(),n.retryTimer=e.setTimeout(()=>{p().catch(()=>h())},jt)},v=()=>{o(()=>{p().catch(()=>h())})};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=zt(e,v),t.defer_initial_sync){v();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,c=new Map,d=()=>{n?.(),n=null},p=()=>{r?.(),r=null,o?.(),o=null},h=(I,f,u)=>{let _=s?.sessionKey!==I||s?.sourceWindow!==f||s?.targetOrigin!==u;s={sessionKey:I,sourceWindow:f,targetOrigin:u},_&&(a=null)},v=()=>{for(let I of c.values())I();c.clear()},l=I=>{i=I.routeId==="/"?null:I;let f=`${I.routeId}:${I.version}`;a!==f&&(o?.(),o=null,y({kind:"route-ready",payload:{routeId:I.routeId,version:I.version}}),s&&(a=f))},R=()=>{i&&l(i)},y=I=>{s&&s.sourceWindow.postMessage($({type:"event",...I},{sessionKey:s.sessionKey}),s.targetOrigin)},b=(I,f,u,_)=>{let x=ne(e.document,f.clientX,f.clientY),C=x?P(x,u==="full"?O(e.document,x,t.getCurrentDocument?.()??null):Me(e.document,x,t.getCurrentDocument?.()??null),t.getDocumentEntry,u):null;_&&C&&(I==="pointer-click"||I==="pointer-double-click")&&(_.preventDefault(),_.stopPropagation(),typeof _.stopImmediatePropagation=="function"&&_.stopImmediatePropagation()),y({kind:I,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:C}})},k=(I,f,u)=>{p(),s={sessionKey:I,sourceWindow:f,targetOrigin:u};let _=An(e.document),x=null,C=null,g=()=>{C=null;let m=x;x=null,m&&b("pointer-move",m,"summary")},N=m=>{x={clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},C===null&&(C=Ue(e,g))},j=m=>{b("pointer-down",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},K=m=>{b("pointer-up",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"summary",m)},A=m=>{b("pointer-cancel",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"summary",m)},M=m=>{b("pointer-click",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},U=m=>{b("pointer-double-click",{clientX:Number(m.clientX),clientY:Number(m.clientY),buttons:Number(m.buttons)},"full",m)},H=()=>{y({kind:"scroll",payload:{metrics:te(e)}})};e.document.addEventListener("pointerdown",j,!0),e.document.addEventListener("pointermove",N,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",K,!0),e.document.addEventListener("pointercancel",A,!0),e.document.addEventListener("click",M,!0),e.document.addEventListener("dblclick",U,!0),e.addEventListener("scroll",H,{passive:!0}),r=()=>{C!==null&&(He(e,C),C=null),x=null,_(),e.document.removeEventListener("pointerdown",j,!0),e.document.removeEventListener("pointermove",N,!0),e.document.removeEventListener("pointerup",K,!0),e.document.removeEventListener("pointercancel",A,!0),e.document.removeEventListener("click",M,!0),e.document.removeEventListener("dblclick",U,!0),e.removeEventListener("scroll",H)}},Re=I=>{let f=I.detail;f?.routeId&&l(f)},xe=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 u=f.body,_=typeof f.sessionKey=="string"?f.sessionKey:null,x=I.source,C=I.origin;if(!_||!C||!x||typeof x.postMessage!="function"||s&&(s.sessionKey!==_||s.sourceWindow!==x||s.targetOrigin!==C))return;h(_,x,C),R();let g=N=>{let j=typeof u.id=="string"?u.id:"unknown";x.postMessage($({id:j,...N},{sessionKey:_}),C)};try{if(Be(u)){Ht({message:u,sendEvent:S=>{x.postMessage($({type:"event",...S},{sessionKey:_}),C)},sendResponse:g,subscriptions:c,getCurrentDocument:t.getCurrentDocument,windowLike:e});return}if(u.kind==="apply-node-patch"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for patch target"});return}let E=u.payload.preview,T=E?Sn(E.sessionId,u.payload.ref):null;if(T&&E){let X=G.get(T)??-1;if(E.revision<X){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:E.revision,stale:!0,latestRevision:X}});return}if(E.revision===X){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:E.revision,duplicate:!0,latestRevision:X}});return}}if(yn(S,u.payload.patch),T&&E&&En(T,E.revision),E?.responseDetail==="none"){g({type:"response",ok:!0,result:{applied:!0,appliedRevision:E.revision}});return}g({type:"response",ok:!0,result:P(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,E?.responseDetail??"full")});return}if(u.kind==="get-hit-by-ref"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for hit target"});return}g({type:"response",ok:!0,result:P(S,O(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(u.kind==="get-path-by-ref"){let S=q(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for path target"});return}let E=[],T=S;for(;T;)T.getAttribute("data-vcp-edit-key")&&E.push(P(T,O(e.document,T,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),T=T.parentElement;g({type:"response",ok:!0,result:E.reverse()});return}if(u.kind==="get-scroll-metrics"){g({type:"response",ok:!0,result:te(e)});return}if(u.kind==="scroll-to"){let S=Number(u.payload.x),E=Number(u.payload.y);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:S,top:E}),g({type:"response",ok:!0,result:te(e)});return}if(u.kind==="scroll-by"){let S=Number(u.payload.deltaX),E=Number(u.payload.deltaY);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:S,top:E}),g({type:"response",ok:!0,result:{...te(e),scrolled:!0}});return}if(u.kind==="set-interaction-mode"){u.payload.enabled?k(_,x,C):s?.sourceWindow===x&&s.targetOrigin===C&&s.sessionKey===_&&p(),g({type:"response",ok:!0,result:{interactionEnabled:u.payload.enabled}});return}if(u.kind==="set-theme-override"){vn(e.document,u.payload),g({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(u.kind==="clear-theme-override"){In(e.document),g({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(u.kind==="get-theme-variables"){g({type:"response",ok:!0,result:Rn(e.document,u.payload.names)});return}if(u.kind==="compute-drop-target-at-point"){let S=Number(u.payload?.x),E=Number(u.payload?.y);if(!Number.isFinite(S)||!Number.isFinite(E)){g({type:"response",ok:!1,error:"Invalid drop target point"});return}g({type:"response",ok:!0,result:pn(e,S,E,u.payload.dragKind,u.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(u.kind==="observe-node-bounds"){let S=u.payload.ref;if(!S){g({type:"response",ok:!1,error:"Missing bounds observer target"});return}let E=q(e.document,S,t.getCurrentDocument?.()??null);if(!E){g({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=dn(e,E,S,t.getDocumentEntry,T=>y({kind:"node-bounds-change",payload:{hit:T}})),g({type:"response",ok:!0,result:{observing:!0}}),y({kind:"node-bounds-change",payload:{hit:P(E,S,t.getDocumentEntry,"summary")}});return}if(u.kind==="clear-node-bounds-observer"){o?.(),o=null,g({type:"response",ok:!0,result:{cleared:!0}});return}if(u.kind!=="hit-test-at-point"&&u.kind!=="start-text-edit-at-point")return;let N=Number(u.payload?.x),j=Number(u.payload?.y);if(!Number.isFinite(N)||!Number.isFinite(j)){g({type:"response",ok:!1,error:"Invalid text edit point"});return}let K=u.kind==="hit-test-at-point"?ne(e.document,N,j):Zt(e.document,N,j,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!K){g({type:"response",ok:!1,error:u.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let A=u.kind==="start-text-edit-at-point"?K:null,M=u.kind==="hit-test-at-point"?K:A.element,U=u.payload.detailLevel??"full",H=U==="full"?O(e.document,M,t.getCurrentDocument?.()??null):Me(e.document,M,t.getCurrentDocument?.()??null),m=A&&typeof A.textSegmentIndex=="number"?{...H,textSegmentIndex:A.textSegmentIndex}:H,bt=P(M,m,t.getDocumentEntry,U);if(u.kind==="hit-test-at-point"){g({type:"response",ok:!0,result:bt});return}d(),n=Tn(e,M,m,S=>{x.postMessage($({type:"event",...S},{sessionKey:_}),C)},A?{textNode:A.textNode}:void 0),g({type:"response",ok:!0,result:{ref:m}})}catch(N){g({type:"response",ok:!1,error:N instanceof Error?N.message:"Failed to start text edit"})}};return e.addEventListener("message",xe),e.addEventListener(he,Re),()=>{d(),p(),s=null,v(),e.removeEventListener("message",xe),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 c=i.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:a}})});r.set(a,c),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 zt(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 Yt(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 Mt.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=ne(e,t,n),i=ze(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=O(e,i,r),d=o?.(c.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 h=Lt(e,t,n,i);if(!h)return null;let v=tn(i,h);return v===null?null:{element:i,textNode:h,textSegmentIndex:v}}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 ne(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=ze(o);if(s)return s}return null}function ze(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===L||t.startsWith(`${L}/`)||t.includes(`/${L}/`)||t.endsWith(`/${L}`)}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 Me(e,t,n){return O(e,t,n)}function q(e,t,n){let r=re(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=(re(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 Ye(e,t)[n]?.key??t}function sn(e,t){let n=re(t);if(!n)return null;let o=Ye(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function Ye(e,t){return(e?.entries??[]).filter(n=>(re(n.key)??n.key)===t)}var an=2,cn=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&cn)!==0?-1:(r&an)!==0?1:0})}function re(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(je);if(n<0)break;let r=Number(t.slice(n+je.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function un(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=oe(e),c=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),h=!!(s&&/^[A-Z]/.test(s.tag)),v=!s||!h;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:h?"component-call":"jsx"}:{},...h&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:d.canMove,removable:d.canRemove,textEditable:d.canUpdateText,container:p?!1:(s?.childKeys.length??0)>0||d.canInsertChild||v&&ye(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:ln(e),spacing:un(e)}}function dn(e,t,n,r,o){let s=ge(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=Ue(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let l=ge(t.getBoundingClientRect());fn(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 h=e.MutationObserver,v=typeof h=="function"?new h(a):null;return v?.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(),v?.disconnect(),e.document.removeEventListener("load",a,!0)}}function ge(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,c=ne(a,t,n);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let d=o?q(a,o,s):null;if(d&&We(c,d))return ee(a,c,"self-or-descendant",s,i);let p=null,h=!1,v=c,l=c.parentElement;for(;l;){if(l.getAttribute("data-vcp-edit-key")){if(d&&We(l,d))return ee(a,c,"self-or-descendant",s,i);let y=Ke(l,r,i);if(y==="accept"){p={child:v,targetParent:l};break}y==="blocked"&&(h=!0),v=l}l=l.parentElement}let R=Ke(c,r,i);if(R==="accept"){if(p){let y=qe(p.child,p.targetParent,t,n,"edge");if(y)return fe(a,p.child,p.targetParent,y,s,i)}return fe(a,c,c,hn(c,t,n),s,i)}if(p){let y=qe(p.child,p.targetParent,t,n,"nearest");return fe(a,p.child,p.targetParent,y??"after",s,i)}return R==="blocked"||h?ee(a,c,"operation-boundary-blocked",s,i):ee(a,c,"no-accepting-parent",s,i)}function ee(e,t,n,r,o){return{anchorHit:P(t,O(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function fe(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"),c=oe(n).indicatorOrientation,d=r==="append"||r==="prepend"?mn(n.getBoundingClientRect(),c,r):gn(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,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=oe(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=oe(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 oe(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 te(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,G=new Map;function Sn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function En(e,t){if(G.size>=bn){let n=G.keys().next().value;n&&G.delete(n)}G.set(e,t)}var z=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 z)r.has(o)||n?.removeProperty(o);z.clear();for(let o of r)z.add(o);Cn(e,t.stylesheets??[])}function In(e){let t=e.documentElement?.style;for(let n of z)t?.removeProperty(n);z.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=xn(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 xn(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=_n(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 _n(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?kn(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??"",c=Nn(i),d=!1,p=()=>{e.document.removeEventListener("pointerdown",v,!0),i.removeEventListener("keydown",l),i.removeEventListener("blur",R),i.removeEventListener("input",y),Dn(i,c)},h=b=>{if(d)return;d=!0;let k=i.textContent??"";if(p(),b==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(k),b==="commit"&&k!==a){r({kind:"text-edit-commit",payload:{ref:n,value:k}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function v(b){let k=b.target;k&&i.contains(k)||h("commit")}function l(b){if(b.key==="Escape"){b.preventDefault(),h("cancel");return}b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),h("commit"))}function R(){h("commit")}function y(){r({kind:"text-edit-input",payload:{ref:n,hit:P(t,n,void 0,"full")}})}return Pn(i),e.document.addEventListener("pointerdown",v,!0),i.addEventListener("keydown",l),i.addEventListener("blur",R),i.addEventListener("input",y),Fn(i),jn(i,e.document),p}function kn(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 Nn(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){pe(e,"contenteditable",t.contentEditable),pe(e,"spellcheck",t.spellcheck),pe(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 pe(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 jn(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 Mn,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 zn="127.0.0.1",Yn=30218,Jn="/__vcp/site-edit/bridge",Xn=128*1024,et="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function mo(e){let t=rt(e),n=st(t),r=ot(),o=r.get(n);if(o)return o;let s=new se(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 se(rt(t),e,!1);return n.start({listen:!1}),n}var se=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??zn,port:e.port??Yn,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 Ge(e){let t=new Map,n=[],r=new Map,o=[],s=a=>{let c=t.get(a);if(typeof c=="number")return c;let l=n.length;return n.push(a),t.set(a,l),l},i=a=>{let c=null;for(let l of Gt(a)){let d=`${c??"root"}\0${l}`,m=r.get(d);if(typeof m=="number"){c=m;continue}let E=o.length;o.push({parent:c,token:s(l)}),r.set(d,E),c=E}if(c===null)throw new Error("Document key must not be empty");return c};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 ze(e){if(!$t(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 $t(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function Gt(e){if(!e)return[];let t=[],n=0,r=$e(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=$e(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 $e(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var A=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==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!q(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?q(t.payload)&&typeof t.payload.id=="string":t.type==="event"?q(t.payload)&&q(t.payload.event):t.type==="auth"?q(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?q(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!q(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":case"resolve-source-location":return typeof t.key=="string"&&(t.routeId===void 0||typeof t.routeId=="string");case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return zt(t.request)&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return!0}}},le=class{constructor(t){this.options=t,this.messageQueue=new _e,this.eventDispatcher=new Ie(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:Ge((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"get-source-tree":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:o,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId: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=A.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(A.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",o=Jt(t);this.sendJson({type:"error",payload:{...o,message:r}})}}sendJson(t){this.options.socket.send(A.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()}}},Ie=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)})}},_e=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 q(e){return typeof e=="object"&&e!==null}function zt(e){return q(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"&&q(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&q(e.params)}function Jt(e){try{return A.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var Yt="vcp:designer:trace",Xt="designer_trace",Je="__VCP_DESIGNER_TRACE__";var Qt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Zt(e=globalThis){let t=e;try{if(t.localStorage?.getItem(Yt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Xt)==="1"}catch{return!1}}function U(e,t={},n=globalThis){if(!Zt(n))return;let r={type:e,timestamp:Date.now(),payload:Lt(t)},o=n,s=o[Je]??[];s.push(r),s.length>200&&s.splice(0,s.length-200),o[Je]=s;let i=n.console?.debug;typeof i=="function"&&i.call(n.console,"[designer-trace]",r)}function Lt(e){return Re(e,0)}function Re(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Re(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Qt.test(r)){n[r]="[redacted]";continue}n[r]=Re(o,t+1)}return n}var de=class{constructor(t){this.options=t,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===Ce&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((t,n)=>{let r;try{r=this.createSocket(this.options.url)}catch(a){let c=te(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let o={socket:r,settled:!1,reject:n};this.connectAttempt=o,this.socket=r;let s=()=>{this.socket!==r||this.connectAttempt!==o||(o.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},i=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(A.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){i(te(a,"WebSocket auth failed"),"failed")}return}s()}},r.onerror=a=>{if(this.socket!==r)return;let c=te(a,"WebSocket failed");i(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===o&&!o.settled){this.handleAuthHandshakeMessage(a.data,r,o,()=>{s()});return}this.handleMessage(a.data)}},r.onclose=()=>{if(this.socket!==r)return;let a=this.intentionalClose,c=new Error(a?"WebSocket disconnected":"WebSocket closed");i(c,a?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let t=this.socket;if(!t){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(t,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(t){return this.connectionStatusListeners.add(t),t({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(t)}}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})}getSourceTree(){return this.request("get-source-tree",{})}getSourceFile(t){return this.request("get-source-file",t)}resolveSourceLocation(t){return this.request("resolve-source-location",t)}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||r.readyState!==Ce||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let o=`${t}-${this.sequence+=1}`,s=sn(o,t,n);return U("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Ye(n.request,"kind"),documentVersion:Ye(n.request,"documentVersion")}),new Promise((i,a)=>{let c=this.resolveRequestTimeoutMs(t),l=c>0?setTimeout(()=>{let d=this.pending.get(o);d&&(this.pending.delete(o),U("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;l?.unref?.(),this.pending.set(o,{kind:t,timeout:l,resolve:d=>i(d),reject:a});try{r.send(A.stringifyMessage(s))}catch(d){let m=te(d,"WebSocket send failed");this.clearPendingRequest(o),a(m),this.cleanupSocket(r,m,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(A.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(s){let i=te(s,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,i,"failed")}}handleMessage(t){let n=A.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.clearPendingRequest(n.payload.id),n.type==="error"){U("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}U("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:rn(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:ze(n.payload.result.data)}:n.payload.result)}}rejectAll(t){for(let[n,r]of[...this.pending])this.clearPendingRequest(n),r.reject(t)}clearPendingRequest(t){let n=this.pending.get(t);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(t))}resolveRequestTimeoutMs(t){let n=this.options.requestTimeoutMsByKind?.[t];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):nn[t]??tn}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let o=this.connectAttempt;this.connectAttempt=null,o.settled||(o.settled=!0,o.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(r,n.message),t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null;try{(t.readyState===en||t.readyState===Ce)&&t.close()}catch{}}setConnectionState(t,n){if(this.connectionState===t&&!n)return;this.connectionState=t;let r={state:t,...n?{message:n}:{}};this.options.onConnectionStatus?.(r);for(let o of this.connectionStatusListeners)o(r)}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)}},en=0,Ce=1,tn=15e3,nn={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function te(e,t){return e instanceof Error?e:new Error(t)}function Ye(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function rn(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 Xe(e){return new xe(e)}var xe=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,an(r)])),this.editContextCache=new Map(Object.entries(t.initialDetails??{}).map(([n,r])=>[n,cn(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 on(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 getSourceTree(){return this.params.client.getSourceTree()}async getSourceFile(t){return this.params.client.getSourceFile(t)}async resolveSourceLocation(t){return this.params.client.resolveSourceLocation({...t,routeId:t.routeId??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 U("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){U("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}U("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 on(e){return e.version===0&&e.rootKeys.length===0}function sn(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"get-source-tree":return{type:"request",payload:{id:e,kind:t}};case"get-source-file":return{type:"request",payload:{id:e,kind:t,path:String(n.path)}};case"resolve-source-location":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 an(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 cn(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 Qe="vcp-window-message",Ao=1;function un(e){return{source:Qe,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function ln(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===Qe&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var Ze="site-edit",Le="frame-runtime";function ne(e,t={}){return un({namespace:Ze,channel:Le,sessionKey:t.sessionKey,body:e})}function et(e){return!ln(e)||e.namespace!==Ze||e.channel!==Le?!1:typeof e.body?.type=="string"}var Pe="vcp-site-edit:route-ready",Ne="vcp-site-edit:bridge-status",tt=1e3,dn="data-vcp-ui-component",ut="data-vcp-theme-preview",nt="::repeat-item#",fe="components/ui",fn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),pn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function pe(e,t=""){let n=kn(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function hn(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 mn(e,t={}){if(t.explicit_ws_url)return t.explicit_ws_url.startsWith("/")?`${e.location.protocol==="https:"?"wss:":"ws:"}//${e.location.host}${t.explicit_ws_url}`:t.explicit_ws_url;let n=e.location.protocol==="https:"?"wss:":"ws:",r=t.port?`${e.location.hostname}:${t.port}`:e.location.host;return`${n}//${r}${t.path??"/__vcp/site-edit/bridge"}`}async function Mo(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,unsubscribeConnectionStatus:void 0,unbindRouteChange:void 0},r=t.create_client??(h=>new de({url:h,authKey:t.bridge_session_key})),o=t.schedule_after_navigation??In,s=mn(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),i=()=>{n.retryTimer&&(e.clearTimeout(n.retryTimer),n.retryTimer=void 0)},a=h=>{Rn(e,h)},c=h=>{n.currentDocument=h,n.currentEntriesByKey=new Map((h?.entries??[]).map(y=>[y.key,y]))},l=()=>{n.unsubscribeConnectionStatus?.(),n.unsubscribeConnectionStatus=void 0,n.unsubscribeDocument?.(),n.unsubscribeDocument=void 0},d=(h,y)=>y===n.routeSequence&&h===pe(e.location.pathname,t.basePath||""),m=async(h,y)=>{let _=e.__VCP_SITE_EDIT__;if(!_)return null;let C=await _.getDocument(h);return d(h,y)&&c(C.data),C.data},E=()=>{l(),c(null),delete e.__VCP_SITE_EDIT__;let h=n.activeClient;n.activeClient=null,h?.disconnect()},b=h=>h===e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__?.routeId&&!!e.__VCP_SITE_EDIT__&&!!(n.currentDocument&&xn(n.currentDocument,h))&&Cn(n.activeClient),D=h=>Math.min(tt*2**Math.max(0,h),8e3),R=(h,y,_)=>{i();let C=D(_);a({state:"reconnecting",routeId:h,attempt:_,retryInMs:C,messageKey:"studio.status.previewBridgeConnecting"}),n.retryTimer=e.setTimeout(()=>{y===n.routeSequence&&X(_+1).catch(B=>{let k=pe(e.location.pathname,t.basePath||"");if(h===k){if(he(B)){a({state:"reload-required",routeId:h,attempt:_,messageKey:"studio.errors.previewBridgeReloadRequired"});return}R(h,n.routeSequence,_+1)}})},C)},T=(h,y,_)=>{if(!d(h,y)||n.activeClient===null)return;let C=n.activeClient;l(),c(null),delete e.__VCP_SITE_EDIT__,n.activeClient=null,C?.disconnect(),R(h,y,0)},K=h=>{let y=pe(e.location.pathname,t.basePath||""),_=n.routeSequence;if(!(!d(y,_)||n.activeClient===null)){if(he(h)){E(),i(),a({state:"reload-required",routeId:y,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}ft(h)&&T(y,_,{state:"failed",message:Oe(h,"Site edit bridge request failed")})}};n.cleanupFrameRuntime=yn(e,{getCurrentDocument:()=>n.currentDocument,getDocumentEntry:h=>n.currentEntriesByKey.get(h)??null,onBridgeRequestError:h=>{K(h)}});let Y=async()=>X(0),X=async h=>{let y=pe(e.location.pathname,t.basePath||"");if(b(y))return;let _=n.routeSequence+=1;i(),E(),a({state:h>0?"reconnecting":"connecting",routeId:y,attempt:h,messageKey:h>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let C=r(s),B=!1;n.activeClient=C,n.unsubscribeConnectionStatus=C.subscribeConnectionStatus?.(k=>{B&&(k.state==="closed"||k.state==="failed")&&T(y,_,k)});try{if(await C.connect(),!d(y,_)){C.disconnect();return}e.__VCP_SITE_EDIT__=Xe({routeId:y,client:C,initialDocument:gn(y)}),n.activeClient=C,n.unsubscribeDocument=e.__VCP_SITE_EDIT__.subscribe(ce=>{ce.type==="site-edit.document.changed"&&ce.routeId===y&&m(y,_).catch(()=>{})}),e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__.routeId=y;let k=await m(y,_);if(!d(y,_)){C.disconnect();return}B=!0,a({state:"ready",routeId:y,attempt:h,messageKey:"studio.status.previewReady"}),hn(e,{documentVersion:k?.version??0,routeId:y,versions:t.runtime_versions}),_n(e,{routeId:y,version:k?.version??0})}catch(k){if(l(),n.activeClient===C&&(n.activeClient=null),C.disconnect(),c(null),delete e.__VCP_SITE_EDIT__,!d(y,_))return;throw a({state:he(k)?"reload-required":"failed",routeId:y,attempt:h,messageKey:he(k)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),k}},Q=()=>{i(),n.retryTimer=e.setTimeout(()=>{X(1).catch(()=>Q())},tt)},Z=()=>{o(()=>{Y().catch(()=>Q())})};if(e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__={started:!0,syncRoute:Y,cleanup:()=>{i(),n.routeSequence+=1,n.unbindRouteChange?.(),n.cleanupFrameRuntime(),E(),delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__}},n.unbindRouteChange=vn(e,Z),t.defer_initial_sync){Z();return}await Y()}function gn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,rootKeys:[],entries:[]}}function yn(e=window,t={}){let n=null,r=null,o=null,s=null,i=null,a=null,c=null,l=null,d=new Map,m=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,E=()=>{n?.(),n=null},b=()=>{r?.(),r=null,o?.(),o=null},D=(p,f,u)=>{let P=s?.sessionKey!==p||s?.sourceWindow!==f||s?.targetOrigin!==u;s={sessionKey:p,sourceWindow:f,targetOrigin:u},P&&(c=null,l=null)},R=(p,f)=>{let u=e.parent&&e.parent!==e?e.parent:null;return!u||f!==u?!1:!m||p===m},T=()=>{for(let p of d.values())p();d.clear()},K=p=>JSON.stringify([p.routeId,p.version]),Y=()=>!a||a.state==="ready",X=p=>JSON.stringify([p.state,p.routeId??null,p.attempt??null,p.retryInMs??null,p.messageKey??null]),Q=p=>{if(!Y())return;let f=K(p);c!==f&&(o?.(),o=null,B({kind:"route-ready",payload:{routeId:p.routeId,version:p.version}}),s&&(c=f))},Z=p=>{let f=X(p);l!==f&&(p.state!=="ready"&&(c=null,i=null),B({kind:"bridge-status",payload:p}),s&&(l=f))},h=p=>{i=p,Q(p)},y=p=>{a=p,Z(p)},_=()=>{i&&Q(i)},C=()=>{a&&Z(a)},B=p=>{s&&s.sourceWindow.postMessage(ne({type:"event",...p},{sessionKey:s.sessionKey}),s.targetOrigin)},k=(p,f,u,P)=>{let x=ye(e.document,f.clientX,f.clientY,t.getCurrentDocument?.()??null),N=x?M(x,u==="full"?w(e.document,x,t.getCurrentDocument?.()??null):ot(e.document,x,t.getCurrentDocument?.()??null),t.getDocumentEntry,u):null;P&&N&&(p==="pointer-click"||p==="pointer-double-click")&&(P.preventDefault(),P.stopPropagation(),typeof P.stopImmediatePropagation=="function"&&P.stopImmediatePropagation()),B({kind:p,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:N}})},ce=(p,f,u)=>{b(),s={sessionKey:p,sourceWindow:f,targetOrigin:u};let P=dr(e.document),x=null,N=null,S=()=>{N=null;let g=x;x=null,g&&k("pointer-move",g,"summary")},F=g=>{x={clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},N===null&&(N=lt(e,S))},V=g=>{k("pointer-down",{clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},"full",g)},$=g=>{k("pointer-up",{clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},"summary",g)},W=g=>{k("pointer-cancel",{clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},"summary",g)},H=g=>{k("pointer-click",{clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},"full",g)},L=g=>{k("pointer-double-click",{clientX:Number(g.clientX),clientY:Number(g.clientY),buttons:Number(g.buttons)},"full",g)},ee=()=>{B({kind:"scroll",payload:{metrics:ge(e)}})};e.document.addEventListener("pointerdown",V,!0),e.document.addEventListener("pointermove",F,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",$,!0),e.document.addEventListener("pointercancel",W,!0),e.document.addEventListener("click",H,!0),e.document.addEventListener("dblclick",L,!0),e.addEventListener("scroll",ee,{passive:!0}),r=()=>{N!==null&&(dt(e,N),N=null),x=null,P(),e.document.removeEventListener("pointerdown",V,!0),e.document.removeEventListener("pointermove",F,!0),e.document.removeEventListener("pointerup",$,!0),e.document.removeEventListener("pointercancel",W,!0),e.document.removeEventListener("click",H,!0),e.document.removeEventListener("dblclick",L,!0),e.removeEventListener("scroll",ee)}},Ve=p=>{let f=p.detail;f?.routeId&&h(f)},Ue=p=>{let f=p.detail;f?.state&&y(f)},He=p=>{let f=p.data;if(!et(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"&&!rt(f.body))return;let u=f.body,P=typeof f.sessionKey=="string"?f.sessionKey:null,x=p.source,N=p.origin;if(!P||!N||!x||typeof x.postMessage!="function"||!R(P,x))return;if(s){if(s.sourceWindow!==x||s.targetOrigin!==N)return;s.sessionKey!==P&&(E(),b(),T(),s=null)}D(P,x,N),C(),_();let S=F=>{let V=typeof u.id=="string"?u.id:"unknown";x.postMessage(ne({id:V,...F},{sessionKey:P}),N)};try{if(rt(u)){bn({message:u,sendEvent:v=>{x.postMessage(ne({type:"event",...v},{sessionKey:P}),N)},sendResponse:S,subscriptions:d,getCurrentDocument:t.getCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(u.kind==="apply-node-patch"){let v=G(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let I=u.payload.preview,O=I?Qn(I.sessionId,u.payload.ref):null;if(O&&I){let ue=re.get(O)??-1;if(I.revision<ue){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,stale:!0,latestRevision:ue}});return}if(I.revision===ue){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:I.revision,duplicate:!0,latestRevision:ue}});return}}if(Yn(v,u.payload.patch),O&&I&&Zn(O,I.revision),I?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:I.revision}});return}S({type:"response",ok:!0,result:M(v,w(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,I?.responseDetail??"full")});return}if(u.kind==="get-hit-by-ref"){let v=G(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:M(v,w(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(u.kind==="get-path-by-ref"){let v=G(e.document,u.payload.ref,t.getCurrentDocument?.()??null);if(!v){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let I=[],O=v;for(;O;)O.getAttribute("data-vcp-edit-key")&&I.push(M(O,w(e.document,O,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),O=O.parentElement;S({type:"response",ok:!0,result:I.reverse()});return}if(u.kind==="get-scroll-metrics"){S({type:"response",ok:!0,result:ge(e)});return}if(u.kind==="scroll-to"){let v=Number(u.payload.x),I=Number(u.payload.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:I}),S({type:"response",ok:!0,result:ge(e)});return}if(u.kind==="scroll-by"){let v=Number(u.payload.deltaX),I=Number(u.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:I}),S({type:"response",ok:!0,result:{...ge(e),scrolled:!0}});return}if(u.kind==="set-interaction-mode"){u.payload.enabled?ce(P,x,N):s?.sourceWindow===x&&s.targetOrigin===N&&s.sessionKey===P&&b(),S({type:"response",ok:!0,result:{interactionEnabled:u.payload.enabled}});return}if(u.kind==="set-theme-override"){Ln(e.document,u.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(u.kind==="clear-theme-override"){er(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(u.kind==="get-theme-variables"){S({type:"response",ok:!0,result:tr(e.document,u.payload.names)});return}if(u.kind==="compute-drop-target-at-point"){let v=Number(u.payload?.x),I=Number(u.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(I)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:$n(e,v,I,u.payload.dragKind,u.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(u.kind==="observe-node-bounds"){let v=u.payload.ref;if(!v){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let I=G(e.document,v,t.getCurrentDocument?.()??null);if(!I){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=Un(e,I,v,t.getDocumentEntry,O=>B({kind:"node-bounds-change",payload:{hit:O}})),S({type:"response",ok:!0,result:{observing:!0}}),B({kind:"node-bounds-change",payload:{hit:M(I,v,t.getDocumentEntry,"summary")}});return}if(u.kind==="clear-node-bounds-observer"){o?.(),o=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(u.kind!=="hit-test-at-point"&&u.kind!=="start-text-edit-at-point")return;let F=Number(u.payload?.x),V=Number(u.payload?.y);if(!Number.isFinite(F)||!Number.isFinite(V)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let $=u.kind==="hit-test-at-point"?ye(e.document,F,V,t.getCurrentDocument?.()??null):Nn(e.document,F,V,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!$){S({type:"response",ok:!1,error:u.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let W=u.kind==="start-text-edit-at-point"?$:null,H=u.kind==="hit-test-at-point"?$:W.element,L=u.payload.detailLevel??"full",ee=L==="full"?w(e.document,H,t.getCurrentDocument?.()??null):ot(e.document,H,t.getCurrentDocument?.()??null),g=W&&typeof W.textSegmentIndex=="number"?{...ee,textSegmentIndex:W.textSegmentIndex}:ee,Ht=M(H,g,t.getDocumentEntry,L);if(u.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:Ht});return}E(),n=sr(e,H,g,v=>{x.postMessage(ne({type:"event",...v},{sessionKey:P}),N)},W?{textNode:W.textNode}:void 0),S({type:"response",ok:!0,result:{ref:g}})}catch(F){S({type:"response",ok:!1,error:F instanceof Error?F.message:"Failed to start text edit"})}};return e.addEventListener("message",He),e.addEventListener(Pe,Ve),e.addEventListener(Ne,Ue),()=>{E(),b(),s=null,T(),e.removeEventListener("message",He),e.removeEventListener(Pe,Ve),e.removeEventListener(Ne,Ue)}}function rt(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-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}async function bn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,onBridgeRequestError:s,windowLike:i}){let a=i.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-get-document":n({type:"response",ok:!0,result:await a.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:a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId)});return;case"bridge-get-object-summary":n({type:"response",ok:!0,result:await a.getObjectSummary(e.payload.key,e.payload.routeId)});return;case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let c=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Sn(c,e.payload.key,i.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":n({type:"response",ok:!0,result:await a.execute(e.payload.request)});return;case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let c=e.payload.subscriptionId;r.get(c)?.();let l=a.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:c}})});r.set(c,l),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let c=e.payload.subscriptionId;r.get(c)?.(),r.delete(c),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(c){s?.(c,e),n({type:"response",ok:!1,error:Tn(c)})}}function Sn(e,t,n,r){if(!e.ok||!e.data.styleContext)return e;let o=G(n,{key:t},r),s=o?En(o):null;return s?{...e,data:{...e.data,styleContext:{...e.data.styleContext,computedStyle:{...e.data.styleContext.computedStyle??{},...s}}}}:e}function En(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 vn(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 In(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function lt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function dt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function _n(e,t){e.dispatchEvent(new CustomEvent(Pe,{detail:t}))}function Rn(e,t){e.dispatchEvent(new CustomEvent(Ne,{detail:t}))}function Cn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function xn(e,t){return e.routeId===t}function Oe(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function ft(e){let t=Oe(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Tn(e){let t=Oe(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":ft(t)?"Site edit bridge disconnected":t}function he(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"";return/bridge key|session|unauthorized|forbidden|expired/i.test(t)}function kn(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Be(e){return fn.has(ht(e))}function Pn(e){return pn.has(ht(e))}function pt(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:Pn(e.tagName),canInsertChild:Be(e.tagName),canMove:!1,canRemove:!1}}function ht(e){return e?.trim().toLowerCase()??""}function Nn(e,t,n,r,o){let s=ye(e,t,n,r),i=mt(s);if(!i)return null;let a=i.getAttribute("data-vcp-edit-key")??"",c=w(e,i,r),l=o?.(c.key)??o?.(a);if(!pt({operationSummary:l?.operationSummary,tagName:i.tagName,fallbackMode:"preview"}).canUpdateText)return null;if((l?.childKeys.length??0)===0)return{element:i};let m=Dn(e,t,n,i);if(!m)return null;let E=On(i,m);return E===null?null:{element:i,textNode:m,textSegmentIndex:E}}function Dn(e,t,n,r){let o=An(e,t,n);return!o||o.parentElement!==r?null:o}function An(e,t,n){let r=e,s=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(De(s))return s;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return De(a)?a:null}function On(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!De(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function De(e){return e?.nodeType===3}function ye(e,t,n,r=null){let o=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let s of o){let i=mt(s),a=i?.getAttribute("data-vcp-edit-key")??"";if(i&&qn(i,r,a))return i}return null}function mt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Fe(t))return n??t;!Bn(r)&&!n&&(n=t)}t=t.parentElement}return n}function Fe(e){return e.getAttribute(dn)!==null}function Bn(e){return Fn(e.split("::")[0]??"")}function Fn(e){if(!e)return!1;let t=Mn(e);return t===fe||t.startsWith(`${fe}/`)||t.includes(`/${fe}/`)||t.endsWith(`/${fe}`)}function Mn(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 w(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=gt(bt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${It(r)}"]`))),n,r);if(o.length<=1)return{key:st(n,r,0)};let s=o.indexOf(t);return s>=0?{key:st(n,r,s),instanceIndex:s,instanceCount:o.length}:{key:r}}function ot(e,t,n){return w(e,t,n)}function G(e,t,n){let r=se(t.key)??t.key,o=gt(bt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${It(r)}"]`))),n,t.key);if(o.length===0)return null;let s=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<o.length?t.instanceIndex:null,i=(se(t.key)??t.key)!==t.key;if(s!==null&&!i)return o[s]??null;let a=Kn(n,t.key);return a!==null&&a>=0&&a<o.length?o[a]??null:s!==null?o[s]??null:o[0]??null}function st(e,t,n){return Me(e,t)[n]?.key??t}function Kn(e,t){let n=se(t);if(!n)return null;let o=Me(e,n).findIndex(s=>s.key===t);return o>=0?o:null}function Me(e,t){return(e?.entries??[]).filter(n=>(se(n.key)??n.key)===t)}function gt(e,t,n){let r=yt(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function qn(e,t,n){let r=yt(t,n);return!r||e.tagName.toLowerCase()===r}function yt(e,t){let n=se(t)??t,o=(e?.entries.find(s=>s.key===t)??Me(e,n)[0])?.tag.trim();return!o||o!==o.toLowerCase()?null:o}var jn=2,wn=4;function bt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&wn)!==0?-1:(r&jn)!==0?1:0})}function se(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(nt);if(n<0)break;let r=Number(t.slice(n+nt.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Wn(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 Vn(e){return Array.from(e.children).filter(t=>typeof t.getBoundingClientRect=="function").map(t=>Ae(t.getBoundingClientRect())).filter(t=>t.width>0&&t.height>0)}function M(e,t,n,r="full"){let o=e.getBoundingClientRect(),s=n?.(t.key)??null,i=e.tagName.toLowerCase(),a=be(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([b,D])=>[b,D??""])),attributes:Object.fromEntries(e.getAttributeNames().map(b=>[b,e.getAttribute(b)??""]))}:{},l=pt({operationSummary:s?.operationSummary,tagName:i,fallbackMode:"preview"}),d=Fe(e),m=!!(s&&/^[A-Z]/.test(s.tag)),E=!s||!m;return{ref:t,key:t.key,detailLevel:r,tagName:i,...s?{sourceKind:m?"component-call":"jsx"}:{},...m&&s?.tag?{componentName:s.tag}:{},...s?.parentKey?{parentKey:s.parentKey}:{},...c,runtimeFlags:{selectable:!0,movable:l.canMove,removable:l.canRemove,textEditable:l.canUpdateText,container:d?!1:(s?.childKeys.length??0)>0||l.canInsertChild||E&&Be(i)},layout:a,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childRects:Vn(e),spacing:Wn(e)}}function Un(e,t,n,r,o){let s=Ae(t.getBoundingClientRect()),i=null,a=()=>{i===null&&(i=lt(e,c))},c=()=>{if(i=null,"isConnected"in t&&!t.isConnected)return;let D=Ae(t.getBoundingClientRect());Hn(s,D)&&(s=D,o(M(t,n,r,"summary")))},l=e.ResizeObserver,d=typeof l=="function"?new l(a):null;d?.observe(t);let m=e.MutationObserver,E=typeof m=="function"?new m(a):null;E?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",a,{passive:!0});let b=e.visualViewport;return b?.addEventListener?.("resize",a,{passive:!0}),e.document.addEventListener("load",a,!0),()=>{i!==null&&(dt(e,i),i=null),d?.disconnect(),E?.disconnect(),e.removeEventListener("resize",a),b?.removeEventListener?.("resize",a),e.document.removeEventListener("load",a,!0)}}function Ae(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function Hn(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 $n(e,t,n,r,o,s,i){let a=e.document,c=ye(a,t,n,s);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let l=o?G(a,o,s):null;if(l&&ct(c,l))return me(a,c,"self-or-descendant",s,i);let d=null,m=!1,E=c,b=c.parentElement;for(;b;){if(b.getAttribute("data-vcp-edit-key")){if(l&&ct(b,l))return me(a,c,"self-or-descendant",s,i);let R=it(b,r,i);if(R==="accept"){d={child:E,targetParent:b};break}R==="blocked"&&(m=!0),E=b}b=b.parentElement}let D=it(c,r,i);if(D==="accept"){if(d){let R=at(d.child,d.targetParent,t,n,"edge");if(R)return Te(a,d.child,d.targetParent,R,s,i)}return Te(a,c,c,Gn(c,t,n),s,i)}if(d){let R=at(d.child,d.targetParent,t,n,"nearest");return Te(a,d.child,d.targetParent,R??"after",s,i)}return D==="blocked"||m?me(a,c,"operation-boundary-blocked",s,i):me(a,c,"no-accepting-parent",s,i)}function me(e,t,n,r,o){return{anchorHit:M(t,w(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Te(e,t,n,r,o,s){let i=M(t,w(e,t,o),s,"summary"),a=M(n,w(e,n,o),s,"summary"),c=be(n).indicatorOrientation,l=r==="append"||r==="prepend"?zn(n.getBoundingClientRect(),c,r):Jn(t.getBoundingClientRect(),c,r);return{anchorHit:i,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:l}}function it(e,t,n){if(Fe(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 Be(s)?"accept":"not-container"}function at(e,t,n,r,o){let s=be(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 Gn(e,t,n){let r=be(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 be(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 zn(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 Jn(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 ct(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ge(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:j(e.scrollX),scrollY:j(e.scrollY),scrollWidth:Math.max(j(t?.scrollWidth),j(n?.scrollWidth),j(e.innerWidth)),scrollHeight:Math.max(j(t?.scrollHeight),j(n?.scrollHeight),j(e.innerHeight)),viewportWidth:j(e.innerWidth),viewportHeight:j(e.innerHeight)}}function Yn(e,t){Object.entries(t.attributes??{}).forEach(([r,o])=>{if(o===null){e.removeAttribute(r);return}e.setAttribute(r,o)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,o])=>{if(n.has(r))return;let s=e.style,i=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(o==null||o===""){s.removeProperty(i);return}s.setProperty(i,String(o))}),t.styleDeclarations?.forEach(r=>{let o=e.style,s=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),i=r.value;if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i),r.priority)})}var Xn=500,re=new Map;function Qn(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Zn(e,t){if(re.size>=Xn){let n=re.keys().next().value;n&&re.delete(n)}re.set(e,t)}var oe=new Set;function Ln(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 oe)r.has(o)||n?.removeProperty(o);oe.clear();for(let o of r)oe.add(o);or(e,t.stylesheets??[])}function er(e){let t=e.documentElement?.style;for(let n of oe)t?.removeProperty(n);oe.clear();for(let n of vt(e))n.remove()}function tr(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=St(o,i);a&&(s[i]=a)}return s}function St(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Et(e,r,n)}function Et(e,t,n){if(!t)return null;let r=nr(t);if(!r)return t;let o=St(e,r.name,n);return o||(r.fallback?Et(e,r.fallback,n)??r.fallback:null)}function nr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=rr(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 rr(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 or(e,t){let n=new Set(t.filter(s=>typeof s=="string"&&s.length>0)),r=new Map;for(let s of vt(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(ut,"true"),i.setAttribute("href",s),o.appendChild(i)}}function vt(e){return Array.from(e.querySelectorAll(`link[${ut}]`))}function sr(e,t,n,r,o={}){let s=o.textNode?ir(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??"",c=ar(i),l=!1,d=()=>{e.document.removeEventListener("pointerdown",E,!0),i.removeEventListener("keydown",b),i.removeEventListener("blur",D),i.removeEventListener("input",R),ur(i,c)},m=T=>{if(l)return;l=!0;let K=i.textContent??"";if(d(),T==="cancel"){s?.restore(a),s||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(s?.restore(K),T==="commit"&&K!==a){r({kind:"text-edit-commit",payload:{ref:n,value:K}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function E(T){let K=T.target;K&&i.contains(K)||m("commit")}function b(T){if(T.key==="Escape"){T.preventDefault(),m("cancel");return}T.key==="Enter"&&(T.metaKey||T.ctrlKey)&&(T.preventDefault(),m("commit"))}function D(){m("commit")}function R(){r({kind:"text-edit-input",payload:{ref:n,hit:M(t,n,void 0,"full")}})}return cr(i),e.document.addEventListener("pointerdown",E,!0),i.addEventListener("keydown",b),i.addEventListener("blur",D),i.addEventListener("input",R),fr(i),pr(i,e.document),d}function ir(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 ar(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 cr(e){lr(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 ur(e,t){ke(e,"contenteditable",t.contentEditable),ke(e,"spellcheck",t.spellcheck),ke(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function lr(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 ke(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function dr(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 fr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function pr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function It(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function j(e){let t=Number(e);return Number.isFinite(t)?t:0}import hr from"node:http";import{randomBytes as mr,timingSafeEqual as gr}from"node:crypto";import yr from"node:path";import{WebSocket as Tt,WebSocketServer as br}from"ws";import{createPreviewSiteEditEngineRuntime as Sr}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Er,scanNextAppRouterRoutes as vr}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ir}from"@vcp-dev/site-edit-engine/source-watcher";import{SiteEditOperationRequestSchema as _r}from"@vcp-dev/contracts";var Rr="127.0.0.1",Cr=30218,xr="/__vcp/site-edit/bridge",Tr=6*1024*1024,kr=3e3,_t=50,Rt="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function zo(e){let t=Pt(e),n=Dt(t),r=Nt(),o=r.get(n);if(o)return o;let s=new Se(t);r.set(n,s);try{s.start()}catch(i){throw r.delete(n),s.stop(),i}return s}function kt(e,t){let n=new Se(Pt(t),e,!1);return n.start({listen:!1}),n}var Se=class{constructor(t,n=hr.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.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=Sr({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=Pr({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 Ir({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??_t,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=Nt(),n=Dt(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)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute: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.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??_t;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of t)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let t=this.options.runtime.routes?.length?this.options.runtime.routes:vr(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=Er(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 Pt(e){return{siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:yr.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Rr,port:e.port??Cr,path:e.path??xr,sessionKey:e.sessionKey??Mr(),allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function Nt(){let e=globalThis;return e[Rt]??=new Map,e[Rt]}function Dt(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}`}function Pr(e){let t=new br({maxPayload:Tr,noServer:!0}),n=new WeakSet,r=s=>{new le({socket:new qe(s),engine:e.engine,validateOperationRequest:i=>_r.safeParse(i).success})},o=(s,i,a)=>{if(!Nr(s,e))return;let c=Dr(s,e);if(!c){i.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 Q({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 Mn(32).toString("base64url")}import sr from"node:http";import{existsSync as V,readFileSync as W}from"node:fs";import{createRequire as dt}from"node:module";import ae from"node:path";import{basename as ft,dirname as Y,join as J}from"node:path";import{fileURLToPath as pt}from"node:url";var ir="next",ar="127.0.0.1",cr=3e3,ht="/__vcp/site-edit/bridge",ie="/__vcp/site-edit/client/",ur=`${ie}auto-bootstrap.js`,mt='data-vcp-site-edit-bootstrap="true"',lr=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],dr="@vcp-dev/site-edit-engine/webpack-loader",fr=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,pr=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],hr=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function xo(e={}){let t=ae.resolve(e.projectRoot??process.cwd()),n=e.host??ar,r=e.port??Ur(process.env.PORT)??cr,o=e.bridgePath??ht,s=Fr(),i=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=await Kr(t),c=mr(t),d=a({dev:!0,dir:t,hostname:n,port:r,...gr(c)}),p=d.getRequestHandler();await d.prepare();let h=sr.createServer((R,y)=>{Tr({basePath:i,bridgePath:o,bridgeSessionKey:s,handle:p,request:R,response:y}).catch(b=>{console.error(b),y.headersSent||(y.statusCode=500),y.end("site edit preview request failed")})}),v=nt(h,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??Vr(t),projectRoot:t,basePath:i,host:n,port:r,path:o,sessionKey:s});Sr({server:h,bridgePath:o,handleUpgrade:d.getUpgradeHandler()});let l=()=>{v.stop(),d.close().catch(()=>{}),h.close()};return process.on("SIGINT",l),process.on("SIGTERM",l),await Hr(h,r,n),{bundler:c,close:l,server:h}}function mr(e){let t=yr(e);return t&&br(t)?"webpack":"turbopack"}function gr(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function yr(e){for(let t of lr){let n=J(e,t);if(V(n))return W(n,"utf8")}return null}function br(e){return e.includes(dr)?!0:fr.test(e)&&pr.some(t=>t.test(e))}function Sr(e){let t=(n,r,o)=>{Er(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 Er(e,t){return new URL(e??"/","http://localhost").pathname===t}function vr(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Ir()});return`<script type="module" ${mt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(ur)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ir(){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=Rr(n,e);if(!r)return;let o=JSON.parse(W(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Rr(e,t){let n=ae.parse(e).root,r=Y(e);for(;r&&r!==n;){let o=J(r,"package.json");if(V(o))try{if(JSON.parse(W(o,"utf8")).name===t)return o}catch{return}r=Y(r)}}function xr(e,t){if(e.includes(mt))return e;let n=vr(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function _o(e,t=Y(pt(import.meta.url)),n=V){return gt(e,t,n)?.path??null}function gt(e,t=Y(pt(import.meta.url)),n=V){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(ie))return null;let o=r.slice(ie.length);if(!hr.has(o))return null;let s=Ie(qr(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 _r(e,t){let n=gt(e.url);if(!n)return!1;if(!V(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Cr(W(n.path,"utf8")):W(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Cr(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Tr({basePath:e,bridgePath:t,bridgeSessionKey:n,handle:r,request:o,response:s}){if(await _r(o,s))return;let i=kr(o),a=Nr(o),c=i||a?Or(s,{basePath:e,bridgePath:t,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(o,s)}catch(d){throw c(),d}}function kr(e){return Pr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Nr(e){return Dr(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Pr(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(ie)||t===ht)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Dr(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 Or(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,c,d)=>(a!==void 0&&n.push(ct(a,ut(c))),lt(c),lt(d),!0),r.end=(a,c,d)=>{let p=typeof a=="function"?void 0:a;p!==void 0&&n.push(ct(p,ut(c))),r.write=s,r.end=i,r.flushHeaders=o;let h=Buffer.concat(n),v=Ar(e,h,t);v!==h&&!e.headersSent&&e.removeHeader("content-length");let l=typeof a=="function"?a:typeof c=="function"?c:typeof d=="function"?d:void 0;return l?i(v,l):i(v)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function Ar(e,t,n){if(jr(e,t))return Buffer.from(xr(t.toString("utf8"),n));if(n.patchNextDevChunk&&Br(e)){let r=t.toString("utf8"),o=Mr(r);if(o!==r)return Buffer.from(o)}return t}function Fr(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function jr(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 Br(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 Mr(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
+ `),i.destroy();return}c.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,i,a,l=>{t.emit("connection",l,s)})};return e.server.on("upgrade",o),t.on("connection",(s,i)=>{if(n.has(i)){r(s);return}Ar(s,e.sessionKey,()=>{r(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var qe=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===Tt.OPEN&&this.socket.send(t)}close(t,n){this.socket.close(t,n)}};function Nr(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Dr(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Ke(e.headers["x-vcp-site-edit-key"]),o=At(r,t.sessionKey),s=Ke(e.headers.host),i=Ke(e.headers.origin);return s&&!Or(s,t.host,i)?null:i?Fr(i,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Ar(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},kr),o,s=()=>{clearTimeout(r),e.off("message",o),e.off("close",s)},i=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let c=A.parseMessage(a.toString());if(c.type!=="auth"||!At(c.payload.key,t)){i();return}s(),e.readyState===Tt.OPEN&&e.send(A.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{i()}},e.on("message",o),e.on("close",s)}function At(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&gr(n,r)}function Or(e,t,n){let r=xt(e),o=xt(t);return r===o||Ct(o)&&Ct(r)&&(!n||je(n,e))||Br(o)&&(!n||je(n,e))}function Br(e){return e==="0.0.0.0"||e==="::"}function Ct(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Fr(e,t,n){return n.includes(e)||(t?je(e,t):!1)}function je(e,t){try{return new URL(e).host===Ot(t)}catch{return!1}}function xt(e){let t=Ot(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Ot(e){return e.trim().toLowerCase()}function Ke(e){return Array.isArray(e)?e[0]:e}function Mr(){return mr(32).toString("base64url")}import Kr from"node:http";import{existsSync as J,readFileSync as z}from"node:fs";import{createRequire as Kt}from"node:module";import ve from"node:path";import{basename as qt,dirname as ie,join as ae}from"node:path";import{fileURLToPath as jt}from"node:url";var qr="next",jr="127.0.0.1",wr=3e3,wt="/__vcp/site-edit/bridge",Ee="/__vcp/site-edit/client/",Wr=`${Ee}auto-bootstrap.js`,Wt='data-vcp-site-edit-bootstrap="true"',Vr=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ur="@vcp-dev/site-edit-engine/webpack-loader",Hr=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,$r=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Gr=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function ns(e={}){let t=ve.resolve(e.projectRoot??process.cwd()),n=e.host??jr,r=e.port??Io(process.env.PORT)??wr,o=e.bridgePath??wt,s=po(),i=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=await bo(t),c=zr(t),l=a({dev:!0,dir:t,hostname:n,port:r,...Jr(c)}),d=l.getRequestHandler();await l.prepare();let m=Kr.createServer((D,R)=>{so({basePath:i,bridgePath:o,bridgeSessionKey:s,handle:d,request:D,response:R}).catch(T=>{console.error(T),R.headersSent||(R.statusCode=500),R.end("site edit preview request failed")})}),E=kt(m,{siteId:e.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:e.snapshotId??process.env.VCP_SNAPSHOT_ID??vo(t),projectRoot:t,basePath:i,host:n,port:r,path:o,sessionKey:s});Qr({server:m,bridgePath:o,handleUpgrade:l.getUpgradeHandler()});let b=()=>{E.stop(),l.close().catch(()=>{}),m.close()};return process.on("SIGINT",b),process.on("SIGTERM",b),await _o(m,r,n),{bundler:c,close:b,server:m}}function zr(e){let t=Yr(e);return t&&Xr(t)?"webpack":"turbopack"}function Jr(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Yr(e){for(let t of Vr){let n=ae(e,t);if(J(n))return z(n,"utf8")}return null}function Xr(e){return e.includes(Ur)?!0:Hr.test(e)&&$r.some(t=>t.test(e))}function Qr(e){let t=(n,r,o)=>{Zr(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 Zr(e,t){return new URL(e??"/","http://localhost").pathname===t}function Lr(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??eo()});return`<script type="module" ${Wt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Wr)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function eo(){return{bridge:we("@vcp-dev/site-edit-bridge"),contracts:we("@vcp-dev/contracts"),engine:we("@vcp-dev/site-edit-engine")}}function we(e){let t=Kt(import.meta.url);try{let n=t.resolve(e),r=to(n,e);if(!r)return;let o=JSON.parse(z(r,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function to(e,t){let n=ve.parse(e).root,r=ie(e);for(;r&&r!==n;){let o=ae(r,"package.json");if(J(o))try{if(JSON.parse(z(o,"utf8")).name===t)return o}catch{return}r=ie(r)}}function no(e,t){if(e.includes(Wt))return e;let n=Lr(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function rs(e,t=ie(jt(import.meta.url)),n=J){return Vt(e,t,n)?.path??null}function Vt(e,t=ie(jt(import.meta.url)),n=J){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Ee))return null;let o=r.slice(Ee.length);if(!Gr.has(o))return null;let s=We(So(t),o);if(qt(t)!=="src")return{path:s,requiresTranspile:!1};let i=We(t,o.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:s,requiresTranspile:!1}}async function ro(e,t){let n=Vt(e.url);if(!n)return!1;if(!J(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await oo(z(n.path,"utf8")):z(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function oo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function so({basePath:e,bridgePath:t,bridgeSessionKey:n,handle:r,request:o,response:s}){if(await ro(o,s))return;let i=io(o),a=ao(o),c=i||a?lo(s,{basePath:e,bridgePath:t,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(o,s)}catch(l){throw c(),l}}function io(e){return co(e)?(e.headers["accept-encoding"]="identity",!0):!1}function ao(e){return uo(e)?(e.headers["accept-encoding"]="identity",!0):!1}function co(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Ee)||t===wt)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function uo(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 lo(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,c,l)=>(a!==void 0&&n.push(Bt(a,Ft(c))),Mt(c),Mt(l),!0),r.end=(a,c,l)=>{let d=typeof a=="function"?void 0:a;d!==void 0&&n.push(Bt(d,Ft(c))),r.write=s,r.end=i,r.flushHeaders=o;let m=Buffer.concat(n),E=fo(e,m,t);E!==m&&!e.headersSent&&e.removeHeader("content-length");let b=typeof a=="function"?a:typeof c=="function"?c:typeof l=="function"?l:void 0;return b?i(E,b):i(E)},()=>{r.write=s,r.end=i,r.flushHeaders=o}}function fo(e,t,n){if(ho(e,t))return Buffer.from(no(t.toString("utf8"),n));if(n.patchNextDevChunk&&mo(e)){let r=t.toString("utf8"),o=go(r);if(o!==r)return Buffer.from(o)}return t}function po(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ho(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 mo(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 go(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])=>wr(n,r,o),e)}function wr(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 ct(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function ut(e){return typeof e=="string"?e:void 0}function lt(e){typeof e=="function"&&e()}async function Kr(e){let n=dt(J(e,"package.json"))(ir);return n.default??n}function qr(e){return ft(e)!=="src"?e:Ie(Wr(e),"dist")}function Wr(e){return yt(e)?ae.posix.dirname(e):Y(e)}function Ie(e,t){return yt(e)?ae.posix.join(e,t):J(e,t)}function yt(e){return e.includes("/")&&!e.includes("\\")}function Vr(e){let t=J(e,".vcp/current-snapshot.json");if(!V(t))return"sandbox_worktree";try{let n=JSON.parse(W(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Ur(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Hr(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,se as SiteEditBridgeServer,Q as SiteEditBridgeSocketServer,F as SiteEditBridgeTransport,Z as SiteEditWebSocketClient,he as VCP_SITE_EDIT_ROUTE_READY_EVENT,De as VCP_WINDOW_MESSAGE_SOURCE,Lr as VCP_WINDOW_MESSAGE_VERSION,Sr as attachNextDevUpgradeHandler,nt as attachSiteEditBridgeServer,Qn as attachSiteEditWebSocketServer,vr as createSiteEditAutoBootstrapHtmlSnippet,Pe as createSiteEditBridge,$ as createSiteEditFrameRuntimeMessage,At as createVcpWindowMessageEnvelope,Te as decodeRenderDocument,Ce as encodeRenderDocument,mo as ensureSiteEditBridgeServerStarted,xr as injectSiteEditAutoBootstrap,St as isCompactRenderDocument,Ct as isDesignerTraceEnabled,Fe as isSiteEditFrameRuntimeMessage,Ft as isVcpWindowMessageEnvelope,Mr as patchNextFirefoxDevChunk,Nr as prepareFirefoxNextDevChunkPatchRequest,kr as prepareSiteEditHtmlInjectionRequest,gt as resolveSiteEditClientAsset,_o as resolveSiteEditClientAssetPath,mr as resolveSiteEditNextDevBundler,Kt as resolveSiteEditRouteId,Wt as resolveSiteEditWebSocketUrl,Tt as sanitizeTracePayload,ro as startSiteEditAutoBootstrap,Ut as startSiteEditFrameRuntime,xo as startSiteEditNextDevServer,w as traceDesignerEvent,Cr 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])=>yo(n,r,o),e)}function yo(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 Bt(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Ft(e){return typeof e=="string"?e:void 0}function Mt(e){typeof e=="function"&&e()}async function bo(e){let n=Kt(ae(e,"package.json"))(qr);return n.default??n}function So(e){return qt(e)!=="src"?e:We(Eo(e),"dist")}function Eo(e){return Ut(e)?ve.posix.dirname(e):ie(e)}function We(e,t){return Ut(e)?ve.posix.join(e,t):ae(e,t)}function Ut(e){return e.includes("/")&&!e.includes("\\")}function vo(e){let t=ae(e,".vcp/current-snapshot.json");if(!J(t))return"sandbox_worktree";try{let n=JSON.parse(z(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Io(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function _o(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),r()})})}export{Tr as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,Le as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Ze as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,Se as SiteEditBridgeServer,le as SiteEditBridgeSocketServer,A as SiteEditBridgeTransport,de as SiteEditWebSocketClient,Ne as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Pe as VCP_SITE_EDIT_ROUTE_READY_EVENT,Qe as VCP_WINDOW_MESSAGE_SOURCE,Ao as VCP_WINDOW_MESSAGE_VERSION,Qr as attachNextDevUpgradeHandler,kt as attachSiteEditBridgeServer,Pr as attachSiteEditWebSocketServer,Lr as createSiteEditAutoBootstrapHtmlSnippet,Xe as createSiteEditBridge,ne as createSiteEditFrameRuntimeMessage,un as createVcpWindowMessageEnvelope,ze as decodeRenderDocument,Ge as encodeRenderDocument,zo as ensureSiteEditBridgeServerStarted,no as injectSiteEditAutoBootstrap,$t as isCompactRenderDocument,Zt as isDesignerTraceEnabled,et as isSiteEditFrameRuntimeMessage,ln as isVcpWindowMessageEnvelope,go as patchNextFirefoxDevChunk,ao as prepareFirefoxNextDevChunkPatchRequest,io as prepareSiteEditHtmlInjectionRequest,Vt as resolveSiteEditClientAsset,rs as resolveSiteEditClientAssetPath,zr as resolveSiteEditNextDevBundler,pe as resolveSiteEditRouteId,mn as resolveSiteEditWebSocketUrl,Lt as sanitizeTracePayload,Mo as startSiteEditAutoBootstrap,yn as startSiteEditFrameRuntime,ns as startSiteEditNextDevServer,U as traceDesignerEvent,oo as transpileSiteEditClientSource};
@@ -1,6 +1,6 @@
1
- import ke from"node:http";import{existsSync as y,readFileSync as m}from"node:fs";import{createRequire as U}from"node:module";import v from"node:path";import{basename as J,dirname as b,join as S}from"node:path";import{fileURLToPath as W}from"node:url";import Y from"node:http";import{randomBytes as ee,timingSafeEqual as te}from"node:crypto";import ne from"node:path";import{WebSocket as re,WebSocketServer as se}from"ws";import{createPreviewSiteEditEngineRuntime as oe}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as ie,scanNextAppRouterRoutes as ae}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ce}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 u=n.length;return n.push(i),e.set(i,u),u},c=i=>{let a=null;for(let u of Q(i)){let p=`${a??"root"}\0${u}`,d=r.get(p);if(typeof d=="number"){a=d;continue}let f=s.length;s.push({parent:a,token:o(u)}),r.set(p,f),a=f}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(c),entries:t.entries.map(i=>({keyNodeId:c(i.key),tag:i.tag,label:i.label,parentKeyNodeId:i.parentKey?c(i.parentKey):null,childKeyNodeIds:i.childKeys.map(c),operationSummary:i.operationSummary}))}}function Q(t){if(!t)return[];let e=[],n=0,r=B(t,n);if(r<0)return e.push(t),e;for(e.push(t.slice(0,r)),n=r;n<t.length;){if(r=B(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 B(t,e){let n=t.indexOf("/",e),r=t.indexOf("::",e);return n<0?r:r<0?n:Math.min(n,r)}var g=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!h(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):!1}static isRequestPayload(e,n={}){if(!h(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 Z(e.request)&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return!0}}},R=class{constructor(e){this.options=e,this.messageQueue=new k,this.eventDispatcher=new I(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=g.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(g.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(g.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()}}},I=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 h(t){return typeof t=="object"&&t!==null}function Z(t){return h(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"&&h(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function X(t){try{return g.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}import{SiteEditOperationRequestSchema as ue}from"@vcp-dev/contracts";var de="127.0.0.1",fe=30218,he="/__vcp/site-edit/bridge",pe=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=oe({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=ye({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 ce({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=ge(),n=me(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:ae(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=ie(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:ne.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??de,port:t.port??fe,path:t.path??he,sessionKey:t.sessionKey??Ie(),allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function ge(){let t=globalThis;return t[H]??=new Map,t[H]}function me(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}`}function ye(t){let e=new se({maxPayload:pe,noServer:!0}),n=(r,s,o)=>{if(be(r,t)){if(!Se(r,t)){s.write(`HTTP/1.1 401 Unauthorized\r
1
+ import Pe from"node:http";import{existsSync as y,readFileSync as m}from"node:fs";import{createRequire as L}from"node:module";import I from"node:path";import{basename as $,dirname as S,join as b}from"node:path";import{fileURLToPath as V}from"node:url";import re from"node:http";import{randomBytes as se,timingSafeEqual as oe}from"node:crypto";import ie from"node:path";import{WebSocket as A,WebSocketServer as ae}from"ws";import{createPreviewSiteEditEngineRuntime as ue}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as ce,scanNextAppRouterRoutes as de}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as he}from"@vcp-dev/site-edit-engine/source-watcher";function N(t){let e=new Map,n=[],r=new Map,s=[],o=a=>{let u=e.get(a);if(typeof u=="number")return u;let c=n.length;return n.push(a),e.set(a,c),c},i=a=>{let u=null;for(let c of ee(a)){let p=`${u??"root"}\0${c}`,d=r.get(p);if(typeof d=="number"){u=d;continue}let l=s.length;s.push({parent:u,token:o(c)}),r.set(p,l),u=l}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,tokens:n,nodes:s,rootKeyNodeIds:t.rootKeys.map(i),entries:t.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 ee(t){if(!t)return[];let e=[],n=0,r=B(t,n);if(r<0)return e.push(t),e;for(e.push(t.slice(0,r)),n=r;n<t.length;){if(r=B(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 B(t,e){let n=t.indexOf("/",e),r=t.indexOf("::",e);return n<0?r:r<0?n:Math.min(n,r)}var f=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==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?h(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,n={}){if(!h(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":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return te(e.request)&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return!0}}},x=class{constructor(e){this.options=e,this.messageQueue=new v,this.eventDispatcher=new k(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:N((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"get-source-tree":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:s,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId: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=f.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(f.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",s=ne(e);this.sendJson({type:"error",payload:{...s,message:r}})}}sendJson(e){this.options.socket.send(f.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()}}},k=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},v=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},r=this.queue.then(n,n);return this.queue=r.then(()=>{},()=>{}),r}};function h(t){return typeof t=="object"&&t!==null}function te(t){return h(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"&&h(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function ne(t){try{return f.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}import{SiteEditOperationRequestSchema as fe}from"@vcp-dev/contracts";var le="127.0.0.1",pe=30218,ge="/__vcp/site-edit/bridge",me=6*1024*1024,ye=3e3,H=50,O="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function D(t,e){let n=new _(Se(e),t,!1);return n.start({listen:!1}),n}var _=class{constructor(e,n=re.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.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.runtime=ue({siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes});let n=xe({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 he({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??H,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.isStarted=!0}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=be(),n=we(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)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute: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.handleFilesChanged([e])}handleFilesChanged(e){for(let r of e)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??H;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((n,r)=>n.localeCompare(r));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of e)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:de(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=ce(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 Se(t){return{siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:ie.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??le,port:t.port??pe,path:t.path??ge,sessionKey:t.sessionKey??Ce(),allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function be(){let t=globalThis;return t[O]??=new Map,t[O]}function we(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}`}function xe(t){let e=new ae({maxPayload:me,noServer:!0}),n=new WeakSet,r=o=>{new x({socket:new C(o),engine:t.engine,validateOperationRequest:i=>fe.safeParse(i).success})},s=(o,i,a)=>{if(!Re(o,t))return;let u=Ie(o,t);if(!u){i.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),s.destroy();return}e.handleUpgrade(r,s,o,c=>{e.emit("connection",c,r)})}};return t.server.on("upgrade",n),e.on("connection",r=>{new R({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===re.OPEN&&this.socket.send(e)}close(e,n){this.socket.close(e,n)}};function be(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(!we(r,e.sessionKey))return!1;let s=E(t.headers.host),o=E(t.headers.origin);return s&&!Re(s,e.host,o)?!1:o?e.allowedOrigins.includes(o)||ve(o)||(s?q(o,s):!1):!0}function we(t,e){if(!t)return!1;let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&te(n,r)}function Re(t,e,n){let r=O(t),s=O(e);return r===s||r==="localhost"||r==="127.0.0.1"||r==="::1"||xe(s)&&!!(n&&q(n,t))}function xe(t){return t==="0.0.0.0"||t==="::"}function ve(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 ee(32).toString("base64url")}var Ee="next",Pe="127.0.0.1",je=3e3,$="/__vcp/site-edit/bridge",x="/__vcp/site-edit/client/",Ce=`${x}auto-bootstrap.js`,L='data-vcp-site-edit-bootstrap="true"',Ne=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Be="@vcp-dev/site-edit-engine/webpack-loader",_e=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,He=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Oe=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Bt(t={}){let e=v.resolve(t.projectRoot??process.cwd()),n=t.host??Pe,r=t.port??ut(process.env.PORT)??je,s=t.bridgePath??$,o=et(),c=t.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",i=await ot(e),a=Ke(e),u=i({dev:!0,dir:e,hostname:n,port:r,...qe(a)}),p=u.getRequestHandler();await u.prepare();let d=ke.createServer((z,w)=>{Ve({basePath:c,bridgePath:s,bridgeSessionKey:o,handle:p,request:z,response:w}).catch(G=>{console.error(G),w.headersSent||(w.statusCode=500),w.end("site edit preview request failed")})}),f=K(d,{siteId:t.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:t.snapshotId??process.env.VCP_SNAPSHOT_ID??ct(e),projectRoot:e,basePath:c,host:n,port:r,path:s,sessionKey:o});Ae({server:d,bridgePath:s,handleUpgrade:u.getUpgradeHandler()});let l=()=>{f.stop(),u.close().catch(()=>{}),d.close()};return process.on("SIGINT",l),process.on("SIGTERM",l),await dt(d,r,n),{bundler:a,close:l,server:d}}function Ke(t){let e=Te(t);return e&&Me(e)?"webpack":"turbopack"}function qe(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function Te(t){for(let e of Ne){let n=S(t,e);if(y(n))return m(n,"utf8")}return null}function Me(t){return t.includes(Be)?!0:_e.test(t)&&He.some(e=>e.test(t))}function Ae(t){let e=(n,r,s)=>{De(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 De(t,e){return new URL(t??"/","http://localhost").pathname===e}function Ue(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??Je()});return`<script type="module" ${L}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ce)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function Je(){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=U(import.meta.url);try{let n=e.resolve(t),r=We(n,t);if(!r)return;let s=JSON.parse(m(r,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function We(t,e){let n=v.parse(t).root,r=b(t);for(;r&&r!==n;){let s=S(r,"package.json");if(y(s))try{if(JSON.parse(m(s,"utf8")).name===e)return s}catch{return}r=b(r)}}function $e(t,e){if(t.includes(L))return t;let n=Ue(e),r=/<\/body\s*>/i.exec(t);return r?`${t.slice(0,r.index)}${n}${t.slice(r.index)}`:`${t}${n}`}function _t(t,e=b(W(import.meta.url)),n=y){return F(t,e,n)?.path??null}function F(t,e=b(W(import.meta.url)),n=y){let r=new URL(t??"/","http://localhost").pathname;if(!r.startsWith(x))return null;let s=r.slice(x.length);if(!Oe.has(s))return null;let o=N(it(e),s);if(J(e)!=="src")return{path:o,requiresTranspile:!1};let c=N(e,s.replace(/\.js$/,".ts"));return n(c)?{path:c,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Le(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 Fe(m(n.path,"utf8")):m(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(r),!0}async function Fe(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ve({basePath:t,bridgePath:e,bridgeSessionKey:n,handle:r,request:s,response:o}){if(await Le(s,o))return;let c=ze(s),i=Ge(s),a=c||i?Xe(o,{basePath:t,bridgePath:e,bridgeSessionKey:n,patchNextDevChunk:i}):()=>{};try{await r(s,o)}catch(u){throw a(),u}}function ze(t){return Qe(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ge(t){return Ze(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Qe(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(x)||e===$)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Ze(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 Xe(t,e){let n=[],r=t,s=r.flushHeaders.bind(t),o=r.write.bind(t),c=r.end.bind(t);return r.flushHeaders=()=>{},r.write=(i,a,u)=>(i!==void 0&&n.push(M(i,A(a))),D(a),D(u),!0),r.end=(i,a,u)=>{let p=typeof i=="function"?void 0:i;p!==void 0&&n.push(M(p,A(a))),r.write=o,r.end=c,r.flushHeaders=s;let d=Buffer.concat(n),f=Ye(t,d,e);f!==d&&!t.headersSent&&t.removeHeader("content-length");let l=typeof i=="function"?i:typeof a=="function"?a:typeof u=="function"?u:void 0;return l?c(f,l):c(f)},()=>{r.write=o,r.end=c,r.flushHeaders=s}}function Ye(t,e,n){if(tt(t,e))return Buffer.from($e(e.toString("utf8"),n));if(n.patchNextDevChunk&&nt(t)){let r=e.toString("utf8"),s=rt(r);if(s!==r)return Buffer.from(s)}return e}function et(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function tt(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 nt(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 rt(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
+ `),i.destroy();return}u.authenticatedByHeader&&n.add(o),e.handleUpgrade(o,i,a,c=>{e.emit("connection",c,o)})};return t.server.on("upgrade",s),e.on("connection",(o,i)=>{if(n.has(i)){r(o);return}ke(o,t.sessionKey,()=>{r(o)})}),e.stop=()=>{t.server.off("upgrade",s);for(let o of e.clients)o.close(1001,"bridge stopped");e.close()},e}var C=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===A.OPEN&&this.socket.send(e)}close(e,n){this.socket.close(e,n)}};function Re(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ie(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=E(t.headers["x-vcp-site-edit-key"]),s=q(r,e.sessionKey),o=E(t.headers.host),i=E(t.headers.origin);return o&&!ve(o,e.host,i)?null:i?_e(i,o,e.allowedOrigins)?{authenticatedByHeader:s}:null:s?{authenticatedByHeader:!0}:null}function ke(t,e,n){let r=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},ye),s,o=()=>{clearTimeout(r),t.off("message",s),t.off("close",o)},i=()=>{o(),t.close(1008,"bridge authentication failed")};s=a=>{try{let u=f.parseMessage(a.toString());if(u.type!=="auth"||!q(u.payload.key,e)){i();return}o(),t.readyState===A.OPEN&&t.send(f.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{i()}},t.on("message",s),t.on("close",o)}function q(t,e){if(!t)return!1;let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&oe(n,r)}function ve(t,e,n){let r=M(t),s=M(e);return r===s||K(s)&&K(r)&&(!n||P(n,t))||Ee(s)&&(!n||P(n,t))}function Ee(t){return t==="0.0.0.0"||t==="::"}function K(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function _e(t,e,n){return n.includes(t)||(e?P(t,e):!1)}function P(t,e){try{return new URL(t).host===F(e)}catch{return!1}}function M(t){let e=F(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function F(t){return t.trim().toLowerCase()}function E(t){return Array.isArray(t)?t[0]:t}function Ce(){return se(32).toString("base64url")}var Te="next",je="127.0.0.1",Be=3e3,z="/__vcp/site-edit/bridge",R="/__vcp/site-edit/client/",Ne=`${R}auto-bootstrap.js`,G='data-vcp-site-edit-bootstrap="true"',He=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Oe="@vcp-dev/site-edit-engine/webpack-loader",Ke=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Me=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Ae=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ot(t={}){let e=I.resolve(t.projectRoot??process.cwd()),n=t.host??je,r=t.port??lt(process.env.PORT)??Be,s=t.bridgePath??z,o=st(),i=t.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",a=await ct(e),u=De(e),c=a({dev:!0,dir:e,hostname:n,port:r,...qe(u)}),p=c.getRequestHandler();await c.prepare();let d=Pe.createServer((X,w)=>{Ye({basePath:i,bridgePath:s,bridgeSessionKey:o,handle:p,request:X,response:w}).catch(Z=>{console.error(Z),w.headersSent||(w.statusCode=500),w.end("site edit preview request failed")})}),l=D(d,{siteId:t.siteId??process.env.VCP_SITE_ID??"site_preview",snapshotId:t.snapshotId??process.env.VCP_SNAPSHOT_ID??ft(e),projectRoot:e,basePath:i,host:n,port:r,path:s,sessionKey:o});Je({server:d,bridgePath:s,handleUpgrade:c.getUpgradeHandler()});let g=()=>{l.stop(),c.close().catch(()=>{}),d.close()};return process.on("SIGINT",g),process.on("SIGTERM",g),await pt(d,r,n),{bundler:u,close:g,server:d}}function De(t){let e=Fe(t);return e&&Ue(e)?"webpack":"turbopack"}function qe(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function Fe(t){for(let e of He){let n=b(t,e);if(y(n))return m(n,"utf8")}return null}function Ue(t){return t.includes(Oe)?!0:Ke.test(t)&&Me.some(e=>e.test(t))}function Je(t){let e=(n,r,s)=>{We(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 We(t,e){return new URL(t??"/","http://localhost").pathname===e}function Le(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??$e()});return`<script type="module" ${G}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ne)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function $e(){return{bridge:T("@vcp-dev/site-edit-bridge"),contracts:T("@vcp-dev/contracts"),engine:T("@vcp-dev/site-edit-engine")}}function T(t){let e=L(import.meta.url);try{let n=e.resolve(t),r=Ve(n,t);if(!r)return;let s=JSON.parse(m(r,"utf8"));return typeof s.version=="string"?s.version:void 0}catch{return}}function Ve(t,e){let n=I.parse(t).root,r=S(t);for(;r&&r!==n;){let s=b(r,"package.json");if(y(s))try{if(JSON.parse(m(s,"utf8")).name===e)return s}catch{return}r=S(r)}}function ze(t,e){if(t.includes(G))return t;let n=Le(e),r=/<\/body\s*>/i.exec(t);return r?`${t.slice(0,r.index)}${n}${t.slice(r.index)}`:`${t}${n}`}function Kt(t,e=S(V(import.meta.url)),n=y){return Q(t,e,n)?.path??null}function Q(t,e=S(V(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(!Ae.has(s))return null;let o=j(dt(e),s);if($(e)!=="src")return{path:o,requiresTranspile:!1};let i=j(e,s.replace(/\.js$/,".ts"));return n(i)?{path:i,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Ge(t,e){let n=Q(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 Qe(m(n.path,"utf8")):m(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(r),!0}async function Qe(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ye({basePath:t,bridgePath:e,bridgeSessionKey:n,handle:r,request:s,response:o}){if(await Ge(s,o))return;let i=Xe(s),a=Ze(s),u=i||a?nt(o,{basePath:t,bridgePath:e,bridgeSessionKey:n,patchNextDevChunk:a}):()=>{};try{await r(s,o)}catch(c){throw u(),c}}function Xe(t){return et(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ze(t){return tt(t)?(t.headers["accept-encoding"]="identity",!0):!1}function et(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(R)||e===z)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function tt(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 nt(t,e){let n=[],r=t,s=r.flushHeaders.bind(t),o=r.write.bind(t),i=r.end.bind(t);return r.flushHeaders=()=>{},r.write=(a,u,c)=>(a!==void 0&&n.push(U(a,J(u))),W(u),W(c),!0),r.end=(a,u,c)=>{let p=typeof a=="function"?void 0:a;p!==void 0&&n.push(U(p,J(u))),r.write=o,r.end=i,r.flushHeaders=s;let d=Buffer.concat(n),l=rt(t,d,e);l!==d&&!t.headersSent&&t.removeHeader("content-length");let g=typeof a=="function"?a:typeof u=="function"?u:typeof c=="function"?c:void 0;return g?i(l,g):i(l)},()=>{r.write=o,r.end=i,r.flushHeaders=s}}function rt(t,e,n){if(ot(t,e))return Buffer.from(ze(e.toString("utf8"),n));if(n.patchNextDevChunk&&it(t)){let r=e.toString("utf8"),s=at(r);if(s!==r)return Buffer.from(s)}return e}function st(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function ot(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 it(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 at(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
- `)],[["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])=>st(n,r,s),t)}function st(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 D(t){typeof t=="function"&&t()}async function ot(t){let n=U(S(t,"package.json"))(Ee);return n.default??n}function it(t){return J(t)!=="src"?t:N(at(t),"dist")}function at(t){return V(t)?v.posix.dirname(t):b(t)}function N(t,e){return V(t)?v.posix.join(t,e):S(t,e)}function V(t){return t.includes("/")&&!t.includes("\\")}function ct(t){let e=S(t,".vcp/current-snapshot.json");if(!y(e))return"sandbox_worktree";try{let n=JSON.parse(m(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function ut(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function dt(t,e,n){return new Promise((r,s)=>{t.once("error",s),t.listen(e,n,()=>{t.off("error",s),r()})})}export{Ae as attachNextDevUpgradeHandler,Ue as createSiteEditAutoBootstrapHtmlSnippet,$e as injectSiteEditAutoBootstrap,rt as patchNextFirefoxDevChunk,Ge as prepareFirefoxNextDevChunkPatchRequest,ze as prepareSiteEditHtmlInjectionRequest,F as resolveSiteEditClientAsset,_t as resolveSiteEditClientAssetPath,Ke as resolveSiteEditNextDevBundler,Bt as startSiteEditNextDevServer,Fe 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,s])=>ut(n,r,s),t)}function ut(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 U(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function J(t){return typeof t=="string"?t:void 0}function W(t){typeof t=="function"&&t()}async function ct(t){let n=L(b(t,"package.json"))(Te);return n.default??n}function dt(t){return $(t)!=="src"?t:j(ht(t),"dist")}function ht(t){return Y(t)?I.posix.dirname(t):S(t)}function j(t,e){return Y(t)?I.posix.join(t,e):b(t,e)}function Y(t){return t.includes("/")&&!t.includes("\\")}function ft(t){let e=b(t,".vcp/current-snapshot.json");if(!y(e))return"sandbox_worktree";try{let n=JSON.parse(m(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function lt(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function pt(t,e,n){return new Promise((r,s)=>{t.once("error",s),t.listen(e,n,()=>{t.off("error",s),r()})})}export{Je as attachNextDevUpgradeHandler,Le as createSiteEditAutoBootstrapHtmlSnippet,ze as injectSiteEditAutoBootstrap,at as patchNextFirefoxDevChunk,Ze as prepareFirefoxNextDevChunkPatchRequest,Xe as prepareSiteEditHtmlInjectionRequest,Q as resolveSiteEditClientAsset,Kt as resolveSiteEditClientAssetPath,De as resolveSiteEditNextDevBundler,Ot as startSiteEditNextDevServer,Qe as transpileSiteEditClientSource};