@vcp-dev/site-edit-bridge 0.4.3 → 0.4.5

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