@vcp-dev/site-edit-bridge 0.6.2 → 0.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-bootstrap.js +1 -1
- package/dist/client.js +1 -1
- package/dist/document-codec.d.ts +1 -1
- package/dist/document-codec.js +1 -1
- package/dist/index.js +3 -3
- package/dist/mutation-session-queue.js +18 -0
- package/dist/next-dev-server.d.ts +27 -3
- package/dist/next-dev-server.js +3 -3
- package/dist/protocol.js +419 -0
- package/dist/server.js +2 -2
- package/dist/start-next-dev-server-cli.js +74 -0
- package/dist/start-next-dev-server.js +2 -59
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
function Ne(e){let t=new Map,n=[],r=new Map,i=[],o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],s=new Map(o.map((d,g)=>[d,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(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((d,g)=>d.dynamicDataSummary?[[g,d.dynamicDataSummary]]:[]),c=d=>{let g=t.get(d);if(typeof g=="number")return g;let y=n.length;return n.push(d),t.set(d,y),y},f=d=>{let g=null;for(let y of fn(d)){let x=`${g??"root"}\0${y}`,I=r.get(x);if(typeof I=="number"){g=I;continue}let k=i.length;i.push([g,c(y)]),r.set(x,k),g=k}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(d=>{let g=d.pageCompositionUnitKey?s.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&g<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[f(d.key),ln(d.operationSummary),...g>=0?[g]:[]]}),...u.length>0?{dynamicDataSummaries:u}:{}}}function Be(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[u,c]=a,f=e.tokens[c];if(typeof f!="string")throw new Error(`Missing compact document token ${c}`);let d=`${u===null?"":i(u)}${f}`;return t.set(o,d),d};return{siteId:e.siteId,snapshotId:e.snapshotId,routeId:e.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((o,s)=>{let[a,u,c]=o,f=c===void 0?void 0:n[c];if(c!==void 0&&!f)throw new Error(`Missing page composition unit ${c}`);return{key:i(a),...f?{pageCompositionUnitKey:f}:{},operationSummary:dn(u),...r.get(s)?{dynamicDataSummary:r.get(s)}:{}}})}}function ln(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 hn(e){return typeof e=="object"&&e!==null&&"encoding"in e&&e.encoding==="segment-trie-v1"}function fn(e){if(!e)return[];let t=[],n=0,r=nt(e,n);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),n=r;n<e.length;){if(r=nt(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 nt(e,t){let n=e.indexOf("/",t),r=e.indexOf("::",t);return n<0?r:r<0?n:Math.min(n,r)}var B=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!V(t)||typeof t.type!="string"?!1:t.type==="request"?e.isRequestPayload(t.payload,n):t.type==="response"||t.type==="error"?V(t.payload)&&typeof t.payload.id=="string":t.type==="event"?V(t.payload)&&V(t.payload.event):t.type==="auth"?V(t.payload)&&typeof t.payload.key=="string":t.type==="auth-ok"?V(t.payload)&&t.payload.ok===!0:!1}static isRequestPayload(t,n={}){if(!V(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||Ae(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 pn(t.request)&&(t.request.mutationContext===void 0||Ae(t.request.mutationContext))&&(n.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return t.mutationContext===void 0||Ae(t.mutationContext)}}},pe=class{constructor(t){this.options=t,this.messageQueue=new Me,this.eventDispatcher=new Fe(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:Ne(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:Ne((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=B.extractRequestInfo(t);this.sendJson({type:"error",payload:{...r,message:it(n),code:rt(n)}})}}async handleRawMessage(t){try{await this.handleMessage(B.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let r=n instanceof Error?n.message:"Invalid websocket message",i=gn(t);this.sendJson({type:"error",payload:{...i,message:r}})}}sendJson(t){this.options.socket.send(B.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:it(i),code:rt(i)}}),this.eventDispatcher.flush()}}},Fe=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)})}},Me=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 V(e){return typeof e=="object"&&e!==null}function pn(e){return V(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"&&V(e.target)&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&V(e.params)}function Ae(e){return mn(e)}function rt(e){if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function it(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 mn(e){return V(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 gn(e){try{return B.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var yn="vcp:designer:trace",bn="designer_trace",ot="__VCP_DESIGNER_TRACE__";var Sn=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function vn(e=globalThis){let t=e;try{if(t.localStorage?.getItem(yn)==="1")return!0}catch{}try{let n=t.location?.search??"";return new URLSearchParams(n).get(bn)==="1"}catch{return!1}}function $(e,t={},n=globalThis){if(!vn(n))return;let r={type:e,timestamp:Date.now(),payload:En(t)},i=n,o=i[ot]??[];o.push(r),o.length>200&&o.splice(0,o.length-200),i[ot]=o;let s=n.console?.debug;typeof s=="function"&&s.call(n.console,"[designer-trace]",r)}function En(e){return we(e,0)}function we(e,t){if(t>4)return"[truncated]";if(Array.isArray(e))return e.map(r=>we(r,t+1));if(!e||typeof e!="object")return e;let n={};for(let[r,i]of Object.entries(e)){if(Sn.test(r)){n[r]="[redacted]";continue}n[r]=we(i,t+1)}return n}var me=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===Oe&&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 u=ie(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);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,u)=>{this.cleanupSocket(r,a,u)};r.onopen=()=>{if(!(this.socket!==r||this.connectAttempt!==i)){if(this.options.authKey){try{r.send(B.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 u=ie(a,"WebSocket failed");s(u,"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 u=this.intentionalClose,c=new Error(Rn(a,{intentional:u}));s(c,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let t=this.socket;if(!t){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(t,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(t){return this.connectionStatusListeners.add(t),t({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(t)}}getDocument(t){return this.request("get-document",{routeId:t})}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!==Oe||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=kn(i,t,n);return $("bridge.request",{id:i,kind:t,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:st(n.request,"kind"),documentVersion:st(n.request,"documentVersion")}),new Promise((s,a)=>{let u=this.resolveRequestTimeoutMs(t),c=u>0?setTimeout(()=>{let f=this.pending.get(i);f&&(this.pending.delete(i),$("bridge.response",{id:i,kind:t,ok:!1,timedOut:!0}),f.reject(new Error(`Bridge request timed out after ${u}ms: ${t}`)))},u):null;c?.unref?.(),this.pending.set(i,{kind:t,timeout:c,resolve:f=>s(f),reject:a});try{r.send(B.stringifyMessage(o))}catch(f){let d=ie(f,"WebSocket send failed");this.clearPendingRequest(i),a(d),this.cleanupSocket(r,d,"failed")}})}handleAuthHandshakeMessage(t,n,r,i){try{if(B.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=B.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"){$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!1}),r.reject(new Error(n.payload.message));return}$("bridge.response",{id:n.payload.id,kind:r.kind,ok:!0,resultVersion:_n(n.payload.result)}),r.resolve(r.kind==="get-document"?{...n.payload.result,data:Be(n.payload.result.data)}:r.kind==="initialize-session"?Tn(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):Cn[t]??xn}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===In||t.readyState===Oe)&&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)}},In=0,Oe=1,xn=15e3,Cn={"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 Rn(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 st(e,t){if(!e||typeof e!="object")return null;let r=e[t];return typeof r=="string"||typeof r=="number"?r:null}function _n(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 ut(e){return new Ve(e)}var Ve=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=!at(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=at(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(u=>(this.objectGeneration===s&&this.editContextCache.set(r,u.data),u)).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(u=>(this.objectGeneration===s&&this.classNameSourceCache.set(r,u),u)).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 $("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;if(this.refreshInFlight){$("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!0,source:n});let i=await this.refreshInFlight;if(typeof t!="number"||i.version>=t||this.currentDocument.version>=t)return this.currentDocument}$("bridge.document-refresh",{routeId:this.params.routeId,minVersion:t,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.params.routeId).then(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 at(e){return e.version===0&&e.entries.length===0}function Tn(e){let t=e;return{...t,data:{...t.data,document:Be(t.data.document)}}}function kn(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",mo=1;function Dn(e){return{source:ct,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function Pn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.source===ct&&t.version===1&&typeof t.namespace=="string"&&typeof t.channel=="string"&&"body"in t}var lt="site-edit",dt="frame-runtime";function oe(e,t={}){return Dn({namespace:lt,channel:dt,sessionKey:t.sessionKey,body:e})}function ht(e){return!Pn(e)||e.namespace!==lt||e.channel!==dt?!1:typeof e.body?.type=="string"}var He="vcp-site-edit:route-ready",je="vcp-site-edit:bridge-status",Nn=1e3,Bn="data-vcp-ui-component",St="data-vcp-theme-preview",ft="::repeat-item#",ge="components/ui",An=new Set(["article","aside","div","footer","form","header","li","main","nav","ol","section","select","table","tbody","tfoot","thead","tr","ul"]),Fn=new Set(["a","button","em","h1","h2","h3","h4","h5","h6","label","p","small","span","strong"]);function Mn(e,t=""){let n=Ct(t),r=n&&(e===n||e.startsWith(`${n}/`))?e.slice(n.length)||"/":e,i=r.startsWith("/")?r:`/${r}`;return i==="/"?"/":i.replace(/\/+$/,"")}function wn(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 On(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 So(e=window,t={}){let n=On(e,{explicit_ws_url:t.explicit_ws_url,port:t.ws_port,path:t.wsPath||"/__vcp/site-edit/bridge"}),r=Vn({bridgeUrl:n,options:t}),i=e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__;if(i?.started){if(Kn(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,u=t.create_client??(p=>new me({url:p,authKey:t.bridge_session_key})),c=t.schedule_after_navigation??Xn,f=()=>{o.retryTimer&&(e.clearTimeout(o.retryTimer),o.retryTimer=void 0)},d=()=>Mn(e.location.pathname,t.basePath||""),g=!!e.parent&&e.parent!==e,y=p=>{Qn(e,p)},x=p=>{o.currentDocument=p,o.currentEntriesByKey=new Map((p?.entries??[]).map(b=>[b.key,b]))},I=()=>{o.unsubscribeConnectionStatus?.(),o.unsubscribeConnectionStatus=void 0,o.unsubscribeDocument?.(),o.unsubscribeDocument=void 0},k=(p,b)=>!o.disposed&&b===o.routeSequence&&p===d(),R=async(p,b)=>{let T=o.activeBridge;if(!T)return null;let h=await T.getDocument(p);return k(p,b)&&x(h.data),h.data},N=()=>{I(),x(null);let p=o.activeBridge;o.activeBridge=null,p&&e.__VCP_SITE_EDIT__===p&&delete e.__VCP_SITE_EDIT__;let b=o.activeClient;o.activeClient=null,b?.disconnect()},G=p=>p===s.routeId&&!!o.activeBridge&&(g||!!(o.currentDocument&&Ln(o.currentDocument,p)))&&Zn(o.activeClient),ee=p=>Math.min(Nn*2**Math.max(0,p),8e3),w=(p,b,T)=>{if(o.disposed)return;f();let h=ee(T);y({state:"reconnecting",routeId:p,attempt:T,retryInMs:h,messageKey:"studio.status.previewBridgeConnecting"}),o.retryTimer=e.setTimeout(()=>{o.retryTimer=void 0,!(o.disposed||b!==o.routeSequence)&&de(T+1).catch(m=>{let l=d();if(p===l){if(Q(m)){y({state:"reload-required",routeId:p,attempt:T,messageKey:"studio.errors.previewBridgeReloadRequired"});return}w(p,o.routeSequence,T+1)}})},h)},J=(p,b,T)=>{if(!k(p,b)||o.activeClient===null)return;if(Q(T.message)){N(),f(),y({state:"reload-required",routeId:p,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}let h=o.activeClient;I(),x(null);let m=o.activeBridge;o.activeBridge=null,m&&e.__VCP_SITE_EDIT__===m&&delete e.__VCP_SITE_EDIT__,o.activeClient=null,h?.disconnect(),w(p,b,0)},De=p=>{let b=d(),T=o.routeSequence;if(!(!k(b,T)||o.activeClient===null)){if(Q(p)){N(),f(),y({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}xt(p)&&J(b,T,{state:"failed",message:$e(p,"Site edit bridge request failed")})}};o.cleanupFrameRuntime=Wn(e,{getCurrentDocument:()=>o.currentDocument,getDocumentEntry:p=>o.currentEntriesByKey.get(p)??null,setCurrentDocument:x,onBridgeRequestError:p=>{De(p)}});let te=async()=>de(0),de=async p=>{if(o.disposed)return;let b=d();if(G(b))return;let T=o.syncInFlight;if(T?.routeId===b)return T.promise;let h=o.routeSequence+1,m=Pe(b,h,p);o.syncInFlight={routeId:b,sequence:h,promise:m};try{await m}finally{o.syncInFlight?.promise===m&&(o.syncInFlight=null)}},Pe=async(p,b,T)=>{o.routeSequence=b,f(),N(),y({state:T>0?"reconnecting":"connecting",routeId:p,attempt:T,messageKey:T>0?"studio.status.previewBridgeConnecting":"studio.status.previewLoading"});let h=u(n),m=!1;o.activeClient=h,o.unsubscribeConnectionStatus=h.subscribeConnectionStatus?.(l=>{m&&(l.state==="closed"||l.state==="failed")&&J(p,b,l)});try{if(await h.connect(),!k(p,b)){h.disconnect();return}let l=ut({routeId:p,client:h,initialDocument:Un(p)});o.activeBridge=l,a()&&(e.__VCP_SITE_EDIT__=l),o.activeClient=h,o.unsubscribeDocument=l.subscribe(D=>{D.type==="site-edit.document.changed"&&D.routeId===p&&o.currentDocument&&D.version>o.currentDocument.version&&R(p,b).catch(()=>{})}),a()&&(s.routeId=p);let _=(g?null:await l.initializeSession({routeId:p}))?.data.document??null;if(_&&x(_),!k(p,b)){h.disconnect();return}m=!0,y({state:"ready",routeId:p,attempt:T,messageKey:"studio.status.previewReady"}),wn(e,{documentVersion:_?.version??0,routeId:p,versions:t.runtime_versions}),_&&It(e,{routeId:p,version:_.version})}catch(l){if(I(),o.activeClient===h&&(o.activeClient=null),o.activeBridge&&e.__VCP_SITE_EDIT__===o.activeBridge&&delete e.__VCP_SITE_EDIT__,o.activeBridge=null,h.disconnect(),x(null),!k(p,b))return;throw y({state:Q(l)?"reload-required":"failed",routeId:p,attempt:T,messageKey:Q(l)?"studio.errors.previewBridgeReloadRequired":"studio.errors.previewBridgeDisconnected"}),l}},U=p=>{if(o.disposed)return;let b=d();if(Q(p)){f(),y({state:"reload-required",routeId:b,attempt:0,messageKey:"studio.errors.previewBridgeReloadRequired"});return}w(b,o.routeSequence,0)},H=()=>{o.syncScheduled||o.disposed||(o.syncScheduled=!0,c(()=>{o.syncScheduled=!1,!o.disposed&&te().catch(p=>U(p))}))},he=()=>{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(),N(),a()&&delete e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__)};if(s={started:!0,signature:r,syncRoute:te,cleanup:he},e.__VCP_SITE_EDIT_AUTO_BOOTSTRAP__=s,o.unbindBootstrapLifecycle=Hn(e,he),o.unbindRouteChange=Yn(e,H,d),t.defer_initial_sync){H();return}await te()}function Vn(e){return{basePath:Ct(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:qn(e.options.bridge_session_key)}}function Kn(e,t){return!!e&&JSON.stringify(e)===JSON.stringify(t)}function qn(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 Hn(e,t){let n=()=>t();return e.addEventListener("pagehide",n),e.addEventListener("beforeunload",n),jn(t),()=>{e.removeEventListener("pagehide",n),e.removeEventListener("beforeunload",n)}}function jn(e){let t=import.meta.hot,n=import.meta.webpackHot,r=t??n;!r||typeof r.dispose!="function"||r.dispose(()=>e())}function Un(e){return{siteId:"preview",snapshotId:"preview",routeId:e,version:0,pageComposition:{status:"unsupported",reason:"ROUTE_RETURN_NOT_FOUND",diagnostics:[]},entries:[]}}function Wn(e=window,t={}){let n=null,r=null,i=null,o=null,s=null,a=null,u=null,c=null,f=null,d=new Map,g=typeof t.expectedSessionKey=="string"&&t.expectedSessionKey.length>0?t.expectedSessionKey:null,y=()=>{n?.(),n=null,r=null},x=()=>{i?.(),i=null,o?.(),o=null},I=(h,m,l)=>{let P=s?.sessionKey!==h||s?.sourceWindow!==m||s?.targetOrigin!==l;s={sessionKey:h,sourceWindow:m,targetOrigin:l},P&&(c=null,f=null)},k=(h,m)=>{let l=e.parent&&e.parent!==e?e.parent:null;return!l||m!==l?!1:!g||h===g},R=()=>{for(let h of d.values())h();d.clear()},N=h=>JSON.stringify([h.routeId,h.version]),G=()=>!u||u.state==="ready",ee=h=>JSON.stringify([h.state,h.routeId??null,h.attempt??null,h.retryInMs??null,h.messageKey??null]),w=h=>{if(!G())return;let m=N(h);c!==m&&(o?.(),o=null,U({kind:"route-ready",payload:{routeId:h.routeId,version:h.version}}),s&&(c=m))},J=h=>{let m=ee(h);f!==m&&(h.state!=="ready"&&(c=null,a=null),U({kind:"bridge-status",payload:h}),s&&(f=m))},De=h=>{a=h,w(h)},te=h=>{u=h,J(h)},de=()=>{a&&w(a)},Pe=()=>{u&&J(u)},U=h=>{s&&s.sourceWindow.postMessage(oe({type:"event",...h},{sessionKey:s.sessionKey}),s.targetOrigin)},H=(h,m,l,P)=>{let _=Ee(e.document,m.clientX,m.clientY,t.getCurrentDocument?.()??null),D=_?M(_,l==="full"?q(e.document,_,t.getCurrentDocument?.()??null):gt(e.document,_,t.getCurrentDocument?.()??null),t.getDocumentEntry,l):null;P&&D&&(h==="pointer-click"||h==="pointer-double-click")&&(P.preventDefault(),P.stopPropagation(),typeof P.stopImmediatePropagation=="function"&&P.stopImmediatePropagation()),U({kind:h,payload:{clientX:m.clientX,clientY:m.clientY,buttons:Number(m.buttons??0),hit:D}})},he=(h,m,l)=>{x(),s={sessionKey:h,sourceWindow:m,targetOrigin:l};let P=Wr(e.document),_=null,D=null,S=()=>{D=null;let v=_;_=null,v&&H("pointer-move",v,"summary")},O=v=>{_={clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},D===null&&(D=vt(e,S))},W=v=>{H("pointer-down",{clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},"full",v)},X=v=>{H("pointer-up",{clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},"summary",v)},j=v=>{H("pointer-cancel",{clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},"summary",v)},Y=v=>{H("pointer-click",{clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},"full",v)},ne=v=>{H("pointer-double-click",{clientX:Number(v.clientX),clientY:Number(v.clientY),buttons:Number(v.buttons)},"full",v)},re=()=>{U({kind:"scroll",payload:{metrics:Se(e)}})};e.document.addEventListener("pointerdown",W,!0),e.document.addEventListener("pointermove",O,{passive:!0,capture:!0}),e.document.addEventListener("pointerup",X,!0),e.document.addEventListener("pointercancel",j,!0),e.document.addEventListener("click",Y,!0),e.document.addEventListener("dblclick",ne,!0),e.addEventListener("scroll",re,{passive:!0}),i=()=>{D!==null&&(Et(e,D),D=null),_=null,P(),e.document.removeEventListener("pointerdown",W,!0),e.document.removeEventListener("pointermove",O,!0),e.document.removeEventListener("pointerup",X,!0),e.document.removeEventListener("pointercancel",j,!0),e.document.removeEventListener("click",Y,!0),e.document.removeEventListener("dblclick",ne,!0),e.removeEventListener("scroll",re)}},p=h=>{let m=h.detail;m?.routeId&&De(m)},b=h=>{let m=h.detail;m?.state&&te(m)},T=h=>{let m=h.data;if(!ht(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"&&!pt(m.body))return;let l=m.body,P=typeof m.sessionKey=="string"?m.sessionKey:null,_=h.source,D=h.origin;if(!P||!D||!_||typeof _.postMessage!="function"||!k(P,_))return;if(s){if(s.sourceWindow!==_||s.targetOrigin!==D)return;s.sessionKey!==P&&(y(),x(),R(),s=null)}I(P,_,D),Pe(),de();let S=O=>{let W=typeof l.id=="string"?l.id:"unknown";_.postMessage(oe({id:W,...O},{sessionKey:P}),D)};try{if(pt(l)){zn({message:l,sendEvent:E=>{_.postMessage(oe({type:"event",...E},{sessionKey:P}),D)},sendResponse:S,subscriptions:d,getCurrentDocument:t.getCurrentDocument,setCurrentDocument:t.setCurrentDocument,onBridgeRequestError:t.onBridgeRequestError,windowLike:e});return}if(l.kind==="apply-node-patch"){let E=z(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!E){S({type:"response",ok:!1,error:"No editable element found for patch target"});return}let C=l.payload.preview,F=C?Pr(C.sessionId,l.payload.ref):null;if(F&&C){let fe=se.get(F)??-1;if(C.revision<fe){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,stale:!0,latestRevision:fe}});return}if(C.revision===fe){S({type:"response",ok:!0,result:{applied:!1,appliedRevision:C.revision,duplicate:!0,latestRevision:fe}});return}}if(kr(E,l.payload.patch),F&&C&&Nr(F,C.revision),C?.responseDetail==="none"){S({type:"response",ok:!0,result:{applied:!0,appliedRevision:C.revision}});return}S({type:"response",ok:!0,result:M(E,q(e.document,E,t.getCurrentDocument?.()??null),t.getDocumentEntry,C?.responseDetail??"full")});return}if(l.kind==="get-hit-by-ref"){let E=z(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!E){S({type:"response",ok:!1,error:"No editable element found for hit target"});return}S({type:"response",ok:!0,result:M(E,q(e.document,E,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")});return}if(l.kind==="get-path-by-ref"){let E=z(e.document,l.payload.ref,t.getCurrentDocument?.()??null);if(!E){S({type:"response",ok:!1,error:"No editable element found for path target"});return}let C=[],F=E;for(;F;)F.getAttribute("data-vcp-edit-key")&&C.push(M(F,q(e.document,F,t.getCurrentDocument?.()??null),t.getDocumentEntry,"full")),F=F.parentElement;S({type:"response",ok:!0,result:C.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&&mt(r.ref,E)&&(r=null),S({type:"response",ok:!0,result:{cleared:!0}});return}if(!r||!mt(r.ref,E)){S({type:"response",ok:!1,error:"No pending text edit rollback snapshot"});return}let C=nr(e.document,r,t.getCurrentDocument?.()??null);r=null,S(C?{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"){S({type:"response",ok:!0,result:Se(e)});return}if(l.kind==="scroll-to"){let E=Number(l.payload.x),C=Number(l.payload.y);if(!Number.isFinite(E)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid scroll position"});return}e.scrollTo({left:E,top:C}),S({type:"response",ok:!0,result:Se(e)});return}if(l.kind==="scroll-by"){let E=Number(l.payload.deltaX),C=Number(l.payload.deltaY);if(!Number.isFinite(E)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid scroll delta"});return}e.scrollBy({left:E,top:C}),S({type:"response",ok:!0,result:{...Se(e),scrolled:!0}});return}if(l.kind==="set-interaction-mode"){l.payload.enabled?he(P,_,D):s?.sourceWindow===_&&s.targetOrigin===D&&s.sessionKey===P&&x(),S({type:"response",ok:!0,result:{interactionEnabled:l.payload.enabled}});return}if(l.kind==="set-theme-override"){Br(e.document,l.payload),S({type:"response",ok:!0,result:{themeOverrideApplied:!0}});return}if(l.kind==="clear-theme-override"){Ar(e.document),S({type:"response",ok:!0,result:{themeOverrideCleared:!0}});return}if(l.kind==="get-theme-variables"){S({type:"response",ok:!0,result:Fr(e.document,l.payload.names)});return}if(l.kind==="compute-drop-target-at-point"){let E=Number(l.payload?.x),C=Number(l.payload?.y);if(!Number.isFinite(E)||!Number.isFinite(C)){S({type:"response",ok:!1,error:"Invalid drop target point"});return}S({type:"response",ok:!0,result:Ir(e,E,C,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){S({type:"response",ok:!1,error:"Missing bounds observer target"});return}let C=z(e.document,E,t.getCurrentDocument?.()??null);if(!C){S({type:"response",ok:!1,error:"No editable element found for bounds observer target"});return}o?.(),o=yr(e,C,E,t.getCurrentDocument,t.getDocumentEntry,F=>U({kind:"node-bounds-change",payload:{hit:F}})),S({type:"response",ok:!0,result:{observing:!0}}),U({kind:"node-bounds-change",payload:{hit:M(C,E,t.getDocumentEntry,"summary")}});return}if(l.kind==="clear-node-bounds-observer"){o?.(),o=null,S({type:"response",ok:!0,result:{cleared:!0}});return}if(l.kind!=="hit-test-at-point"&&l.kind!=="start-text-edit-at-point")return;let O=Number(l.payload?.x),W=Number(l.payload?.y);if(!Number.isFinite(O)||!Number.isFinite(W)){S({type:"response",ok:!1,error:"Invalid text edit point"});return}let X=l.kind==="hit-test-at-point"?Ee(e.document,O,W,t.getCurrentDocument?.()??null):ir(e.document,O,W,t.getCurrentDocument?.()??null,t.getDocumentEntry);if(!X){S({type:"response",ok:!1,error:l.kind==="hit-test-at-point"?"No editable element at point":"No editable text element at point"});return}let j=l.kind==="start-text-edit-at-point"?X:null,Y=l.kind==="hit-test-at-point"?X:j.element,ne=l.payload.detailLevel??"full",re=ne==="full"?q(e.document,Y,t.getCurrentDocument?.()??null):gt(e.document,Y,t.getCurrentDocument?.()??null),v=j&&typeof j.textSegmentIndex=="number"?{...re,textSegmentIndex:j.textSegmentIndex}:re,cn=M(Y,v,t.getDocumentEntry,ne);if(l.kind==="hit-test-at-point"){S({type:"response",ok:!0,result:cn});return}y(),n=Vr(e,Y,v,E=>{_.postMessage(oe({type:"event",...E},{sessionKey:P}),D)},{...j?.textNode?{textNode:j.textNode}:{},onCommitSnapshot:E=>{r=E}}),S({type:"response",ok:!0,result:{ref:v}})}catch(O){S({type:"response",ok:!1,error:O instanceof Error?O.message:"Failed to start text edit"})}};return e.addEventListener("message",T),e.addEventListener(He,p),e.addEventListener(je,b),()=>{y(),x(),s=null,R(),e.removeEventListener("message",T),e.removeEventListener(He,p),e.removeEventListener(je,b)}}function pt(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 $n(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 zn({message:e,sendEvent:t,sendResponse:n,subscriptions:r,getCurrentDocument:i,setCurrentDocument:o,onBridgeRequestError:s,windowLike:a}){let u=a.__VCP_SITE_EDIT__;if(!u){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 c=await u.initializeSession({routeId:e.payload.routeId});o?.(c.data.document),It(a,{routeId:c.data.document.routeId,version:c.data.document.version}),n({type:"response",ok:!0,result:c});return}case"bridge-get-document":{let c=await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-get-history-status":n({type:"response",ok:!0,result:await u.getHistoryStatus()});return;case"bridge-get-style-context":n({type:"response",ok:!0,result:await u.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 c=u.ensureDocumentVersion?await u.ensureDocumentVersion(e.payload.routeId,Number(e.payload.minVersion)):await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-acknowledge-document-version":{if(!Number.isFinite(Number(e.payload.version))){n({type:"response",ok:!1,error:"Invalid document version"});return}let c=u.acknowledgeDocumentVersion?await u.acknowledgeDocumentVersion(e.payload.routeId,Number(e.payload.version)):await u.getDocument(e.payload.routeId);o?.(c.data),n({type:"response",ok:!0,result:c});return}case"bridge-get-object-edit-context":n({type:"response",ok:!0,result:await u.getObjectEditContext(e.payload.key,e.payload.routeId)});return;case"bridge-get-class-name-source":{let c=await u.getClassNameSource(e.payload.key,e.payload.routeId);n({type:"response",ok:!0,result:Gn(c,e.payload.key,a.document,i?.()??null)});return}case"bridge-get-source-tree":n({type:"response",ok:!0,result:await u.getSourceTree()});return;case"bridge-get-source-file":n({type:"response",ok:!0,result:await u.getSourceFile({path:e.payload.path})});return;case"bridge-resolve-source-location":n({type:"response",ok:!0,result:await u.resolveSourceLocation({key:e.payload.key,routeId:e.payload.routeId})});return;case"bridge-execute":{let c=await u.execute(e.payload.request),f=i?.()?.routeId;if(c.ok&&f&&u.acknowledgeDocumentVersion&&$n(e.payload.request)){let d=await u.acknowledgeDocumentVersion(f,c.data.resultVersion);o?.(d.data)}n({type:"response",ok:!0,result:c});return}case"bridge-undo":n({type:"response",ok:!0,result:await u.undo()});return;case"bridge-redo":n({type:"response",ok:!0,result:await u.redo()});return;case"bridge-subscribe":{let c=e.payload.subscriptionId;r.get(c)?.();let f=u.subscribe(d=>{t({kind:"bridge-event",payload:{event:d,subscriptionId:c}})});r.set(c,f),n({type:"response",ok:!0,result:{subscribed:!0}});return}case"bridge-unsubscribe":{let c=e.payload.subscriptionId;r.get(c)?.(),r.delete(c),n({type:"response",ok:!0,result:{unsubscribed:!0}});return}}}catch(c){s?.(c,e),n({type:"response",ok:!1,error:er(c)})}}function Gn(e,t,n,r){if(!e.ok)return e;let i=z(n,{key:t},r),o=i?Jn(i):null;return o?{...e,data:{...e.data,computedStyle:{...e.data.computedStyle??{},...o}}}: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 Yn(e,t,n=()=>e.location.pathname){let r=e.history.pushState,i=e.history.replaceState,o=n(),s=()=>{let c=n();c!==o&&(o=c,t())},a=()=>s(),u=()=>s();return e.history.pushState=function(...f){let d=r.apply(this,f);return s(),d},e.history.replaceState=function(...f){let d=i.apply(this,f);return s(),d},e.addEventListener("popstate",a),e.addEventListener("hashchange",u),()=>{e.history.pushState=r,e.history.replaceState=i,e.removeEventListener("popstate",a),e.removeEventListener("hashchange",u)}}function Xn(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 Et(e,t){if(typeof e.cancelAnimationFrame=="function"){e.cancelAnimationFrame(t);return}e.clearTimeout(t)}function It(e,t){e.dispatchEvent(new CustomEvent(He,{detail:t}))}function Qn(e,t){e.dispatchEvent(new CustomEvent(je,{detail:t}))}function Zn(e){return e?e.getConnectionState?e.getConnectionState()==="open":!0:!1}function Ln(e,t){return e.routeId===t}function $e(e,t){return e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t}function xt(e){let t=$e(e,"");return/websocket|readyState|not open|disconnected|bridge request timed out|network|econnreset|broken pipe|socket closed/i.test(t)}function er(e){let t=$e(e,"Site edit bridge request failed");return/bridge request timed out/i.test(t)?"Site edit bridge request timed out":xt(t)?"Site edit bridge disconnected":t}function Q(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 Ct(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function ze(e){return An.has(_t(e))}function tr(e){return Fn.has(_t(e))}function Rt(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:tr(e.tagName),canInsertChild:ze(e.tagName),canMove:!1,canRemove:!1}}function _t(e){return e?.trim().toLowerCase()??""}function mt(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 nr(e,t,n){let r=z(e,t.ref,n);if(!r)return!1;if(typeof t.ref.textSegmentIndex=="number"){let i=rr(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 rr(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!ve(r)||(r.textContent??"").trim().length===0)){if(n===t)return r;n+=1}return null}function ir(e,t,n,r,i){let o=Ee(e,t,n,r),s=Tt(o);if(!s)return null;let a=s.getAttribute("data-vcp-edit-key")??"",u=q(e,s,r),c=i?.(u.key)??i?.(a);if(!Rt({operationSummary:c?.operationSummary,tagName:s.tagName,fallbackMode:"preview"}).canUpdateText)return null;let d=or(e,t,n,s);if(d){let g=ar(s,d);if(g!==null)return{element:s,textNode:d,textSegmentIndex:g}}return Ce(s)?null:{element:s}}function or(e,t,n,r){let i=sr(e,t,n);return!i||i.parentElement!==r?null:i}function sr(e,t,n){let r=e,o=r.caretPositionFromPoint?.(t,n)?.offsetNode??null;if(ve(o))return o;let a=r.caretRangeFromPoint?.(t,n)?.startContainer??null;return ve(a)?a:null}function ar(e,t){let n=0;for(let r of Array.from(e.childNodes))if(!(!ve(r)||(r.textContent??"").trim().length===0)){if(r===t)return n;n+=1}return null}function ve(e){return e?.nodeType===3}function Ee(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=Tt(o),a=s?.getAttribute("data-vcp-edit-key")??"";if(s&&hr(s,r,a))return s}return null}function Tt(e){let t=e,n=null;for(;t;){let r=t.getAttribute("data-vcp-edit-key")??"";if(r){if(Ge(t))return n??t;!ur(r)&&!n&&(n=t)}t=t.parentElement}return n}function Ge(e){return e.getAttribute(Bn)!==null}function ur(e){return cr(e.split("::")[0]??"")}function cr(e){if(!e)return!1;let t=lr(e);return t===ge||t.startsWith(`${ge}/`)||t.includes(`/${ge}/`)||t.endsWith(`/${ge}`)}function lr(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=Dt(Nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ot(r)}"]`))),n,r);if(i.length<=1)return{key:yt(n,r,0)};let o=i.indexOf(t);return o>=0?{key:yt(n,r,o),instanceIndex:o,instanceCount:i.length}:{key:r}}function gt(e,t,n){return q(e,t,n)}function z(e,t,n){let r=Ie(t.key)??t.key,i=Dt(Nt(Array.from(e.querySelectorAll(`[data-vcp-edit-key="${Ot(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=(Ie(t.key)??t.key)!==t.key;if(o!==null&&!s)return i[o]??null;let a=dr(n,t.key);return a!==null&&a>=0&&a<i.length?i[a]??null:o!==null?i[o]??null:i[0]??null}function yt(e,t,n){return kt(e,t)[n]?.key??t}function dr(e,t){let n=Ie(t);if(!n)return null;let i=kt(e,n).findIndex(o=>o.key===t);return i>=0?i:null}function kt(e,t){return(e?.entries??[]).filter(n=>(Ie(n.key)??n.key)===t)}function Dt(e,t,n){let r=Pt(t,n);return r?e.filter(i=>i.tagName.toLowerCase()===r):e}function hr(e,t,n){let r=Pt(t,n);return!r||e.tagName.toLowerCase()===r}function Pt(e,t){return null}var fr=2,pr=4;function Nt(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&fr)!==0?1:0})}function Ie(e){if(typeof e!="string"||e.length===0)return e??null;let t=e;for(;;){let n=t.lastIndexOf(ft);if(n<0)break;let r=Number(t.slice(n+ft.length));if(!Number.isInteger(r)||r<0)return e;t=t.slice(0,n)}return t}function mr(e){let n=e.ownerDocument?.defaultView?.getComputedStyle(e);return{...Bt(n),paddingTop:A(n?.paddingTop),paddingRight:A(n?.paddingRight),paddingBottom:A(n?.paddingBottom),paddingLeft:A(n?.paddingLeft),borderTopWidth:A(n?.borderTopWidth),borderRightWidth:A(n?.borderRightWidth),borderBottomWidth:A(n?.borderBottomWidth),borderLeftWidth:A(n?.borderLeftWidth),columnGap:A(n?.columnGap),rowGap:A(n?.rowGap)}}function Bt(e){return{marginTop:A(e?.marginTop,!0),marginRight:A(e?.marginRight,!0),marginBottom:A(e?.marginBottom,!0),marginLeft:A(e?.marginLeft,!0)}}function A(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:Er(n.getBoundingClientRect()),margin:Bt(t?.getComputedStyle(n))})).filter(({rect:n})=>n.width>0&&n.height>0)}function M(e,t,n,r="full"){let i=e.getBoundingClientRect(),o=n?.(t.key)??null,s=e.tagName.toLowerCase(),a=xe(e),u=r==="full"?{textPreview:e.textContent?.trim().slice(0,80),dataset:Object.fromEntries(Object.entries(e.dataset).map(([x,I])=>[x,I??""])),attributes:Object.fromEntries(e.getAttributeNames().map(x=>[x,e.getAttribute(x)??""]))}:{},c=Rt({operationSummary:o?.operationSummary,tagName:s,fallbackMode:"preview"}),f=Ge(e),d=!0,g=At(e)?.getAttribute("data-vcp-edit-key")??null,y=gr(e);return{ref:t,key:t.key,detailLevel:r,tagName:s,...o?{sourceKind:"jsx"}:{},...g?{parentKey:g}:{},...o?.pageCompositionUnitKey?{pageCompositionUnitKey:o.pageCompositionUnitKey}:{},...u,runtimeFlags:{selectable:!0,movable:c.canMove,removable:c.canRemove,textEditable:c.canUpdateText,container:f?!1:!!Ce(e)||c.canInsertChild||d&&ze(s)},layout:a,rect:{top:i.top,left:i.left,width:i.width,height:i.height},childBoxes:y,childRects:y.map(({rect:x})=>x),spacing:mr(e)}}function yr(e,t,n,r,i,o){let s=t,a=M(s,n,i,"summary"),u=null,c=()=>{u===null&&(u=vt(e,f))},f=()=>{u=null;let k=z(e.document,n,r?.()??null);if(!k)return;k!==s&&(g?.unobserve(s),s=k,g?.observe(s));let R=M(s,n,i,"summary");R.rect.width<=0||R.rect.height<=0||br(a,R)&&(a=R,o(R))},d=e.ResizeObserver,g=typeof d=="function"?new d(c):null;g?.observe(s);let y=e.MutationObserver,x=typeof y=="function"?new y(c):null;x?.observe(e.document.documentElement,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.addEventListener("resize",c,{passive:!0});let I=e.visualViewport;return I?.addEventListener?.("resize",c,{passive:!0}),e.document.addEventListener("load",c,!0),()=>{u!==null&&(Et(e,u),u=null),g?.disconnect(),x?.disconnect(),e.removeEventListener("resize",c),I?.removeEventListener?.("resize",c),e.document.removeEventListener("load",c,!0)}}function br(e,t){return Je(e.rect,t.rect)||Sr(e.childBoxes,t.childBoxes)||vr(e.childRects,t.childRects)||Ue(e.spacing,t.spacing)||Ue(e.layout,t.layout)}function Sr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>{let s=r[o];return!s||Je(i.rect,s.rect)||Ue(i.margin,s.margin)})}function vr(e,t){let n=e??[],r=t??[];return n.length!==r.length||n.some((i,o)=>Je(i,r[o]??i))}function Ue(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 Er(e){return{top:e.top,left:e.left,width:e.width,height:e.height}}function Je(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 Ir(e,t,n,r,i,o,s){let a=e.document,u=Ee(a,t,n,o);if(!u)return{anchorHit:null,targetParentHit:null,relation:"none",rejectionReason:"no-editable-hit"};let c=i?z(a,i,o):null;if(c&&We(u,c))return ye(a,u,"self-or-descendant",o,s);if(r==="move"&&c){let I=_r(a,u,c,o,s);if(I){let k=Ke(I.child,I.targetParent,t,n,"nearest");if(k)return be(a,I.child,I.targetParent,k,o,s)}}let f=null,d=!1,g=u,y=u.parentElement;for(;y;){if(y.getAttribute("data-vcp-edit-key")){if(c&&We(y,c))return ye(a,u,"self-or-descendant",o,s);let I=bt(y,r,s);if(I==="accept"){f={child:g,targetParent:y};break}I==="blocked"&&(d=!0),g=y}y=y.parentElement}let x=bt(u,r,s);if(x==="accept"){if(f){let I=Ke(f.child,f.targetParent,t,n,"edge");if(I)return be(a,f.child,f.targetParent,I,o,s)}return be(a,u,u,xr(u,t,n),o,s)}if(f){let I=Ke(f.child,f.targetParent,t,n,"nearest");return be(a,f.child,f.targetParent,I??"after",o,s)}return x==="blocked"||d?ye(a,u,"operation-boundary-blocked",o,s):ye(a,u,"no-accepting-parent",o,s)}function ye(e,t,n,r,i){return{anchorHit:M(t,q(e,t,r),i,"summary"),targetParentHit:null,relation:"none",rejectionReason:n}}function be(e,t,n,r,i,o){let s=M(t,q(e,t,i),o,"summary"),a=M(n,q(e,n,i),o,"summary"),u=xe(n).indicatorOrientation,c=r==="append"||r==="prepend"?Cr(n.getBoundingClientRect(),u,r):Rr(t.getBoundingClientRect(),u,r);return{anchorHit:s,targetParentHit:a,relation:r,indicatorOrientation:u,indicatorBounds:c}}function bt(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":Ce(e)?"blocked":"not-container";let o=e.tagName.toLowerCase();return ze(o)?"accept":"not-container"}function Ke(e,t,n,r,i){let o=xe(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 xr(e,t,n){let r=xe(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 xe(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 Cr(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 Rr(e,t,n){if(t==="vertical")return{left:n==="before"?e.left:e.left+e.width-3,top:e.top,width:3,height:e.height};let r=n==="before"?e.top:e.top+e.height-3;return{left:e.left,top:r,width:e.width,height:3}}function We(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentElement}return!1}function _r(e,t,n,r,i){let o=Tr(e,t,n,r,i);if(o)return o;let s=At(n);if(!s||t===s)return null;let a=t,u=t.getAttribute("data-vcp-edit-key")?t:null;for(;a&&a!==s;)a.getAttribute("data-vcp-edit-key")&&(u=a),a=a.parentElement;return a!==s||!u||u===s||u===n||We(u,n)?null:{child:u,targetParent:s}}function Tr(e,t,n,r,i){return null}function At(e){let t=e.parentElement;for(;t;){if(t.getAttribute("data-vcp-edit-key"))return t;t=t.parentElement}return null}function Ce(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=Ce(n);if(r)return r}return null}function Se(e){let t=e.document.documentElement,n=e.document.body;return{scrollX:K(e.scrollX),scrollY:K(e.scrollY),scrollWidth:Math.max(K(t?.scrollWidth),K(n?.scrollWidth),K(e.innerWidth)),scrollHeight:Math.max(K(t?.scrollHeight),K(n?.scrollHeight),K(e.innerHeight)),viewportWidth:K(e.innerWidth),viewportHeight:K(e.innerHeight)}}function kr(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 Dr=500,se=new Map;function Pr(e,t){return`${e}:${t.key}:${t.instanceIndex??""}`}function Nr(e,t){if(se.size>=Dr){let n=se.keys().next().value;n&&se.delete(n)}se.set(e,t)}var ae=new Set;function Br(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 ae)r.has(i)||n?.removeProperty(i);ae.clear();for(let i of r)ae.add(i);Or(e,t.stylesheets??[])}function Ar(e){let t=e.documentElement?.style;for(let n of ae)t?.removeProperty(n);ae.clear();for(let n of wt(e))n.remove()}function Fr(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=Ft(i,s);a&&(o[s]=a)}return o}function Ft(e,t,n=new Set){if(!e||n.has(t))return null;n.add(t);let r=e.getPropertyValue(t).trim();return Mt(e,r,n)}function Mt(e,t,n){if(!t)return null;let r=Mr(t);if(!r)return t;let i=Ft(e,r.name,n);return i||(r.fallback?Mt(e,r.fallback,n)??r.fallback:null)}function Mr(e){let t=e.trim();if(!t.startsWith("var(")||!t.endsWith(")"))return null;let n=t.slice(4,-1).trim(),r=wr(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 wr(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="("){t+=1;continue}if(r===")"){t=Math.max(0,t-1);continue}if(r===","&&t===0)return n}return-1}function Or(e,t){let n=new Set(t.filter(o=>typeof o=="string"&&o.length>0)),r=new Map;for(let o of wt(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(St,"true"),s.setAttribute("href",o),i.appendChild(s)}}function wt(e){return Array.from(e.querySelectorAll(`link[${St}]`))}function Vr(e,t,n,r,i={}){let o=i.textNode?Kr(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??"",u=o?void 0:t.innerHTML,c=qr(s),f=!1,d=()=>{e.document.removeEventListener("pointerdown",y,!0),s.removeEventListener("keydown",x),s.removeEventListener("blur",I),s.removeEventListener("input",k),jr(s,c)},g=R=>{if(f)return;f=!0;let N=s.textContent??"";if(d(),R==="cancel"){o?.restore(a),o||(t.textContent=a),r({kind:"text-edit-cancel",payload:{ref:n}});return}if(o?.restore(N),R==="commit"&&N!==a){i.onCommitSnapshot?.({ref:n,initialText:a,...u!==void 0?{initialHtml:u}:{}}),r({kind:"text-edit-commit",payload:{ref:n,value:N}});return}r({kind:"text-edit-exit",payload:{ref:n}})};function y(R){let N=R.target;N&&s.contains(N)||g("commit")}function x(R){if(R.key==="Escape"){R.preventDefault(),g("cancel");return}R.key==="Enter"&&(R.metaKey||R.ctrlKey)&&(R.preventDefault(),g("commit"))}function I(){g("commit")}function k(){r({kind:"text-edit-input",payload:{ref:n,hit:M(t,n,void 0,"full")}})}return Hr(s),e.document.addEventListener("pointerdown",y,!0),s.addEventListener("keydown",x),s.addEventListener("blur",I),s.addEventListener("input",k),$r(s),zr(s,e.document),d}function Kr(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 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 Hr(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 jr(e,t){qe(e,"contenteditable",t.contentEditable),qe(e,"spellcheck",t.spellcheck),qe(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 qe(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 $r(e){try{e.focus({preventScroll:!0})}catch{e.focus()}}function zr(e,t){let n=t.createRange();n.selectNodeContents(e);let r=t.getSelection?.();r?.removeAllRanges(),r?.addRange(n)}function Ot(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function K(e){let t=Number(e);return Number.isFinite(t)?t:0}import Gr from"node:http";import{createHash as Ut,randomBytes as Jr,timingSafeEqual as Yr}from"node:crypto";import Qe from"node:path";import{WebSocket as Wt,WebSocketServer as Xr}from"ws";import{createPreviewSiteEditEngineRuntime as Qr,openFileHistoryStore as Zr}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Lr,scanNextAppRouterRoutes as ei}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as ti}from"@vcp-dev/site-edit-engine/source-watcher";var Re=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as ni}from"@vcp-dev/contracts";var ri="127.0.0.1",ii=30218,oi="/__vcp/site-edit/bridge",$t=6*1024*1024,si=$t*2,ai=3e3,Vt=50,Kt="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Bo(e){let t=Gt(e),n=Yt(t),r=Jt(),i=r.get(n);if(i)return i;let o=new _e(t);r.set(n,o);try{o.start()}catch(s){throw r.delete(n),o.stop(),s}return o}function zt(e,t,n={}){let r=new _e(Gt(t),e,!1,n);return r.start({listen:!1}),r}var _e=class{constructor(t,n=Gr.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 Re,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=ci({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 ti({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??Vt,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=Jt(),n=Yt(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??Qr)({...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 Ye(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 Ye(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 Ye(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??Zr)(ui({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??Vt;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:ei(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=Lr(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 Gt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:Qe.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??ri,port:e.port??ii,path:e.path??oi,sessionKey:e.sessionKey??gi(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{}}}function ui(e){return Qe.join(Qe.resolve(e.root),qt(e.siteId),qt(e.snapshotId),Ut("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function qt(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ut("sha256").update(e).digest("hex").slice(0,32)}function Jt(){let e=globalThis;return e[Kt]??=new Map,e[Kt]}function Yt(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function Ye(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 ci(e){let t=new Xr({maxPayload:$t,noServer:!0}),n=new WeakSet,r=o=>{new pe({socket:new Ze(o),engine:e.engine,validateOperationRequest:s=>ni.safeParse(s).success})},i=(o,s,a)=>{if(!li(o,e))return;let u=di(o,e);if(!u){s.write(`HTTP/1.1 401 Unauthorized\r
|
|
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&>(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
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),s.destroy();return}u.authenticatedByHeader&&n.add(o),t.handleUpgrade(o,s,a,c=>{t.emit("connection",c,o)})};return e.server.on("upgrade",i),t.on("connection",(o,s)=>{if(n.has(s)){r(o);return}hi(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 Ze=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===Wt.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>si){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function li(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function di(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let r=Xe(e.headers["x-vcp-site-edit-key"]),i=Xt(r,t.sessionKey),o=Xe(e.headers.host),s=Xe(e.headers.origin);return o&&!fi(o,t.host,s)?null:s?mi(s,o,t.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function hi(e,t,n){let r=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ai),i,o=()=>{clearTimeout(r),e.off("message",i),e.off("close",o)},s=()=>{o(),e.close(1008,"bridge authentication failed")};i=a=>{try{let u=B.parseMessage(a.toString());if(u.type!=="auth"||!Xt(u.payload.key,t)){s();return}o(),e.readyState===Wt.OPEN&&e.send(B.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{s()}},e.on("message",i),e.on("close",o)}function Xt(e,t){if(!e)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Yr(n,r)}function fi(e,t,n){let r=jt(e),i=jt(t);return r===i||Ht(i)&&Ht(r)&&(!n||Le(n,e))||pi(i)&&(!n||Le(n,e))}function pi(e){return e==="0.0.0.0"||e==="::"}function Ht(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function mi(e,t,n){return n.includes(e)||(t?Le(e,t):!1)}function Le(e,t){try{return new URL(e).host===Qt(t)}catch{return!1}}function jt(e){let t=Qt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Qt(e){return e.trim().toLowerCase()}function Xe(e){return Array.isArray(e)?e[0]:e}function gi(){return Jr(32).toString("base64url")}import yi from"node:http";import{existsSync as L,readFileSync as Z}from"node:fs";import{createRequire as tn}from"node:module";import ue from"node:path";import{basename as nn,dirname as ce,join as le}from"node:path";import{fileURLToPath as rn}from"node:url";var bi="next",Si="127.0.0.1",vi=3e3,Te="/__vcp/site-edit/bridge",on="/__vcp/site-edit/health",ke="/__vcp/site-edit/client/",Ei=`${ke}auto-bootstrap.js`,sn='data-vcp-site-edit-bootstrap="true"',Ii=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],xi="@vcp-dev/site-edit-engine/webpack-loader",Ci=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Ri=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],_i=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Ho(e={}){let t=ue.resolve(e.projectRoot??process.cwd()),n=e.host??Si,r=e.port??io(process.env.PORT)??vi,i=e.bridgePath??Te,o=Ai(i),s=Yi(),a=e.basePath??process.env.VCP_SITE_PREVIEW_BASE_PATH??"/",u=(e.tenantId??process.env.VCP_TENANT_ID)?.trim()||void 0,c=await eo(t),f=Ti(t),d=c({dev:!0,dir:t,hostname:n,port:r,...ki(f)}),g=d.getRequestHandler(),y=e.siteId??process.env.VCP_SITE_ID??"site_preview",x=e.snapshotId??process.env.VCP_SNAPSHOT_ID??ro(t),I=e.historyRoot??process.env.VCP_SITE_EDIT_HISTORY_ROOT,k=I?.trim()?ue.resolve(I):void 0;await d.prepare();let R=null,N=yi.createServer((ee,w)=>{qi({basePath:a,bridgePath:i,bridgeHealthPath:o,bridgeSessionKey:s,getBridgeHealth:()=>R?.getHealth()??ji(i),handle:g,request:ee,response:w}).catch(J=>{console.error(J),w.headersSent||(w.statusCode=500),w.end("site edit preview request failed")})});R=zt(N,{...u?{tenantId:u}:{},siteId:y,snapshotId:x,projectRoot:t,basePath:a,host:n,port:r,path:i,sessionKey:s,...k?{historyRoot:k}:{}}),Ni({server:N,bridgePath:i,handleUpgrade:d.getUpgradeHandler()});let G=()=>{R?.stop(),d.close().catch(()=>{}),N.close()};return process.on("SIGINT",G),process.on("SIGTERM",G),await oo(N,r,n),{bundler:f,close:G,server:N}}function Ti(e){let t=Di(e);return t&&Pi(t)?"webpack":"turbopack"}function ki(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Di(e){for(let t of Ii){let n=le(e,t);if(L(n))return Z(n,"utf8")}return null}function Pi(e){return e.includes(xi)?!0:Ci.test(e)&&Ri.some(t=>t.test(e))}function Ni(e){let t=(n,r,i)=>{Bi(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 Bi(e,t){return new URL(e??"/","http://localhost").pathname===t}function Ai(e=Te){if(e===Te)return on;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Fi(e){let t=JSON.stringify({basePath:e.basePath,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Mi()});return`<script type="module" ${sn}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ei)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Mi(){return{bridge:et("@vcp-dev/site-edit-bridge"),contracts:et("@vcp-dev/contracts"),engine:et("@vcp-dev/site-edit-engine")}}function et(e){let t=tn(import.meta.url);try{let n=t.resolve(e),r=wi(n,e);if(!r)return;let i=JSON.parse(Z(r,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function wi(e,t){let n=ue.parse(e).root,r=ce(e);for(;r&&r!==n;){let i=le(r,"package.json");if(L(i))try{if(JSON.parse(Z(i,"utf8")).name===t)return i}catch{return}r=ce(r)}}function Oi(e,t){if(e.includes(sn))return e;let n=Fi(t),r=/<\/body\s*>/i.exec(e);return r?`${e.slice(0,r.index)}${n}${e.slice(r.index)}`:`${e}${n}`}function jo(e,t=ce(rn(import.meta.url)),n=L){return an(e,t,n)?.path??null}function an(e,t=ce(rn(import.meta.url)),n=L){let r=new URL(e??"/","http://localhost").pathname;if(!r.startsWith(ke))return null;let i=r.slice(ke.length);if(!_i.has(i))return null;let o=tt(to(t),i);if(nn(t)!=="src")return{path:o,requiresTranspile:!1};let s=tt(t,i.replace(/\.js$/,".ts"));return n(s)?{path:s,requiresTranspile:!0}:{path:o,requiresTranspile:!1}}async function Vi(e,t){let n=an(e.url);if(!n)return!1;if(!L(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let r=n.requiresTranspile?await Ki(Z(n.path,"utf8")):Z(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(r),!0}async function Ki(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function qi({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:r,getBridgeHealth:i,handle:o,request:s,response:a}){if(Hi(s,a,n,i)||await Vi(s,a))return;let u=Ui(s),c=Wi(s),f=u||c?Gi(a,{basePath:e,bridgePath:t,bridgeSessionKey:r,patchNextDevChunk:c}):()=>{};try{await o(s,a)}catch(d){throw f(),d}}function Hi(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 ji(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ui(e){return $i(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Wi(e){return zi(e)?(e.headers["accept-encoding"]="identity",!0):!1}function $i(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost").pathname;if(t.startsWith("/_next/")||t.startsWith(ke)||t===Te||t===on)return!1;let n=e.headers.accept??"";return n===""||n.includes("text/html")}function zi(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 Gi(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,u,c)=>(a!==void 0&&n.push(Zt(a,Lt(u))),en(u),en(c),!0),r.end=(a,u,c)=>{let f=typeof a=="function"?void 0:a;f!==void 0&&n.push(Zt(f,Lt(u))),r.write=o,r.end=s,r.flushHeaders=i;let d=Buffer.concat(n),g=Ji(e,d,t);g!==d&&!e.headersSent&&e.removeHeader("content-length");let y=typeof a=="function"?a:typeof u=="function"?u:typeof c=="function"?c:void 0;return y?s(g,y):s(g)},()=>{r.write=o,r.end=s,r.flushHeaders=i}}function Ji(e,t,n){if(Xi(e,t))return Buffer.from(Oi(t.toString("utf8"),n));if(n.patchNextDevChunk&&Qi(e)){let r=t.toString("utf8"),i=Zi(r);if(i!==r)return Buffer.from(i)}return t}function Yi(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function Xi(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 Qi(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 Zi(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}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(`
|
|
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])=>
|
|
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};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serializes the complete Bridge mutation boundary for one preview server.
|
|
3
|
+
*
|
|
4
|
+
* The queue deliberately covers assertion verification, durable-history session
|
|
5
|
+
* binding and the Engine mutation itself. Serializing only history-store open is
|
|
6
|
+
* insufficient because another session can replace/dispose the active runtime
|
|
7
|
+
* between bind and execute.
|
|
8
|
+
*/
|
|
9
|
+
export class SiteEditBridgeMutationQueue {
|
|
10
|
+
constructor() {
|
|
11
|
+
this.tail = Promise.resolve();
|
|
12
|
+
}
|
|
13
|
+
run(operation) {
|
|
14
|
+
const result = this.tail.then(operation, operation);
|
|
15
|
+
this.tail = result.then(() => undefined, () => undefined);
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import http, { type IncomingMessage, type Server as HttpServer } from "node:http";
|
|
1
|
+
import http, { type IncomingMessage, type Server as HttpServer, type RequestListener, type ServerResponse } from "node:http";
|
|
2
2
|
import type { Duplex } from "node:stream";
|
|
3
3
|
import type { SiteEditRuntimeVersions } from "./auto-bootstrap.js";
|
|
4
|
+
import { attachSiteEditBridgeServer, type SiteEditBridgeHealth } from "./server.js";
|
|
4
5
|
export type SiteEditNextDevServerOptions = {
|
|
5
6
|
basePath?: string;
|
|
6
7
|
bridgePath?: string;
|
|
@@ -13,13 +14,36 @@ export type SiteEditNextDevServerOptions = {
|
|
|
13
14
|
historyRoot?: string;
|
|
14
15
|
};
|
|
15
16
|
export type SiteEditNextDevBundler = "turbopack" | "webpack";
|
|
17
|
+
type NextDevApp = {
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
getRequestHandler(): (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
|
20
|
+
getUpgradeHandler(): (request: IncomingMessage, socket: Duplex, head: Buffer) => Promise<void>;
|
|
21
|
+
prepare(): Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
type SiteEditBridgeAttachment = {
|
|
24
|
+
getHealth(): SiteEditBridgeHealth;
|
|
25
|
+
stop(): void;
|
|
26
|
+
};
|
|
27
|
+
type SiteEditNextDevServerProcess = {
|
|
28
|
+
env: NodeJS.ProcessEnv;
|
|
29
|
+
off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
30
|
+
on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
31
|
+
};
|
|
32
|
+
export type SiteEditNextDevServerDependencies = {
|
|
33
|
+
attachBridgeServer?: (server: HttpServer, options: Parameters<typeof attachSiteEditBridgeServer>[1]) => SiteEditBridgeAttachment;
|
|
34
|
+
createServer?: (requestListener: RequestListener) => HttpServer;
|
|
35
|
+
loadNext?: (projectRoot: string) => Promise<(options: Record<string, unknown>) => NextDevApp>;
|
|
36
|
+
process?: SiteEditNextDevServerProcess;
|
|
37
|
+
};
|
|
16
38
|
type SiteEditClientAsset = {
|
|
17
39
|
path: string;
|
|
18
40
|
requiresTranspile: boolean;
|
|
19
41
|
};
|
|
20
|
-
export declare function startSiteEditNextDevServer(options?: SiteEditNextDevServerOptions): Promise<{
|
|
42
|
+
export declare function startSiteEditNextDevServer(options?: SiteEditNextDevServerOptions, dependencies?: SiteEditNextDevServerDependencies): Promise<{
|
|
21
43
|
bundler: SiteEditNextDevBundler;
|
|
22
|
-
close: () => void
|
|
44
|
+
close: () => Promise<void>;
|
|
45
|
+
host: string;
|
|
46
|
+
port: number;
|
|
23
47
|
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
24
48
|
}>;
|
|
25
49
|
export declare function resolveSiteEditNextDevBundler(projectRoot: string): SiteEditNextDevBundler;
|