@vcp-dev/site-edit-bridge 0.6.4 → 0.6.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 Fe(e){if(!Ft(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),i=o=>{let s=t.get(o);if(s)return s;let c=e.nodes[o];if(!c)throw new Error(`Missing compact document node ${o}`);let[a,u]=c,m=e.tokens[u];if(typeof m!="string")throw new Error(`Missing compact document token ${u}`);let g=`${a===null?"":i(a)}${m}`;return t.set(o,g),g};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((o,s)=>{let[c,a,u]=o,m=u===void 0?void 0:n[u];if(u!==void 0&&!m)throw new Error(`Missing page composition unit ${u}`);return{key:i(c),...m?{pageCompositionUnitKey:m}:{},operationSummary:Ot(a),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function Ot(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function Ft(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!Xe(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(i=>typeof i=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((i,o)=>Array.isArray(i)&&i.length===2&&(i[0]===null||re(i[0])&&i[0]<o)&&re(i[1])&&i[1]<t.tokens.length)||!t.entries.every(i=>Array.isArray(i)&&(i.length===2||i.length===3)&&re(i[0])&&i[0]<n.length&&re(i[1])&&i[1]<=15&&(i.length===2||re(i[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(i=>Array.isArray(i)&&i.length===2&&re(i[0])&&i[0]<t.entries.length&&Xe(i[1]))}function Xe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}var L=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",i=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||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!U(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?U(t.payload)&&typeof t.payload.id=="string":t.type==="event"?U(t.payload)&&U(t.payload.event):t.type==="auth"?U(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?U(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!U(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||Be(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";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-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Bt(t.request)&&(t.request.mutationContext===void 0||Be(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||Be(t.mutationContext)}}};function U(e){return typeof e=="object"&&e!==null}function Bt(e){return U(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"&&U(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&U(e.params)}function Be(e){return Mt(e)}function Mt(e){return U(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}var qt="vcp:designer:trace",Kt="designer_trace",Je="__VCP_DESIGNER_TRACE__";var Vt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Ut(e=globalThis){let t=e;try{if(t.localStorage?.getItem(qt)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Kt)==="1"}catch{return!1}}function J(e,t={},n=globalThis){if(!Ut(n))return;let r={type:e,timestamp:Date.now(),payload:wt(t)},i=n,o=i[Je]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),i[Je]=o;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function wt(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,i]of Object.entries(e)){if(Vt.test(r)){n[r]="[redacted]";continue}n[r]=Me(i,t+1)}return n}var Se=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===qe&&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 a=le(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",a.message),n(a);return}let i={socket:r,settled:!1,reject:n};this.connectAttempt=i,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==i||(i.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(c,a)=>{this.cleanupSocket(r,c,a)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==i)){if(this.options.authKey){try{r.send(L.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){s(le(c,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=c=>{if(this.socket!==r)return;let a=le(c,"WebSocket failed");s(a,"failed")},r.onmessage=c=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===i&&!i.settled){this.handleAuthHandshakeMessage(c.data,r,i,()=>{o()});return}this.handleMessage(c.data)}},r.onclose=c=>{if(this.socket!==r)return;let a=this.intentionalClose,u=new Error(zt(c,{intentional:a}));s(u,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})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}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,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){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!==qe||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let i=`${t}-${this.sequence+=1}`,o=Yt(i,t,n);return J("bridge.request",{id:i,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Qe(n.request,"kind"),documentVersion:Qe(n.request,"documentVersion")}),new Promise((s,c)=>{let a=this.resolveRequestTimeoutMs(t),u=a>0?setTimeout(()=>{let m=this.pending.get(i);m&&(this.pending.delete(i),J("bridge.response",{id:i,kind:t,ok:!1,timedOut:!0}),m.reject(new Error(`Bridge request timed out after ${a}ms: ${t}`)))},a):null;u?.unref?.(),this.pending.set(i,{kind:t,timeout:u,resolve:m=>s(m),reject:c});try{r.send(L.stringifyMessage(o))}catch(m){let g=le(m,"WebSocket send failed");this.clearPendingRequest(i),c(g),this.cleanupSocket(r,g,"failed")}})}handleAuthHandshakeMessage(t,n,r,i){try{if(L.parseMessage(t).type==="auth-ok"){i();return}throw new Error("Bridge authentication failed")}catch(o){let s=le(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=L.parseMessage(t);if(n.type==="event"){for(let i of this.listeners)i(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"){J("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}J("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Ht(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Fe(n.payload.result.data)}:r.kind==="initialize-session"?Gt(n.payload.result):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):$t[t]??jt}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let i=this.connectAttempt;this.connectAttempt=null,i.settled||(i.settled=!0,i.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===Wt||t.readyState===qe)&&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 i of this.connectionStatusListeners)i(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)}},Wt=0,qe=1,jt=15e3,$t={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function le(e,t){return e instanceof Error?e:new Error(t)}function zt(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 Qe(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Ht(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 Ke(e)}var Ke=class{constructor(t){this.params=t,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!Ze(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=Ze(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let i=this.styleGeneration,o=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===i&&(this.styleContextCache={generation:i,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===o&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:i,request:o},o}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 acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),i=this.editContextCache.get(r);if(i)return{ok:!0,data:i};let o=this.editContextInFlight.get(r);if(o)return o;let s=this.objectGeneration,c=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.editContextCache.set(r,a.data),a)).finally(()=>{this.editContextInFlight.get(r)===c&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,c),c}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),i=this.classNameSourceCache.get(r);if(i)return i;let o=this.classNameSourceInFlight.get(r);if(o)return o;let s=this.objectGeneration,c=this.params.client.getClassNameSource(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,a),a)).finally(()=>{this.classNameSourceInFlight.get(r)===c&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,c),c}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,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){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.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return J("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){J("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let i=await this.refreshInFlight;if(typeof t!="number"||i.version>=t||this.currentDocument.version>=t)return this.currentDocument}J("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(i=>(this.currentDocument=i.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,i.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function Ze(e){return e.version===0&&e.entries.length===0}function Gt(e){let t=e;return{...t,data:{...t.data,document:Fe(t.data.document)}}}function Yt(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};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,mutationContext:n.mutationContext}}}}var et="vcp-window-message";function Xt(e){return{source:et,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Jt(e){try{return I(e)?G(e,"source",et)&&G(e,"version",1)&&P(e,"namespace")&&P(e,"channel")&&W(e,"body")&&(!ee(e,"sessionKey")||P(e,"sessionKey")):!1}catch{return!1}}var tt="site-edit",nt="frame-runtime";function fe(e,t={}){return Xt({namespace:tt,channel:nt,sessionKey:t.sessionKey,body:e})}function rt(e){try{return!Jt(e)||e.namespace!==tt||e.channel!==nt?!1:ln(e.body)}catch{return!1}}var ee=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function W(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function h(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function G(e,t,n){return W(e,t)&&h(e,t)===n}function P(e,t){return W(e,t)&&typeof h(e,t)=="string"}function it(e,t){return W(e,t)&&typeof h(e,t)=="boolean"}function q(e,t){let n=h(e,t);return W(e,t)&&typeof n=="number"&&Number.isFinite(n)}function de(e,t){return!ee(e,t)||h(e,t)===void 0||P(e,t)}function ie(e,t){return!ee(e,t)||h(e,t)===void 0||q(e,t)}function Ee(e,t){let n=h(e,t);return!ee(e,t)||n===void 0||W(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function w(e,t){return!ee(e,t)||h(e,t)===void 0}function I(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qt(e){return I(e)&&Reflect.ownKeys(e).length===0}function ot(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function pe(e){return I(e)&&P(e,"key")&&Ee(e,"instanceIndex")&&Ee(e,"instanceCount")&&Ee(e,"textSegmentIndex")}function Zt(e){return I(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&W(e,t)&&(typeof h(e,t)=="string"||h(e,t)===null))}function st(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Lt(e){return I(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&W(e,t)&&st(h(e,t)))}function en(e){if(!I(e))return!1;let t=h(e,"priority");return P(e,"property")&&W(e,"value")&&st(h(e,"value"))&&(!ee(e,"priority")||t===void 0||t==="important")}function tn(e){return I(e)?(w(e,"attributes")||Zt(h(e,"attributes")))&&de(e,"className")&&(w(e,"style")||Lt(h(e,"style")))&&(w(e,"styleDeclarations")||Array.isArray(h(e,"styleDeclarations"))&&h(e,"styleDeclarations").every(en)):!1}function nn(e){return I(e)&&q(e,"x")&&q(e,"y")&&(w(e,"detailLevel")||G(e,"detailLevel","summary")||G(e,"detailLevel","full"))}function rn(e){return I(e)&&pe(h(e,"ref"))}function on(e){if(!I(e)||!I(h(e,"variables")))return!1;let t=h(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&P(t,n))?w(e,"stylesheets")||ot(h(e,"stylesheets")):!1}function sn(e){if(!G(e,"type","request")||!P(e,"id")||!P(e,"kind")||!W(e,"payload"))return!1;let t=h(e,"kind"),n=h(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return nn(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return Qt(n);case"bridge-get-source-file":return I(n)&&P(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return I(n)&&P(n,"key")&&de(n,"routeId");case"scroll-to":return I(n)&&q(n,"x")&&q(n,"y");case"scroll-by":return I(n)&&q(n,"deltaX")&&q(n,"deltaY");case"set-interaction-mode":return I(n)&&it(n,"enabled");case"set-theme-override":return on(n);case"get-theme-variables":return I(n)&&ot(h(n,"names"));case"compute-drop-target-at-point":return I(n)&&q(n,"x")&&q(n,"y")&&(G(n,"dragKind","insert")||G(n,"dragKind","move"))&&(w(n,"movingRef")||pe(h(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return I(n)&&(w(n,"ref")||pe(h(n,"ref")));case"apply-node-patch":return I(n)&&pe(h(n,"ref"))&&tn(h(n,"patch"))&&(w(n,"preview")||I(h(n,"preview"))&&P(h(n,"preview"),"sessionId")&&Ee(h(n,"preview"),"revision")&&ee(h(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return rn(n);case"bridge-initialize-session":case"bridge-get-style-context":return I(n)&&P(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return I(n)&&P(n,"routeId")&&ie(n,"minVersion")&&ie(n,"version");case"bridge-execute":return I(n)&&I(h(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return I(n)&&P(n,"subscriptionId");default:return!1}}function cn(e){return G(e,"type","response")&&P(e,"id")&&it(e,"ok")&&(w(e,"error")||P(e,"error"))}var an=new Set(["pointer-down","pointer-move","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function un(e){if(!G(e,"type","event")||!P(e,"kind")||!I(h(e,"payload")))return!1;let t=h(e,"kind"),n=h(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return pe(h(n,"ref"))&&de(n,"value")&&(w(n,"hit")||I(h(n,"hit")));case"node-bounds-change":return I(h(n,"hit"));case"bridge-event":return P(n,"subscriptionId")&&I(h(n,"event"));case"route-ready":return P(n,"routeId")&&ie(n,"version");case"bridge-status":{let r=h(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&de(n,"routeId")&&ie(n,"attempt")&&ie(n,"retryInMs")&&de(n,"messageKey")}case"scroll":{let r=h(n,"metrics");return I(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(i=>q(r,i))}default:return an.has(t)&&q(n,"clientX")&&q(n,"clientY")&&ie(n,"buttons")&&(h(n,"hit")===null||I(h(n,"hit")))}}function ln(e){if(!I(e))return!1;switch(h(e,"type")){case"request":return sn(e);case"response":return cn(e);case"event":return un(e);default:return!1}}var we="vcp-site-edit:route-ready",We="vcp-site-edit:bridge-status",dn=1e3,pn="data-vcp-ui-component",ft="data-vcp-theme-preview",ct="::repeat-item#",Ie="components/ui",fn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),mn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function hn(e,t=""){let n=bt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,i=r.startsWith("/")?r:`/${r}`;return i==="/"?"/":i.replace(/\/+$/,"")}function gn(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 yn(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 Vr(e=window,t={}){let n=yn(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=bn({bridgeUrl:n,options:t}),i=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(i?.started){if(Sn(i.signature,r)){await i.syncRoute?.();return}i.cleanup?.()}let o={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,a=t.create_client??(p=>new Se({url:p,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Nn,m=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},g=()=>hn(e.location.pathname,t.basePath||""),D=!!e.parent&&e.parent!==e,C=p=>{An(e,p)},v=p=>{o.currentDocument=p,o.currentEntriesByKey=new Map((p?.entries??[]).map(y=>[y.key,y]))},R=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},O=(p,y)=>!o.disposed&&y===o.routeSequence&&p===g(),k=async(p,y)=>{let T=o.activeBridge;if(!T)return null;let d=await T.getDocument(p);return O(p,y)&&v(d.data),d.data},B=()=>{R(),v(null);let p=o.activeBridge;o.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let y=o.activeClient;o.activeClient=null,y?.disconnect()},Ne=p=>p===s.routeId&&!!o.activeBridge&&(D||!!(o.currentDocument&&On(o.currentDocument,p)))&&Pn(o.activeClient),Ae=p=>Math.min(dn*2**Math.max(0,p),8e3),te=(p,y,T)=>{if(o.disposed)return;m();let d=Ae(T);C({state:"reconnecting",routeId:p,attempt:T,retryInMs:d,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||y!==o.routeSequence)&&ge(T+1).catch(f=>{let l=g();if(p===l){if(oe(f)){C({state:"reload-required",routeId:p,attempt:T,messageKey:"studio.errors.previewBridgeReloadRequired"});return}te(p,o.routeSequence,T+1)}})},d)},se=(p,y,T)=>{if(!O(p,y)||o.activeClient===null)return;if(oe(T.message)){B(),m(),C({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let d=o.activeClient;R(),v(null);let f=o.activeBridge;o.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,d?.disconnect(),te(p,y,0)},Pe=p=>{let y=g(),T=o.routeSequence;if(!(!O(y,T)||o.activeClient===null)){if(oe(p)){B(),m(),C({state:"reload-required",routeId:y,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}yt(p)&&se(y,T,{state:"failed",message:ze(p,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=vn(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:p=>o.currentEntriesByKey.get(p)??null,setCurrentDocument:v,onBridgeRequestError:p=>{Pe(p)}});let ce=async()=>ge(0),ge=async p=>{if(o.disposed)return;let y=g();if(Ne(y))return;let T=o.syncInFlight;if(T?.routeId===y)return T.promise;let d=o.routeSequence+1,f=Oe(y,d,p);o.syncInFlight={routeId:y,sequence:d,promise:f};try{await f}finally{o.syncInFlight?.promise===f&&(o.syncInFlight=null)}},Oe=async(p,y,T)=>{o.routeSequence=y,m(),B(),C({state:T>0?"reconnecting":"connecting",routeId:p,attempt:T,messageKey:T>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let d=a(n),f=!1;o.activeClient=d,o.unsubscribeConnectionStatus=d.subscribeConnectionStatus?.(l=>{f&&(l.state==="closed"||l.state==="failed")&&se(p,y,l)});try{if(await d.connect(),!O(p,y)){d.disconnect();return}let l=Le({routeId:p,client:d,initialDocument:xn(p)});o.activeBridge=l,c()&&(e.__VCP_SITE_EDIT__=l),o.activeClient=d,o.unsubscribeDocument=l.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===p&&o.currentDocument&&N.version>o.currentDocument.version&&k(p,y).catch(()=>{})}),c()&&(s.routeId=p);let _=(D?null:await l.initializeSession({routeId:p}))?.data.document??null;if(_&&v(_),!O(p,y)){d.disconnect();return}f=!0,C({state:"ready",routeId:p,attempt:T,messageKey:"studio.status.previewReady"}),gn(e,{documentVersion:_?.version??0,routeId:p,versions:t.runtime_versions}),_&&gt(e,{routeId:p,version:_.version})}catch(l){if(R(),o.activeClient===d&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,d.disconnect(),v(null),!O(p,y))return;throw C({state:oe(l)?"reload-required":"failed",routeId:p,attempt:T,messageKey:oe(l)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),l}},Y=p=>{if(o.disposed)return;let y=g();if(oe(p)){m(),C({state:"reload-required",routeId:y,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}te(y,o.routeSequence,0)},z=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,u(()=>{o.syncScheduled=!1,!o.disposed&&ce().catch(p=>Y(p))}))},ye=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,m(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),B(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:ce,cleanup:ye},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,o.unbindBootstrapLifecycle=In(e,ye),o.unbindRouteChange=kn(e,z,g),t.defer_initial_sync){z();return}await ce()}function bn(e){return{basePath:bt(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:En(e.options.bridge_session_key)}}function Sn(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function En(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function In(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Cn(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Cn(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function xn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function vn(e=window,t={}){let n=null,r=null,i=null,o=null,s=null,c=null,a=null,u=null,m=null,g=new Map,D=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,C=()=>{n?.(),n=null,r=null},v=()=>{i?.(),i=null,o?.(),o=null},R=(d,f,l)=>{let A=s?.sessionKey!==d||s?.sourceWindow!==f||s?.targetOrigin!==l;s={sessionKey:d,sourceWindow:f,targetOrigin:l},A&&(u=null,m=null)},O=(d,f)=>{let l=e.parent&&e.parent!==e?e.parent:null;return!l||f!==l?!1:!D||d===D},k=()=>{for(let d of g.values())d();g.clear()},B=d=>JSON.stringify([d.routeId,d.version]),Ne=()=>!a||a.state==="ready",Ae=d=>JSON.stringify([d.state,d.routeId??null,d.attempt??null,d.retryInMs??null,d.messageKey??null]),te=d=>{if(!Ne())return;let f=B(d);u!==f&&(o?.(),o=null,Y({kind:"route-ready",payload:{routeId:d.routeId,version:d.version}}),s&&(u=f))},se=d=>{let f=Ae(d);m!==f&&(d.state!=="ready"&&(u=null,c=null),Y({kind:"bridge-status",payload:d}),s&&(m=f))},Pe=d=>{c=d,te(d)},ce=d=>{a=d,se(d)},ge=()=>{c&&te(c)},Oe=()=>{a&&se(a)},Y=d=>{s&&s.sourceWindow.postMessage(fe({type:"event",...d},{sessionKey:s.sessionKey}),s.targetOrigin)},z=(d,f,l,A)=>{let _=_e(e.document,f.clientX,f.clientY,t.getCurrentDocument?.()??null),N=_?K(_,l==="full"?$(e.document,_,t.getCurrentDocument?.()??null):lt(e.document,_,t.getCurrentDocument?.()??null),t.getDocumentEntry,l):null;A&&N&&(d==="pointer-click"||d==="pointer-double-click")&&(A.preventDefault(),A.stopPropagation(),typeof A.stopImmediatePropagation=="function"&&A.stopImmediatePropagation()),Y({kind:d,payload:{clientX:f.clientX,clientY:f.clientY,buttons:Number(f.buttons??0),hit:N}})},ye=(d,f,l)=>{v(),s={sessionKey:d,sourceWindow:f,targetOrigin:l};let A=vr(e.document),_=null,N=null,b=()=>{N=null;let S=_;_=null,S&&z("pointer-move",S,"summary")},V=S=>{_={clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},N===null&&(N=mt(e,b))},X=S=>{z("pointer-down",{clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},"full",S)},ne=S=>{z("pointer-up",{clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},"summary",S)},H=S=>{z("pointer-cancel",{clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},"summary",S)},Z=S=>{z("pointer-click",{clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},"full",S)},ae=S=>{z("pointer-double-click",{clientX:Number(S.clientX),clientY:Number(S.clientY),buttons:Number(S.buttons)},"full",S)},ue=()=>{Y({kind:"scroll",payload:{metrics:ve(e)}})};e.document.addEventListener("pointerdown",X,!0),e.document.addEventListener("pointermove",V,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",ne,!0),e.document.addEventListener("pointercancel",H,!0),e.document.addEventListener("click",Z,!0),e.document.addEventListener("dblclick",ae,!0),e.addEventListener("scroll",ue,{passive:!0}),i=()=>{N!==null&&(ht(e,N),N=null),_=null,A(),e.document.removeEventListener("pointerdown",X,!0),e.document.removeEventListener("pointermove",V,!0),e.document.removeEventListener("pointerup",ne,!0),e.document.removeEventListener("pointercancel",H,!0),e.document.removeEventListener("click",Z,!0),e.document.removeEventListener("dblclick",ae,!0),e.removeEventListener("scroll",ue)}},p=d=>{let f=d.detail;f?.routeId&&Pe(f)},y=d=>{let f=d.detail;f?.state&&ce(f)},T=d=>{let f=d.data;if(!rt(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!=="restore-text-edit"&&f.body.kind!=="clear-text-edit-rollback"&&f.body.kind!=="start-text-edit-at-point"&&f.body.kind!=="hit-test-at-point"&&!at(f.body))return;let l=f.body,A=typeof f.sessionKey=="string"?f.sessionKey:null,_=d.source,N=d.origin;if(!A||!N||!_||typeof _.postMessage!="function"||!O(A,_))return;if(s){if(s.sourceWindow!==_||s.targetOrigin!==N)return;s.sessionKey!==A&&(C(),v(),k(),s=null)}R(A,_,N),Oe(),ge();let b=V=>{let X=typeof l.id=="string"?l.id:"unknown";_.postMessage(fe({id:X,...V},{sessionKey:A}),N)};try{if(at(l)){_n({message:l,sendEvent:E=>{_.postMessage(fe({type:"event",...E},{sessionKey:A}),N)},sendResponse:b,subscriptions:g,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(l.kind==="apply-node-patch"){let E=Q(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 x=l.payload.preview,M=x?lr(x.sessionId,l.payload.ref):null;if(M&&x){let be=me.get(M)??-1;if(x.revision<be){b({type:"response",ok:!0,result:{applied:!1,appliedRevision:x.revision,stale:!0,latestRevision:be}});return}if(x.revision===be){b({type:"response",ok:!0,result:{applied:!1,appliedRevision:x.revision,duplicate:!0,latestRevision:be}});return}}if(ar(E,l.payload.patch),M&&x&&dr(M,x.revision),x?.responseDetail==="none"){b({type:"response",ok:!0,result:{applied:!0,appliedRevision:x.revision}});return}b({type:"response",ok:!0,result:K(E,$(e.document,E,t.getCurrentDocument?.()??null),t.getDocumentEntry,x?.responseDetail??"full")});return}if(l.kind==="get-hit-by-ref"){let E=Q(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:K(E,$(e.document,E,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(l.kind==="get-path-by-ref"){let E=Q(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 x=[],M=E;for(;M;)M.getAttribute("data-vcp-edit-key")&&x.push(K(M,$(e.document,M,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),M=M.parentElement;b({type:"response",ok:!0,result:x.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&&ut(r.ref,E)&&(r=null),b({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!ut(r.ref,E)){b({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let x=Mn(e.document,r,t.getCurrentDocument?.()??null);r=null,b(x?{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:ve(e)});return}if(l.kind==="scroll-to"){let E=Number(l.payload.x),x=Number(l.payload.y);if(!Number.isFinite(E)||!Number.isFinite(x)){b({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:E,top:x}),b({type:"response",ok:!0,result:ve(e)});return}if(l.kind==="scroll-by"){let E=Number(l.payload.deltaX),x=Number(l.payload.deltaY);if(!Number.isFinite(E)||!Number.isFinite(x)){b({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:E,top:x}),b({type:"response",ok:!0,result:{...ve(e),scrolled:!0}});return}if(l.kind==="set-interaction-mode"){l.payload.enabled?ye(A,_,N):s?.sourceWindow===_&&s.targetOrigin===N&&s.sessionKey===A&&v(),b({type:"response",ok:!0,result:{interactionEnabled:l.payload.enabled}});return}if(l.kind==="set-theme-override"){pr(e.document,l.payload),b({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(l.kind==="clear-theme-override"){fr(e.document),b({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(l.kind==="get-theme-variables"){b({type:"response",ok:!0,result:mr(e.document,l.payload.names)});return}if(l.kind==="compute-drop-target-at-point"){let E=Number(l.payload?.x),x=Number(l.payload?.y);if(!Number.isFinite(E)||!Number.isFinite(x)){b({type:"response",ok:!1,error:"Invalid drop target point"});return}b({type:"response",ok:!0,result:nr(e,E,x,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 x=Q(e.document,E,t.getCurrentDocument?.()??null);if(!x){b({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=Qn(e,x,E,t.getCurrentDocument,t.getDocumentEntry,M=>Y({kind:"node-bounds-change",payload:{hit:M}})),b({type:"response",ok:!0,result:{observing:!0}}),Y({kind:"node-bounds-change",payload:{hit:K(x,E,t.getDocumentEntry,"summary")}});return}if(l.kind==="clear-node-bounds-observer"){o?.(),o=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 V=Number(l.payload?.x),X=Number(l.payload?.y);if(!Number.isFinite(V)||!Number.isFinite(X)){b({type:"response",ok:!1,error:"Invalid text edit point"});return}let ne=l.kind==="hit-test-at-point"?_e(e.document,V,X,t.getCurrentDocument?.()??null):Kn(e.document,V,X,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!ne){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"?ne:null,Z=l.kind==="hit-test-at-point"?ne:H.element,ae=l.payload.detailLevel??"full",ue=ae==="full"?$(e.document,Z,t.getCurrentDocument?.()??null):lt(e.document,Z,t.getCurrentDocument?.()??null),S=H&&typeof H.textSegmentIndex=="number"?{...ue,textSegmentIndex:H.textSegmentIndex}:ue,Pt=K(Z,S,t.getDocumentEntry,ae);if(l.kind==="hit-test-at-point"){b({type:"response",ok:!0,result:Pt});return}C(),n=br(e,Z,S,E=>{_.postMessage(fe({type:"event",...E},{sessionKey:A}),N)},{...H?.textNode?{textNode:H.textNode}:{},onCommitSnapshot:E=>{r=E}}),b({type:"response",ok:!0,result:{ref:S}})}catch(V){b({type:"response",ok:!1,error:V instanceof Error?V.message:"Failed to start text edit"})}};return e.addEventListener("message",T),e.addEventListener(we,p),e.addEventListener(We,y),()=>{C(),v(),s=null,k(),e.removeEventListener("message",T),e.removeEventListener(we,p),e.removeEventListener(We,y)}}function at(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function Rn(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function _n({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:i,setCurrentDocument:o,onBridgeRequestError:s,windowLike:c}){let a=c.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let u=await a.initializeSession({routeId:e.payload.routeId});o?.(u.data.document),gt(c,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await a.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await a.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await a.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.acknowledgeDocumentVersion?await a.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await a.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Tn(u,e.payload.key,c.document,i?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let u=await a.execute(e.payload.request),m=i?.()?.routeId;if(u.ok&&m&&a.acknowledgeDocumentVersion&&Rn(e.payload.request)){let g=await a.acknowledgeDocumentVersion(m,u.data.resultVersion);o?.(g.data)}n({type:"response",ok:!0,result:u});return}case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let m=a.subscribe(g=>{t({kind:"bridge-event",payload:{event:g,subscriptionId:u}})});r.set(u,m),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:Fn(u)})}}function Tn(e,t,n,r){if(!e.ok)return e;let i=Q(n,{key:t},r),o=i?Dn(i):null;return o?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...o}}}:e}function Dn(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 kn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,i=e.history.replaceState,o=n(),s=()=>{let u=n();u!==o&&(o=u,t())},c=()=>s(),a=()=>s();return e.history.pushState=function(...m){let g=r.apply(this,m);return s(),g},e.history.replaceState=function(...m){let g=i.apply(this,m);return s(),g},e.addEventListener("popstate",c),e.addEventListener("hashchange",a),()=>{e.history.pushState=r,e.history.replaceState=i,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",a)}}function Nn(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function mt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function ht(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function gt(e,t){e.dispatchEvent(new CustomEvent(we,{detail:t}))}function An(e,t){e.dispatchEvent(new CustomEvent(We,{detail:t}))}function Pn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function On(e,t){return e.routeId===t}function ze(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function yt(e){let t=ze(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Fn(e){let t=ze(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":yt(t)?"Site edit bridge disconnected":t}function oe(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 bt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function He(e){return fn.has(Et(e))}function Bn(e){return mn.has(Et(e))}function St(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:He(e.tagName),canMove:!1,canRemove:!1}}function Et(e){return e?.trim().toLowerCase()??""}function ut(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 Mn(e,t,n){let r=Q(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let i=qn(r,t.ref.textSegmentIndex);return i?(i.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function qn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!Re(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Kn(e,t,n,r,i){let o=_e(e,t,n,r),s=It(o);if(!s)return null;let c=s.getAttribute("data-vcp-edit-key")??"",a=$(e,s,r),u=i?.(a.key)??i?.(c);if(!St({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let g=Vn(e,t,n,s);if(g){let D=wn(s,g);if(D!==null)return{element:s,textNode:g,textSegmentIndex:D}}return ke(s)?null:{element:s}}function Vn(e,t,n,r){let i=Un(e,t,n);return!i||i.parentElement!==r?null:i}function Un(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(Re(o))return o;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return Re(c)?c:null}function wn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!Re(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function Re(e){return e?.nodeType===3}function _e(e,t,n,r=null){let i=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of i){let s=It(o),c=s?.getAttribute("data-vcp-edit-key")??"";if(s&&Hn(s,r,c))return s}return null}function It(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ge(t))return n??t;!Wn(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ge(e){return e.getAttribute(pn)!==null}function Wn(e){return jn(e.split("::")[0]??"")}function jn(e){if(!e)return!1;let t=$n(e);return t===Ie||t.startsWith(`${Ie}/`)||t.includes(`/${Ie}/`)||t.endsWith(`/${Ie}`)}function $n(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let i of n.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}return r.join("/")}function $(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",i=xt(Rt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${At(r)}"]`))),n,r);if(i.length<=1)return{key:dt(n,r,0)};let o=i.indexOf(t);return o>=0?{key:dt(n,r,o),instanceIndex:o,instanceCount:i.length}:{key:r}}function lt(e,t,n){return $(e,t,n)}function Q(e,t,n){let r=Te(t.key)??t.key,i=xt(Rt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${At(r)}"]`))),n,t.key);if(i.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<i.length?t.instanceIndex:null,s=(Te(t.key)??t.key)!==t.key;if(o!==null&&!s)return i[o]??null;let c=zn(n,t.key);return c!==null&&c>=0&&c<i.length?i[c]??null:o!==null?i[o]??null:i[0]??null}function dt(e,t,n){return Ct(e,t)[n]?.key??t}function zn(e,t){let n=Te(t);if(!n)return null;let i=Ct(e,n).findIndex(o=>o.key===t);return i>=0?i:null}function Ct(e,t){return(e?.entries??[]).filter(n=>(Te(n.key)??n.key)===t)}function xt(e,t,n){let r=vt(t,n);return r?e.filter(i=>i.tagName.toLowerCase()===r):e}function Hn(e,t,n){let r=vt(t,n);return!r||e.tagName.toLowerCase()===r}function vt(e,t){return null}var Gn=2,Yn=4;function Rt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&Yn)!==0?-1:(r&Gn)!==0?1:0})}function Te(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(ct);if(n<0)break;let r=Number(t.slice(n+ct.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function Xn(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{..._t(n),paddingTop:F(n?.paddingTop),paddingRight:F(n?.paddingRight),paddingBottom:F(n?.paddingBottom),paddingLeft:F(n?.paddingLeft),borderTopWidth:F(n?.borderTopWidth),borderRightWidth:F(n?.borderRightWidth),borderBottomWidth:F(n?.borderBottomWidth),borderLeftWidth:F(n?.borderLeftWidth),columnGap:F(n?.columnGap),rowGap:F(n?.rowGap)}}function _t(e){return{marginTop:F(e?.marginTop,!0),marginRight:F(e?.marginRight,!0),marginBottom:F(e?.marginBottom,!0),marginLeft:F(e?.marginLeft,!0)}}function F(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function Jn(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:tr(n.getBoundingClientRect()),margin:_t(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function K(e,t,n,r="full"){let i=e.getBoundingClientRect(),o=n?.(t.key)??null,s=e.tagName.toLowerCase(),c=De(e),a=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([v,R])=>[v,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(v=>[v,e.getAttribute(v)??""]))}:{},u=St({operationSummary:o?.operationSummary,tagName:s,fallbackMode:"preview"}),m=Ge(e),g=!0,D=Tt(e)?.getAttribute("data-vcp-edit-key")??null,C=Jn(e);return{ref:t,key:t.key,detailLevel:r,tagName:s,...o?{sourceKind:"jsx"}:{},...D?{parentKey:D}:{},...o?.pageCompositionUnitKey?{pageCompositionUnitKey:o.pageCompositionUnitKey}:{},...a,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:m?!1:!!ke(e)||u.canInsertChild||g&&He(s)},layout:c,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:C,childRects:C.map(({rect:v})=>v),spacing:Xn(e)}}function Qn(e,t,n,r,i,o){let s=t,c=K(s,n,i,"summary"),a=null,u=()=>{a===null&&(a=mt(e,m))},m=()=>{a=null;let O=Q(e.document,n,r?.()??null);if(!O)return;O!==s&&(D?.unobserve(s),s=O,D?.observe(s));let k=K(s,n,i,"summary");k.rect.width<=0||k.rect.height<=0||Zn(c,k)&&(c=k,o(k))},g=e.ResizeObserver,D=typeof g=="function"?new g(u):null;D?.observe(s);let C=e.MutationObserver,v=typeof C=="function"?new C(u):null;v?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",u,{passive:!0});let R=e.visualViewport;return R?.addEventListener?.("resize",u,{passive:!0}),e.document.addEventListener("load",u,!0),()=>{a!==null&&(ht(e,a),a=null),D?.disconnect(),v?.disconnect(),e.removeEventListener("resize",u),R?.removeEventListener?.("resize",u),e.document.removeEventListener("load",u,!0)}}function Zn(e,t){return Ye(e.rect,t.rect)||Ln(e.childBoxes,t.childBoxes)||er(e.childRects,t.childRects)||je(e.spacing,t.spacing)||je(e.layout,t.layout)}function Ln(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>{let s=r[o];return!s||Ye(i.rect,s.rect)||je(i.margin,s.margin)})}function er(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>Ye(i,r[o]??i))}function je(e,t){let n=e??{},r=t??{},i=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(i).some(o=>n[o]!==r[o])}function tr(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function Ye(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 nr(e,t,n,r,i,o,s){let c=e.document,a=_e(c,t,n,o);if(!a)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=i?Q(c,i,o):null;if(u&&$e(a,u))return Ce(c,a,"self-or-descendant",o,s);if(r==="move"&&u){let R=sr(c,a,u,o,s);if(R){let O=Ve(R.child,R.targetParent,t,n,"nearest");if(O)return xe(c,R.child,R.targetParent,O,o,s)}}let m=null,g=!1,D=a,C=a.parentElement;for(;C;){if(C.getAttribute("data-vcp-edit-key")){if(u&&$e(C,u))return Ce(c,a,"self-or-descendant",o,s);let R=pt(C,r,s);if(R==="accept"){m={child:D,targetParent:C};break}R==="blocked"&&(g=!0),D=C}C=C.parentElement}let v=pt(a,r,s);if(v==="accept"){if(m){let R=Ve(m.child,m.targetParent,t,n,"edge");if(R)return xe(c,m.child,m.targetParent,R,o,s)}return xe(c,a,a,rr(a,t,n),o,s)}if(m){let R=Ve(m.child,m.targetParent,t,n,"nearest");return xe(c,m.child,m.targetParent,R??"after",o,s)}return v==="blocked"||g?Ce(c,a,"operation-boundary-blocked",o,s):Ce(c,a,"no-accepting-parent",o,s)}function Ce(e,t,n,r,i){return{anchorHit:K(t,$(e,t,r),i,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function xe(e,t,n,r,i,o){let s=K(t,$(e,t,i),o,"summary"),c=K(n,$(e,n,i),o,"summary"),a=De(n).indicatorOrientation,u=r==="append"||r==="prepend"?ir(n.getBoundingClientRect(),a,r):or(t.getBoundingClientRect(),a,r);return{anchorHit:s,targetParentHit:c,relation:r,indicatorOrientation:a,indicatorBounds:u}}function pt(e,t,n){if(Ge(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",i=n?.(r)??null;if(i)return i.operationSummary.canInsertChild===!0?"accept":ke(e)?"blocked":"not-container";let o=e.tagName.toLowerCase();return He(o)?"accept":"not-container"}function Ve(e,t,n,r,i){let o=De(t).indicatorOrientation,s=e.getBoundingClientRect(),c=o==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return i==="edge"&&c>=.25&&c<=.75?null:c<.5?"before":"after"}function rr(e,t,n){let r=De(e).indicatorOrientation,i=e.getBoundingClientRect();return(r==="vertical"?i.width>0?(t-i.left)/i.width:.5:i.height>0?(n-i.top)/i.height:.5)<.5?"prepend":"append"}function De(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",i=n?.flexDirection,o=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(i??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...i?{flexDirection:i}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:s}}function ir(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 or(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 $e(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function sr(e,t,n,r,i){let o=cr(e,t,n,r,i);if(o)return o;let s=Tt(n);if(!s||t===s)return null;let c=t,a=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==s;)c.getAttribute("data-vcp-edit-key")&&(a=c),c=c.parentElement;return c!==s||!a||a===s||a===n||$e(a,n)?null:{child:a,targetParent:s}}function cr(e,t,n,r,i){return null}function Tt(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function ke(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=ke(n);if(r)return r}return null}function ve(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 ar(e,t){Object.entries(t.attributes??{}).forEach(([r,i])=>{if(i===null){e.removeAttribute(r);return}e.setAttribute(r,i)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,i])=>{if(n.has(r))return;let o=e.style,s=r.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i))}),t.styleDeclarations?.forEach(r=>{let i=e.style,o=r.property.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`),s=r.value;if(s==null||s===""){i.removeProperty(o);return}i.setProperty(o,String(s),r.priority)})}var ur=500,me=new Map;function lr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function dr(e,t){if(me.size>=ur){let n=me.keys().next().value;n&&me.delete(n)}me.set(e,t)}var he=new Set;function pr(e,t){let n=e.documentElement?.style,r=new Set;for(let[i,o]of Object.entries(t.variables??{}))i.startsWith("--")&&(r.add(i),n?.setProperty(i,o));for(let i of he)r.has(i)||n?.removeProperty(i);he.clear();for(let i of r)he.add(i);yr(e,t.stylesheets??[])}function fr(e){let t=e.documentElement?.style;for(let n of he)t?.removeProperty(n);he.clear();for(let n of Nt(e))n.remove()}function mr(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,i=r?e.defaultView?.getComputedStyle(r):null,o={};for(let s of n){let c=Dt(i,s);c&&(o[s]=c)}return o}function Dt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return kt(e,r,n)}function kt(e,t,n){if(!t)return null;let r=hr(t);if(!r)return t;let i=Dt(e,r.name,n);return i||(r.fallback?kt(e,r.fallback,n)??r.fallback:null)}function hr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=gr(n),i=r>=0?n.slice(0,r).trim():n;if(!i.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:i,fallback:o||null}}function gr(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 yr(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of Nt(e)){let s=o.getAttribute("href")??"";if(!n.has(s)||r.has(s)){o.remove();continue}r.set(s,o)}let i=e.head;if(i)for(let o of n){if(r.has(o))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(ft,"true"),s.setAttribute("href",o),i.appendChild(s)}}function Nt(e){return Array.from(e.querySelectorAll(`link[${ft}]`))}function br(e,t,n,r,i={}){let o=i.textNode?Sr(e.document,i.textNode):null;if(i.textNode&&!o)throw new Error("Failed to prepare text segment editor");let s=o?.element??t,c=s.textContent??"",a=o?void 0:t.innerHTML,u=Er(s),m=!1,g=()=>{e.document.removeEventListener("pointerdown",C,!0),s.removeEventListener("keydown",v),s.removeEventListener("blur",R),s.removeEventListener("input",O),Cr(s,u)},D=k=>{if(m)return;m=!0;let B=s.textContent??"";if(g(),k==="cancel"){o?.restore(c),o||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(B),k==="commit"&&B!==c){i.onCommitSnapshot?.({ref:n,initialText:c,...a!==void 0?{initialHtml:a}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:B}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function C(k){let B=k.target;B&&s.contains(B)||D("commit")}function v(k){if(k.key==="Escape"){k.preventDefault(),D("cancel");return}k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),D("commit"))}function R(){D("commit")}function O(){r({kind:"text-edit-input",payload:{ref:n,hit:K(t,n,void 0,"full")}})}return Ir(s),e.document.addEventListener("pointerdown",C,!0),s.addEventListener("keydown",v),s.addEventListener("blur",R),s.addEventListener("input",O),Rr(s),_r(s,e.document),g}function Sr(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(i){t.nodeValue=i,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Er(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 Ir(e){xr(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 Cr(e,t){Ue(e,"contenteditable",t.contentEditable),Ue(e,"spellcheck",t.spellcheck),Ue(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function xr(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 Ue(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 Rr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function _r(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function At(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function j(e){let t=Number(e);return Number.isFinite(t)?t:0}export{We as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,we as VCP_SITE_EDIT_ROUTE_READY_EVENT,hn as resolveSiteEditRouteId,yn as resolveSiteEditWebSocketUrl,Vr as startSiteEditAutoBootstrap,vn as startSiteEditFrameRuntime};
1
+ function Ue(e){if(!zt(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),o=i=>{let s=t.get(i);if(s)return s;let c=e.nodes[i];if(!c)throw new Error(`Missing compact document node ${i}`);let[a,u]=c,h=e.tokens[u];if(typeof h!="string")throw new Error(`Missing compact document token ${u}`);let y=`${a===null?"":o(a)}${h}`;return t.set(i,y),y};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((i,s)=>{let[c,a,u]=i,h=u===void 0?void 0:n[u];if(u!==void 0&&!h)throw new Error(`Missing page composition unit ${u}`);return{key:o(c),...h?{pageCompositionUnitKey:h}:{},operationSummary:$t(a),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function $t(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function zt(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!at(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(o=>typeof o=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((o,i)=>Array.isArray(o)&&o.length===2&&(o[0]===null||ce(o[0])&&o[0]<i)&&ce(o[1])&&o[1]<t.tokens.length)||!t.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&ce(o[0])&&o[0]<n.length&&ce(o[1])&&o[1]<=15&&(o.length===2||ce(o[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(o=>Array.isArray(o)&&o.length===2&&ce(o[0])&&o[0]<t.entries.length&&at(o[1]))}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}var ne=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==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||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"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||We(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";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-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Gt(t.request)&&(t.request.mutationContext===void 0||We(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||We(t.mutationContext)}}};function j(e){return typeof e=="object"&&e!==null}function Gt(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 We(e){return Ht(e)}function Ht(e){return j(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}var Yt="vcp:designer:trace",Xt="designer_trace",ut="__VCP_DESIGNER_TRACE__";var Jt=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Qt(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 Z(e,t={},n=globalThis){if(!Qt(n))return;let r={type:e,timestamp:Date.now(),payload:Zt(t)},o=n,i=o[ut]??[];i.push(r),i.length>200&&i.splice(0,i.length-200),o[ut]=i;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Zt(e){return je(e,0)}function je(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>je(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e)){if(Jt.test(r)){n[r]="[redacted]";continue}n[r]=je(o,t+1)}return n}var xe=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===we&&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 a=me(c,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",a.message),n(a);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,a)=>{this.cleanupSocket(r,c,a)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==o)){if(this.options.authKey){try{r.send(ne.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(c){s(me(c,"WebSocket auth failed"),"failed")}return}i()}},r.onerror=c=>{if(this.socket!==r)return;let a=me(c,"WebSocket failed");s(a,"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 a=this.intentionalClose,u=new Error(nn(c,{intentional:a}));s(u,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})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}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,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){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!==we||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=sn(o,t,n);return Z("bridge.request",{id:o,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:lt(n.request,"kind"),documentVersion:lt(n.request,"documentVersion")}),new Promise((s,c)=>{let a=this.resolveRequestTimeoutMs(t),u=a>0?setTimeout(()=>{let h=this.pending.get(o);h&&(this.pending.delete(o),Z("bridge.response",{id:o,kind:t,ok:!1,timedOut:!0}),h.reject(new Error(`Bridge request timed out after ${a}ms: ${t}`)))},a):null;u?.unref?.(),this.pending.set(o,{kind:t,timeout:u,resolve:h=>s(h),reject:c});try{r.send(ne.stringifyMessage(i))}catch(h){let y=me(h,"WebSocket send failed");this.clearPendingRequest(o),c(y),this.cleanupSocket(r,y,"failed")}})}handleAuthHandshakeMessage(t,n,r,o){try{if(ne.parseMessage(t).type==="auth-ok"){o();return}throw new Error("Bridge authentication failed")}catch(i){let s=me(i,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=ne.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"){Z("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}Z("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:Ue(n.payload.result.data)}:r.kind==="initialize-session"?on(n.payload.result):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):tn[t]??en}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===Lt||t.readyState===we)&&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)}},Lt=0,we=1,en=15e3,tn={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function me(e,t){return e instanceof Error?e:new Error(t)}function nn(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 lt(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 pt(e){return new $e(e)}var $e=class{constructor(t){this.params=t,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!dt(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=dt(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let o=this.styleGeneration,i=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===o&&(this.styleContextCache={generation:o,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===i&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:o,request:i},i}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 acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),o=this.editContextCache.get(r);if(o)return{ok:!0,data:o};let i=this.editContextInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.editContextCache.set(r,a.data),a)).finally(()=>{this.editContextInFlight.get(r)===c&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,c),c}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),o=this.classNameSourceCache.get(r);if(o)return o;let i=this.classNameSourceInFlight.get(r);if(i)return i;let s=this.objectGeneration,c=this.params.client.getClassNameSource(t,n??this.params.routeId).then(a=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,a),a)).finally(()=>{this.classNameSourceInFlight.get(r)===c&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,c),c}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,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){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.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return Z("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){Z("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}Z("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.observedDocumentVersion=Math.max(this.observedDocumentVersion,o.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function dt(e){return e.version===0&&e.entries.length===0}function on(e){let t=e;return{...t,data:{...t.data,document:Ue(t.data.document)}}}function sn(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};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,mutationContext:n.mutationContext}}}}var ft="vcp-window-message";function cn(e){return{source:ft,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function an(e){try{return E(e)?J(e,"source",ft)&&J(e,"version",1)&&P(e,"namespace")&&P(e,"channel")&&$(e,"body")&&(!oe(e,"sessionKey")||P(e,"sessionKey")):!1}catch{return!1}}var mt="site-edit",ht="frame-runtime";function ge(e,t={}){return cn({namespace:mt,channel:ht,sessionKey:t.sessionKey,body:e})}function gt(e){try{return!an(e)||e.namespace!==mt||e.channel!==ht?!1:xn(e.body)}catch{return!1}}var oe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function $(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function m(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function J(e,t,n){return $(e,t)&&m(e,t)===n}function P(e,t){return $(e,t)&&typeof m(e,t)=="string"}function ze(e,t){return $(e,t)&&typeof m(e,t)=="boolean"}function F(e,t){let n=m(e,t);return $(e,t)&&typeof n=="number"&&Number.isFinite(n)}function he(e,t){return!oe(e,t)||m(e,t)===void 0||P(e,t)}function ae(e,t){return!oe(e,t)||m(e,t)===void 0||F(e,t)}function Re(e,t){let n=m(e,t);return!oe(e,t)||n===void 0||$(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function w(e,t){return!oe(e,t)||m(e,t)===void 0}function E(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function un(e){return E(e)&&Reflect.ownKeys(e).length===0}function yt(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function re(e){return E(e)&&P(e,"key")&&Re(e,"instanceIndex")&&Re(e,"instanceCount")&&Re(e,"textSegmentIndex")}function ln(e){return E(e)&&F(e,"top")&&F(e,"left")&&F(e,"width")&&F(e,"height")}function dn(e){return E(e)&&P(e,"blockId")&&re(m(e,"ref"))&&ln(m(e,"rect"))&&ze(e,"targetIsSectionRoot")}function pn(e){if(!E(e))return!1;let t=m(e,"placement"),n=m(e,"boundary");return P(e,"anchorBlockId")&&re(m(e,"anchorRef"))&&(t==="before"||t==="after")&&E(n)&&F(n,"top")&&F(n,"left")&&F(n,"width")}function fn(e){return E(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&$(e,t)&&(typeof m(e,t)=="string"||m(e,t)===null))}function bt(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function mn(e){return E(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&$(e,t)&&bt(m(e,t)))}function hn(e){if(!E(e))return!1;let t=m(e,"priority");return P(e,"property")&&$(e,"value")&&bt(m(e,"value"))&&(!oe(e,"priority")||t===void 0||t==="important")}function gn(e){return E(e)?(w(e,"attributes")||fn(m(e,"attributes")))&&he(e,"className")&&(w(e,"style")||mn(m(e,"style")))&&(w(e,"styleDeclarations")||Array.isArray(m(e,"styleDeclarations"))&&m(e,"styleDeclarations").every(hn)):!1}function yn(e){return E(e)&&F(e,"x")&&F(e,"y")&&(w(e,"detailLevel")||J(e,"detailLevel","summary")||J(e,"detailLevel","full"))}function bn(e){return E(e)&&re(m(e,"ref"))}function Sn(e){if(!E(e)||!E(m(e,"variables")))return!1;let t=m(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&P(t,n))?w(e,"stylesheets")||yt(m(e,"stylesheets")):!1}function En(e){if(!J(e,"type","request")||!P(e,"id")||!P(e,"kind")||!$(e,"payload"))return!1;let t=m(e,"kind"),n=m(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return yn(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return un(n);case"bridge-get-source-file":return E(n)&&P(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return E(n)&&P(n,"key")&&he(n,"routeId");case"scroll-to":return E(n)&&F(n,"x")&&F(n,"y");case"scroll-by":return E(n)&&F(n,"deltaX")&&F(n,"deltaY");case"set-interaction-mode":return E(n)&&ze(n,"enabled");case"set-theme-override":return Sn(n);case"get-theme-variables":return E(n)&&yt(m(n,"names"));case"compute-drop-target-at-point":return E(n)&&F(n,"x")&&F(n,"y")&&(J(n,"dragKind","insert")||J(n,"dragKind","move"))&&(w(n,"movingRef")||re(m(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return E(n)&&(w(n,"ref")||re(m(n,"ref")));case"apply-node-patch":return E(n)&&re(m(n,"ref"))&&gn(m(n,"patch"))&&(w(n,"preview")||E(m(n,"preview"))&&P(m(n,"preview"),"sessionId")&&Re(m(n,"preview"),"revision")&&oe(m(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return bn(n);case"bridge-initialize-session":case"bridge-get-style-context":return E(n)&&P(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return E(n)&&P(n,"routeId")&&ae(n,"minVersion")&&ae(n,"version");case"bridge-execute":return E(n)&&E(m(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return E(n)&&P(n,"subscriptionId");default:return!1}}function In(e){return J(e,"type","response")&&P(e,"id")&&ze(e,"ok")&&(w(e,"error")||P(e,"error"))}var Cn=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function vn(e){if(!J(e,"type","event")||!P(e,"kind")||!E(m(e,"payload")))return!1;let t=m(e,"kind"),n=m(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return re(m(n,"ref"))&&he(n,"value")&&(w(n,"hit")||E(m(n,"hit")));case"node-bounds-change":return E(m(n,"hit"));case"bridge-event":return P(n,"subscriptionId")&&E(m(n,"event"));case"route-ready":return P(n,"routeId")&&ae(n,"version");case"bridge-status":{let r=m(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&he(n,"routeId")&&ae(n,"attempt")&&ae(n,"retryInMs")&&he(n,"messageKey")}case"scroll":{let r=m(n,"metrics");return E(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(o=>F(r,o))}default:return Cn.has(t)&&F(n,"clientX")&&F(n,"clientY")&&ae(n,"buttons")&&(m(n,"hit")===null||E(m(n,"hit")))&&(m(n,"section")===null||dn(m(n,"section")))&&(m(n,"sectionGap")===null||pn(m(n,"sectionGap")))}}function xn(e){if(!E(e))return!1;switch(m(e,"type")){case"request":return En(e);case"response":return In(e);case"event":return vn(e);default:return!1}}var Ye="vcp-site-edit:route-ready",Xe="vcp-site-edit:bridge-status",Rn=1e3,_n="data-vcp-ui-component",xt="data-vcp-theme-preview",St="::repeat-item#",_e="components/ui",Tn=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),kn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Dn(e,t=""){let n=Dt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,o=r.startsWith("/")?r:`/${r}`;return o==="/"?"/":o.replace(/\/+$/,"")}function Nn(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 An(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 no(e=window,t={}){let n=An(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Pn({bridgeUrl:n,options:t}),o=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(o?.started){if(Fn(o.signature,r)){await o.syncRoute?.();return}o.cleanup?.()}let i={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,c=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,a=t.create_client??(f=>new xe({url:f,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??$n,h=()=>{i.retryTimer&&(e.clearTimeout(i.retryTimer),i.retryTimer=void 0)},y=()=>Dn(e.location.pathname,t.basePath||""),D=!!e.parent&&e.parent!==e,v=f=>{zn(e,f)},x=f=>{i.currentDocument=f,i.currentEntriesByKey=new Map((f?.entries??[]).map(I=>[I.key,I]))},R=()=>{i.unsubscribeConnectionStatus?.(),i.unsubscribeConnectionStatus=void 0,i.unsubscribeDocument?.(),i.unsubscribeDocument=void 0},B=(f,I)=>!i.disposed&&I===i.routeSequence&&f===y(),A=async(f,I)=>{let _=i.activeBridge;if(!_)return null;let N=await _.getDocument(f);return B(f,I)&&x(N.data),N.data},U=()=>{R(),x(null);let f=i.activeBridge;i.activeBridge=null,f&&e.__VCP_SITE_EDIT__===f&&delete e.__VCP_SITE_EDIT__;let I=i.activeClient;i.activeClient=null,I?.disconnect()},Me=f=>f===s.routeId&&!!i.activeBridge&&(D||!!(i.currentDocument&&Hn(i.currentDocument,f)))&&Gn(i.activeClient),qe=f=>Math.min(Rn*2**Math.max(0,f),8e3),ie=(f,I,_)=>{if(i.disposed)return;h();let N=qe(_);v({state:"reconnecting",routeId:f,attempt:_,retryInMs:N,messageKey:"studio.status.previewBridgeConnecting"}),i.retryTimer=e.setTimeout(()=>{i.retryTimer=void 0,!(i.disposed||I!==i.routeSequence)&&Se(_+1).catch(p=>{let l=y();if(f===l){if(ue(p)){v({state:"reload-required",routeId:f,attempt:_,messageKey:"studio.errors.previewBridgeReloadRequired"});return}ie(f,i.routeSequence,_+1)}})},N)},le=(f,I,_)=>{if(!B(f,I)||i.activeClient===null)return;if(ue(_.message)){U(),h(),v({state:"reload-required",routeId:f,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let N=i.activeClient;R(),x(null);let p=i.activeBridge;i.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__,i.activeClient=null,N?.disconnect(),ie(f,I,0)},Ke=f=>{let I=y(),_=i.routeSequence;if(!(!B(I,_)||i.activeClient===null)){if(ue(f)){U(),h(),v({state:"reload-required",routeId:I,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}kt(f)&&le(I,_,{state:"failed",message:Ze(f,"Site edit bridge request failed")})}};i.cleanupFrameRuntime=Kn(e,{getCurrentDocument:()=>i.currentDocument,getDocumentEntry:f=>i.currentEntriesByKey.get(f)??null,setCurrentDocument:x,onBridgeRequestError:f=>{Ke(f)}});let de=async()=>Se(0),Se=async f=>{if(i.disposed)return;let I=y();if(Me(I))return;let _=i.syncInFlight;if(_?.routeId===I)return _.promise;let N=i.routeSequence+1,p=Ve(I,N,f);i.syncInFlight={routeId:I,sequence:N,promise:p};try{await p}finally{i.syncInFlight?.promise===p&&(i.syncInFlight=null)}},Ve=async(f,I,_)=>{i.routeSequence=I,h(),U(),v({state:_>0?"reconnecting":"connecting",routeId:f,attempt:_,messageKey:_>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let N=a(n),p=!1;i.activeClient=N,i.unsubscribeConnectionStatus=N.subscribeConnectionStatus?.(l=>{p&&(l.state==="closed"||l.state==="failed")&&le(f,I,l)});try{if(await N.connect(),!B(f,I)){N.disconnect();return}let l=pt({routeId:f,client:N,initialDocument:qn(f)});i.activeBridge=l,c()&&(e.__VCP_SITE_EDIT__=l),i.activeClient=N,i.unsubscribeDocument=l.subscribe(k=>{k.type==="site-edit.document.changed"&&k.routeId===f&&i.currentDocument&&k.version>i.currentDocument.version&&A(f,I).catch(()=>{})}),c()&&(s.routeId=f);let T=(D?null:await l.initializeSession({routeId:f}))?.data.document??null;if(T&&x(T),!B(f,I)){N.disconnect();return}p=!0,v({state:"ready",routeId:f,attempt:_,messageKey:"studio.status.previewReady"}),Nn(e,{documentVersion:T?.version??0,routeId:f,versions:t.runtime_versions}),T&&Tt(e,{routeId:f,version:T.version})}catch(l){if(R(),i.activeClient===N&&(i.activeClient=null),i.activeBridge&&e.__VCP_SITE_EDIT__===i.activeBridge&&delete e.__VCP_SITE_EDIT__,i.activeBridge=null,N.disconnect(),x(null),!B(f,I))return;throw v({state:ue(l)?"reload-required":"failed",routeId:f,attempt:_,messageKey:ue(l)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),l}},H=f=>{if(i.disposed)return;let I=y();if(ue(f)){h(),v({state:"reload-required",routeId:I,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}ie(I,i.routeSequence,0)},Y=()=>{i.syncScheduled||i.disposed||(i.syncScheduled=!0,u(()=>{i.syncScheduled=!1,!i.disposed&&de().catch(f=>H(f))}))},Ee=()=>{i.disposed||(i.disposed=!0,i.syncScheduled=!1,i.syncInFlight=null,h(),i.routeSequence+=1,i.unbindRouteChange?.(),i.unbindRouteChange=void 0,i.unbindBootstrapLifecycle?.(),i.unbindBootstrapLifecycle=void 0,i.cleanupFrameRuntime(),U(),c()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:de,cleanup:Ee},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,i.unbindBootstrapLifecycle=On(e,Ee),i.unbindRouteChange=wn(e,Y,y),t.defer_initial_sync){Y();return}await de()}function Pn(e){return{basePath:Dt(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:Bn(e.options.bridge_session_key)}}function Fn(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Bn(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function On(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Mn(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Mn(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function qn(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function Kn(e=window,t={}){let n=null,r=null,o=null,i=null,s=null,c=null,a=null,u=null,h=null,y=new Map,D=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,v=()=>{n?.(),n=null,r=null},x=()=>{o?.(),o=null,i?.(),i=null},R=(p,l,d)=>{let T=s?.sessionKey!==p||s?.sourceWindow!==l||s?.targetOrigin!==d;s={sessionKey:p,sourceWindow:l,targetOrigin:d},T&&(u=null,h=null)},B=(p,l)=>{let d=e.parent&&e.parent!==e?e.parent:null;return!d||l!==d?!1:!D||p===D},A=()=>{for(let p of y.values())p();y.clear()},U=p=>JSON.stringify([p.routeId,p.version]),Me=()=>!a||a.state==="ready",qe=p=>JSON.stringify([p.state,p.routeId??null,p.attempt??null,p.retryInMs??null,p.messageKey??null]),ie=p=>{if(!Me())return;let l=U(p);u!==l&&(i?.(),i=null,H({kind:"route-ready",payload:{routeId:p.routeId,version:p.version}}),s&&(u=l))},le=p=>{let l=qe(p);h!==l&&(p.state!=="ready"&&(u=null,c=null),H({kind:"bridge-status",payload:p}),s&&(h=l))},Ke=p=>{c=p,ie(p)},de=p=>{a=p,le(p)},Se=()=>{c&&ie(c)},Ve=()=>{a&&le(a)},H=p=>{s&&s.sourceWindow.postMessage(ge({type:"event",...p},{sessionKey:s.sessionKey}),s.targetOrigin)},Y=(p,l,d,T)=>{let k=t.getCurrentDocument?.()??null,M=nr(e.document,l.clientX,l.clientY),g=Ae(e.document,l.clientX,l.clientY,k),K=g?W(g,d==="full"?G(e.document,g,k):Pe(e.document,g,k),t.getDocumentEntry,d):null,X=rr(e.document,M,k),Q=ir(e.document,l,k);T&&K&&(p==="pointer-click"||p==="pointer-double-click")&&(T.preventDefault(),T.stopPropagation(),typeof T.stopImmediatePropagation=="function"&&T.stopImmediatePropagation()),H({kind:p,payload:{clientX:l.clientX,clientY:l.clientY,buttons:Number(l.buttons??0),hit:K,section:X,sectionGap:Q}})},Ee=p=>{H({kind:"pointer-leave",payload:{clientX:p?.clientX??0,clientY:p?.clientY??0,buttons:Number(p?.buttons??0),hit:null,section:null,sectionGap:null}})},f=(p,l,d)=>{x(),s={sessionKey:p,sourceWindow:l,targetOrigin:d};let T=Wr(e.document),k=null,M=null,g=null,K=()=>{g!==null&&(_t(e,g),g=null),k=null},X=()=>{g=null;let b=k;k=null,b&&Y("pointer-move",b,"summary")},Q=b=>{M=b,k=b,g===null&&(g=Rt(e,X))},O=()=>{M&&Q(M)},ee=b=>{Q({clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)})},pe=b=>{Y("pointer-down",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},fe=b=>{Y("pointer-up",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},se=b=>{Y("pointer-cancel",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"summary",b)},Ie=b=>{Y("pointer-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},S=b=>{Y("pointer-double-click",{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)},"full",b)},C=b=>{let wt=b?{clientX:Number(b.clientX),clientY:Number(b.clientY),buttons:Number(b.buttons)}:M;K(),M=null,Ee(wt??void 0)},q=()=>C(),te=()=>{H({kind:"scroll",payload:{metrics:De(e)}}),O()};e.document.addEventListener("pointerdown",pe,!0),e.document.addEventListener("pointermove",ee,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",fe,!0),e.document.addEventListener("pointercancel",se,!0),e.document.addEventListener("click",Ie,!0),e.document.addEventListener("dblclick",S,!0),e.addEventListener("scroll",te,{passive:!0}),e.addEventListener("resize",O,{passive:!0}),e.addEventListener("blur",q),e.document.addEventListener("load",O,!0);let Ce=e.document.documentElement,rt=typeof Ce.addEventListener=="function"?Ce:e.document;rt.addEventListener("pointerleave",C,!0);let ve=e.visualViewport;ve?.addEventListener?.("resize",O,{passive:!0}),ve?.addEventListener?.("scroll",O,{passive:!0});let ot=e.ResizeObserver,it=typeof ot=="function"?new ot(O):null;it?.observe(Ce);let st=e.MutationObserver,ct=typeof st=="function"?new st(O):null;ct?.observe(Ce,{attributes:!0,childList:!0,subtree:!0}),o=()=>{K(),M=null,it?.disconnect(),ct?.disconnect(),T(),e.document.removeEventListener("pointerdown",pe,!0),e.document.removeEventListener("pointermove",ee,!0),e.document.removeEventListener("pointerup",fe,!0),e.document.removeEventListener("pointercancel",se,!0),e.document.removeEventListener("click",Ie,!0),e.document.removeEventListener("dblclick",S,!0),e.removeEventListener("scroll",te),e.removeEventListener("resize",O),e.removeEventListener("blur",q),e.document.removeEventListener("load",O,!0),rt.removeEventListener("pointerleave",C,!0),ve?.removeEventListener?.("resize",O),ve?.removeEventListener?.("scroll",O)}},I=p=>{let l=p.detail;l?.routeId&&Ke(l)},_=p=>{let l=p.detail;l?.state&&de(l)},N=p=>{let l=p.data;if(!gt(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!=="restore-text-edit"&&l.body.kind!=="clear-text-edit-rollback"&&l.body.kind!=="start-text-edit-at-point"&&l.body.kind!=="hit-test-at-point"&&!Et(l.body))return;let d=l.body,T=typeof l.sessionKey=="string"?l.sessionKey:null,k=p.source,M=p.origin;if(!T||!M||!k||typeof k.postMessage!="function"||!B(T,k))return;if(s){if(s.sourceWindow!==k||s.targetOrigin!==M)return;s.sessionKey!==T&&(v(),x(),A(),s=null)}R(T,k,M),Ve(),Se();let g=K=>{let X=typeof d.id=="string"?d.id:"unknown";k.postMessage(ge({id:X,...K},{sessionKey:T}),M)};try{if(Et(d)){Un({message:d,sendEvent:S=>{k.postMessage(ge({type:"event",...S},{sessionKey:T}),M)},sendResponse:g,subscriptions:y,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(d.kind==="apply-node-patch"){let S=L(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for patch target"});return}let C=d.payload.preview,q=C?Tr(C.sessionId,d.payload.ref):null;if(q&&C){let te=ye.get(q)??-1;if(C.revision<te){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,stale:!0,latestRevision:te}});return}if(C.revision===te){g({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,duplicate:!0,latestRevision:te}});return}}if(Rr(S,d.payload.patch),q&&C&&kr(q,C.revision),C?.responseDetail==="none"){g({type:"response",ok:!0,result:{applied:!0,appliedRevision:C.revision}});return}g({type:"response",ok:!0,result:W(S,G(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,C?.responseDetail??"full")});return}if(d.kind==="get-hit-by-ref"){let S=L(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for hit target"});return}g({type:"response",ok:!0,result:W(S,G(e.document,S,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(d.kind==="get-path-by-ref"){let S=L(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!S){g({type:"response",ok:!1,error:"No editable element found for path target"});return}let C=[],q=S;for(;q;)q.getAttribute("data-vcp-edit-key")&&C.push(W(q,G(e.document,q,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),q=q.parentElement;g({type:"response",ok:!0,result:C.reverse()});return}if(d.kind==="restore-text-edit"||d.kind==="clear-text-edit-rollback"){let S=d.payload.ref;if(d.kind==="clear-text-edit-rollback"){r&&It(r.ref,S)&&(r=null),g({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!It(r.ref,S)){g({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let C=Jn(e.document,r,t.getCurrentDocument?.()??null);r=null,g(C?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(d.kind==="get-scroll-metrics"){g({type:"response",ok:!0,result:De(e)});return}if(d.kind==="scroll-to"){let S=Number(d.payload.x),C=Number(d.payload.y);if(!Number.isFinite(S)||!Number.isFinite(C)){g({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:S,top:C}),g({type:"response",ok:!0,result:De(e)});return}if(d.kind==="scroll-by"){let S=Number(d.payload.deltaX),C=Number(d.payload.deltaY);if(!Number.isFinite(S)||!Number.isFinite(C)){g({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:S,top:C}),g({type:"response",ok:!0,result:{...De(e),scrolled:!0}});return}if(d.kind==="set-interaction-mode"){d.payload.enabled?f(T,k,M):s?.sourceWindow===k&&s.targetOrigin===M&&s.sessionKey===T&&x(),g({type:"response",ok:!0,result:{interactionEnabled:d.payload.enabled}});return}if(d.kind==="set-theme-override"){Dr(e.document,d.payload),g({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(d.kind==="clear-theme-override"){Nr(e.document),g({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(d.kind==="get-theme-variables"){g({type:"response",ok:!0,result:Ar(e.document,d.payload.names)});return}if(d.kind==="compute-drop-target-at-point"){let S=Number(d.payload?.x),C=Number(d.payload?.y);if(!Number.isFinite(S)||!Number.isFinite(C)){g({type:"response",ok:!1,error:"Invalid drop target point"});return}g({type:"response",ok:!0,result:Sr(e,S,C,d.payload.dragKind,d.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(d.kind==="observe-node-bounds"){let S=d.payload.ref;if(!S){g({type:"response",ok:!1,error:"Missing bounds observer target"});return}let C=L(e.document,S,t.getCurrentDocument?.()??null);if(!C){g({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}i?.(),i=hr(e,C,S,t.getCurrentDocument,t.getDocumentEntry,q=>H({kind:"node-bounds-change",payload:{hit:q}})),g({type:"response",ok:!0,result:{observing:!0}}),H({kind:"node-bounds-change",payload:{hit:W(C,S,t.getDocumentEntry,"summary")}});return}if(d.kind==="clear-node-bounds-observer"){i?.(),i=null,g({type:"response",ok:!0,result:{cleared:!0}});return}if(d.kind!=="hit-test-at-point"&&d.kind!=="start-text-edit-at-point")return;let K=Number(d.payload?.x),X=Number(d.payload?.y);if(!Number.isFinite(K)||!Number.isFinite(X)){g({type:"response",ok:!1,error:"Invalid text edit point"});return}let Q=d.kind==="hit-test-at-point"?Ae(e.document,K,X,t.getCurrentDocument?.()??null):Zn(e.document,K,X,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!Q){g({type:"response",ok:!1,error:d.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let O=d.kind==="start-text-edit-at-point"?Q:null,ee=d.kind==="hit-test-at-point"?Q:O.element,pe=d.payload.detailLevel??"full",fe=pe==="full"?G(e.document,ee,t.getCurrentDocument?.()??null):Pe(e.document,ee,t.getCurrentDocument?.()??null),se=O&&typeof O.textSegmentIndex=="number"?{...fe,textSegmentIndex:O.textSegmentIndex}:fe,Ie=W(ee,se,t.getDocumentEntry,pe);if(d.kind==="hit-test-at-point"){g({type:"response",ok:!0,result:Ie});return}v(),n=Or(e,ee,se,S=>{k.postMessage(ge({type:"event",...S},{sessionKey:T}),M)},{...O?.textNode?{textNode:O.textNode}:{},onCommitSnapshot:S=>{r=S}}),g({type:"response",ok:!0,result:{ref:se}})}catch(K){g({type:"response",ok:!1,error:K instanceof Error?K.message:"Failed to start text edit"})}};return e.addEventListener("message",N),e.addEventListener(Ye,I),e.addEventListener(Xe,_),()=>{v(),x(),s=null,A(),e.removeEventListener("message",N),e.removeEventListener(Ye,I),e.removeEventListener(Xe,_)}}function Et(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function Vn(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Un({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:o,setCurrentDocument:i,onBridgeRequestError:s,windowLike:c}){let a=c.__VCP_SITE_EDIT__;if(!a){n({type:"response",ok:!1,error:"Site edit bridge is not ready in preview frame"});return}try{switch(e.kind){case"bridge-initialize-session":{let u=await a.initializeSession({routeId:e.payload.routeId});i?.(u.data.document),Tt(c,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await a.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await a.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.ensureDocumentVersion?await a.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=a.acknowledgeDocumentVersion?await a.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await a.getDocument(e.payload.routeId);i?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await a.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let u=await a.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Wn(u,e.payload.key,c.document,o?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await a.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await a.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await a.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let u=await a.execute(e.payload.request),h=o?.()?.routeId;if(u.ok&&h&&a.acknowledgeDocumentVersion&&Vn(e.payload.request)){let y=await a.acknowledgeDocumentVersion(h,u.data.resultVersion);i?.(y.data)}n({type:"response",ok:!0,result:u});return}case"bridge-undo":n({type:"response",ok:!0,result:await a.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await a.redo()});return;case"bridge-subscribe":{let u=e.payload.subscriptionId;r.get(u)?.();let h=a.subscribe(y=>{t({kind:"bridge-event",payload:{event:y,subscriptionId:u}})});r.set(u,h),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:Yn(u)})}}function Wn(e,t,n,r){if(!e.ok)return e;let o=L(n,{key:t},r),i=o?jn(o):null;return i?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...i}}}:e}function jn(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 wn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,o=e.history.replaceState,i=n(),s=()=>{let u=n();u!==i&&(i=u,t())},c=()=>s(),a=()=>s();return e.history.pushState=function(...h){let y=r.apply(this,h);return s(),y},e.history.replaceState=function(...h){let y=o.apply(this,h);return s(),y},e.addEventListener("popstate",c),e.addEventListener("hashchange",a),()=>{e.history.pushState=r,e.history.replaceState=o,e.removeEventListener("popstate",c),e.removeEventListener("hashchange",a)}}function $n(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Rt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function _t(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Tt(e,t){e.dispatchEvent(new CustomEvent(Ye,{detail:t}))}function zn(e,t){e.dispatchEvent(new CustomEvent(Xe,{detail:t}))}function Gn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Hn(e,t){return e.routeId===t}function Ze(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function kt(e){let t=Ze(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Yn(e){let t=Ze(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":kt(t)?"Site edit bridge disconnected":t}function ue(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 Dt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Le(e){return Tn.has(At(e))}function Xn(e){return kn.has(At(e))}function Nt(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:Xn(e.tagName),canInsertChild:Le(e.tagName),canMove:!1,canRemove:!1}}function At(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 Jn(e,t,n){let r=L(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let o=Qn(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 Qn(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!Ne(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Zn(e,t,n,r,o){let i=Ae(e,t,n,r),s=Pt(i);if(!s)return null;let c=s.getAttribute("data-vcp-edit-key")??"",a=G(e,s,r),u=o?.(a.key)??o?.(c);if(!Nt({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let y=Ln(e,t,n,s);if(y){let D=tr(s,y);if(D!==null)return{element:s,textNode:y,textSegmentIndex:D}}return Oe(s)?null:{element:s}}function Ln(e,t,n,r){let o=er(e,t,n);return!o||o.parentElement!==r?null:o}function er(e,t,n){let r=e,i=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(Ne(i))return i;let c=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return Ne(c)?c:null}function tr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!Ne(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function Ne(e){return e?.nodeType===3}function nr(e,t,n){return(typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean))[0]??null}function rr(e,t,n){let r=t;for(;r&&!r.getAttribute("data-site-block-id");)r=r.parentElement;if(!r)return null;let o=r.getAttribute("data-site-block-id")??"",i=r.getAttribute("data-vcp-edit-key")??"";return!o||!i?null:{blockId:o,ref:Pe(e,r,n),rect:tt(r.getBoundingClientRect()),targetIsSectionRoot:t===r}}function or(e,t){return Array.from(e.querySelectorAll("[data-site-block-id]")).filter(n=>{let r=n.parentElement;for(;r;){if(r.getAttribute("data-site-block-id"))return!1;r=r.parentElement}return!!(n.getAttribute("data-site-block-id")&&n.getAttribute("data-vcp-edit-key"))}).map(n=>({element:n,blockId:n.getAttribute("data-site-block-id")??"",ref:Pe(e,n,t),rect:tt(n.getBoundingClientRect())})).filter(({rect:n})=>n.width>0&&n.height>0).sort((n,r)=>n.rect.top-r.rect.top||n.rect.left-r.rect.left)}function ir(e,t,n){let r=or(e,n),o=r[0],i=r.at(-1);return!o||!i?null:[{anchorBlockId:o.blockId,anchorRef:o.ref,placement:"before",boundary:{top:o.rect.top,left:o.rect.left,width:o.rect.width}},...r.slice(1).map(c=>({anchorBlockId:c.blockId,anchorRef:c.ref,placement:"before",boundary:{top:c.rect.top,left:c.rect.left,width:c.rect.width}})),{anchorBlockId:i.blockId,anchorRef:i.ref,placement:"after",boundary:{top:i.rect.top+i.rect.height,left:i.rect.left,width:i.rect.width}}].find(({boundary:c})=>t.clientX>=c.left&&t.clientX<=c.left+c.width&&Math.abs(t.clientY-c.top)<=12)??null}function Ae(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=Pt(i),c=s?.getAttribute("data-vcp-edit-key")??"";if(s&&lr(s,r,c))return s}return null}function Pt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(et(t))return n??t;!sr(r)&&!n&&(n=t)}t=t.parentElement}return n}function et(e){return e.getAttribute(_n)!==null}function sr(e){return cr(e.split("::")[0]??"")}function cr(e){if(!e)return!1;let t=ar(e);return t===_e||t.startsWith(`${_e}/`)||t.includes(`/${_e}/`)||t.endsWith(`/${_e}`)}function ar(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 G(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",o=Bt(Mt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${jt(r)}"]`))),n,r);if(o.length<=1)return{key:Ct(n,r,0)};let i=o.indexOf(t);return i>=0?{key:Ct(n,r,i),instanceIndex:i,instanceCount:o.length}:{key:r}}function Pe(e,t,n){return G(e,t,n)}function L(e,t,n){let r=Fe(t.key)??t.key,o=Bt(Mt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${jt(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=(Fe(t.key)??t.key)!==t.key;if(i!==null&&!s)return o[i]??null;let c=ur(n,t.key);return c!==null&&c>=0&&c<o.length?o[c]??null:i!==null?o[i]??null:o[0]??null}function Ct(e,t,n){return Ft(e,t)[n]?.key??t}function ur(e,t){let n=Fe(t);if(!n)return null;let o=Ft(e,n).findIndex(i=>i.key===t);return o>=0?o:null}function Ft(e,t){return(e?.entries??[]).filter(n=>(Fe(n.key)??n.key)===t)}function Bt(e,t,n){let r=Ot(t,n);return r?e.filter(o=>o.tagName.toLowerCase()===r):e}function lr(e,t,n){let r=Ot(t,n);return!r||e.tagName.toLowerCase()===r}function Ot(e,t){return null}var dr=2,pr=4;function Mt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&pr)!==0?-1:(r&dr)!==0?1:0})}function Fe(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(St);if(n<0)break;let r=Number(t.slice(n+St.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function fr(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...qt(n),paddingTop:V(n?.paddingTop),paddingRight:V(n?.paddingRight),paddingBottom:V(n?.paddingBottom),paddingLeft:V(n?.paddingLeft),borderTopWidth:V(n?.borderTopWidth),borderRightWidth:V(n?.borderRightWidth),borderBottomWidth:V(n?.borderBottomWidth),borderLeftWidth:V(n?.borderLeftWidth),columnGap:V(n?.columnGap),rowGap:V(n?.rowGap)}}function qt(e){return{marginTop:V(e?.marginTop,!0),marginRight:V(e?.marginRight,!0),marginBottom:V(e?.marginBottom,!0),marginLeft:V(e?.marginLeft,!0)}}function V(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function mr(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:tt(n.getBoundingClientRect()),margin:qt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function W(e,t,n,r="full"){let o=e.getBoundingClientRect(),i=n?.(t.key)??null,s=e.tagName.toLowerCase(),c=Be(e),a=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([x,R])=>[x,R??""])),attributes:Object.fromEntries(e.getAttributeNames().map(x=>[x,e.getAttribute(x)??""]))}:{},u=Nt({operationSummary:i?.operationSummary,tagName:s,fallbackMode:"preview"}),h=et(e),y=!0,D=Kt(e)?.getAttribute("data-vcp-edit-key")??null,v=mr(e);return{ref:t,key:t.key,detailLevel:r,tagName:s,...i?{sourceKind:"jsx"}:{},...D?{parentKey:D}:{},...i?.pageCompositionUnitKey?{pageCompositionUnitKey:i.pageCompositionUnitKey}:{},...a,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:h?!1:!!Oe(e)||u.canInsertChild||y&&Le(s)},layout:c,rect:{top:o.top,left:o.left,width:o.width,height:o.height},childBoxes:v,childRects:v.map(({rect:x})=>x),spacing:fr(e)}}function hr(e,t,n,r,o,i){let s=t,c=W(s,n,o,"summary"),a=null,u=()=>{a===null&&(a=Rt(e,h))},h=()=>{a=null;let B=L(e.document,n,r?.()??null);if(!B)return;B!==s&&(D?.unobserve(s),s=B,D?.observe(s));let A=W(s,n,o,"summary");A.rect.width<=0||A.rect.height<=0||gr(c,A)&&(c=A,i(A))},y=e.ResizeObserver,D=typeof y=="function"?new y(u):null;D?.observe(s);let v=e.MutationObserver,x=typeof v=="function"?new v(u):null;x?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",u,{passive:!0});let R=e.visualViewport;return R?.addEventListener?.("resize",u,{passive:!0}),e.document.addEventListener("load",u,!0),()=>{a!==null&&(_t(e,a),a=null),D?.disconnect(),x?.disconnect(),e.removeEventListener("resize",u),R?.removeEventListener?.("resize",u),e.document.removeEventListener("load",u,!0)}}function gr(e,t){return nt(e.rect,t.rect)||yr(e.childBoxes,t.childBoxes)||br(e.childRects,t.childRects)||Je(e.spacing,t.spacing)||Je(e.layout,t.layout)}function yr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>{let s=r[i];return!s||nt(o.rect,s.rect)||Je(o.margin,s.margin)})}function br(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((o,i)=>nt(o,r[i]??o))}function Je(e,t){let n=e??{},r=t??{},o=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(o).some(i=>n[i]!==r[i])}function tt(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function nt(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 Sr(e,t,n,r,o,i,s){let c=e.document,a=Ae(c,t,n,i);if(!a)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=o?L(c,o,i):null;if(u&&Qe(a,u))return Te(c,a,"self-or-descendant",i,s);if(r==="move"&&u){let R=vr(c,a,u,i,s);if(R){let B=Ge(R.child,R.targetParent,t,n,"nearest");if(B)return ke(c,R.child,R.targetParent,B,i,s)}}let h=null,y=!1,D=a,v=a.parentElement;for(;v;){if(v.getAttribute("data-vcp-edit-key")){if(u&&Qe(v,u))return Te(c,a,"self-or-descendant",i,s);let R=vt(v,r,s);if(R==="accept"){h={child:D,targetParent:v};break}R==="blocked"&&(y=!0),D=v}v=v.parentElement}let x=vt(a,r,s);if(x==="accept"){if(h){let R=Ge(h.child,h.targetParent,t,n,"edge");if(R)return ke(c,h.child,h.targetParent,R,i,s)}return ke(c,a,a,Er(a,t,n),i,s)}if(h){let R=Ge(h.child,h.targetParent,t,n,"nearest");return ke(c,h.child,h.targetParent,R??"after",i,s)}return x==="blocked"||y?Te(c,a,"operation-boundary-blocked",i,s):Te(c,a,"no-accepting-parent",i,s)}function Te(e,t,n,r,o){return{anchorHit:W(t,G(e,t,r),o,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function ke(e,t,n,r,o,i){let s=W(t,G(e,t,o),i,"summary"),c=W(n,G(e,n,o),i,"summary"),a=Be(n).indicatorOrientation,u=r==="append"||r==="prepend"?Ir(n.getBoundingClientRect(),a,r):Cr(t.getBoundingClientRect(),a,r);return{anchorHit:s,targetParentHit:c,relation:r,indicatorOrientation:a,indicatorBounds:u}}function vt(e,t,n){if(et(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",o=n?.(r)??null;if(o)return o.operationSummary.canInsertChild===!0?"accept":Oe(e)?"blocked":"not-container";let i=e.tagName.toLowerCase();return Le(i)?"accept":"not-container"}function Ge(e,t,n,r,o){let i=Be(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 Er(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,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 Ir(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 Cr(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 Qe(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function vr(e,t,n,r,o){let i=xr(e,t,n,r,o);if(i)return i;let s=Kt(n);if(!s||t===s)return null;let c=t,a=t.getAttribute("data-vcp-edit-key")?t:null;for(;c&&c!==s;)c.getAttribute("data-vcp-edit-key")&&(a=c),c=c.parentElement;return c!==s||!a||a===s||a===n||Qe(a,n)?null:{child:a,targetParent:s}}function xr(e,t,n,r,o){return null}function Kt(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function Oe(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=Oe(n);if(r)return r}return null}function De(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:z(e.scrollX),scrollY:z(e.scrollY),scrollWidth:Math.max(z(t?.scrollWidth),z(n?.scrollWidth),z(e.innerWidth)),scrollHeight:Math.max(z(t?.scrollHeight),z(n?.scrollHeight),z(e.innerHeight)),viewportWidth:z(e.innerWidth),viewportHeight:z(e.innerHeight)}}function Rr(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 _r=500,ye=new Map;function Tr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function kr(e,t){if(ye.size>=_r){let n=ye.keys().next().value;n&&ye.delete(n)}ye.set(e,t)}var be=new Set;function Dr(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 be)r.has(o)||n?.removeProperty(o);be.clear();for(let o of r)be.add(o);Br(e,t.stylesheets??[])}function Nr(e){let t=e.documentElement?.style;for(let n of be)t?.removeProperty(n);be.clear();for(let n of Wt(e))n.remove()}function Ar(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=Vt(o,s);c&&(i[s]=c)}return i}function Vt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Ut(e,r,n)}function Ut(e,t,n){if(!t)return null;let r=Pr(t);if(!r)return t;let o=Vt(e,r.name,n);return o||(r.fallback?Ut(e,r.fallback,n)??r.fallback:null)}function Pr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Fr(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 Fr(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 Br(e,t){let n=new Set(t.filter(i=>typeof i=="string"&&i.length>0)),r=new Map;for(let i of Wt(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(xt,"true"),s.setAttribute("href",i),o.appendChild(s)}}function Wt(e){return Array.from(e.querySelectorAll(`link[${xt}]`))}function Or(e,t,n,r,o={}){let i=o.textNode?Mr(e.document,o.textNode):null;if(o.textNode&&!i)throw new Error("Failed to prepare text segment editor");let s=i?.element??t,c=s.textContent??"",a=i?void 0:t.innerHTML,u=qr(s),h=!1,y=()=>{e.document.removeEventListener("pointerdown",v,!0),s.removeEventListener("keydown",x),s.removeEventListener("blur",R),s.removeEventListener("input",B),Vr(s,u)},D=A=>{if(h)return;h=!0;let U=s.textContent??"";if(y(),A==="cancel"){i?.restore(c),i||(t.textContent=c),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(i?.restore(U),A==="commit"&&U!==c){o.onCommitSnapshot?.({ref:n,initialText:c,...a!==void 0?{initialHtml:a}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:U}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function v(A){let U=A.target;U&&s.contains(U)||D("commit")}function x(A){if(A.key==="Escape"){A.preventDefault(),D("cancel");return}A.key==="Enter"&&(A.metaKey||A.ctrlKey)&&(A.preventDefault(),D("commit"))}function R(){D("commit")}function B(){r({kind:"text-edit-input",payload:{ref:n,hit:W(t,n,void 0,"full")}})}return Kr(s),e.document.addEventListener("pointerdown",v,!0),s.addEventListener("keydown",x),s.addEventListener("blur",R),s.addEventListener("input",B),jr(s),wr(s,e.document),y}function Mr(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 qr(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 Kr(e){Ur(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 Vr(e,t){He(e,"contenteditable",t.contentEditable),He(e,"spellcheck",t.spellcheck),He(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Ur(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 He(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Wr(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 jr(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function wr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function jt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function z(e){let t=Number(e);return Number.isFinite(t)?t:0}export{Xe as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,Ye as VCP_SITE_EDIT_ROUTE_READY_EVENT,Dn as resolveSiteEditRouteId,An as resolveSiteEditWebSocketUrl,no as startSiteEditAutoBootstrap,Kn as startSiteEditFrameRuntime};
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- function $e(e){let t=new Map,n=[],r=new Map,i=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(o.map((l,g)=>[l,g])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(l=>({placementKey:l.placementKey,placementUnitKey:l.placementUnitKey,relation:l.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},c=e.entries.flatMap((l,g)=>l.dynamicDataSummary?[[g,l.dynamicDataSummary]]:[]),u=l=>{let g=t.get(l);if(typeof g=="number")return g;let b=n.length;return n.push(l),t.set(l,b),b},p=l=>{let g=null;for(let b of Nn(l)){let R=`${g??"root"}\0${b}`,x=r.get(R);if(typeof x=="number"){g=x;continue}let T=i.length;i.push([g,u(b)]),r.set(R,T),g=T}if(g===null)throw new Error("Document key must not be empty");return g};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:a,tokens:n,nodes:i,entries:e.entries.map(l=>{let g=l.pageCompositionUnitKey?s.get(l.pageCompositionUnitKey)??-1:-1;if(l.pageCompositionUnitKey&&g<0)throw new Error(`Render entry ${l.key} references unknown page composition unit ${l.pageCompositionUnitKey}`);return[p(l.key),kn(l.operationSummary),...g>=0?[g]:[]]}),...c.length>0?{dynamicDataSummaries:c}:{}}}function ze(e){if(!Pn(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),i=o=>{let s=t.get(o);if(s)return s;let a=e.nodes[o];if(!a)throw new Error(`Missing compact document node ${o}`);let[c,u]=a,p=e.tokens[u];if(typeof p!="string")throw new Error(`Missing compact document token ${u}`);let l=`${c===null?"":i(c)}${p}`;return t.set(o,l),l};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((o,s)=>{let[a,c,u]=o,p=u===void 0?void 0:n[u];if(u!==void 0&&!p)throw new Error(`Missing page composition unit ${u}`);return{key:i(a),...p?{pageCompositionUnitKey:p}:{},operationSummary:Dn(c),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function kn(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function Dn(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function Pn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!gt(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(i=>typeof i=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((i,o)=>Array.isArray(i)&&i.length===2&&(i[0]===null||de(i[0])&&i[0]<o)&&de(i[1])&&i[1]<t.tokens.length)||!t.entries.every(i=>Array.isArray(i)&&(i.length===2||i.length===3)&&de(i[0])&&i[0]<n.length&&de(i[1])&&i[1]<=15&&(i.length===2||de(i[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(i=>Array.isArray(i)&&i.length===2&&de(i[0])&&i[0]<t.entries.length&&gt(i[1]))}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Nn(e){if(!e)return[];let t=[],n=0,r=yt(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=yt(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 yt(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var w=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",i=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||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!U(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?U(t.payload)&&typeof t.payload.id=="string":t.type==="event"?U(t.payload)&&U(t.payload.event):t.type==="auth"?U(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?U(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!U(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||Ge(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";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-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return An(t.request)&&(t.request.mutationContext===void 0||Ge(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||Ge(t.mutationContext)}}},ke=class{constructor(t){this.options=t,this.messageQueue=new Je,this.eventDispatcher=new Ye(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:i}=r;switch(r.kind){case"initialize-session":{let o=await this.options.engine.initializeSession({routeId:r.routeId,...r.mutationContext?{mutationContext:r.mutationContext}:{}});this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:{document:$e(o.data.document),historyStatus:o.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:$e((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getStyleContext(r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:i,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:i,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":{await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.execute(r.request));return}case"undo":await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=w.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:St(n),code:bt(n)}})}}async handleRawMessage(t){try{await this.handleMessage(w.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",i=Fn(t);this.sendJson({type:"error",payload:{...i,message:r}})}}sendJson(t){this.options.socket.send(w.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let i=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:i}}),this.eventDispatcher.flush()}catch(i){this.sendJson({type:"error",payload:{id:t,kind:n,message:St(i),code:bt(i)}}),this.eventDispatcher.flush()}}},Ye=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)})}},Je=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 U(e){return typeof e=="object"&&e!==null}function An(e){return U(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"&&U(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&U(e.params)}function Ge(e){return Bn(e)}function bt(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function St(e){if(e instanceof Error)return e.message;if(!e||typeof e!="object")return"Unknown websocket operation failure";let t=e.message;return typeof t=="string"&&t.length>0?t:"Unknown websocket operation failure"}function Bn(e){return U(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}function Fn(e){try{return w.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var wn="vcp:designer:trace",On="designer_trace",Et="__VCP_DESIGNER_TRACE__";var Mn=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Vn(e=globalThis){let t=e;try{if(t.localStorage?.getItem(wn)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(On)==="1"}catch{return!1}}function re(e,t={},n=globalThis){if(!Vn(n))return;let r={type:e,timestamp:Date.now(),payload:Kn(t)},i=n,o=i[Et]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),i[Et]=o;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Kn(e){return Xe(e,0)}function Xe(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>Xe(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,i]of Object.entries(e)){if(Mn.test(r)){n[r]="[redacted]";continue}n[r]=Xe(i,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===Qe&&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=be(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let i={socket:r,settled:!1,reject:n};this.connectAttempt=i,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==i||(i.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==i)){if(this.options.authKey){try{r.send(w.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){s(be(a,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=a=>{if(this.socket!==r)return;let c=be(a,"WebSocket failed");s(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===i&&!i.settled){this.handleAuthHandshakeMessage(a.data,r,i,()=>{o()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let c=this.intentionalClose,u=new Error(Un(a,{intentional:c}));s(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})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}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,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){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!==Qe||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let i=`${t}-${this.sequence+=1}`,o=zn(i,t,n);return re("bridge.request",{id:i,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:It(n.request,"kind"),documentVersion:It(n.request,"documentVersion")}),new Promise((s,a)=>{let c=this.resolveRequestTimeoutMs(t),u=c>0?setTimeout(()=>{let p=this.pending.get(i);p&&(this.pending.delete(i),re("bridge.response",{id:i,kind:t,ok:!1,timedOut:!0}),p.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;u?.unref?.(),this.pending.set(i,{kind:t,timeout:u,resolve:p=>s(p),reject:a});try{r.send(w.stringifyMessage(o))}catch(p){let l=be(p,"WebSocket send failed");this.clearPendingRequest(i),a(l),this.cleanupSocket(r,l,"failed")}})}handleAuthHandshakeMessage(t,n,r,i){try{if(w.parseMessage(t).type==="auth-ok"){i();return}throw new Error("Bridge authentication failed")}catch(o){let s=be(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=w.parseMessage(t);if(n.type==="event"){for(let i of this.listeners)i(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"){re("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}re("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:Wn(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:ze(n.payload.result.data)}:r.kind==="initialize-session"?$n(n.payload.result):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):jn[t]??Hn}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let i=this.connectAttempt;this.connectAttempt=null,i.settled||(i.settled=!0,i.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===qn||t.readyState===Qe)&&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 i of this.connectionStatusListeners)i(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)}},qn=0,Qe=1,Hn=15e3,jn={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function be(e,t){return e instanceof Error?e:new Error(t)}function Un(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 It(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function Wn(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 xt(e){return new Ze(e)}var Ze=class{constructor(t){this.params=t,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!vt(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=vt(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let i=this.styleGeneration,o=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===i&&(this.styleContextCache={generation:i,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===o&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:i,request:o},o}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 acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),i=this.editContextCache.get(r);if(i)return{ok:!0,data:i};let o=this.editContextInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(c=>(this.objectGeneration===s&&this.editContextCache.set(r,c.data),c)).finally(()=>{this.editContextInFlight.get(r)===a&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,a),a}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),i=this.classNameSourceCache.get(r);if(i)return i;let o=this.classNameSourceInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getClassNameSource(t,n??this.params.routeId).then(c=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,c),c)).finally(()=>{this.classNameSourceInFlight.get(r)===a&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,a),a}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,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){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.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return re("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){re("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let i=await this.refreshInFlight;if(typeof t!="number"||i.version>=t||this.currentDocument.version>=t)return this.currentDocument}re("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(i=>(this.currentDocument=i.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,i.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function vt(e){return e.version===0&&e.entries.length===0}function $n(e){let t=e;return{...t,data:{...t.data,document:ze(t.data.document)}}}function zn(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};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,mutationContext:n.mutationContext}}}}var Ct="vcp-window-message",Jo=1;function Gn(e){return{source:Ct,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Yn(e){try{return C(e)?te(e,"source",Ct)&&te(e,"version",1)&&B(e,"namespace")&&B(e,"channel")&&G(e,"body")&&(!ae(e,"sessionKey")||B(e,"sessionKey")):!1}catch{return!1}}var Rt="site-edit",_t="frame-runtime";function Ie(e,t={}){return Gn({namespace:Rt,channel:_t,sessionKey:t.sessionKey,body:e})}function Tt(e){try{return!Yn(e)||e.namespace!==Rt||e.channel!==_t?!1:ar(e.body)}catch{return!1}}var ae=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function G(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function y(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function te(e,t,n){return G(e,t)&&y(e,t)===n}function B(e,t){return G(e,t)&&typeof y(e,t)=="string"}function kt(e,t){return G(e,t)&&typeof y(e,t)=="boolean"}function q(e,t){let n=y(e,t);return G(e,t)&&typeof n=="number"&&Number.isFinite(n)}function Se(e,t){return!ae(e,t)||y(e,t)===void 0||B(e,t)}function le(e,t){return!ae(e,t)||y(e,t)===void 0||q(e,t)}function Pe(e,t){let n=y(e,t);return!ae(e,t)||n===void 0||G(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function z(e,t){return!ae(e,t)||y(e,t)===void 0}function C(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jn(e){return C(e)&&Reflect.ownKeys(e).length===0}function Dt(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function Ee(e){return C(e)&&B(e,"key")&&Pe(e,"instanceIndex")&&Pe(e,"instanceCount")&&Pe(e,"textSegmentIndex")}function Xn(e){return C(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&G(e,t)&&(typeof y(e,t)=="string"||y(e,t)===null))}function Pt(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Qn(e){return C(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&G(e,t)&&Pt(y(e,t)))}function Zn(e){if(!C(e))return!1;let t=y(e,"priority");return B(e,"property")&&G(e,"value")&&Pt(y(e,"value"))&&(!ae(e,"priority")||t===void 0||t==="important")}function Ln(e){return C(e)?(z(e,"attributes")||Xn(y(e,"attributes")))&&Se(e,"className")&&(z(e,"style")||Qn(y(e,"style")))&&(z(e,"styleDeclarations")||Array.isArray(y(e,"styleDeclarations"))&&y(e,"styleDeclarations").every(Zn)):!1}function er(e){return C(e)&&q(e,"x")&&q(e,"y")&&(z(e,"detailLevel")||te(e,"detailLevel","summary")||te(e,"detailLevel","full"))}function tr(e){return C(e)&&Ee(y(e,"ref"))}function nr(e){if(!C(e)||!C(y(e,"variables")))return!1;let t=y(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&B(t,n))?z(e,"stylesheets")||Dt(y(e,"stylesheets")):!1}function rr(e){if(!te(e,"type","request")||!B(e,"id")||!B(e,"kind")||!G(e,"payload"))return!1;let t=y(e,"kind"),n=y(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return er(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return Jn(n);case"bridge-get-source-file":return C(n)&&B(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return C(n)&&B(n,"key")&&Se(n,"routeId");case"scroll-to":return C(n)&&q(n,"x")&&q(n,"y");case"scroll-by":return C(n)&&q(n,"deltaX")&&q(n,"deltaY");case"set-interaction-mode":return C(n)&&kt(n,"enabled");case"set-theme-override":return nr(n);case"get-theme-variables":return C(n)&&Dt(y(n,"names"));case"compute-drop-target-at-point":return C(n)&&q(n,"x")&&q(n,"y")&&(te(n,"dragKind","insert")||te(n,"dragKind","move"))&&(z(n,"movingRef")||Ee(y(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return C(n)&&(z(n,"ref")||Ee(y(n,"ref")));case"apply-node-patch":return C(n)&&Ee(y(n,"ref"))&&Ln(y(n,"patch"))&&(z(n,"preview")||C(y(n,"preview"))&&B(y(n,"preview"),"sessionId")&&Pe(y(n,"preview"),"revision")&&ae(y(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return tr(n);case"bridge-initialize-session":case"bridge-get-style-context":return C(n)&&B(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return C(n)&&B(n,"routeId")&&le(n,"minVersion")&&le(n,"version");case"bridge-execute":return C(n)&&C(y(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return C(n)&&B(n,"subscriptionId");default:return!1}}function ir(e){return te(e,"type","response")&&B(e,"id")&&kt(e,"ok")&&(z(e,"error")||B(e,"error"))}var or=new Set(["pointer-down","pointer-move","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function sr(e){if(!te(e,"type","event")||!B(e,"kind")||!C(y(e,"payload")))return!1;let t=y(e,"kind"),n=y(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return Ee(y(n,"ref"))&&Se(n,"value")&&(z(n,"hit")||C(y(n,"hit")));case"node-bounds-change":return C(y(n,"hit"));case"bridge-event":return B(n,"subscriptionId")&&C(y(n,"event"));case"route-ready":return B(n,"routeId")&&le(n,"version");case"bridge-status":{let r=y(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&Se(n,"routeId")&&le(n,"attempt")&&le(n,"retryInMs")&&Se(n,"messageKey")}case"scroll":{let r=y(n,"metrics");return C(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(i=>q(r,i))}default:return or.has(t)&&q(n,"clientX")&&q(n,"clientY")&&le(n,"buttons")&&(y(n,"hit")===null||C(y(n,"hit")))}}function ar(e){if(!C(e))return!1;switch(y(e,"type")){case"request":return rr(e);case"response":return ir(e);case"event":return sr(e);default:return!1}}var tt="vcp-site-edit:route-ready",nt="vcp-site-edit:bridge-status",cr=1e3,ur="data-vcp-ui-component",Mt="data-vcp-theme-preview",Nt="::repeat-item#",Ne="components/ui",dr=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),lr=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function fr(e,t=""){let n=jt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,i=r.startsWith("/")?r:`/${r}`;return i==="/"?"/":i.replace(/\/+$/,"")}function hr(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 pr(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 Lo(e=window,t={}){let n=pr(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=mr({bridgeUrl:n,options:t}),i=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(i?.started){if(gr(i.signature,r)){await i.syncRoute?.();return}i.cleanup?.()}let o={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,c=t.create_client??(h=>new De({url:h,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Tr,p=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},l=()=>fr(e.location.pathname,t.basePath||""),g=!!e.parent&&e.parent!==e,b=h=>{kr(e,h)},R=h=>{o.currentDocument=h,o.currentEntriesByKey=new Map((h?.entries??[]).map(S=>[S.key,S]))},x=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},T=(h,S)=>!o.disposed&&S===o.routeSequence&&h===l(),P=async(h,S)=>{let D=o.activeBridge;if(!D)return null;let f=await D.getDocument(h);return T(h,S)&&R(f.data),f.data},F=()=>{x(),R(null);let h=o.activeBridge;o.activeBridge=null,h&&e.__VCP_SITE_EDIT__===h&&delete e.__VCP_SITE_EDIT__;let S=o.activeClient;o.activeClient=null,S?.disconnect()},me=h=>h===s.routeId&&!!o.activeBridge&&(g||!!(o.currentDocument&&Pr(o.currentDocument,h)))&&Dr(o.activeClient),ce=h=>Math.min(cr*2**Math.max(0,h),8e3),X=(h,S,D)=>{if(o.disposed)return;p();let f=ce(D);b({state:"reconnecting",routeId:h,attempt:D,retryInMs:f,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||S!==o.routeSequence)&&Z(D+1).catch(m=>{let d=l();if(h===d){if(fe(m)){b({state:"reload-required",routeId:h,attempt:D,messageKey:"studio.errors.previewBridgeReloadRequired"});return}X(h,o.routeSequence,D+1)}})},f)},W=(h,S,D)=>{if(!T(h,S)||o.activeClient===null)return;if(fe(D.message)){F(),p(),b({state:"reload-required",routeId:h,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let f=o.activeClient;x(),R(null);let m=o.activeBridge;o.activeBridge=null,m&&e.__VCP_SITE_EDIT__===m&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,f?.disconnect(),X(h,S,0)},$=h=>{let S=l(),D=o.routeSequence;if(!(!T(S,D)||o.activeClient===null)){if(fe(h)){F(),p(),b({state:"reload-required",routeId:S,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Ht(h)&&W(S,D,{state:"failed",message:ot(h,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Ir(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:h=>o.currentEntriesByKey.get(h)??null,setCurrentDocument:R,onBridgeRequestError:h=>{$(h)}});let Q=async()=>Z(0),Z=async h=>{if(o.disposed)return;let S=l();if(me(S))return;let D=o.syncInFlight;if(D?.routeId===S)return D.promise;let f=o.routeSequence+1,m=oe(S,f,h);o.syncInFlight={routeId:S,sequence:f,promise:m};try{await m}finally{o.syncInFlight?.promise===m&&(o.syncInFlight=null)}},oe=async(h,S,D)=>{o.routeSequence=S,p(),F(),b({state:D>0?"reconnecting":"connecting",routeId:h,attempt:D,messageKey:D>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let f=c(n),m=!1;o.activeClient=f,o.unsubscribeConnectionStatus=f.subscribeConnectionStatus?.(d=>{m&&(d.state==="closed"||d.state==="failed")&&W(h,S,d)});try{if(await f.connect(),!T(h,S)){f.disconnect();return}let d=xt({routeId:h,client:f,initialDocument:Er(h)});o.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),o.activeClient=f,o.unsubscribeDocument=d.subscribe(N=>{N.type==="site-edit.document.changed"&&N.routeId===h&&o.currentDocument&&N.version>o.currentDocument.version&&P(h,S).catch(()=>{})}),a()&&(s.routeId=h);let k=(g?null:await d.initializeSession({routeId:h}))?.data.document??null;if(k&&R(k),!T(h,S)){f.disconnect();return}m=!0,b({state:"ready",routeId:h,attempt:D,messageKey:"studio.status.previewReady"}),hr(e,{documentVersion:k?.version??0,routeId:h,versions:t.runtime_versions}),k&&qt(e,{routeId:h,version:k.version})}catch(d){if(x(),o.activeClient===f&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,f.disconnect(),R(null),!T(h,S))return;throw b({state:fe(d)?"reload-required":"failed",routeId:h,attempt:D,messageKey:fe(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},M=h=>{if(o.disposed)return;let S=l();if(fe(h)){p(),b({state:"reload-required",routeId:S,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}X(S,o.routeSequence,0)},V=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,u(()=>{o.syncScheduled=!1,!o.disposed&&Q().catch(h=>M(h))}))},L=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,p(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),F(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:Q,cleanup:L},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,o.unbindBootstrapLifecycle=br(e,L),o.unbindRouteChange=_r(e,V,l),t.defer_initial_sync){V();return}await Q()}function mr(e){return{basePath:jt(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:yr(e.options.bridge_session_key)}}function gr(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function yr(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function br(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Sr(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Sr(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Er(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function Ir(e=window,t={}){let n=null,r=null,i=null,o=null,s=null,a=null,c=null,u=null,p=null,l=new Map,g=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,b=()=>{n?.(),n=null,r=null},R=()=>{i?.(),i=null,o?.(),o=null},x=(f,m,d)=>{let A=s?.sessionKey!==f||s?.sourceWindow!==m||s?.targetOrigin!==d;s={sessionKey:f,sourceWindow:m,targetOrigin:d},A&&(u=null,p=null)},T=(f,m)=>{let d=e.parent&&e.parent!==e?e.parent:null;return!d||m!==d?!1:!g||f===g},P=()=>{for(let f of l.values())f();l.clear()},F=f=>JSON.stringify([f.routeId,f.version]),me=()=>!c||c.state==="ready",ce=f=>JSON.stringify([f.state,f.routeId??null,f.attempt??null,f.retryInMs??null,f.messageKey??null]),X=f=>{if(!me())return;let m=F(f);u!==m&&(o?.(),o=null,M({kind:"route-ready",payload:{routeId:f.routeId,version:f.version}}),s&&(u=m))},W=f=>{let m=ce(f);p!==m&&(f.state!=="ready"&&(u=null,a=null),M({kind:"bridge-status",payload:f}),s&&(p=m))},$=f=>{a=f,X(f)},Q=f=>{c=f,W(f)},Z=()=>{a&&X(a)},oe=()=>{c&&W(c)},M=f=>{s&&s.sourceWindow.postMessage(Ie({type:"event",...f},{sessionKey:s.sessionKey}),s.targetOrigin)},V=(f,m,d,A)=>{let k=Oe(e.document,m.clientX,m.clientY,t.getCurrentDocument?.()??null),N=k?H(k,d==="full"?J(e.document,k,t.getCurrentDocument?.()??null):Ft(e.document,k,t.getCurrentDocument?.()??null),t.getDocumentEntry,d):null;A&&N&&(f==="pointer-click"||f==="pointer-double-click")&&(A.preventDefault(),A.stopPropagation(),typeof A.stopImmediatePropagation=="function"&&A.stopImmediatePropagation()),M({kind:f,payload:{clientX:m.clientX,clientY:m.clientY,buttons:Number(m.buttons??0),hit:N}})},L=(f,m,d)=>{R(),s={sessionKey:f,sourceWindow:m,targetOrigin:d};let A=Ii(e.document),k=null,N=null,E=()=>{N=null;let I=k;k=null,I&&V("pointer-move",I,"summary")},j=I=>{k={clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},N===null&&(N=Vt(e,E))},ne=I=>{V("pointer-down",{clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},"full",I)},ue=I=>{V("pointer-up",{clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},"summary",I)},ee=I=>{V("pointer-cancel",{clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},"summary",I)},se=I=>{V("pointer-click",{clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},"full",I)},ge=I=>{V("pointer-double-click",{clientX:Number(I.clientX),clientY:Number(I.clientY),buttons:Number(I.buttons)},"full",I)},ye=()=>{M({kind:"scroll",payload:{metrics:Fe(e)}})};e.document.addEventListener("pointerdown",ne,!0),e.document.addEventListener("pointermove",j,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",ue,!0),e.document.addEventListener("pointercancel",ee,!0),e.document.addEventListener("click",se,!0),e.document.addEventListener("dblclick",ge,!0),e.addEventListener("scroll",ye,{passive:!0}),i=()=>{N!==null&&(Kt(e,N),N=null),k=null,A(),e.document.removeEventListener("pointerdown",ne,!0),e.document.removeEventListener("pointermove",j,!0),e.document.removeEventListener("pointerup",ue,!0),e.document.removeEventListener("pointercancel",ee,!0),e.document.removeEventListener("click",se,!0),e.document.removeEventListener("dblclick",ge,!0),e.removeEventListener("scroll",ye)}},h=f=>{let m=f.detail;m?.routeId&&$(m)},S=f=>{let m=f.detail;m?.state&&Q(m)},D=f=>{let m=f.data;if(!Tt(m)||m.body.type!=="request"||m.body.kind!=="apply-node-patch"&&m.body.kind!=="get-hit-by-ref"&&m.body.kind!=="get-path-by-ref"&&m.body.kind!=="get-scroll-metrics"&&m.body.kind!=="scroll-to"&&m.body.kind!=="scroll-by"&&m.body.kind!=="set-interaction-mode"&&m.body.kind!=="set-theme-override"&&m.body.kind!=="clear-theme-override"&&m.body.kind!=="get-theme-variables"&&m.body.kind!=="compute-drop-target-at-point"&&m.body.kind!=="observe-node-bounds"&&m.body.kind!=="clear-node-bounds-observer"&&m.body.kind!=="restore-text-edit"&&m.body.kind!=="clear-text-edit-rollback"&&m.body.kind!=="start-text-edit-at-point"&&m.body.kind!=="hit-test-at-point"&&!At(m.body))return;let d=m.body,A=typeof m.sessionKey=="string"?m.sessionKey:null,k=f.source,N=f.origin;if(!A||!N||!k||typeof k.postMessage!="function"||!T(A,k))return;if(s){if(s.sourceWindow!==k||s.targetOrigin!==N)return;s.sessionKey!==A&&(b(),R(),P(),s=null)}x(A,k,N),oe(),Z();let E=j=>{let ne=typeof d.id=="string"?d.id:"unknown";k.postMessage(Ie({id:ne,...j},{sessionKey:A}),N)};try{if(At(d)){xr({message:d,sendEvent:v=>{k.postMessage(Ie({type:"event",...v},{sessionKey:A}),N)},sendResponse:E,subscriptions:l,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(d.kind==="apply-node-patch"){let v=ie(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!v){E({type:"response",ok:!1,error:"No editable element found for patch target"});return}let _=d.payload.preview,K=_?ai(_.sessionId,d.payload.ref):null;if(K&&_){let Te=ve.get(K)??-1;if(_.revision<Te){E({type:"response",ok:!0,result:{applied:!1,appliedRevision:_.revision,stale:!0,latestRevision:Te}});return}if(_.revision===Te){E({type:"response",ok:!0,result:{applied:!1,appliedRevision:_.revision,duplicate:!0,latestRevision:Te}});return}}if(oi(v,d.payload.patch),K&&_&&ci(K,_.revision),_?.responseDetail==="none"){E({type:"response",ok:!0,result:{applied:!0,appliedRevision:_.revision}});return}E({type:"response",ok:!0,result:H(v,J(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,_?.responseDetail??"full")});return}if(d.kind==="get-hit-by-ref"){let v=ie(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!v){E({type:"response",ok:!1,error:"No editable element found for hit target"});return}E({type:"response",ok:!0,result:H(v,J(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(d.kind==="get-path-by-ref"){let v=ie(e.document,d.payload.ref,t.getCurrentDocument?.()??null);if(!v){E({type:"response",ok:!1,error:"No editable element found for path target"});return}let _=[],K=v;for(;K;)K.getAttribute("data-vcp-edit-key")&&_.push(H(K,J(e.document,K,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),K=K.parentElement;E({type:"response",ok:!0,result:_.reverse()});return}if(d.kind==="restore-text-edit"||d.kind==="clear-text-edit-rollback"){let v=d.payload.ref;if(d.kind==="clear-text-edit-rollback"){r&&Bt(r.ref,v)&&(r=null),E({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!Bt(r.ref,v)){E({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let _=Br(e.document,r,t.getCurrentDocument?.()??null);r=null,E(_?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(d.kind==="get-scroll-metrics"){E({type:"response",ok:!0,result:Fe(e)});return}if(d.kind==="scroll-to"){let v=Number(d.payload.x),_=Number(d.payload.y);if(!Number.isFinite(v)||!Number.isFinite(_)){E({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:_}),E({type:"response",ok:!0,result:Fe(e)});return}if(d.kind==="scroll-by"){let v=Number(d.payload.deltaX),_=Number(d.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(_)){E({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:_}),E({type:"response",ok:!0,result:{...Fe(e),scrolled:!0}});return}if(d.kind==="set-interaction-mode"){d.payload.enabled?L(A,k,N):s?.sourceWindow===k&&s.targetOrigin===N&&s.sessionKey===A&&R(),E({type:"response",ok:!0,result:{interactionEnabled:d.payload.enabled}});return}if(d.kind==="set-theme-override"){ui(e.document,d.payload),E({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(d.kind==="clear-theme-override"){di(e.document),E({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(d.kind==="get-theme-variables"){E({type:"response",ok:!0,result:li(e.document,d.payload.names)});return}if(d.kind==="compute-drop-target-at-point"){let v=Number(d.payload?.x),_=Number(d.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(_)){E({type:"response",ok:!1,error:"Invalid drop target point"});return}E({type:"response",ok:!0,result:Lr(e,v,_,d.payload.dragKind,d.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(d.kind==="observe-node-bounds"){let v=d.payload.ref;if(!v){E({type:"response",ok:!1,error:"Missing bounds observer target"});return}let _=ie(e.document,v,t.getCurrentDocument?.()??null);if(!_){E({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=Yr(e,_,v,t.getCurrentDocument,t.getDocumentEntry,K=>M({kind:"node-bounds-change",payload:{hit:K}})),E({type:"response",ok:!0,result:{observing:!0}}),M({kind:"node-bounds-change",payload:{hit:H(_,v,t.getDocumentEntry,"summary")}});return}if(d.kind==="clear-node-bounds-observer"){o?.(),o=null,E({type:"response",ok:!0,result:{cleared:!0}});return}if(d.kind!=="hit-test-at-point"&&d.kind!=="start-text-edit-at-point")return;let j=Number(d.payload?.x),ne=Number(d.payload?.y);if(!Number.isFinite(j)||!Number.isFinite(ne)){E({type:"response",ok:!1,error:"Invalid text edit point"});return}let ue=d.kind==="hit-test-at-point"?Oe(e.document,j,ne,t.getCurrentDocument?.()??null):wr(e.document,j,ne,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!ue){E({type:"response",ok:!1,error:d.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let ee=d.kind==="start-text-edit-at-point"?ue:null,se=d.kind==="hit-test-at-point"?ue:ee.element,ge=d.payload.detailLevel??"full",ye=ge==="full"?J(e.document,se,t.getCurrentDocument?.()??null):Ft(e.document,se,t.getCurrentDocument?.()??null),I=ee&&typeof ee.textSegmentIndex=="number"?{...ye,textSegmentIndex:ee.textSegmentIndex}:ye,Tn=H(se,I,t.getDocumentEntry,ge);if(d.kind==="hit-test-at-point"){E({type:"response",ok:!0,result:Tn});return}b(),n=mi(e,se,I,v=>{k.postMessage(Ie({type:"event",...v},{sessionKey:A}),N)},{...ee?.textNode?{textNode:ee.textNode}:{},onCommitSnapshot:v=>{r=v}}),E({type:"response",ok:!0,result:{ref:I}})}catch(j){E({type:"response",ok:!1,error:j instanceof Error?j.message:"Failed to start text edit"})}};return e.addEventListener("message",D),e.addEventListener(tt,h),e.addEventListener(nt,S),()=>{b(),R(),s=null,P(),e.removeEventListener("message",D),e.removeEventListener(tt,h),e.removeEventListener(nt,S)}}function At(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function vr(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function xr({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:i,setCurrentDocument:o,onBridgeRequestError:s,windowLike:a}){let c=a.__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-initialize-session":{let u=await c.initializeSession({routeId:e.payload.routeId});o?.(u.data.document),qt(a,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await c.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await c.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=c.ensureDocumentVersion?await c.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=c.acknowledgeDocumentVersion?await c.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});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:Cr(u,e.payload.key,a.document,i?.()??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":{let u=await c.execute(e.payload.request),p=i?.()?.routeId;if(u.ok&&p&&c.acknowledgeDocumentVersion&&vr(e.payload.request)){let l=await c.acknowledgeDocumentVersion(p,u.data.resultVersion);o?.(l.data)}n({type:"response",ok:!0,result:u});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 p=c.subscribe(l=>{t({kind:"bridge-event",payload:{event:l,subscriptionId:u}})});r.set(u,p),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:Nr(u)})}}function Cr(e,t,n,r){if(!e.ok)return e;let i=ie(n,{key:t},r),o=i?Rr(i):null;return o?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...o}}}:e}function Rr(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 _r(e,t,n=()=>e.location.pathname){let r=e.history.pushState,i=e.history.replaceState,o=n(),s=()=>{let u=n();u!==o&&(o=u,t())},a=()=>s(),c=()=>s();return e.history.pushState=function(...p){let l=r.apply(this,p);return s(),l},e.history.replaceState=function(...p){let l=i.apply(this,p);return s(),l},e.addEventListener("popstate",a),e.addEventListener("hashchange",c),()=>{e.history.pushState=r,e.history.replaceState=i,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",c)}}function Tr(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Vt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function Kt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function qt(e,t){e.dispatchEvent(new CustomEvent(tt,{detail:t}))}function kr(e,t){e.dispatchEvent(new CustomEvent(nt,{detail:t}))}function Dr(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Pr(e,t){return e.routeId===t}function ot(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Ht(e){let t=ot(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function Nr(e){let t=ot(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Ht(t)?"Site edit bridge disconnected":t}function fe(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 jt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function st(e){return dr.has(Wt(e))}function Ar(e){return lr.has(Wt(e))}function Ut(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:Ar(e.tagName),canInsertChild:st(e.tagName),canMove:!1,canRemove:!1}}function Wt(e){return e?.trim().toLowerCase()??""}function Bt(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 Br(e,t,n){let r=ie(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let i=Fr(r,t.ref.textSegmentIndex);return i?(i.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function Fr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!we(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function wr(e,t,n,r,i){let o=Oe(e,t,n,r),s=$t(o);if(!s)return null;let a=s.getAttribute("data-vcp-edit-key")??"",c=J(e,s,r),u=i?.(c.key)??i?.(a);if(!Ut({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let l=Or(e,t,n,s);if(l){let g=Vr(s,l);if(g!==null)return{element:s,textNode:l,textSegmentIndex:g}}return Ke(s)?null:{element:s}}function Or(e,t,n,r){let i=Mr(e,t,n);return!i||i.parentElement!==r?null:i}function Mr(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(we(o))return o;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return we(a)?a:null}function Vr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!we(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function we(e){return e?.nodeType===3}function Oe(e,t,n,r=null){let i=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of i){let s=$t(o),a=s?.getAttribute("data-vcp-edit-key")??"";if(s&&Ur(s,r,a))return s}return null}function $t(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(at(t))return n??t;!Kr(r)&&!n&&(n=t)}t=t.parentElement}return n}function at(e){return e.getAttribute(ur)!==null}function Kr(e){return qr(e.split("::")[0]??"")}function qr(e){if(!e)return!1;let t=Hr(e);return t===Ne||t.startsWith(`${Ne}/`)||t.includes(`/${Ne}/`)||t.endsWith(`/${Ne}`)}function Hr(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let i of n.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}return r.join("/")}function J(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",i=Gt(Jt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${tn(r)}"]`))),n,r);if(i.length<=1)return{key:wt(n,r,0)};let o=i.indexOf(t);return o>=0?{key:wt(n,r,o),instanceIndex:o,instanceCount:i.length}:{key:r}}function Ft(e,t,n){return J(e,t,n)}function ie(e,t,n){let r=Me(t.key)??t.key,i=Gt(Jt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${tn(r)}"]`))),n,t.key);if(i.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<i.length?t.instanceIndex:null,s=(Me(t.key)??t.key)!==t.key;if(o!==null&&!s)return i[o]??null;let a=jr(n,t.key);return a!==null&&a>=0&&a<i.length?i[a]??null:o!==null?i[o]??null:i[0]??null}function wt(e,t,n){return zt(e,t)[n]?.key??t}function jr(e,t){let n=Me(t);if(!n)return null;let i=zt(e,n).findIndex(o=>o.key===t);return i>=0?i:null}function zt(e,t){return(e?.entries??[]).filter(n=>(Me(n.key)??n.key)===t)}function Gt(e,t,n){let r=Yt(t,n);return r?e.filter(i=>i.tagName.toLowerCase()===r):e}function Ur(e,t,n){let r=Yt(t,n);return!r||e.tagName.toLowerCase()===r}function Yt(e,t){return null}var Wr=2,$r=4;function Jt(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&$r)!==0?-1:(r&Wr)!==0?1:0})}function Me(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 zr(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...Xt(n),paddingTop:O(n?.paddingTop),paddingRight:O(n?.paddingRight),paddingBottom:O(n?.paddingBottom),paddingLeft:O(n?.paddingLeft),borderTopWidth:O(n?.borderTopWidth),borderRightWidth:O(n?.borderRightWidth),borderBottomWidth:O(n?.borderBottomWidth),borderLeftWidth:O(n?.borderLeftWidth),columnGap:O(n?.columnGap),rowGap:O(n?.rowGap)}}function Xt(e){return{marginTop:O(e?.marginTop,!0),marginRight:O(e?.marginRight,!0),marginBottom:O(e?.marginBottom,!0),marginLeft:O(e?.marginLeft,!0)}}function O(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function Gr(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:Zr(n.getBoundingClientRect()),margin:Xt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function H(e,t,n,r="full"){let i=e.getBoundingClientRect(),o=n?.(t.key)??null,s=e.tagName.toLowerCase(),a=Ve(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([R,x])=>[R,x??""])),attributes:Object.fromEntries(e.getAttributeNames().map(R=>[R,e.getAttribute(R)??""]))}:{},u=Ut({operationSummary:o?.operationSummary,tagName:s,fallbackMode:"preview"}),p=at(e),l=!0,g=Qt(e)?.getAttribute("data-vcp-edit-key")??null,b=Gr(e);return{ref:t,key:t.key,detailLevel:r,tagName:s,...o?{sourceKind:"jsx"}:{},...g?{parentKey:g}:{},...o?.pageCompositionUnitKey?{pageCompositionUnitKey:o.pageCompositionUnitKey}:{},...c,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:p?!1:!!Ke(e)||u.canInsertChild||l&&st(s)},layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:b,childRects:b.map(({rect:R})=>R),spacing:zr(e)}}function Yr(e,t,n,r,i,o){let s=t,a=H(s,n,i,"summary"),c=null,u=()=>{c===null&&(c=Vt(e,p))},p=()=>{c=null;let T=ie(e.document,n,r?.()??null);if(!T)return;T!==s&&(g?.unobserve(s),s=T,g?.observe(s));let P=H(s,n,i,"summary");P.rect.width<=0||P.rect.height<=0||Jr(a,P)&&(a=P,o(P))},l=e.ResizeObserver,g=typeof l=="function"?new l(u):null;g?.observe(s);let b=e.MutationObserver,R=typeof b=="function"?new b(u):null;R?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",u,{passive:!0});let x=e.visualViewport;return x?.addEventListener?.("resize",u,{passive:!0}),e.document.addEventListener("load",u,!0),()=>{c!==null&&(Kt(e,c),c=null),g?.disconnect(),R?.disconnect(),e.removeEventListener("resize",u),x?.removeEventListener?.("resize",u),e.document.removeEventListener("load",u,!0)}}function Jr(e,t){return ct(e.rect,t.rect)||Xr(e.childBoxes,t.childBoxes)||Qr(e.childRects,t.childRects)||rt(e.spacing,t.spacing)||rt(e.layout,t.layout)}function Xr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>{let s=r[o];return!s||ct(i.rect,s.rect)||rt(i.margin,s.margin)})}function Qr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>ct(i,r[o]??i))}function rt(e,t){let n=e??{},r=t??{},i=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(i).some(o=>n[o]!==r[o])}function Zr(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function ct(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 Lr(e,t,n,r,i,o,s){let a=e.document,c=Oe(a,t,n,o);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=i?ie(a,i,o):null;if(u&&it(c,u))return Ae(a,c,"self-or-descendant",o,s);if(r==="move"&&u){let x=ri(a,c,u,o,s);if(x){let T=Le(x.child,x.targetParent,t,n,"nearest");if(T)return Be(a,x.child,x.targetParent,T,o,s)}}let p=null,l=!1,g=c,b=c.parentElement;for(;b;){if(b.getAttribute("data-vcp-edit-key")){if(u&&it(b,u))return Ae(a,c,"self-or-descendant",o,s);let x=Ot(b,r,s);if(x==="accept"){p={child:g,targetParent:b};break}x==="blocked"&&(l=!0),g=b}b=b.parentElement}let R=Ot(c,r,s);if(R==="accept"){if(p){let x=Le(p.child,p.targetParent,t,n,"edge");if(x)return Be(a,p.child,p.targetParent,x,o,s)}return Be(a,c,c,ei(c,t,n),o,s)}if(p){let x=Le(p.child,p.targetParent,t,n,"nearest");return Be(a,p.child,p.targetParent,x??"after",o,s)}return R==="blocked"||l?Ae(a,c,"operation-boundary-blocked",o,s):Ae(a,c,"no-accepting-parent",o,s)}function Ae(e,t,n,r,i){return{anchorHit:H(t,J(e,t,r),i,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Be(e,t,n,r,i,o){let s=H(t,J(e,t,i),o,"summary"),a=H(n,J(e,n,i),o,"summary"),c=Ve(n).indicatorOrientation,u=r==="append"||r==="prepend"?ti(n.getBoundingClientRect(),c,r):ni(t.getBoundingClientRect(),c,r);return{anchorHit:s,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:u}}function Ot(e,t,n){if(at(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",i=n?.(r)??null;if(i)return i.operationSummary.canInsertChild===!0?"accept":Ke(e)?"blocked":"not-container";let o=e.tagName.toLowerCase();return st(o)?"accept":"not-container"}function Le(e,t,n,r,i){let o=Ve(t).indicatorOrientation,s=e.getBoundingClientRect(),a=o==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return i==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function ei(e,t,n){let r=Ve(e).indicatorOrientation,i=e.getBoundingClientRect();return(r==="vertical"?i.width>0?(t-i.left)/i.width:.5:i.height>0?(n-i.top)/i.height:.5)<.5?"prepend":"append"}function Ve(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",i=n?.flexDirection,o=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(i??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...i?{flexDirection:i}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:s}}function ti(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 ni(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 it(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function ri(e,t,n,r,i){let o=ii(e,t,n,r,i);if(o)return o;let s=Qt(n);if(!s||t===s)return null;let a=t,c=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==s;)a.getAttribute("data-vcp-edit-key")&&(c=a),a=a.parentElement;return a!==s||!c||c===s||c===n||it(c,n)?null:{child:c,targetParent:s}}function ii(e,t,n,r,i){return null}function Qt(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function Ke(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=Ke(n);if(r)return r}return null}function Fe(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:Y(e.scrollX),scrollY:Y(e.scrollY),scrollWidth:Math.max(Y(t?.scrollWidth),Y(n?.scrollWidth),Y(e.innerWidth)),scrollHeight:Math.max(Y(t?.scrollHeight),Y(n?.scrollHeight),Y(e.innerHeight)),viewportWidth:Y(e.innerWidth),viewportHeight:Y(e.innerHeight)}}function oi(e,t){Object.entries(t.attributes??{}).forEach(([r,i])=>{if(i===null){e.removeAttribute(r);return}e.setAttribute(r,i)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,i])=>{if(n.has(r))return;let o=e.style,s=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i))}),t.styleDeclarations?.forEach(r=>{let i=e.style,o=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),s=r.value;if(s==null||s===""){i.removeProperty(o);return}i.setProperty(o,String(s),r.priority)})}var si=500,ve=new Map;function ai(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function ci(e,t){if(ve.size>=si){let n=ve.keys().next().value;n&&ve.delete(n)}ve.set(e,t)}var xe=new Set;function ui(e,t){let n=e.documentElement?.style,r=new Set;for(let[i,o]of Object.entries(t.variables??{}))i.startsWith("--")&&(r.add(i),n?.setProperty(i,o));for(let i of xe)r.has(i)||n?.removeProperty(i);xe.clear();for(let i of r)xe.add(i);pi(e,t.stylesheets??[])}function di(e){let t=e.documentElement?.style;for(let n of xe)t?.removeProperty(n);xe.clear();for(let n of en(e))n.remove()}function li(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,i=r?e.defaultView?.getComputedStyle(r):null,o={};for(let s of n){let a=Zt(i,s);a&&(o[s]=a)}return o}function Zt(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Lt(e,r,n)}function Lt(e,t,n){if(!t)return null;let r=fi(t);if(!r)return t;let i=Zt(e,r.name,n);return i||(r.fallback?Lt(e,r.fallback,n)??r.fallback:null)}function fi(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=hi(n),i=r>=0?n.slice(0,r).trim():n;if(!i.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:i,fallback:o||null}}function hi(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function pi(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of en(e)){let s=o.getAttribute("href")??"";if(!n.has(s)||r.has(s)){o.remove();continue}r.set(s,o)}let i=e.head;if(i)for(let o of n){if(r.has(o))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(Mt,"true"),s.setAttribute("href",o),i.appendChild(s)}}function en(e){return Array.from(e.querySelectorAll(`link[${Mt}]`))}function mi(e,t,n,r,i={}){let o=i.textNode?gi(e.document,i.textNode):null;if(i.textNode&&!o)throw new Error("Failed to prepare text segment editor");let s=o?.element??t,a=s.textContent??"",c=o?void 0:t.innerHTML,u=yi(s),p=!1,l=()=>{e.document.removeEventListener("pointerdown",b,!0),s.removeEventListener("keydown",R),s.removeEventListener("blur",x),s.removeEventListener("input",T),Si(s,u)},g=P=>{if(p)return;p=!0;let F=s.textContent??"";if(l(),P==="cancel"){o?.restore(a),o||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(F),P==="commit"&&F!==a){i.onCommitSnapshot?.({ref:n,initialText:a,...c!==void 0?{initialHtml:c}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:F}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function b(P){let F=P.target;F&&s.contains(F)||g("commit")}function R(P){if(P.key==="Escape"){P.preventDefault(),g("cancel");return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),g("commit"))}function x(){g("commit")}function T(){r({kind:"text-edit-input",payload:{ref:n,hit:H(t,n,void 0,"full")}})}return bi(s),e.document.addEventListener("pointerdown",b,!0),s.addEventListener("keydown",R),s.addEventListener("blur",x),s.addEventListener("input",T),vi(s),xi(s,e.document),l}function gi(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(i){t.nodeValue=i,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function yi(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 bi(e){Ei(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 Si(e,t){et(e,"contenteditable",t.contentEditable),et(e,"spellcheck",t.spellcheck),et(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Ei(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 et(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Ii(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 vi(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function xi(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function tn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Y(e){let t=Number(e);return Number.isFinite(t)?t:0}import Ci from"node:http";import{createHash as cn,randomBytes as Ri,timingSafeEqual as _i}from"node:crypto";import lt from"node:path";import{WebSocket as un,WebSocketServer as Ti}from"ws";import{createPreviewSiteEditEngineRuntime as ki,openFileHistoryStore as Di}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Pi,scanNextAppRouterRoutes as Ni}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ai}from"@vcp-dev/site-edit-engine/source-watcher";var qe=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Bi}from"@vcp-dev/contracts";var Fi="127.0.0.1",wi=30218,Oi="/__vcp/site-edit/bridge",dn=6*1024*1024,Mi=dn*2,Vi=3e3,nn=50,rn="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function fs(e){let t=fn(e),n=pn(t),r=hn(),i=r.get(n);if(i)return i;let o=new He(t);r.set(n,o);try{o.start()}catch(s){throw r.delete(n),o.stop(),s}return o}function ln(e,t,n={}){let r=new He(fn(t),e,!1,n);return r.start({listen:!1}),r}var He=class{constructor(t,n=Ci.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,i={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new qe,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=qi({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 Ai({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??nn,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=hn(),n=pn(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let i=(this.dependencies.createRuntime??ki)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version);for(let s of this.eventListeners)s(o)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=i,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:r,resolvedRouteId:i}=await this.activateRoute(t.routeId),o=r.getDocument(i).data;await this.recordRuntimeVersion(o.version);let s=(await r.getHistoryStatus()).data;return{ok:!0,data:{document:o,historyStatus:s}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),i=n.getDocument(r);return await this.recordRuntimeVersion(i.data.version),i},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),i=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,i)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=await this.bindHistorySession(this.options.snapshotId);if(!r.ok)return ut(r,t);let i=await this.getRuntime().executeOperation(this.normalizeRequest(t));return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),undo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return ut(t);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return ut(t);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??Di)(Ki({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let i=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,i),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??nn;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:Ni(this.options.projectRoot),n=new Map(this.routes.map(i=>[i.routeId,i.entryFile])),r=new Set(t.map(i=>i.routeId));this.routes=t;for(let i of t)n.get(i.routeId)!==i.entryFile&&this.runtime?.registerRoute(i.routeId,i.entryFile);for(let i of n.keys())r.has(i)||this.runtime?.unregisterRoute(i)}resolveRouteId(t){let n=Pi(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 fn(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:lt.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Fi,port:e.port??wi,path:e.path??Oi,sessionKey:e.sessionKey??Gi(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function Ki(e){return lt.join(lt.resolve(e.root),on(e.siteId),on(e.snapshotId),cn("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function on(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:cn("sha256").update(e).digest("hex").slice(0,32)}function hn(){let e=globalThis;return e[rn]??=new Map,e[rn]}function pn(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function ut(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function qi(e){let t=new Ti({maxPayload:dn,noServer:!0}),n=new WeakSet,r=o=>{new ke({socket:new ft(o),engine:e.engine,validateOperationRequest:s=>Bi.safeParse(s).success})},i=(o,s,a)=>{if(!Hi(o,e))return;let c=ji(o,e);if(!c){s.write(`HTTP/1.1 401 Unauthorized\r
1
+ function Qe(e){let t=new Map,n=[],r=new Map,i=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(o.map((l,y)=>[l,y])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(l=>({placementKey:l.placementKey,placementUnitKey:l.placementUnitKey,relation:l.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},c=e.entries.flatMap((l,y)=>l.dynamicDataSummary?[[y,l.dynamicDataSummary]]:[]),u=l=>{let y=t.get(l);if(typeof y=="number")return y;let S=n.length;return n.push(l),t.set(l,S),S},f=l=>{let y=null;for(let S of jn(l)){let _=`${y??"root"}\0${S}`,C=r.get(_);if(typeof C=="number"){y=C;continue}let T=i.length;i.push([y,u(S)]),r.set(_,T),y=T}if(y===null)throw new Error("Document key must not be empty");return y};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:a,tokens:n,nodes:i,entries:e.entries.map(l=>{let y=l.pageCompositionUnitKey?s.get(l.pageCompositionUnitKey)??-1:-1;if(l.pageCompositionUnitKey&&y<0)throw new Error(`Render entry ${l.key} references unknown page composition unit ${l.pageCompositionUnitKey}`);return[f(l.key),Kn(l.operationSummary),...y>=0?[y]:[]]}),...c.length>0?{dynamicDataSummaries:c}:{}}}function Ze(e){if(!Hn(e))return e;let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),i=o=>{let s=t.get(o);if(s)return s;let a=e.nodes[o];if(!a)throw new Error(`Missing compact document node ${o}`);let[c,u]=a,f=e.tokens[u];if(typeof f!="string")throw new Error(`Missing compact document token ${u}`);let l=`${c===null?"":i(c)}${f}`;return t.set(o,l),l};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((o,s)=>{let[a,c,u]=o,f=u===void 0?void 0:n[u];if(u!==void 0&&!f)throw new Error(`Missing page composition unit ${u}`);return{key:i(a),...f?{pageCompositionUnitKey:f}:{},operationSummary:qn(c),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function Kn(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function qn(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function Hn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||typeof t.routeId!="string"||!Number.isInteger(t.version)||t.version<0||!Pt(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(i=>typeof i=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((i,o)=>Array.isArray(i)&&i.length===2&&(i[0]===null||pe(i[0])&&i[0]<o)&&pe(i[1])&&i[1]<t.tokens.length)||!t.entries.every(i=>Array.isArray(i)&&(i.length===2||i.length===3)&&pe(i[0])&&i[0]<n.length&&pe(i[1])&&i[1]<=15&&(i.length===2||pe(i[2]))))return!1;let r=t.dynamicDataSummaries;return r===void 0||Array.isArray(r)&&r.every(i=>Array.isArray(i)&&i.length===2&&pe(i[0])&&i[0]<t.entries.length&&Pt(i[1]))}function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function jn(e){if(!e)return[];let t=[],n=0,r=Dt(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=Dt(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 Dt(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var H=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",i=e.isRequestKind(n.kind)?n.kind:"get-document";return{id:r,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||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!$(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?$(t.payload)&&typeof t.payload.id=="string":t.type==="event"?$(t.payload)&&$(t.payload.event):t.type==="auth"?$(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?$(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!$(t)||typeof t.id!="string"||!e.isRequestKind(t.kind))return!1;switch(t.kind){case"initialize-session":return typeof t.routeId=="string"&&(t.mutationContext===void 0||Le(t.mutationContext));case"get-document":case"get-style-context":return typeof t.routeId=="string";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-history-status":return t.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof t.path=="string";case"execute":return Un(t.request)&&(t.request.mutationContext===void 0||Le(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||Le(t.mutationContext)}}},Be=class{constructor(t){this.options=t,this.messageQueue=new tt,this.eventDispatcher=new et(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:i}=r;switch(r.kind){case"initialize-session":{let o=await this.options.engine.initializeSession({routeId:r.routeId,...r.mutationContext?{mutationContext:r.mutationContext}:{}});this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:{document:Qe(o.data.document),historyStatus:o.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:{ok:!0,data:Qe((await this.options.engine.getDocument(r.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getStyleContext(r.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:i,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:i,kind:r.kind,result:await this.options.engine.getClassNameSource(r.key,r.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.getSourceFile({path:r.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:i,kind:r.kind,result:await this.options.engine.resolveSourceLocation({key:r.key,routeId:r.routeId})}});return;case"execute":{await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.execute(r.request));return}case"undo":await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(i,r.kind,()=>this.options.engine.redo());return}}catch(n){let r=H.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:At(n),code:Nt(n)}})}}async handleRawMessage(t){try{await this.handleMessage(H.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",i=$n(t);this.sendJson({type:"error",payload:{...i,message:r}})}}sendJson(t){this.options.socket.send(H.stringifyMessage(t))}async handleBufferedOperation(t,n,r){this.eventDispatcher.beginBuffering();try{let i=await r();this.sendJson({type:"response",payload:{id:t,kind:n,result:i}}),this.eventDispatcher.flush()}catch(i){this.sendJson({type:"error",payload:{id:t,kind:n,message:At(i),code:Nt(i)}}),this.eventDispatcher.flush()}}},et=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)})}},tt=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 $(e){return typeof e=="object"&&e!==null}function Un(e){return $(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"&&$(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&$(e.params)}function Le(e){return Wn(e)}function Nt(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function At(e){if(e instanceof Error)return e.message;if(!e||typeof e!="object")return"Unknown websocket operation failure";let t=e.message;return typeof t=="string"&&t.length>0?t:"Unknown websocket operation failure"}function Wn(e){return $(e)?typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0:!1}function $n(e){try{return H.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var zn="vcp:designer:trace",Gn="designer_trace",Bt="__VCP_DESIGNER_TRACE__";var Yn=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Jn(e=globalThis){let t=e;try{if(t.localStorage?.getItem(zn)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(Gn)==="1"}catch{return!1}}function oe(e,t={},n=globalThis){if(!Jn(n))return;let r={type:e,timestamp:Date.now(),payload:Xn(t)},i=n,o=i[Bt]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),i[Bt]=o;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function Xn(e){return nt(e,0)}function nt(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>nt(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,i]of Object.entries(e)){if(Yn.test(r)){n[r]="[redacted]";continue}n[r]=nt(i,t+1)}return n}var Fe=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===rt&&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=Ie(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",c.message),n(c);return}let i={socket:r,settled:!1,reject:n};this.connectAttempt=i,this.socket=r;let o=()=>{this.socket!==r||this.connectAttempt!==i||(i.settled=!0,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),t())},s=(a,c)=>{this.cleanupSocket(r,a,c)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==i)){if(this.options.authKey){try{r.send(H.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){s(Ie(a,"WebSocket auth failed"),"failed")}return}o()}},r.onerror=a=>{if(this.socket!==r)return;let c=Ie(a,"WebSocket failed");s(c,"failed")},r.onmessage=a=>{if(this.socket===r){if(this.options.authKey&&this.connectAttempt===i&&!i.settled){this.handleAuthHandshakeMessage(a.data,r,i,()=>{o()});return}this.handleMessage(a.data)}},r.onclose=a=>{if(this.socket!==r)return;let c=this.intentionalClose,u=new Error(er(a,{intentional:c}));s(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})}initializeSession(t){return this.request("initialize-session",t)}getHistoryStatus(){return this.request("get-history-status",{})}getStyleContext(t){return this.request("get-style-context",{routeId:t})}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,n){return this.request("execute",{request:t})}undo(t){return this.request("undo",{})}redo(t){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!==rt||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${r?.readyState??"none"})`));let i=`${t}-${this.sequence+=1}`,o=rr(i,t,n);return oe("bridge.request",{id:i,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:Ft(n.request,"kind"),documentVersion:Ft(n.request,"documentVersion")}),new Promise((s,a)=>{let c=this.resolveRequestTimeoutMs(t),u=c>0?setTimeout(()=>{let f=this.pending.get(i);f&&(this.pending.delete(i),oe("bridge.response",{id:i,kind:t,ok:!1,timedOut:!0}),f.reject(new Error(`Bridge request timed out after ${c}ms: ${t}`)))},c):null;u?.unref?.(),this.pending.set(i,{kind:t,timeout:u,resolve:f=>s(f),reject:a});try{r.send(H.stringifyMessage(o))}catch(f){let l=Ie(f,"WebSocket send failed");this.clearPendingRequest(i),a(l),this.cleanupSocket(r,l,"failed")}})}handleAuthHandshakeMessage(t,n,r,i){try{if(H.parseMessage(t).type==="auth-ok"){i();return}throw new Error("Bridge authentication failed")}catch(o){let s=Ie(o,"Bridge authentication failed");this.connectAttempt===r&&this.cleanupSocket(n,s,"failed")}}handleMessage(t){let n=H.parseMessage(t);if(n.type==="event"){for(let i of this.listeners)i(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"){oe("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}oe("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:tr(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Ze(n.payload.result.data)}:r.kind==="initialize-session"?nr(n.payload.result):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):Ln[t]??Zn}cleanupSocket(t,n,r){if(this.socket===t&&(this.socket=null),this.connectAttempt?.socket===t){let i=this.connectAttempt;this.connectAttempt=null,i.settled||(i.settled=!0,i.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===Qn||t.readyState===rt)&&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 i of this.connectionStatusListeners)i(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)}},Qn=0,rt=1,Zn=15e3,Ln={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,undo:2e4,redo:2e4};function Ie(e,t){return e instanceof Error?e:new Error(t)}function er(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 Ft(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function tr(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 wt(e){return new it(e)}var it=class{constructor(t){this.params=t,this.refreshInFlight=null,this.objectGeneration=0,this.styleGeneration=0,this.editContextCache=new Map,this.editContextInFlight=new Map,this.classNameSourceCache=new Map,this.classNameSourceInFlight=new Map,this.styleContextCache=null,this.styleContextInFlight=null,this.currentDocument=t.initialDocument,this.observedDocumentVersion=t.initialDocument.version,this.sessionInitialized=!Ot(t.initialDocument)}async getDocument(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=Ot(this.currentDocument);return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(t){if(t.routeId!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t.routeId}`);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let n=await this.params.client.initializeSession(t);return this.currentDocument=n.data.document,this.observedDocumentVersion=n.data.document.version,this.sessionInitialized=!0,this.clearObjectCaches(),n}async getHistoryStatus(){return this.params.client.getHistoryStatus()}async getStyleContext(t){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);let n=this.styleContextCache;if(n?.generation===this.styleGeneration)return{ok:!0,data:n.value};let r=this.styleContextInFlight;if(r?.generation===this.styleGeneration)return r.request;let i=this.styleGeneration,o=this.params.client.getStyleContext(t).then(s=>(this.styleGeneration===i&&(this.styleContextCache={generation:i,value:s.data}),s)).finally(()=>{this.styleContextInFlight?.request===o&&(this.styleContextInFlight=null)});return this.styleContextInFlight={generation:i,request:o},o}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 acknowledgeDocumentVersion(t,n){if(t!==this.params.routeId)throw new Error(`Site edit bridge is bound to route ${this.params.routeId}, received ${t}`);return n>this.currentDocument.version&&(this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(t,n){let r=this.objectCacheKey(t,n),i=this.editContextCache.get(r);if(i)return{ok:!0,data:i};let o=this.editContextInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getObjectEditContext(t,n??this.params.routeId).then(c=>(this.objectGeneration===s&&this.editContextCache.set(r,c.data),c)).finally(()=>{this.editContextInFlight.get(r)===a&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,a),a}async getClassNameSource(t,n){let r=this.objectCacheKey(t,n),i=this.classNameSourceCache.get(r);if(i)return i;let o=this.classNameSourceInFlight.get(r);if(o)return o;let s=this.objectGeneration,a=this.params.client.getClassNameSource(t,n??this.params.routeId).then(c=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,c),c)).finally(()=>{this.classNameSourceInFlight.get(r)===a&&this.classNameSourceInFlight.delete(r)});return this.classNameSourceInFlight.set(r,a),a}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,n){let r=t.target.kind==="node"&&!t.routeId?{...t,routeId:this.params.routeId}:t;return this.params.client.execute(r)}async undo(t){return this.params.client.undo()}async redo(t){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.sessionInitialized){this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),n.version>this.currentDocument.version&&this.clearObjectCaches(),t(n);return}t(n)})}async refreshSnapshot(t,n="ensure-version"){if(typeof t=="number"&&this.currentDocument.version>=t)return oe("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){oe("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let i=await this.refreshInFlight;if(typeof t!="number"||i.version>=t||this.currentDocument.version>=t)return this.currentDocument}oe("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(i=>(this.currentDocument=i.data,this.observedDocumentVersion=Math.max(this.observedDocumentVersion,i.data.version),this.clearObjectCaches(),this.currentDocument));this.refreshInFlight=r;try{return await r}finally{this.refreshInFlight===r&&(this.refreshInFlight=null)}}clearObjectCaches(t){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!t?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache=null,this.styleContextInFlight=null)}objectCacheKey(t,n){return`${n??this.params.routeId}\0${t}`}};function Ot(e){return e.version===0&&e.entries.length===0}function nr(e){let t=e;return{...t,data:{...t.data,document:Ze(t.data.document)}}}function rr(e,t,n){switch(t){case"initialize-session":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId),...n.mutationContext?{mutationContext:n.mutationContext}:{}}};case"get-document":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};case"get-history-status":return{type:"request",payload:{id:e,kind:t}};case"get-style-context":return{type:"request",payload:{id:e,kind:t,routeId:String(n.routeId)}};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,mutationContext:n.mutationContext}}}}var Mt="vcp-window-message",fs=1;function ir(e){return{source:Mt,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function or(e){try{return I(e)?re(e,"source",Mt)&&re(e,"version",1)&&B(e,"namespace")&&B(e,"channel")&&J(e,"body")&&(!de(e,"sessionKey")||B(e,"sessionKey")):!1}catch{return!1}}var Vt="site-edit",Kt="frame-runtime";function Re(e,t={}){return ir({namespace:Vt,channel:Kt,sessionKey:t.sessionKey,body:e})}function qt(e){try{return!or(e)||e.namespace!==Vt||e.channel!==Kt?!1:vr(e.body)}catch{return!1}}var de=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function J(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&"value"in n}function g(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function re(e,t,n){return J(e,t)&&g(e,t)===n}function B(e,t){return J(e,t)&&typeof g(e,t)=="string"}function ot(e,t){return J(e,t)&&typeof g(e,t)=="boolean"}function F(e,t){let n=g(e,t);return J(e,t)&&typeof n=="number"&&Number.isFinite(n)}function xe(e,t){return!de(e,t)||g(e,t)===void 0||B(e,t)}function me(e,t){return!de(e,t)||g(e,t)===void 0||F(e,t)}function Oe(e,t){let n=g(e,t);return!de(e,t)||n===void 0||J(e,t)&&typeof n=="number"&&Number.isInteger(n)&&n>=0}function Y(e,t){return!de(e,t)||g(e,t)===void 0}function I(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function sr(e){return I(e)&&Reflect.ownKeys(e).length===0}function Ht(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1){let n=Object.getOwnPropertyDescriptor(e,String(t));if(n===void 0||!("value"in n)||typeof n.value!="string")return!1}return!0}function le(e){return I(e)&&B(e,"key")&&Oe(e,"instanceIndex")&&Oe(e,"instanceCount")&&Oe(e,"textSegmentIndex")}function ar(e){return I(e)&&F(e,"top")&&F(e,"left")&&F(e,"width")&&F(e,"height")}function cr(e){return I(e)&&B(e,"blockId")&&le(g(e,"ref"))&&ar(g(e,"rect"))&&ot(e,"targetIsSectionRoot")}function ur(e){if(!I(e))return!1;let t=g(e,"placement"),n=g(e,"boundary");return B(e,"anchorBlockId")&&le(g(e,"anchorRef"))&&(t==="before"||t==="after")&&I(n)&&F(n,"top")&&F(n,"left")&&F(n,"width")}function lr(e){return I(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&J(e,t)&&(typeof g(e,t)=="string"||g(e,t)===null))}function jt(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function dr(e){return I(e)&&Reflect.ownKeys(e).every(t=>typeof t=="string"&&J(e,t)&&jt(g(e,t)))}function fr(e){if(!I(e))return!1;let t=g(e,"priority");return B(e,"property")&&J(e,"value")&&jt(g(e,"value"))&&(!de(e,"priority")||t===void 0||t==="important")}function hr(e){return I(e)?(Y(e,"attributes")||lr(g(e,"attributes")))&&xe(e,"className")&&(Y(e,"style")||dr(g(e,"style")))&&(Y(e,"styleDeclarations")||Array.isArray(g(e,"styleDeclarations"))&&g(e,"styleDeclarations").every(fr)):!1}function pr(e){return I(e)&&F(e,"x")&&F(e,"y")&&(Y(e,"detailLevel")||re(e,"detailLevel","summary")||re(e,"detailLevel","full"))}function mr(e){return I(e)&&le(g(e,"ref"))}function gr(e){if(!I(e)||!I(g(e,"variables")))return!1;let t=g(e,"variables");return Reflect.ownKeys(t).every(n=>typeof n=="string"&&B(t,n))?Y(e,"stylesheets")||Ht(g(e,"stylesheets")):!1}function yr(e){if(!re(e,"type","request")||!B(e,"id")||!B(e,"kind")||!J(e,"payload"))return!1;let t=g(e,"kind"),n=g(e,"payload");switch(t){case"hit-test-at-point":case"start-text-edit-at-point":return pr(n);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return sr(n);case"bridge-get-source-file":return I(n)&&B(n,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return I(n)&&B(n,"key")&&xe(n,"routeId");case"scroll-to":return I(n)&&F(n,"x")&&F(n,"y");case"scroll-by":return I(n)&&F(n,"deltaX")&&F(n,"deltaY");case"set-interaction-mode":return I(n)&&ot(n,"enabled");case"set-theme-override":return gr(n);case"get-theme-variables":return I(n)&&Ht(g(n,"names"));case"compute-drop-target-at-point":return I(n)&&F(n,"x")&&F(n,"y")&&(re(n,"dragKind","insert")||re(n,"dragKind","move"))&&(Y(n,"movingRef")||le(g(n,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return I(n)&&(Y(n,"ref")||le(g(n,"ref")));case"apply-node-patch":return I(n)&&le(g(n,"ref"))&&hr(g(n,"patch"))&&(Y(n,"preview")||I(g(n,"preview"))&&B(g(n,"preview"),"sessionId")&&Oe(g(n,"preview"),"revision")&&de(g(n,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return mr(n);case"bridge-initialize-session":case"bridge-get-style-context":return I(n)&&B(n,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return I(n)&&B(n,"routeId")&&me(n,"minVersion")&&me(n,"version");case"bridge-execute":return I(n)&&I(g(n,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return I(n)&&B(n,"subscriptionId");default:return!1}}function br(e){return re(e,"type","response")&&B(e,"id")&&ot(e,"ok")&&(Y(e,"error")||B(e,"error"))}var Sr=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function Er(e){if(!re(e,"type","event")||!B(e,"kind")||!I(g(e,"payload")))return!1;let t=g(e,"kind"),n=g(e,"payload");switch(t){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return le(g(n,"ref"))&&xe(n,"value")&&(Y(n,"hit")||I(g(n,"hit")));case"node-bounds-change":return I(g(n,"hit"));case"bridge-event":return B(n,"subscriptionId")&&I(g(n,"event"));case"route-ready":return B(n,"routeId")&&me(n,"version");case"bridge-status":{let r=g(n,"state");return(r==="connecting"||r==="ready"||r==="reconnecting"||r==="failed"||r==="reload-required")&&xe(n,"routeId")&&me(n,"attempt")&&me(n,"retryInMs")&&xe(n,"messageKey")}case"scroll":{let r=g(n,"metrics");return I(r)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(i=>F(r,i))}default:return Sr.has(t)&&F(n,"clientX")&&F(n,"clientY")&&me(n,"buttons")&&(g(n,"hit")===null||I(g(n,"hit")))&&(g(n,"section")===null||cr(g(n,"section")))&&(g(n,"sectionGap")===null||ur(g(n,"sectionGap")))}}function vr(e){if(!I(e))return!1;switch(g(e,"type")){case"request":return yr(e);case"response":return br(e);case"event":return Er(e);default:return!1}}var ct="vcp-site-edit:route-ready",ut="vcp-site-edit:bridge-status",Ir=1e3,xr="data-vcp-ui-component",Yt="data-vcp-theme-preview",Ut="::repeat-item#",we="components/ui",Rr=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Cr=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function _r(e,t=""){let n=Lt(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,i=r.startsWith("/")?r:`/${r}`;return i==="/"?"/":i.replace(/\/+$/,"")}function Tr(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 kr(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 gs(e=window,t={}){let n=kr(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Pr({bridgeUrl:n,options:t}),i=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(i?.started){if(Dr(i.signature,r)){await i.syncRoute?.();return}i.cleanup?.()}let o={activeClient:null,activeBridge:null,cleanupFrameRuntime:(()=>{}),retryTimer:void 0,routeSequence:0,syncInFlight:null,syncScheduled:!1,disposed:!1,currentDocument:null,currentEntriesByKey:new Map,unsubscribeDocument:void 0,unsubscribeConnectionStatus:void 0,unbindBootstrapLifecycle:void 0,unbindRouteChange:void 0},s,a=()=>e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__===s,c=t.create_client??(h=>new Fe({url:h,authKey:t.bridge_session_key})),u=t.schedule_after_navigation??Hr,f=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},l=()=>_r(e.location.pathname,t.basePath||""),y=!!e.parent&&e.parent!==e,S=h=>{jr(e,h)},_=h=>{o.currentDocument=h,o.currentEntriesByKey=new Map((h?.entries??[]).map(x=>[x.key,x]))},C=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},T=(h,x)=>!o.disposed&&x===o.routeSequence&&h===l(),N=async(h,x)=>{let k=o.activeBridge;if(!k)return null;let A=await k.getDocument(h);return T(h,x)&&_(A.data),A.data},V=()=>{C(),_(null);let h=o.activeBridge;o.activeBridge=null,h&&e.__VCP_SITE_EDIT__===h&&delete e.__VCP_SITE_EDIT__;let x=o.activeClient;o.activeClient=null,x?.disconnect()},Se=h=>h===s.routeId&&!!o.activeBridge&&(y||!!(o.currentDocument&&Wr(o.currentDocument,h)))&&Ur(o.activeClient),fe=h=>Math.min(Ir*2**Math.max(0,h),8e3),Z=(h,x,k)=>{if(o.disposed)return;f();let A=fe(k);S({state:"reconnecting",routeId:h,attempt:k,retryInMs:A,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||x!==o.routeSequence)&&ee(k+1).catch(m=>{let d=l();if(h===d){if(ge(m)){S({state:"reload-required",routeId:h,attempt:k,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Z(h,o.routeSequence,k+1)}})},A)},z=(h,x,k)=>{if(!T(h,x)||o.activeClient===null)return;if(ge(k.message)){V(),f(),S({state:"reload-required",routeId:h,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let A=o.activeClient;C(),_(null);let m=o.activeBridge;o.activeBridge=null,m&&e.__VCP_SITE_EDIT__===m&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,A?.disconnect(),Z(h,x,0)},G=h=>{let x=l(),k=o.routeSequence;if(!(!T(x,k)||o.activeClient===null)){if(ge(h)){V(),f(),S({state:"reload-required",routeId:x,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Zt(h)&&z(x,k,{state:"failed",message:ft(h,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Or(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:h=>o.currentEntriesByKey.get(h)??null,setCurrentDocument:_,onBridgeRequestError:h=>{G(h)}});let L=async()=>ee(0),ee=async h=>{if(o.disposed)return;let x=l();if(Se(x))return;let k=o.syncInFlight;if(k?.routeId===x)return k.promise;let A=o.routeSequence+1,m=ae(x,A,h);o.syncInFlight={routeId:x,sequence:A,promise:m};try{await m}finally{o.syncInFlight?.promise===m&&(o.syncInFlight=null)}},ae=async(h,x,k)=>{o.routeSequence=x,f(),V(),S({state:k>0?"reconnecting":"connecting",routeId:h,attempt:k,messageKey:k>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let A=c(n),m=!1;o.activeClient=A,o.unsubscribeConnectionStatus=A.subscribeConnectionStatus?.(d=>{m&&(d.state==="closed"||d.state==="failed")&&z(h,x,d)});try{if(await A.connect(),!T(h,x)){A.disconnect();return}let d=wt({routeId:h,client:A,initialDocument:Fr(h)});o.activeBridge=d,a()&&(e.__VCP_SITE_EDIT__=d),o.activeClient=A,o.unsubscribeDocument=d.subscribe(D=>{D.type==="site-edit.document.changed"&&D.routeId===h&&o.currentDocument&&D.version>o.currentDocument.version&&N(h,x).catch(()=>{})}),a()&&(s.routeId=h);let P=(y?null:await d.initializeSession({routeId:h}))?.data.document??null;if(P&&_(P),!T(h,x)){A.disconnect();return}m=!0,S({state:"ready",routeId:h,attempt:k,messageKey:"studio.status.previewReady"}),Tr(e,{documentVersion:P?.version??0,routeId:h,versions:t.runtime_versions}),P&&Qt(e,{routeId:h,version:P.version})}catch(d){if(C(),o.activeClient===A&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,A.disconnect(),_(null),!T(h,x))return;throw S({state:ge(d)?"reload-required":"failed",routeId:h,attempt:k,messageKey:ge(d)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),d}},K=h=>{if(o.disposed)return;let x=l();if(ge(h)){f(),S({state:"reload-required",routeId:x,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}Z(x,o.routeSequence,0)},U=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,u(()=>{o.syncScheduled=!1,!o.disposed&&L().catch(h=>K(h))}))},te=()=>{o.disposed||(o.disposed=!0,o.syncScheduled=!1,o.syncInFlight=null,f(),o.routeSequence+=1,o.unbindRouteChange?.(),o.unbindRouteChange=void 0,o.unbindBootstrapLifecycle?.(),o.unbindBootstrapLifecycle=void 0,o.cleanupFrameRuntime(),V(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:L,cleanup:te},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,o.unbindBootstrapLifecycle=Ar(e,te),o.unbindRouteChange=qr(e,U,l),t.defer_initial_sync){U();return}await L()}function Pr(e){return{basePath:Lt(e.options.basePath??""),bridgeUrl:e.bridgeUrl,runtimeVersions:{bridge:e.options.runtime_versions?.bridge??null,contracts:e.options.runtime_versions?.contracts??null,engine:e.options.runtime_versions?.engine??null},sessionKeyFingerprint:Nr(e.options.bridge_session_key)}}function Dr(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function Nr(e){if(!e)return null;let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(36)}`}function Ar(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),Br(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function Br(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Fr(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function Or(e=window,t={}){let n=null,r=null,i=null,o=null,s=null,a=null,c=null,u=null,f=null,l=new Map,y=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,S=()=>{n?.(),n=null,r=null},_=()=>{i?.(),i=null,o?.(),o=null},C=(m,d,p)=>{let P=s?.sessionKey!==m||s?.sourceWindow!==d||s?.targetOrigin!==p;s={sessionKey:m,sourceWindow:d,targetOrigin:p},P&&(u=null,f=null)},T=(m,d)=>{let p=e.parent&&e.parent!==e?e.parent:null;return!p||d!==p?!1:!y||m===y},N=()=>{for(let m of l.values())m();l.clear()},V=m=>JSON.stringify([m.routeId,m.version]),Se=()=>!c||c.state==="ready",fe=m=>JSON.stringify([m.state,m.routeId??null,m.attempt??null,m.retryInMs??null,m.messageKey??null]),Z=m=>{if(!Se())return;let d=V(m);u!==d&&(o?.(),o=null,K({kind:"route-ready",payload:{routeId:m.routeId,version:m.version}}),s&&(u=d))},z=m=>{let d=fe(m);f!==d&&(m.state!=="ready"&&(u=null,a=null),K({kind:"bridge-status",payload:m}),s&&(f=d))},G=m=>{a=m,Z(m)},L=m=>{c=m,z(m)},ee=()=>{a&&Z(a)},ae=()=>{c&&z(c)},K=m=>{s&&s.sourceWindow.postMessage(Re({type:"event",...m},{sessionKey:s.sessionKey}),s.targetOrigin)},U=(m,d,p,P)=>{let D=t.getCurrentDocument?.()??null,w=Lr(e.document,d.clientX,d.clientY),b=He(e.document,d.clientX,d.clientY,D),q=b?W(b,p==="full"?Q(e.document,b,D):je(e.document,b,D),t.getDocumentEntry,p):null,ne=ei(e.document,w,D),ie=ni(e.document,d,D);P&&q&&(m==="pointer-click"||m==="pointer-double-click")&&(P.preventDefault(),P.stopPropagation(),typeof P.stopImmediatePropagation=="function"&&P.stopImmediatePropagation()),K({kind:m,payload:{clientX:d.clientX,clientY:d.clientY,buttons:Number(d.buttons??0),hit:q,section:ne,sectionGap:ie}})},te=m=>{K({kind:"pointer-leave",payload:{clientX:m?.clientX??0,clientY:m?.clientY??0,buttons:Number(m?.buttons??0),hit:null,section:null,sectionGap:null}})},h=(m,d,p)=>{_(),s={sessionKey:m,sourceWindow:d,targetOrigin:p};let P=Vi(e.document),D=null,w=null,b=null,q=()=>{b!==null&&(Xt(e,b),b=null),D=null},ne=()=>{b=null;let E=D;D=null,E&&U("pointer-move",E,"summary")},ie=E=>{w=E,D=E,b===null&&(b=Jt(e,ne))},O=()=>{w&&ie(w)},ce=E=>{ie({clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)})},Ee=E=>{U("pointer-down",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},ve=E=>{U("pointer-up",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},he=E=>{U("pointer-cancel",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"summary",E)},De=E=>{U("pointer-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},v=E=>{U("pointer-double-click",{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)},"full",E)},R=E=>{let Vn=E?{clientX:Number(E.clientX),clientY:Number(E.clientY),buttons:Number(E.buttons)}:w;q(),w=null,te(Vn??void 0)},M=()=>R(),ue=()=>{K({kind:"scroll",payload:{metrics:Ke(e)}}),O()};e.document.addEventListener("pointerdown",Ee,!0),e.document.addEventListener("pointermove",ce,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",ve,!0),e.document.addEventListener("pointercancel",he,!0),e.document.addEventListener("click",De,!0),e.document.addEventListener("dblclick",v,!0),e.addEventListener("scroll",ue,{passive:!0}),e.addEventListener("resize",O,{passive:!0}),e.addEventListener("blur",M),e.document.addEventListener("load",O,!0);let Ne=e.document.documentElement,Rt=typeof Ne.addEventListener=="function"?Ne:e.document;Rt.addEventListener("pointerleave",R,!0);let Ae=e.visualViewport;Ae?.addEventListener?.("resize",O,{passive:!0}),Ae?.addEventListener?.("scroll",O,{passive:!0});let Ct=e.ResizeObserver,_t=typeof Ct=="function"?new Ct(O):null;_t?.observe(Ne);let Tt=e.MutationObserver,kt=typeof Tt=="function"?new Tt(O):null;kt?.observe(Ne,{attributes:!0,childList:!0,subtree:!0}),i=()=>{q(),w=null,_t?.disconnect(),kt?.disconnect(),P(),e.document.removeEventListener("pointerdown",Ee,!0),e.document.removeEventListener("pointermove",ce,!0),e.document.removeEventListener("pointerup",ve,!0),e.document.removeEventListener("pointercancel",he,!0),e.document.removeEventListener("click",De,!0),e.document.removeEventListener("dblclick",v,!0),e.removeEventListener("scroll",ue),e.removeEventListener("resize",O),e.removeEventListener("blur",M),e.document.removeEventListener("load",O,!0),Rt.removeEventListener("pointerleave",R,!0),Ae?.removeEventListener?.("resize",O),Ae?.removeEventListener?.("scroll",O)}},x=m=>{let d=m.detail;d?.routeId&&G(d)},k=m=>{let d=m.detail;d?.state&&L(d)},A=m=>{let d=m.data;if(!qt(d)||d.body.type!=="request"||d.body.kind!=="apply-node-patch"&&d.body.kind!=="get-hit-by-ref"&&d.body.kind!=="get-path-by-ref"&&d.body.kind!=="get-scroll-metrics"&&d.body.kind!=="scroll-to"&&d.body.kind!=="scroll-by"&&d.body.kind!=="set-interaction-mode"&&d.body.kind!=="set-theme-override"&&d.body.kind!=="clear-theme-override"&&d.body.kind!=="get-theme-variables"&&d.body.kind!=="compute-drop-target-at-point"&&d.body.kind!=="observe-node-bounds"&&d.body.kind!=="clear-node-bounds-observer"&&d.body.kind!=="restore-text-edit"&&d.body.kind!=="clear-text-edit-rollback"&&d.body.kind!=="start-text-edit-at-point"&&d.body.kind!=="hit-test-at-point"&&!Wt(d.body))return;let p=d.body,P=typeof d.sessionKey=="string"?d.sessionKey:null,D=m.source,w=m.origin;if(!P||!w||!D||typeof D.postMessage!="function"||!T(P,D))return;if(s){if(s.sourceWindow!==D||s.targetOrigin!==w)return;s.sessionKey!==P&&(S(),_(),N(),s=null)}C(P,D,w),ae(),ee();let b=q=>{let ne=typeof p.id=="string"?p.id:"unknown";D.postMessage(Re({id:ne,...q},{sessionKey:P}),w)};try{if(Wt(p)){Mr({message:p,sendEvent:v=>{D.postMessage(Re({type:"event",...v},{sessionKey:P}),w)},sendResponse:b,subscriptions:l,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(p.kind==="apply-node-patch"){let v=se(e.document,p.payload.ref,t.getCurrentDocument?.()??null);if(!v){b({type:"response",ok:!1,error:"No editable element found for patch target"});return}let R=p.payload.preview,M=R?Ri(R.sessionId,p.payload.ref):null;if(M&&R){let ue=Ce.get(M)??-1;if(R.revision<ue){b({type:"response",ok:!0,result:{applied:!1,appliedRevision:R.revision,stale:!0,latestRevision:ue}});return}if(R.revision===ue){b({type:"response",ok:!0,result:{applied:!1,appliedRevision:R.revision,duplicate:!0,latestRevision:ue}});return}}if(Ii(v,p.payload.patch),M&&R&&Ci(M,R.revision),R?.responseDetail==="none"){b({type:"response",ok:!0,result:{applied:!0,appliedRevision:R.revision}});return}b({type:"response",ok:!0,result:W(v,Q(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,R?.responseDetail??"full")});return}if(p.kind==="get-hit-by-ref"){let v=se(e.document,p.payload.ref,t.getCurrentDocument?.()??null);if(!v){b({type:"response",ok:!1,error:"No editable element found for hit target"});return}b({type:"response",ok:!0,result:W(v,Q(e.document,v,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(p.kind==="get-path-by-ref"){let v=se(e.document,p.payload.ref,t.getCurrentDocument?.()??null);if(!v){b({type:"response",ok:!1,error:"No editable element found for path target"});return}let R=[],M=v;for(;M;)M.getAttribute("data-vcp-edit-key")&&R.push(W(M,Q(e.document,M,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),M=M.parentElement;b({type:"response",ok:!0,result:R.reverse()});return}if(p.kind==="restore-text-edit"||p.kind==="clear-text-edit-rollback"){let v=p.payload.ref;if(p.kind==="clear-text-edit-rollback"){r&&$t(r.ref,v)&&(r=null),b({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!$t(r.ref,v)){b({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let R=Gr(e.document,r,t.getCurrentDocument?.()??null);r=null,b(R?{type:"response",ok:!0,result:{restored:!0}}:{type:"response",ok:!1,error:"Failed to restore text edit snapshot"});return}if(p.kind==="get-scroll-metrics"){b({type:"response",ok:!0,result:Ke(e)});return}if(p.kind==="scroll-to"){let v=Number(p.payload.x),R=Number(p.payload.y);if(!Number.isFinite(v)||!Number.isFinite(R)){b({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:v,top:R}),b({type:"response",ok:!0,result:Ke(e)});return}if(p.kind==="scroll-by"){let v=Number(p.payload.deltaX),R=Number(p.payload.deltaY);if(!Number.isFinite(v)||!Number.isFinite(R)){b({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:v,top:R}),b({type:"response",ok:!0,result:{...Ke(e),scrolled:!0}});return}if(p.kind==="set-interaction-mode"){p.payload.enabled?h(P,D,w):s?.sourceWindow===D&&s.targetOrigin===w&&s.sessionKey===P&&_(),b({type:"response",ok:!0,result:{interactionEnabled:p.payload.enabled}});return}if(p.kind==="set-theme-override"){_i(e.document,p.payload),b({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(p.kind==="clear-theme-override"){Ti(e.document),b({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(p.kind==="get-theme-variables"){b({type:"response",ok:!0,result:ki(e.document,p.payload.names)});return}if(p.kind==="compute-drop-target-at-point"){let v=Number(p.payload?.x),R=Number(p.payload?.y);if(!Number.isFinite(v)||!Number.isFinite(R)){b({type:"response",ok:!1,error:"Invalid drop target point"});return}b({type:"response",ok:!0,result:gi(e,v,R,p.payload.dragKind,p.payload.movingRef,t.getCurrentDocument?.()??null,t.getDocumentEntry)});return}if(p.kind==="observe-node-bounds"){let v=p.payload.ref;if(!v){b({type:"response",ok:!1,error:"Missing bounds observer target"});return}let R=se(e.document,v,t.getCurrentDocument?.()??null);if(!R){b({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=fi(e,R,v,t.getCurrentDocument,t.getDocumentEntry,M=>K({kind:"node-bounds-change",payload:{hit:M}})),b({type:"response",ok:!0,result:{observing:!0}}),K({kind:"node-bounds-change",payload:{hit:W(R,v,t.getDocumentEntry,"summary")}});return}if(p.kind==="clear-node-bounds-observer"){o?.(),o=null,b({type:"response",ok:!0,result:{cleared:!0}});return}if(p.kind!=="hit-test-at-point"&&p.kind!=="start-text-edit-at-point")return;let q=Number(p.payload?.x),ne=Number(p.payload?.y);if(!Number.isFinite(q)||!Number.isFinite(ne)){b({type:"response",ok:!1,error:"Invalid text edit point"});return}let ie=p.kind==="hit-test-at-point"?He(e.document,q,ne,t.getCurrentDocument?.()??null):Jr(e.document,q,ne,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!ie){b({type:"response",ok:!1,error:p.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let O=p.kind==="start-text-edit-at-point"?ie:null,ce=p.kind==="hit-test-at-point"?ie:O.element,Ee=p.payload.detailLevel??"full",ve=Ee==="full"?Q(e.document,ce,t.getCurrentDocument?.()??null):je(e.document,ce,t.getCurrentDocument?.()??null),he=O&&typeof O.textSegmentIndex=="number"?{...ve,textSegmentIndex:O.textSegmentIndex}:ve,De=W(ce,he,t.getDocumentEntry,Ee);if(p.kind==="hit-test-at-point"){b({type:"response",ok:!0,result:De});return}S(),n=Ai(e,ce,he,v=>{D.postMessage(Re({type:"event",...v},{sessionKey:P}),w)},{...O?.textNode?{textNode:O.textNode}:{},onCommitSnapshot:v=>{r=v}}),b({type:"response",ok:!0,result:{ref:he}})}catch(q){b({type:"response",ok:!1,error:q instanceof Error?q.message:"Failed to start text edit"})}};return e.addEventListener("message",A),e.addEventListener(ct,x),e.addEventListener(ut,k),()=>{S(),_(),s=null,N(),e.removeEventListener("message",A),e.removeEventListener(ct,x),e.removeEventListener(ut,k)}}function Wt(e){let t=e.kind;return t==="bridge-initialize-session"||t==="bridge-get-document"||t==="bridge-get-history-status"||t==="bridge-get-style-context"||t==="bridge-ensure-document-version"||t==="bridge-acknowledge-document-version"||t==="bridge-get-object-edit-context"||t==="bridge-get-class-name-source"||t==="bridge-get-source-tree"||t==="bridge-get-source-file"||t==="bridge-resolve-source-location"||t==="bridge-execute"||t==="bridge-undo"||t==="bridge-redo"||t==="bridge-subscribe"||t==="bridge-unsubscribe"}function wr(e){return e.kind==="update-text"||e.kind==="update-array-item"||e.kind==="set-class-name-source"||e.kind==="set-props"||e.kind==="apply-style-draft"}async function Mr({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:i,setCurrentDocument:o,onBridgeRequestError:s,windowLike:a}){let c=a.__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-initialize-session":{let u=await c.initializeSession({routeId:e.payload.routeId});o?.(u.data.document),Qt(a,{routeId:u.data.document.routeId,version:u.data.document.version}),n({type:"response",ok:!0,result:u});return}case"bridge-get-document":{let u=await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await c.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await c.getStyleContext(e.payload.routeId)});return;case"bridge-ensure-document-version":{if(!Number.isFinite(Number(e.payload.minVersion))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=c.ensureDocumentVersion?await c.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let u=c.acknowledgeDocumentVersion?await c.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await c.getDocument(e.payload.routeId);o?.(u.data),n({type:"response",ok:!0,result:u});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:Vr(u,e.payload.key,a.document,i?.()??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":{let u=await c.execute(e.payload.request),f=i?.()?.routeId;if(u.ok&&f&&c.acknowledgeDocumentVersion&&wr(e.payload.request)){let l=await c.acknowledgeDocumentVersion(f,u.data.resultVersion);o?.(l.data)}n({type:"response",ok:!0,result:u});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 f=c.subscribe(l=>{t({kind:"bridge-event",payload:{event:l,subscriptionId:u}})});r.set(u,f),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:$r(u)})}}function Vr(e,t,n,r){if(!e.ok)return e;let i=se(n,{key:t},r),o=i?Kr(i):null;return o?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...o}}}:e}function Kr(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 qr(e,t,n=()=>e.location.pathname){let r=e.history.pushState,i=e.history.replaceState,o=n(),s=()=>{let u=n();u!==o&&(o=u,t())},a=()=>s(),c=()=>s();return e.history.pushState=function(...f){let l=r.apply(this,f);return s(),l},e.history.replaceState=function(...f){let l=i.apply(this,f);return s(),l},e.addEventListener("popstate",a),e.addEventListener("hashchange",c),()=>{e.history.pushState=r,e.history.replaceState=i,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",c)}}function Hr(e){if(typeof requestAnimationFrame=="function"){requestAnimationFrame(()=>requestAnimationFrame(e));return}setTimeout(e,0)}function Jt(e,t){return typeof e.requestAnimationFrame=="function"?e.requestAnimationFrame(t):e.setTimeout(t,0)}function Xt(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function Qt(e,t){e.dispatchEvent(new CustomEvent(ct,{detail:t}))}function jr(e,t){e.dispatchEvent(new CustomEvent(ut,{detail:t}))}function Ur(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Wr(e,t){return e.routeId===t}function ft(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function Zt(e){let t=ft(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function $r(e){let t=ft(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":Zt(t)?"Site edit bridge disconnected":t}function ge(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 Lt(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ht(e){return Rr.has(tn(e))}function zr(e){return Cr.has(tn(e))}function en(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:zr(e.tagName),canInsertChild:ht(e.tagName),canMove:!1,canRemove:!1}}function tn(e){return e?.trim().toLowerCase()??""}function $t(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 Gr(e,t,n){let r=se(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let i=Yr(r,t.ref.textSegmentIndex);return i?(i.nodeValue=t.initialText,!0):!1}return typeof t.initialHtml=="string"?(r.innerHTML=t.initialHtml,!0):(r.textContent=t.initialText,!0)}function Yr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!qe(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function Jr(e,t,n,r,i){let o=He(e,t,n,r),s=nn(o);if(!s)return null;let a=s.getAttribute("data-vcp-edit-key")??"",c=Q(e,s,r),u=i?.(c.key)??i?.(a);if(!en({operationSummary:u?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let l=Xr(e,t,n,s);if(l){let y=Zr(s,l);if(y!==null)return{element:s,textNode:l,textSegmentIndex:y}}return $e(s)?null:{element:s}}function Xr(e,t,n,r){let i=Qr(e,t,n);return!i||i.parentElement!==r?null:i}function Qr(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(qe(o))return o;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return qe(a)?a:null}function Zr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!qe(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function qe(e){return e?.nodeType===3}function Lr(e,t,n){return(typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean))[0]??null}function ei(e,t,n){let r=t;for(;r&&!r.getAttribute("data-site-block-id");)r=r.parentElement;if(!r)return null;let i=r.getAttribute("data-site-block-id")??"",o=r.getAttribute("data-vcp-edit-key")??"";return!i||!o?null:{blockId:i,ref:je(e,r,n),rect:mt(r.getBoundingClientRect()),targetIsSectionRoot:t===r}}function ti(e,t){return Array.from(e.querySelectorAll("[data-site-block-id]")).filter(n=>{let r=n.parentElement;for(;r;){if(r.getAttribute("data-site-block-id"))return!1;r=r.parentElement}return!!(n.getAttribute("data-site-block-id")&&n.getAttribute("data-vcp-edit-key"))}).map(n=>({element:n,blockId:n.getAttribute("data-site-block-id")??"",ref:je(e,n,t),rect:mt(n.getBoundingClientRect())})).filter(({rect:n})=>n.width>0&&n.height>0).sort((n,r)=>n.rect.top-r.rect.top||n.rect.left-r.rect.left)}function ni(e,t,n){let r=ti(e,n),i=r[0],o=r.at(-1);return!i||!o?null:[{anchorBlockId:i.blockId,anchorRef:i.ref,placement:"before",boundary:{top:i.rect.top,left:i.rect.left,width:i.rect.width}},...r.slice(1).map(a=>({anchorBlockId:a.blockId,anchorRef:a.ref,placement:"before",boundary:{top:a.rect.top,left:a.rect.left,width:a.rect.width}})),{anchorBlockId:o.blockId,anchorRef:o.ref,placement:"after",boundary:{top:o.rect.top+o.rect.height,left:o.rect.left,width:o.rect.width}}].find(({boundary:a})=>t.clientX>=a.left&&t.clientX<=a.left+a.width&&Math.abs(t.clientY-a.top)<=12)??null}function He(e,t,n,r=null){let i=typeof e.elementsFromPoint=="function"?e.elementsFromPoint(t,n):[e.elementFromPoint(t,n)].filter(Boolean);for(let o of i){let s=nn(o),a=s?.getAttribute("data-vcp-edit-key")??"";if(s&&ai(s,r,a))return s}return null}function nn(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(pt(t))return n??t;!ri(r)&&!n&&(n=t)}t=t.parentElement}return n}function pt(e){return e.getAttribute(xr)!==null}function ri(e){return ii(e.split("::")[0]??"")}function ii(e){if(!e)return!1;let t=oi(e);return t===we||t.startsWith(`${we}/`)||t.includes(`/${we}/`)||t.endsWith(`/${we}`)}function oi(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let i of n.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}return r.join("/")}function Q(e,t,n){let r=t.getAttribute("data-vcp-edit-key")??"",i=on(an(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${hn(r)}"]`))),n,r);if(i.length<=1)return{key:zt(n,r,0)};let o=i.indexOf(t);return o>=0?{key:zt(n,r,o),instanceIndex:o,instanceCount:i.length}:{key:r}}function je(e,t,n){return Q(e,t,n)}function se(e,t,n){let r=Ue(t.key)??t.key,i=on(an(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${hn(r)}"]`))),n,t.key);if(i.length===0)return null;let o=typeof t.instanceIndex=="number"&&t.instanceIndex>=0&&t.instanceIndex<i.length?t.instanceIndex:null,s=(Ue(t.key)??t.key)!==t.key;if(o!==null&&!s)return i[o]??null;let a=si(n,t.key);return a!==null&&a>=0&&a<i.length?i[a]??null:o!==null?i[o]??null:i[0]??null}function zt(e,t,n){return rn(e,t)[n]?.key??t}function si(e,t){let n=Ue(t);if(!n)return null;let i=rn(e,n).findIndex(o=>o.key===t);return i>=0?i:null}function rn(e,t){return(e?.entries??[]).filter(n=>(Ue(n.key)??n.key)===t)}function on(e,t,n){let r=sn(t,n);return r?e.filter(i=>i.tagName.toLowerCase()===r):e}function ai(e,t,n){let r=sn(t,n);return!r||e.tagName.toLowerCase()===r}function sn(e,t){return null}var ci=2,ui=4;function an(e){return[...e].sort((t,n)=>{if(t===n)return 0;let r=typeof t.compareDocumentPosition=="function"?t.compareDocumentPosition(n):0;return(r&ui)!==0?-1:(r&ci)!==0?1:0})}function Ue(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(Ut);if(n<0)break;let r=Number(t.slice(n+Ut.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function li(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...cn(n),paddingTop:j(n?.paddingTop),paddingRight:j(n?.paddingRight),paddingBottom:j(n?.paddingBottom),paddingLeft:j(n?.paddingLeft),borderTopWidth:j(n?.borderTopWidth),borderRightWidth:j(n?.borderRightWidth),borderBottomWidth:j(n?.borderBottomWidth),borderLeftWidth:j(n?.borderLeftWidth),columnGap:j(n?.columnGap),rowGap:j(n?.rowGap)}}function cn(e){return{marginTop:j(e?.marginTop,!0),marginRight:j(e?.marginRight,!0),marginBottom:j(e?.marginBottom,!0),marginLeft:j(e?.marginLeft,!0)}}function j(e,t=!1){let n=Number.parseFloat(e??"");return Number.isFinite(n)?t?n:Math.max(0,n):0}function di(e){let t=e.ownerDocument?.defaultView;return Array.from(e.children).filter(n=>typeof n.getBoundingClientRect=="function").map(n=>({rect:mt(n.getBoundingClientRect()),margin:cn(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function W(e,t,n,r="full"){let i=e.getBoundingClientRect(),o=n?.(t.key)??null,s=e.tagName.toLowerCase(),a=We(e),c=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([_,C])=>[_,C??""])),attributes:Object.fromEntries(e.getAttributeNames().map(_=>[_,e.getAttribute(_)??""]))}:{},u=en({operationSummary:o?.operationSummary,tagName:s,fallbackMode:"preview"}),f=pt(e),l=!0,y=un(e)?.getAttribute("data-vcp-edit-key")??null,S=di(e);return{ref:t,key:t.key,detailLevel:r,tagName:s,...o?{sourceKind:"jsx"}:{},...y?{parentKey:y}:{},...o?.pageCompositionUnitKey?{pageCompositionUnitKey:o.pageCompositionUnitKey}:{},...c,runtimeFlags:{selectable:!0,movable:u.canMove,removable:u.canRemove,textEditable:u.canUpdateText,container:f?!1:!!$e(e)||u.canInsertChild||l&&ht(s)},layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:S,childRects:S.map(({rect:_})=>_),spacing:li(e)}}function fi(e,t,n,r,i,o){let s=t,a=W(s,n,i,"summary"),c=null,u=()=>{c===null&&(c=Jt(e,f))},f=()=>{c=null;let T=se(e.document,n,r?.()??null);if(!T)return;T!==s&&(y?.unobserve(s),s=T,y?.observe(s));let N=W(s,n,i,"summary");N.rect.width<=0||N.rect.height<=0||hi(a,N)&&(a=N,o(N))},l=e.ResizeObserver,y=typeof l=="function"?new l(u):null;y?.observe(s);let S=e.MutationObserver,_=typeof S=="function"?new S(u):null;_?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",u,{passive:!0});let C=e.visualViewport;return C?.addEventListener?.("resize",u,{passive:!0}),e.document.addEventListener("load",u,!0),()=>{c!==null&&(Xt(e,c),c=null),y?.disconnect(),_?.disconnect(),e.removeEventListener("resize",u),C?.removeEventListener?.("resize",u),e.document.removeEventListener("load",u,!0)}}function hi(e,t){return gt(e.rect,t.rect)||pi(e.childBoxes,t.childBoxes)||mi(e.childRects,t.childRects)||lt(e.spacing,t.spacing)||lt(e.layout,t.layout)}function pi(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>{let s=r[o];return!s||gt(i.rect,s.rect)||lt(i.margin,s.margin)})}function mi(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>gt(i,r[o]??i))}function lt(e,t){let n=e??{},r=t??{},i=new Set([...Object.keys(n),...Object.keys(r)]);return Array.from(i).some(o=>n[o]!==r[o])}function mt(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function gt(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 gi(e,t,n,r,i,o,s){let a=e.document,c=He(a,t,n,o);if(!c)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let u=i?se(a,i,o):null;if(u&&dt(c,u))return Me(a,c,"self-or-descendant",o,s);if(r==="move"&&u){let C=Ei(a,c,u,o,s);if(C){let T=st(C.child,C.targetParent,t,n,"nearest");if(T)return Ve(a,C.child,C.targetParent,T,o,s)}}let f=null,l=!1,y=c,S=c.parentElement;for(;S;){if(S.getAttribute("data-vcp-edit-key")){if(u&&dt(S,u))return Me(a,c,"self-or-descendant",o,s);let C=Gt(S,r,s);if(C==="accept"){f={child:y,targetParent:S};break}C==="blocked"&&(l=!0),y=S}S=S.parentElement}let _=Gt(c,r,s);if(_==="accept"){if(f){let C=st(f.child,f.targetParent,t,n,"edge");if(C)return Ve(a,f.child,f.targetParent,C,o,s)}return Ve(a,c,c,yi(c,t,n),o,s)}if(f){let C=st(f.child,f.targetParent,t,n,"nearest");return Ve(a,f.child,f.targetParent,C??"after",o,s)}return _==="blocked"||l?Me(a,c,"operation-boundary-blocked",o,s):Me(a,c,"no-accepting-parent",o,s)}function Me(e,t,n,r,i){return{anchorHit:W(t,Q(e,t,r),i,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function Ve(e,t,n,r,i,o){let s=W(t,Q(e,t,i),o,"summary"),a=W(n,Q(e,n,i),o,"summary"),c=We(n).indicatorOrientation,u=r==="append"||r==="prepend"?bi(n.getBoundingClientRect(),c,r):Si(t.getBoundingClientRect(),c,r);return{anchorHit:s,targetParentHit:a,relation:r,indicatorOrientation:c,indicatorBounds:u}}function Gt(e,t,n){if(pt(e))return"not-container";let r=e.getAttribute("data-vcp-edit-key")??"",i=n?.(r)??null;if(i)return i.operationSummary.canInsertChild===!0?"accept":$e(e)?"blocked":"not-container";let o=e.tagName.toLowerCase();return ht(o)?"accept":"not-container"}function st(e,t,n,r,i){let o=We(t).indicatorOrientation,s=e.getBoundingClientRect(),a=o==="vertical"?s.width>0?(n-s.left)/s.width:.5:s.height>0?(r-s.top)/s.height:.5;return i==="edge"&&a>=.25&&a<=.75?null:a<.5?"before":"after"}function yi(e,t,n){let r=We(e).indicatorOrientation,i=e.getBoundingClientRect();return(r==="vertical"?i.width>0?(t-i.left)/i.width:.5:i.height>0?(n-i.top)/i.height:.5)<.5?"prepend":"append"}function We(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e),r=n?.display??"",i=n?.flexDirection,o=n?.gridAutoFlow,s="horizontal";return r==="flex"||r==="inline-flex"?s=(i??"row").startsWith("row")?"vertical":"horizontal":(r==="grid"||r==="inline-grid")&&(s=(o??"row").includes("column")?"vertical":"horizontal"),{display:r,...i?{flexDirection:i}:{},...o?{gridAutoFlow:o}:{},indicatorOrientation:s}}function bi(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 Si(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 dt(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function Ei(e,t,n,r,i){let o=vi(e,t,n,r,i);if(o)return o;let s=un(n);if(!s||t===s)return null;let a=t,c=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==s;)a.getAttribute("data-vcp-edit-key")&&(c=a),a=a.parentElement;return a!==s||!c||c===s||c===n||dt(c,n)?null:{child:c,targetParent:s}}function vi(e,t,n,r,i){return null}function un(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function $e(e){for(let t of Array.from(e.childNodes)){if(typeof t.getAttribute!="function")continue;let n=t;if(n.getAttribute("data-vcp-edit-key"))return n;let r=$e(n);if(r)return r}return null}function Ke(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:X(e.scrollX),scrollY:X(e.scrollY),scrollWidth:Math.max(X(t?.scrollWidth),X(n?.scrollWidth),X(e.innerWidth)),scrollHeight:Math.max(X(t?.scrollHeight),X(n?.scrollHeight),X(e.innerHeight)),viewportWidth:X(e.innerWidth),viewportHeight:X(e.innerHeight)}}function Ii(e,t){Object.entries(t.attributes??{}).forEach(([r,i])=>{if(i===null){e.removeAttribute(r);return}e.setAttribute(r,i)}),typeof t.className=="string"&&(e.className=t.className);let n=new Set(t.styleDeclarations?.map(r=>r.property)??[]);Object.entries(t.style??{}).forEach(([r,i])=>{if(n.has(r))return;let o=e.style,s=r.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);if(i==null||i===""){o.removeProperty(s);return}o.setProperty(s,String(i))}),t.styleDeclarations?.forEach(r=>{let i=e.style,o=r.property.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`),s=r.value;if(s==null||s===""){i.removeProperty(o);return}i.setProperty(o,String(s),r.priority)})}var xi=500,Ce=new Map;function Ri(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Ci(e,t){if(Ce.size>=xi){let n=Ce.keys().next().value;n&&Ce.delete(n)}Ce.set(e,t)}var _e=new Set;function _i(e,t){let n=e.documentElement?.style,r=new Set;for(let[i,o]of Object.entries(t.variables??{}))i.startsWith("--")&&(r.add(i),n?.setProperty(i,o));for(let i of _e)r.has(i)||n?.removeProperty(i);_e.clear();for(let i of r)_e.add(i);Ni(e,t.stylesheets??[])}function Ti(e){let t=e.documentElement?.style;for(let n of _e)t?.removeProperty(n);_e.clear();for(let n of fn(e))n.remove()}function ki(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,i=r?e.defaultView?.getComputedStyle(r):null,o={};for(let s of n){let a=ln(i,s);a&&(o[s]=a)}return o}function ln(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return dn(e,r,n)}function dn(e,t,n){if(!t)return null;let r=Pi(t);if(!r)return t;let i=ln(e,r.name,n);return i||(r.fallback?dn(e,r.fallback,n)??r.fallback:null)}function Pi(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=Di(n),i=r>=0?n.slice(0,r).trim():n;if(!i.startsWith("--"))return null;let o=r>=0?n.slice(r+1).trim():null;return{name:i,fallback:o||null}}function Di(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 Ni(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of fn(e)){let s=o.getAttribute("href")??"";if(!n.has(s)||r.has(s)){o.remove();continue}r.set(s,o)}let i=e.head;if(i)for(let o of n){if(r.has(o))continue;let s=e.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute(Yt,"true"),s.setAttribute("href",o),i.appendChild(s)}}function fn(e){return Array.from(e.querySelectorAll(`link[${Yt}]`))}function Ai(e,t,n,r,i={}){let o=i.textNode?Bi(e.document,i.textNode):null;if(i.textNode&&!o)throw new Error("Failed to prepare text segment editor");let s=o?.element??t,a=s.textContent??"",c=o?void 0:t.innerHTML,u=Fi(s),f=!1,l=()=>{e.document.removeEventListener("pointerdown",S,!0),s.removeEventListener("keydown",_),s.removeEventListener("blur",C),s.removeEventListener("input",T),wi(s,u)},y=N=>{if(f)return;f=!0;let V=s.textContent??"";if(l(),N==="cancel"){o?.restore(a),o||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(V),N==="commit"&&V!==a){i.onCommitSnapshot?.({ref:n,initialText:a,...c!==void 0?{initialHtml:c}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:V}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function S(N){let V=N.target;V&&s.contains(V)||y("commit")}function _(N){if(N.key==="Escape"){N.preventDefault(),y("cancel");return}N.key==="Enter"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),y("commit"))}function C(){y("commit")}function T(){r({kind:"text-edit-input",payload:{ref:n,hit:W(t,n,void 0,"full")}})}return Oi(s),e.document.addEventListener("pointerdown",S,!0),s.addEventListener("keydown",_),s.addEventListener("blur",C),s.addEventListener("input",T),Ki(s),qi(s,e.document),l}function Bi(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(i){t.nodeValue=i,r.parentNode&&r.parentNode.replaceChild(t,r)}}}function Fi(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 Oi(e){Mi(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 wi(e,t){at(e,"contenteditable",t.contentEditable),at(e,"spellcheck",t.spellcheck),at(e,"data-vcp-edit-text-editing",t.marker),e.style.cursor=t.cursor,e.style.userSelect=t.userSelect}function Mi(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 at(e,t,n){if(n===null){e.removeAttribute(t);return}e.setAttribute(t,n)}function Vi(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 Ki(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function qi(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function hn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function X(e){let t=Number(e);return Number.isFinite(t)?t:0}import Hi from"node:http";import{createHash as Sn,randomBytes as ji,timingSafeEqual as Ui}from"node:crypto";import St from"node:path";import{WebSocket as En,WebSocketServer as Wi}from"ws";import{createPreviewSiteEditEngineRuntime as $i,openFileHistoryStore as zi}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Gi,scanNextAppRouterRoutes as Yi}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ji}from"@vcp-dev/site-edit-engine/source-watcher";var ze=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Xi}from"@vcp-dev/contracts";var Qi="127.0.0.1",Zi=30218,Li="/__vcp/site-edit/bridge",vn=6*1024*1024,eo=vn*2,to=3e3,pn=50,mn="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ps(e){let t=xn(e),n=Cn(t),r=Rn(),i=r.get(n);if(i)return i;let o=new Ge(t);r.set(n,o);try{o.start()}catch(s){throw r.delete(n),o.stop(),s}return o}function In(e,t,n={}){let r=new Ge(xn(t),e,!1,n);return r.start({listen:!1}),r}var Ge=class{constructor(t,n=Hi.createServer((o,s)=>{s.writeHead(404),s.end("VCP site edit bridge server")}),r=!0,i={}){this.options=t,this.server=n,this.closeHttpServerOnStop=r,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ze,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(t={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=ro({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 Ji({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??pn,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:r=>this.handleFileChanged(r),on_batch_change:r=>this.handleFilesChanged(r)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let t=!!this.runtime;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let t=Rn(),n=Cn(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1}createRuntime(t,n=null){let r=this.runtime;this.activeHistoryStore=t??null;let i=(this.dependencies.createRuntime??$i)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version);for(let s of this.eventListeners)s(o)},...t?{historyStore:t}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=i,this.activeHistorySessionId=n,r?.dispose()}createBridgeEngine(){return{initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let{runtime:r,resolvedRouteId:i}=await this.activateRoute(t.routeId),o=r.getDocument(i).data;await this.recordRuntimeVersion(o.version);let s=(await r.getHistoryStatus()).data;return{ok:!0,data:{document:o,historyStatus:s}}}),getDocument:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t),i=n.getDocument(r);return await this.recordRuntimeVersion(i.data.version),i},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async t=>{let{runtime:n,resolvedRouteId:r}=await this.activateRoute(t);return n.getStyleContext(r)},getObjectEditContext:async(t,n)=>this.getRuntime().getObjectEditContext(t,n?this.resolveRouteId(n):void 0),getClassNameSource:async(t,n)=>{let r=this.getRuntime(),i=n?this.resolveRouteId(n):void 0;return r.getClassNameSource(t,i)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async t=>this.getRuntime().getSourceFile(t),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,routeId:t.routeId?this.resolveRouteId(t.routeId):void 0}),execute:(t,n)=>this.mutationQueue.run(async()=>{let r=await this.bindHistorySession(this.options.snapshotId);if(!r.ok)return yt(r,t);let i=await this.getRuntime().executeOperation(this.normalizeRequest(t));return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),undo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return yt(t);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let t=await this.bindHistorySession(this.options.snapshotId);if(!t.ok)return yt(t);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let r=await(this.dependencies.openHistoryStore??zi)(no({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let i=r.readDocumentVersion?await r.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,i),this.createRuntime(r,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,t);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(t){let n=this.getRuntime(),r=this.resolveRouteId(t);return await n.setActiveRoute(r),{runtime:n,resolvedRouteId:r}}normalizeRequest(t){return t.target.kind!=="route"?t.routeId?{...t,routeId:this.resolveRouteId(t.routeId)}:t:{...t,target:{...t.target,routeId:this.resolveRouteId(t.target.routeId)}}}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let r of t)this.pendingChangedFiles.add(r);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??pn;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:Yi(this.options.projectRoot),n=new Map(this.routes.map(i=>[i.routeId,i.entryFile])),r=new Set(t.map(i=>i.routeId));this.routes=t;for(let i of t)n.get(i.routeId)!==i.entryFile&&this.runtime?.registerRoute(i.routeId,i.entryFile);for(let i of n.keys())r.has(i)||this.runtime?.unregisterRoute(i)}resolveRouteId(t){let n=Gi(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 xn(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:St.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Qi,port:e.port??Zi,path:e.path??Li,sessionKey:e.sessionKey??lo(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function no(e){return St.join(St.resolve(e.root),gn(e.siteId),gn(e.snapshotId),Sn("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function gn(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Sn("sha256").update(e).digest("hex").slice(0,32)}function Rn(){let e=globalThis;return e[mn]??=new Map,e[mn]}function Cn(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function yt(e,t){return{ok:!1,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function ro(e){let t=new Wi({maxPayload:vn,noServer:!0}),n=new WeakSet,r=o=>{new Be({socket:new Et(o),engine:e.engine,validateOperationRequest:s=>Xi.safeParse(s).success})},i=(o,s,a)=>{if(!io(o,e))return;let c=oo(o,e);if(!c){s.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),s.destroy();return}c.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,s,a,u=>{t.emit("connection",u,o)})};return e.server.on("upgrade",i),t.on("connection",(o,s)=>{if(n.has(s)){r(o);return}Ui(o,e.sessionKey,()=>{r(o)})}),t.stop=()=>{e.server.off("upgrade",i);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var ft=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===un.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Mi){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Hi(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function ji(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=dt(e.headers["x-vcp-site-edit-key"]),i=mn(r,t.sessionKey),o=dt(e.headers.host),s=dt(e.headers.origin);return o&&!Wi(o,t.host,s)?null:s?zi(s,o,t.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function Ui(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Vi),i,o=()=>{clearTimeout(r),e.off("message",i),e.off("close",o)},s=()=>{o(),e.close(1008,"bridge authentication failed")};i=a=>{try{let c=w.parseMessage(a.toString());if(c.type!=="auth"||!mn(c.payload.key,t)){s();return}o(),e.readyState===un.OPEN&&e.send(w.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",i),e.on("close",o)}function mn(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&_i(n,r)}function Wi(e,t,n){let r=an(e),i=an(t);return r===i||sn(i)&&sn(r)&&(!n||ht(n,e))||$i(i)&&(!n||ht(n,e))}function $i(e){return e==="0.0.0.0"||e==="::"}function sn(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function zi(e,t,n){return n.includes(e)||(t?ht(e,t):!1)}function ht(e,t){try{return new URL(e).host===gn(t)}catch{return!1}}function an(e){let t=gn(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function gn(e){return e.trim().toLowerCase()}function dt(e){return Array.isArray(e)?e[0]:e}function Gi(){return Ri(32).toString("base64url")}import Yi from"node:http";import{existsSync as pe,readFileSync as he}from"node:fs";import{createRequire as En}from"node:module";import Ce from"node:path";import{basename as In,dirname as Re,join as _e}from"node:path";import{fileURLToPath as vn}from"node:url";var Ji="next",Xi="127.0.0.1",Qi=3e3,Ue="/__vcp/site-edit/bridge",xn="/__vcp/site-edit/health",We="/__vcp/site-edit/client/",Zi=`${We}auto-bootstrap.js`,Cn='data-vcp-site-edit-bootstrap="true"',Li=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],eo="@vcp-dev/site-edit-engine/webpack-loader",to=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,no=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ro=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Is(e={},t={}){let n=t.process??process,r=t.createServer??Yi.createServer,i=t.attachBridgeServer??ln,o=t.loadNext??Ao,s=Ce.resolve(e.projectRoot??process.cwd()),a=e.host??Xi,c=e.port??Oo(n.env.PORT)??Qi,u=e.bridgePath??Ue,p=lo(u),l=To(),g=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",b=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,R=await o(s),x=io(s),T=R({dev:!0,dir:s,hostname:a,port:c,...oo(x)}),P=T.getRequestHandler(),F=e.siteId??n.env.VCP_SITE_ID??"site_preview",me=e.snapshotId??n.env.VCP_SNAPSHOT_ID??wo(s),ce=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,X=ce?.trim()?Ce.resolve(ce):void 0,W=null,$=r((V,L)=>{bo({basePath:g,bridgePath:u,bridgeHealthPath:p,bridgeSessionKey:l,getBridgeHealth:()=>W?.getHealth()??Eo(u),handle:P,request:V,response:L}).catch(h=>{console.error(h),L.headersSent||(L.statusCode=500),L.end("site edit preview request failed")})}),Q=null,Z=null,oe=()=>Z||(je(()=>n.off("SIGINT",M)),je(()=>n.off("SIGTERM",M)),je(()=>Q?.()),Q=null,je(()=>W?.stop()),W=null,Z=Promise.allSettled([Vo($),Ko(()=>T.close())]).then(()=>{}),Z),M=()=>{oe()};try{return await T.prepare(),W=i($,{...b?{tenantId:b}:{},siteId:F,snapshotId:me,projectRoot:s,basePath:g,host:a,port:c,path:u,sessionKey:l,...X?{historyRoot:X}:{}}),Q=co({server:$,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",M),n.on("SIGTERM",M),await Mo($,c,a),{bundler:x,close:oe,host:a,port:qo($,c),server:$}}catch(V){throw await oe(),V}}function io(e){let t=so(e);return t&&ao(t)?"webpack":"turbopack"}function oo(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function so(e){for(let t of Li){let n=_e(e,t);if(pe(n))return he(n,"utf8")}return null}function ao(e){return e.includes(eo)?!0:to.test(e)&&no.some(t=>t.test(e))}function co(e){let t=(n,r,i)=>{uo(n.url,e.bridgePath)||e.handleUpgrade(n,r,i).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function uo(e,t){return new URL(e??"/","http://localhost").pathname===t}function lo(e=Ue){if(e===Ue)return xn;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function fo(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??ho()});return`<script type="module" ${Cn}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Zi)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function ho(){return{bridge:pt("@vcp-dev/site-edit-bridge"),contracts:pt("@vcp-dev/contracts"),engine:pt("@vcp-dev/site-edit-engine")}}function pt(e){let t=En(import.meta.url);try{let n=t.resolve(e),r=po(n,e);if(!r)return;let i=JSON.parse(he(r,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function po(e,t){let n=Ce.parse(e).root,r=Re(e);for(;r&&r!==n;){let i=_e(r,"package.json");if(pe(i))try{if(JSON.parse(he(i,"utf8")).name===t)return i}catch{return}r=Re(r)}}function mo(e,t){if(e.includes(Cn))return e;let n=fo(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function vs(e,t=Re(vn(import.meta.url)),n=pe){return Rn(e,t,n)?.path??null}function Rn(e,t=Re(vn(import.meta.url)),n=pe){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(We))return null;let i=r.slice(We.length);if(!ro.has(i))return null;let o=mt(Bo(t),i);if(In(t)!=="src")return{path:o,requiresTranspile:!1};let s=mt(t,i.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function go(e,t){let n=Rn(e.url);if(!n)return!1;if(!pe(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await yo(he(n.path,"utf8")):he(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function yo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function bo({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:i,handle:o,request:s,response:a}){if(So(s,a,n,i)||await go(s,a))return;let c=Io(s),u=vo(s),p=c||u?Ro(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await o(s,a)}catch(l){throw p(),l}}function So(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let o=r();return t.writeHead(o.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(o)),!0}function Eo(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Io(e){return xo(e)?(e.headers["accept-encoding"]="identity",!0):!1}function vo(e){return Co(e)?(e.headers["accept-encoding"]="identity",!0):!1}function xo(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(We)||t===Ue||t===xn)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Co(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 Ro(e,t){let n=[],r=e,i=r.flushHeaders.bind(e),o=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,c,u)=>(a!==void 0&&n.push(yn(a,bn(c))),Sn(c),Sn(u),!0),r.end=(a,c,u)=>{let p=typeof a=="function"?void 0:a;p!==void 0&&n.push(yn(p,bn(c))),r.write=o,r.end=s,r.flushHeaders=i;let l=Buffer.concat(n),g=_o(e,l,t);g!==l&&!e.headersSent&&e.removeHeader("content-length");let b=typeof a=="function"?a:typeof c=="function"?c:typeof u=="function"?u:void 0;return b?s(g,b):s(g)},()=>{r.write=o,r.end=s,r.flushHeaders=i}}function _o(e,t,n){if(ko(e,t))return Buffer.from(mo(t.toString("utf8"),n));if(n.patchNextDevChunk&&Do(e)){let r=t.toString("utf8"),i=Po(r);if(i!==r)return Buffer.from(i)}return t}function To(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ko(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 Do(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(`
4
+ `),s.destroy();return}c.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,s,a,u=>{t.emit("connection",u,o)})};return e.server.on("upgrade",i),t.on("connection",(o,s)=>{if(n.has(s)){r(o);return}so(o,e.sessionKey,()=>{r(o)})}),t.stop=()=>{e.server.off("upgrade",i);for(let o of t.clients)o.close(1001,"bridge stopped");t.close()},t}var Et=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===En.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>eo){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function io(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function oo(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=bt(e.headers["x-vcp-site-edit-key"]),i=_n(r,t.sessionKey),o=bt(e.headers.host),s=bt(e.headers.origin);return o&&!ao(o,t.host,s)?null:s?uo(s,o,t.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function so(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},to),i,o=()=>{clearTimeout(r),e.off("message",i),e.off("close",o)},s=()=>{o(),e.close(1008,"bridge authentication failed")};i=a=>{try{let c=H.parseMessage(a.toString());if(c.type!=="auth"||!_n(c.payload.key,t)){s();return}o(),e.readyState===En.OPEN&&e.send(H.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",i),e.on("close",o)}function _n(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Ui(n,r)}function ao(e,t,n){let r=bn(e),i=bn(t);return r===i||yn(i)&&yn(r)&&(!n||vt(n,e))||co(i)&&(!n||vt(n,e))}function co(e){return e==="0.0.0.0"||e==="::"}function yn(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function uo(e,t,n){return n.includes(e)||(t?vt(e,t):!1)}function vt(e,t){try{return new URL(e).host===Tn(t)}catch{return!1}}function bn(e){let t=Tn(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Tn(e){return e.trim().toLowerCase()}function bt(e){return Array.isArray(e)?e[0]:e}function lo(){return ji(32).toString("base64url")}import fo from"node:http";import{existsSync as be,readFileSync as ye}from"node:fs";import{createRequire as Nn}from"node:module";import Te from"node:path";import{basename as An,dirname as ke,join as Pe}from"node:path";import{fileURLToPath as Bn}from"node:url";var ho="next",po="127.0.0.1",mo=3e3,Je="/__vcp/site-edit/bridge",Fn="/__vcp/site-edit/health",Xe="/__vcp/site-edit/client/",go=`${Xe}auto-bootstrap.js`,On='data-vcp-site-edit-bootstrap="true"',yo=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],bo="@vcp-dev/site-edit-engine/webpack-loader",So=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Eo=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],vo=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Vs(e={},t={}){let n=t.process??process,r=t.createServer??fo.createServer,i=t.attachBridgeServer??In,o=t.loadNext??Jo,s=Te.resolve(e.projectRoot??process.cwd()),a=e.host??po,c=e.port??Lo(n.env.PORT)??mo,u=e.bridgePath??Je,f=ko(u),l=Wo(),y=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",S=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,_=await o(s),C=Io(s),T=_({dev:!0,dir:s,hostname:a,port:c,...xo(C)}),N=T.getRequestHandler(),V=e.siteId??n.env.VCP_SITE_ID??"site_preview",Se=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Zo(s),fe=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,Z=fe?.trim()?Te.resolve(fe):void 0,z=null,G=r((U,te)=>{Oo({basePath:y,bridgePath:u,bridgeHealthPath:f,bridgeSessionKey:l,getBridgeHealth:()=>z?.getHealth()??Mo(u),handle:N,request:U,response:te}).catch(h=>{console.error(h),te.headersSent||(te.statusCode=500),te.end("site edit preview request failed")})}),L=null,ee=null,ae=()=>ee||(Ye(()=>n.off("SIGINT",K)),Ye(()=>n.off("SIGTERM",K)),Ye(()=>L?.()),L=null,Ye(()=>z?.stop()),z=null,ee=Promise.allSettled([ts(G),ns(()=>T.close())]).then(()=>{}),ee),K=()=>{ae()};try{return await T.prepare(),z=i(G,{...S?{tenantId:S}:{},siteId:V,snapshotId:Se,projectRoot:s,basePath:y,host:a,port:c,path:u,sessionKey:l,...Z?{historyRoot:Z}:{}}),L=_o({server:G,bridgePath:u,handleUpgrade:T.getUpgradeHandler()}),n.on("SIGINT",K),n.on("SIGTERM",K),await es(G,c,a),{bundler:C,close:ae,host:a,port:rs(G,c),server:G}}catch(U){throw await ae(),U}}function Io(e){let t=Ro(e);return t&&Co(t)?"webpack":"turbopack"}function xo(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Ro(e){for(let t of yo){let n=Pe(e,t);if(be(n))return ye(n,"utf8")}return null}function Co(e){return e.includes(bo)?!0:So.test(e)&&Eo.some(t=>t.test(e))}function _o(e){let t=(n,r,i)=>{To(n.url,e.bridgePath)||e.handleUpgrade(n,r,i).catch(o=>{console.error(o),r.destroyed||r.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function To(e,t){return new URL(e??"/","http://localhost").pathname===t}function ko(e=Je){if(e===Je)return Fn;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Po(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Do()});return`<script type="module" ${On}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(go)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Do(){return{bridge:It("@vcp-dev/site-edit-bridge"),contracts:It("@vcp-dev/contracts"),engine:It("@vcp-dev/site-edit-engine")}}function It(e){let t=Nn(import.meta.url);try{let n=t.resolve(e),r=No(n,e);if(!r)return;let i=JSON.parse(ye(r,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function No(e,t){let n=Te.parse(e).root,r=ke(e);for(;r&&r!==n;){let i=Pe(r,"package.json");if(be(i))try{if(JSON.parse(ye(i,"utf8")).name===t)return i}catch{return}r=ke(r)}}function Ao(e,t){if(e.includes(On))return e;let n=Po(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function Ks(e,t=ke(Bn(import.meta.url)),n=be){return wn(e,t,n)?.path??null}function wn(e,t=ke(Bn(import.meta.url)),n=be){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(Xe))return null;let i=r.slice(Xe.length);if(!vo.has(i))return null;let o=xt(Xo(t),i);if(An(t)!=="src")return{path:o,requiresTranspile:!1};let s=xt(t,i.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Bo(e,t){let n=wn(e.url);if(!n)return!1;if(!be(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Fo(ye(n.path,"utf8")):ye(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Fo(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Oo({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:i,handle:o,request:s,response:a}){if(wo(s,a,n,i)||await Bo(s,a))return;let c=Vo(s),u=Ko(s),f=c||u?jo(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:u}):()=>{};try{await o(s,a)}catch(l){throw f(),l}}function wo(e,t,n,r){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let o=r();return t.writeHead(o.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(o)),!0}function Mo(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Vo(e){return qo(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ko(e){return Ho(e)?(e.headers["accept-encoding"]="identity",!0):!1}function qo(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(Xe)||t===Je||t===Fn)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function Ho(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 jo(e,t){let n=[],r=e,i=r.flushHeaders.bind(e),o=r.write.bind(e),s=r.end.bind(e);return r.flushHeaders=()=>{},r.write=(a,c,u)=>(a!==void 0&&n.push(kn(a,Pn(c))),Dn(c),Dn(u),!0),r.end=(a,c,u)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(kn(f,Pn(c))),r.write=o,r.end=s,r.flushHeaders=i;let l=Buffer.concat(n),y=Uo(e,l,t);y!==l&&!e.headersSent&&e.removeHeader("content-length");let S=typeof a=="function"?a:typeof c=="function"?c:typeof u=="function"?u:void 0;return S?s(y,S):s(y)},()=>{r.write=o,r.end=s,r.flushHeaders=i}}function Uo(e,t,n){if($o(e,t))return Buffer.from(Ao(t.toString("utf8"),n));if(n.patchNextDevChunk&&zo(e)){let r=t.toString("utf8"),i=Go(r);if(i!==r)return Buffer.from(i)}return t}function Wo(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function $o(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 zo(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Go(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
5
5
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
6
- `)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[r,i])=>No(n,r,i),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 yn(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function bn(e){return typeof e=="string"?e:void 0}function Sn(e){typeof e=="function"&&e()}async function Ao(e){let n=En(_e(e,"package.json"))(Ji);return n.default??n}function Bo(e){return In(e)!=="src"?e:mt(Fo(e),"dist")}function Fo(e){return _n(e)?Ce.posix.dirname(e):Re(e)}function mt(e,t){return _n(e)?Ce.posix.join(e,t):_e(e,t)}function _n(e){return e.includes("/")&&!e.includes("\\")}function wo(e){let t=_e(e,".vcp/current-snapshot.json");if(!pe(t))return"sandbox_worktree";try{let n=JSON.parse(he(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Oo(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,i)=>{e.once("error",i),e.listen(t,n,()=>{e.off("error",i),r()})})}function Vo(e){return new Promise(t=>{e.close(()=>t())})}function je(e){try{e()}catch{}}function Ko(e){try{return e()}catch(t){return Promise.reject(t)}}function qo(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{Mi as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,dn as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,_t as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Rt as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,He as SiteEditBridgeServer,ke as SiteEditBridgeSocketServer,w as SiteEditBridgeTransport,De as SiteEditWebSocketClient,nt as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,tt as VCP_SITE_EDIT_ROUTE_READY_EVENT,Ct as VCP_WINDOW_MESSAGE_SOURCE,Jo as VCP_WINDOW_MESSAGE_VERSION,co as attachNextDevUpgradeHandler,ln as attachSiteEditBridgeServer,qi as attachSiteEditWebSocketServer,fo as createSiteEditAutoBootstrapHtmlSnippet,xt as createSiteEditBridge,Ie as createSiteEditFrameRuntimeMessage,Gn as createVcpWindowMessageEnvelope,ze as decodeRenderDocument,$e as encodeRenderDocument,fs as ensureSiteEditBridgeServerStarted,mo as injectSiteEditAutoBootstrap,Pn as isCompactRenderDocument,Vn as isDesignerTraceEnabled,Tt as isSiteEditFrameRuntimeMessage,Yn as isVcpWindowMessageEnvelope,Po as patchNextFirefoxDevChunk,vo as prepareFirefoxNextDevChunkPatchRequest,Io as prepareSiteEditHtmlInjectionRequest,lo as resolveSiteEditBridgeHealthPath,Rn as resolveSiteEditClientAsset,vs as resolveSiteEditClientAssetPath,io as resolveSiteEditNextDevBundler,fr as resolveSiteEditRouteId,pr as resolveSiteEditWebSocketUrl,Kn as sanitizeTracePayload,Lo as startSiteEditAutoBootstrap,Ir as startSiteEditFrameRuntime,Is as startSiteEditNextDevServer,re as traceDesignerEvent,yo 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,i])=>Yo(n,r,i),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 kn(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function Pn(e){return typeof e=="string"?e:void 0}function Dn(e){typeof e=="function"&&e()}async function Jo(e){let n=Nn(Pe(e,"package.json"))(ho);return n.default??n}function Xo(e){return An(e)!=="src"?e:xt(Qo(e),"dist")}function Qo(e){return Mn(e)?Te.posix.dirname(e):ke(e)}function xt(e,t){return Mn(e)?Te.posix.join(e,t):Pe(e,t)}function Mn(e){return e.includes("/")&&!e.includes("\\")}function Zo(e){let t=Pe(e,".vcp/current-snapshot.json");if(!be(t))return"sandbox_worktree";try{let n=JSON.parse(ye(t,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Lo(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function es(e,t,n){return new Promise((r,i)=>{e.once("error",i),e.listen(t,n,()=>{e.off("error",i),r()})})}function ts(e){return new Promise(t=>{e.close(()=>t())})}function Ye(e){try{e()}catch{}}function ns(e){try{return e()}catch(t){return Promise.reject(t)}}function rs(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{eo as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,vn as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,Kt as SITE_EDIT_FRAME_RUNTIME_CHANNEL,Vt as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,Ge as SiteEditBridgeServer,Be as SiteEditBridgeSocketServer,H as SiteEditBridgeTransport,Fe as SiteEditWebSocketClient,ut as VCP_SITE_EDIT_BRIDGE_STATUS_EVENT,ct as VCP_SITE_EDIT_ROUTE_READY_EVENT,Mt as VCP_WINDOW_MESSAGE_SOURCE,fs as VCP_WINDOW_MESSAGE_VERSION,_o as attachNextDevUpgradeHandler,In as attachSiteEditBridgeServer,ro as attachSiteEditWebSocketServer,Po as createSiteEditAutoBootstrapHtmlSnippet,wt as createSiteEditBridge,Re as createSiteEditFrameRuntimeMessage,ir as createVcpWindowMessageEnvelope,Ze as decodeRenderDocument,Qe as encodeRenderDocument,Ps as ensureSiteEditBridgeServerStarted,Ao as injectSiteEditAutoBootstrap,Hn as isCompactRenderDocument,Jn as isDesignerTraceEnabled,qt as isSiteEditFrameRuntimeMessage,or as isVcpWindowMessageEnvelope,Go as patchNextFirefoxDevChunk,Ko as prepareFirefoxNextDevChunkPatchRequest,Vo as prepareSiteEditHtmlInjectionRequest,ko as resolveSiteEditBridgeHealthPath,wn as resolveSiteEditClientAsset,Ks as resolveSiteEditClientAssetPath,Io as resolveSiteEditNextDevBundler,_r as resolveSiteEditRouteId,kr as resolveSiteEditWebSocketUrl,Xn as sanitizeTracePayload,gs as startSiteEditAutoBootstrap,Or as startSiteEditFrameRuntime,Vs as startSiteEditNextDevServer,oe as traceDesignerEvent,Fo as transpileSiteEditClientSource};
@@ -37,7 +37,7 @@ export type SiteEditFrameRuntimeScrollMetrics = {
37
37
  viewportWidth: number;
38
38
  viewportHeight: number;
39
39
  };
40
- export type SiteEditFrameRuntimePointerEventKind = "pointer-down" | "pointer-move" | "pointer-up" | "pointer-cancel" | "pointer-click" | "pointer-double-click";
40
+ export type SiteEditFrameRuntimePointerEventKind = "pointer-down" | "pointer-move" | "pointer-leave" | "pointer-up" | "pointer-cancel" | "pointer-click" | "pointer-double-click";
41
41
  export type SiteEditFrameRuntimeNodePatch = {
42
42
  attributes?: Record<string, string | null>;
43
43
  className?: string;
@@ -292,6 +292,22 @@ export type SiteEditFrameRuntimeChildBox = {
292
292
  rect: SiteEditFrameRuntimeRect;
293
293
  margin: SiteEditFrameRuntimeMargin;
294
294
  };
295
+ export type SiteEditFrameRuntimeSectionContext = {
296
+ blockId: string;
297
+ ref: SiteEditFrameRuntimeRef;
298
+ rect: SiteEditFrameRuntimeRect;
299
+ targetIsSectionRoot: boolean;
300
+ };
301
+ export type SiteEditFrameRuntimeSectionGapCandidate = {
302
+ anchorBlockId: string;
303
+ anchorRef: SiteEditFrameRuntimeRef;
304
+ placement: "before" | "after";
305
+ boundary: {
306
+ top: number;
307
+ left: number;
308
+ width: number;
309
+ };
310
+ };
295
311
  export type SiteEditFrameRuntimeHit = {
296
312
  ref: SiteEditFrameRuntimeRef;
297
313
  key: string;
@@ -380,6 +396,8 @@ export type SiteEditFrameRuntimeEventBody = {
380
396
  clientY: number;
381
397
  buttons?: number;
382
398
  hit: SiteEditFrameRuntimeHit | null;
399
+ section: SiteEditFrameRuntimeSectionContext | null;
400
+ sectionGap: SiteEditFrameRuntimeSectionGapCandidate | null;
383
401
  };
384
402
  } | {
385
403
  type: "event";
@@ -1 +1 @@
1
- var l="vcp-window-message",T=1;function I(e){return{source:l,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function x(e){try{return s(e)?d(e,"source",l)&&d(e,"version",1)&&i(e,"namespace")&&i(e,"channel")&&a(e,"body")&&(!u(e,"sessionKey")||i(e,"sessionKey")):!1}catch{return!1}}var m="site-edit",h="frame-runtime";function q(e,r={}){return I({namespace:m,channel:h,sessionKey:r.sessionKey,body:e})}function B(e){try{return!x(e)||e.namespace!==m||e.channel!==h?!1:C(e.body)}catch{return!1}}var u=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function a(e,r){let t=Object.getOwnPropertyDescriptor(e,r);return t!==void 0&&"value"in t}function n(e,r){return Object.getOwnPropertyDescriptor(e,r)?.value}function d(e,r,t){return a(e,r)&&n(e,r)===t}function i(e,r){return a(e,r)&&typeof n(e,r)=="string"}function E(e,r){return a(e,r)&&typeof n(e,r)=="boolean"}function o(e,r){let t=n(e,r);return a(e,r)&&typeof t=="number"&&Number.isFinite(t)}function y(e,r){return!u(e,r)||n(e,r)===void 0||i(e,r)}function p(e,r){return!u(e,r)||n(e,r)===void 0||o(e,r)}function b(e,r){let t=n(e,r);return!u(e,r)||t===void 0||a(e,r)&&typeof t=="number"&&Number.isInteger(t)&&t>=0}function c(e,r){return!u(e,r)||n(e,r)===void 0}function s(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function N(e){return s(e)&&Reflect.ownKeys(e).length===0}function w(e){if(!Array.isArray(e))return!1;for(let r=0;r<e.length;r+=1){let t=Object.getOwnPropertyDescriptor(e,String(r));if(t===void 0||!("value"in t)||typeof t.value!="string")return!1}return!0}function g(e){return s(e)&&i(e,"key")&&b(e,"instanceIndex")&&b(e,"instanceCount")&&b(e,"textSegmentIndex")}function R(e){return s(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&(typeof n(e,r)=="string"||n(e,r)===null))}function O(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function _(e){return s(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&O(n(e,r)))}function A(e){if(!s(e))return!1;let r=n(e,"priority");return i(e,"property")&&a(e,"value")&&O(n(e,"value"))&&(!u(e,"priority")||r===void 0||r==="important")}function P(e){return s(e)?(c(e,"attributes")||R(n(e,"attributes")))&&y(e,"className")&&(c(e,"style")||_(n(e,"style")))&&(c(e,"styleDeclarations")||Array.isArray(n(e,"styleDeclarations"))&&n(e,"styleDeclarations").every(A)):!1}function D(e){return s(e)&&o(e,"x")&&o(e,"y")&&(c(e,"detailLevel")||d(e,"detailLevel","summary")||d(e,"detailLevel","full"))}function V(e){return s(e)&&g(n(e,"ref"))}function K(e){if(!s(e)||!s(n(e,"variables")))return!1;let r=n(e,"variables");return Reflect.ownKeys(r).every(t=>typeof t=="string"&&i(r,t))?c(e,"stylesheets")||w(n(e,"stylesheets")):!1}function W(e){if(!d(e,"type","request")||!i(e,"id")||!i(e,"kind")||!a(e,"payload"))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"hit-test-at-point":case"start-text-edit-at-point":return D(t);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return N(t);case"bridge-get-source-file":return s(t)&&i(t,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return s(t)&&i(t,"key")&&y(t,"routeId");case"scroll-to":return s(t)&&o(t,"x")&&o(t,"y");case"scroll-by":return s(t)&&o(t,"deltaX")&&o(t,"deltaY");case"set-interaction-mode":return s(t)&&E(t,"enabled");case"set-theme-override":return K(t);case"get-theme-variables":return s(t)&&w(n(t,"names"));case"compute-drop-target-at-point":return s(t)&&o(t,"x")&&o(t,"y")&&(d(t,"dragKind","insert")||d(t,"dragKind","move"))&&(c(t,"movingRef")||g(n(t,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return s(t)&&(c(t,"ref")||g(n(t,"ref")));case"apply-node-patch":return s(t)&&g(n(t,"ref"))&&P(n(t,"patch"))&&(c(t,"preview")||s(n(t,"preview"))&&i(n(t,"preview"),"sessionId")&&b(n(t,"preview"),"revision")&&u(n(t,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return V(t);case"bridge-initialize-session":case"bridge-get-style-context":return s(t)&&i(t,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return s(t)&&i(t,"routeId")&&p(t,"minVersion")&&p(t,"version");case"bridge-execute":return s(t)&&s(n(t,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return s(t)&&i(t,"subscriptionId");default:return!1}}function M(e){return d(e,"type","response")&&i(e,"id")&&E(e,"ok")&&(c(e,"error")||i(e,"error"))}var F=new Set(["pointer-down","pointer-move","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function j(e){if(!d(e,"type","event")||!i(e,"kind")||!s(n(e,"payload")))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return g(n(t,"ref"))&&y(t,"value")&&(c(t,"hit")||s(n(t,"hit")));case"node-bounds-change":return s(n(t,"hit"));case"bridge-event":return i(t,"subscriptionId")&&s(n(t,"event"));case"route-ready":return i(t,"routeId")&&p(t,"version");case"bridge-status":{let f=n(t,"state");return(f==="connecting"||f==="ready"||f==="reconnecting"||f==="failed"||f==="reload-required")&&y(t,"routeId")&&p(t,"attempt")&&p(t,"retryInMs")&&y(t,"messageKey")}case"scroll":{let f=n(t,"metrics");return s(f)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(S=>o(f,S))}default:return F.has(r)&&o(t,"clientX")&&o(t,"clientY")&&p(t,"buttons")&&(n(t,"hit")===null||s(n(t,"hit")))}}function C(e){if(!s(e))return!1;switch(n(e,"type")){case"request":return W(e);case"response":return M(e);case"event":return j(e);default:return!1}}export{h as SITE_EDIT_FRAME_RUNTIME_CHANNEL,m as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,l as VCP_WINDOW_MESSAGE_SOURCE,T as VCP_WINDOW_MESSAGE_VERSION,q as createSiteEditFrameRuntimeMessage,I as createVcpWindowMessageEnvelope,B as isSiteEditFrameRuntimeMessage,x as isVcpWindowMessageEnvelope};
1
+ var l="vcp-window-message",q=1;function I(e){return{source:l,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function R(e){try{return i(e)?d(e,"source",l)&&d(e,"version",1)&&s(e,"namespace")&&s(e,"channel")&&a(e,"body")&&(!u(e,"sessionKey")||s(e,"sessionKey")):!1}catch{return!1}}var h="site-edit",w="frame-runtime";function L(e,r={}){return I({namespace:h,channel:w,sessionKey:r.sessionKey,body:e})}function H(e){try{return!R(e)||e.namespace!==h||e.channel!==w?!1:B(e.body)}catch{return!1}}var u=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function a(e,r){let t=Object.getOwnPropertyDescriptor(e,r);return t!==void 0&&"value"in t}function n(e,r){return Object.getOwnPropertyDescriptor(e,r)?.value}function d(e,r,t){return a(e,r)&&n(e,r)===t}function s(e,r){return a(e,r)&&typeof n(e,r)=="string"}function m(e,r){return a(e,r)&&typeof n(e,r)=="boolean"}function o(e,r){let t=n(e,r);return a(e,r)&&typeof t=="number"&&Number.isFinite(t)}function g(e,r){return!u(e,r)||n(e,r)===void 0||s(e,r)}function y(e,r){return!u(e,r)||n(e,r)===void 0||o(e,r)}function b(e,r){let t=n(e,r);return!u(e,r)||t===void 0||a(e,r)&&typeof t=="number"&&Number.isInteger(t)&&t>=0}function c(e,r){return!u(e,r)||n(e,r)===void 0}function i(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function x(e){return i(e)&&Reflect.ownKeys(e).length===0}function S(e){if(!Array.isArray(e))return!1;for(let r=0;r<e.length;r+=1){let t=Object.getOwnPropertyDescriptor(e,String(r));if(t===void 0||!("value"in t)||typeof t.value!="string")return!1}return!0}function p(e){return i(e)&&s(e,"key")&&b(e,"instanceIndex")&&b(e,"instanceCount")&&b(e,"textSegmentIndex")}function N(e){return i(e)&&o(e,"top")&&o(e,"left")&&o(e,"width")&&o(e,"height")}function _(e){return i(e)&&s(e,"blockId")&&p(n(e,"ref"))&&N(n(e,"rect"))&&m(e,"targetIsSectionRoot")}function A(e){if(!i(e))return!1;let r=n(e,"placement"),t=n(e,"boundary");return s(e,"anchorBlockId")&&p(n(e,"anchorRef"))&&(r==="before"||r==="after")&&i(t)&&o(t,"top")&&o(t,"left")&&o(t,"width")}function P(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&(typeof n(e,r)=="string"||n(e,r)===null))}function E(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function D(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&E(n(e,r)))}function V(e){if(!i(e))return!1;let r=n(e,"priority");return s(e,"property")&&a(e,"value")&&E(n(e,"value"))&&(!u(e,"priority")||r===void 0||r==="important")}function K(e){return i(e)?(c(e,"attributes")||P(n(e,"attributes")))&&g(e,"className")&&(c(e,"style")||D(n(e,"style")))&&(c(e,"styleDeclarations")||Array.isArray(n(e,"styleDeclarations"))&&n(e,"styleDeclarations").every(V)):!1}function W(e){return i(e)&&o(e,"x")&&o(e,"y")&&(c(e,"detailLevel")||d(e,"detailLevel","summary")||d(e,"detailLevel","full"))}function M(e){return i(e)&&p(n(e,"ref"))}function F(e){if(!i(e)||!i(n(e,"variables")))return!1;let r=n(e,"variables");return Reflect.ownKeys(r).every(t=>typeof t=="string"&&s(r,t))?c(e,"stylesheets")||S(n(e,"stylesheets")):!1}function C(e){if(!d(e,"type","request")||!s(e,"id")||!s(e,"kind")||!a(e,"payload"))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"hit-test-at-point":case"start-text-edit-at-point":return W(t);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return x(t);case"bridge-get-source-file":return i(t)&&s(t,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return i(t)&&s(t,"key")&&g(t,"routeId");case"scroll-to":return i(t)&&o(t,"x")&&o(t,"y");case"scroll-by":return i(t)&&o(t,"deltaX")&&o(t,"deltaY");case"set-interaction-mode":return i(t)&&m(t,"enabled");case"set-theme-override":return F(t);case"get-theme-variables":return i(t)&&S(n(t,"names"));case"compute-drop-target-at-point":return i(t)&&o(t,"x")&&o(t,"y")&&(d(t,"dragKind","insert")||d(t,"dragKind","move"))&&(c(t,"movingRef")||p(n(t,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return i(t)&&(c(t,"ref")||p(n(t,"ref")));case"apply-node-patch":return i(t)&&p(n(t,"ref"))&&K(n(t,"patch"))&&(c(t,"preview")||i(n(t,"preview"))&&s(n(t,"preview"),"sessionId")&&b(n(t,"preview"),"revision")&&u(n(t,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return M(t);case"bridge-initialize-session":case"bridge-get-style-context":return i(t)&&s(t,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return i(t)&&s(t,"routeId")&&y(t,"minVersion")&&y(t,"version");case"bridge-execute":return i(t)&&i(n(t,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return i(t)&&s(t,"subscriptionId");default:return!1}}function j(e){return d(e,"type","response")&&s(e,"id")&&m(e,"ok")&&(c(e,"error")||s(e,"error"))}var G=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function T(e){if(!d(e,"type","event")||!s(e,"kind")||!i(n(e,"payload")))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return p(n(t,"ref"))&&g(t,"value")&&(c(t,"hit")||i(n(t,"hit")));case"node-bounds-change":return i(n(t,"hit"));case"bridge-event":return s(t,"subscriptionId")&&i(n(t,"event"));case"route-ready":return s(t,"routeId")&&y(t,"version");case"bridge-status":{let f=n(t,"state");return(f==="connecting"||f==="ready"||f==="reconnecting"||f==="failed"||f==="reload-required")&&g(t,"routeId")&&y(t,"attempt")&&y(t,"retryInMs")&&g(t,"messageKey")}case"scroll":{let f=n(t,"metrics");return i(f)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(O=>o(f,O))}default:return G.has(r)&&o(t,"clientX")&&o(t,"clientY")&&y(t,"buttons")&&(n(t,"hit")===null||i(n(t,"hit")))&&(n(t,"section")===null||_(n(t,"section")))&&(n(t,"sectionGap")===null||A(n(t,"sectionGap")))}}function B(e){if(!i(e))return!1;switch(n(e,"type")){case"request":return C(e);case"response":return j(e);case"event":return T(e);default:return!1}}export{w as SITE_EDIT_FRAME_RUNTIME_CHANNEL,h as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,l as VCP_WINDOW_MESSAGE_SOURCE,q as VCP_WINDOW_MESSAGE_VERSION,L as createSiteEditFrameRuntimeMessage,I as createVcpWindowMessageEnvelope,H as isSiteEditFrameRuntimeMessage,R as isVcpWindowMessageEnvelope};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-bridge",
3
- "version": "0.6.4",
3
+ "version": "0.6.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.6.4",
78
- "@vcp-dev/site-edit-engine": "0.6.4",
77
+ "@vcp-dev/contracts": "0.6.5",
78
+ "@vcp-dev/site-edit-engine": "0.6.5",
79
79
  "@types/ws": "^8.18.1",
80
80
  "ws": "^8.20.1"
81
81
  },