@vcp-dev/site-edit-bridge 0.10.68 → 0.10.70

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/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
1
+ import type { SiteEditCommandSuccess, SiteEditClassNameSourceStyleContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditMutationContext, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
2
2
  import { type SiteEditBridgeInitializeInput, type SiteEditHistoryStatus, type SiteEditBridgeRequestKind } from "./protocol.js";
3
3
  export type { SiteEditHistoryStatus } from "./protocol.js";
4
4
  type SiteEditBridgeCompositionInput = SiteEditCompositionSelector;
@@ -43,8 +43,9 @@ export type SiteEditBridgeClient = {
43
43
  resolveSourceLocation(input: SiteEditResolveSourceLocationInput): Promise<SiteEditCommandSuccess<SiteEditSourceLocation>>;
44
44
  execute(request: SiteEditOperationRequest | Record<string, unknown>, mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
45
45
  getOperationResult?(request: SiteEditOperationRequest): Promise<SiteEditOperationCommandResult | null>;
46
- undo(composition: SiteEditBridgeCompositionInput, mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
47
- redo(composition: SiteEditBridgeCompositionInput, mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
46
+ getHistoryOperationResult?(request: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult | null>;
47
+ undo(composition: SiteEditBridgeCompositionInput, mutationContext?: SiteEditMutationContext, request?: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult>;
48
+ redo(composition: SiteEditBridgeCompositionInput, mutationContext?: SiteEditMutationContext, request?: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult>;
48
49
  subscribe(listener: (event: SiteEditEvent) => void): () => void;
49
50
  };
50
51
  export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
@@ -370,8 +371,9 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
370
371
  }>>;
371
372
  execute(request: SiteEditOperationRequest | Record<string, unknown>, _mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
372
373
  getOperationResult(request: SiteEditOperationRequest): Promise<SiteEditOperationCommandResult | null>;
373
- undo(composition: SiteEditBridgeCompositionInput, _mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
374
- redo(composition: SiteEditBridgeCompositionInput, _mutationContext?: SiteEditMutationContext): Promise<SiteEditOperationCommandResult>;
374
+ getHistoryOperationResult(request: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult | null>;
375
+ undo(composition: SiteEditBridgeCompositionInput, _mutationContext?: SiteEditMutationContext, request?: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult>;
376
+ redo(composition: SiteEditBridgeCompositionInput, _mutationContext?: SiteEditMutationContext, request?: SiteEditHistoryRequest): Promise<SiteEditOperationCommandResult>;
375
377
  subscribe(listener: (event: SiteEditEvent) => void): () => void;
376
378
  private selector;
377
379
  private request;
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- function A(n){if(!P(n)){if(n.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return n}let e=new Map,t=n.pageComposition.status==="supported"?n.pageComposition.placementUnitKeys:[],i=new Map(n.dynamicDataSummaries??[]),s=new Map(n.pageCompositionActionScopes??[]),r=c=>{let o=e.get(c);if(o)return o;let a=n.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,p=n.tokens[d];if(typeof p!="string")throw new Error(`Missing compact document token ${d}`);let C=`${u===null?"":r(u)}${p}`;return e.set(c,C),C};return{siteId:n.siteId,snapshotId:n.snapshotId,composition:{...n.composition},routeId:n.composition.routeId,version:n.version,pageComposition:n.pageComposition,entries:n.entries.map((c,o)=>{let[a,u,d]=c,p=d===void 0?void 0:t[d];if(d!==void 0&&!p)throw new Error(`Missing page composition unit ${d}`);let C=n.entryParentNodeIds?.[o],x=s.get(o),D=x?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:x.siblingEntryIndexes.map(R=>{let M=n.entries[R];if(!M)throw new Error(`Missing source sibling entry ${R}`);return r(M[0])})}:x;return{key:r(a),...n.entryParentNodeIds?{parentKey:C===null?null:r(C)}:{},...p?{pageCompositionUnitKey:p}:{},...D?{pageCompositionActionScope:D}:{},operationSummary:j(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function j(n){return{canUpdateText:(n&1)!==0,canInsertChild:(n&2)!==0,canMove:(n&4)!==0,canRemove:(n&8)!==0}}function P(n){if(typeof n!="object"||n===null)return!1;let e=n;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!$(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!E(e.pageComposition)||!Array.isArray(e.tokens)||!e.tokens.every(o=>typeof o=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let t=e.nodes;if(!t.every((o,a)=>Array.isArray(o)&&o.length===2&&(o[0]===null||m(o[0])&&o[0]<a)&&m(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&m(o[0])&&o[0]<t.length&&m(o[1])&&o[1]<=15&&(o.length===2||m(o[2]))))return!1;let i=e.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==e.entries.length||!i.every(o=>o===null||m(o)&&o<t.length)))return!1;let s=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(o=>{if(!Array.isArray(o)||o.length!==2||!m(o[0])||o[0]>=e.entries.length||!E(o[1])||!["route-unit","source-siblings","unavailable"].includes(String(o[1].kind)))return!1;let a=o[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>m(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(o[0])}))&&(s===void 0||Array.isArray(s)&&s.every(o=>Array.isArray(o)&&o.length===2&&m(o[0])&&o[0]<e.entries.length&&E(o[1])))}function E(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function $(n){return!E(n)||typeof n.routeId!="string"?!1:n.effectiveTemplateId===void 0||typeof n.effectiveTemplateId=="string"}function m(n){return typeof n=="number"&&Number.isInteger(n)&&n>=0}var f=class n{constructor(){}static parseMessage(e,t={}){let i=JSON.parse(e);if(!n.isMessage(i,t))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(h(e)&&h(e.payload)){let t=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:t,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="undo"||e==="redo"}static isMessage(e,t={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?W(e.payload,t):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?h(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&h(e.payload)&&e.payload.ok===!0}};function W(n,e){if(!h(n)||typeof n.id!="string"||!f.isRequestKind(n.kind))return!1;let t=T(n.composition);switch(n.kind){case"initialize-session":return t&&(n.mutationContext===void 0||w(n.mutationContext));case"get-document":case"get-style-context":return t;case"get-object-edit-context":return typeof n.key=="string"&&t&&L(n.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof n.key=="string"&&t;case"get-history-status":return t;case"get-source-tree":return t;case"get-source-file":return typeof n.path=="string"&&t;case"execute":case"get-operation-result":return t&&V(n.request)&&(n.request.mutationContext===void 0||w(n.request.mutationContext))&&(e.validateOperationRequest?.(n.request)??!0);case"undo":case"redo":return t&&n.mutationContext===void 0||t&&w(n.mutationContext)}}function L(n){if(n===void 0)return!0;if(!h(n)||typeof n.key!="string"||n.key.length===0)return!1;let e=n.instanceIndex,t=n.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<=0)||typeof e=="number"&&typeof t=="number"&&e>=t?!1:Object.keys(n).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function V(n){return h(n)&&typeof n.id=="string"&&typeof n.siteId=="string"&&typeof n.baseSnapshotId=="string"&&T(n.composition)&&typeof n.kind=="string"&&h(n.target)&&(n.target.kind!=="route"||T(n.target.composition))&&typeof n.documentVersion=="number"&&Number.isInteger(n.documentVersion)&&n.documentVersion>=0&&h(n.params)}function T(n){return h(n)&&typeof n.routeId=="string"&&n.routeId.length>0&&(n.templateId===void 0||typeof n.templateId=="string"&&n.templateId.length>0)&&Object.keys(n).every(e=>e==="routeId"||e==="templateId")}function h(n){return typeof n=="object"&&n!==null}function w(n){return h(n)&&typeof n.editingSessionId=="string"&&n.editingSessionId.length>0&&typeof n.lockId=="string"&&n.lockId.length>0&&typeof n.ownerId=="string"&&n.ownerId.length>0&&typeof n.leaseAssertion=="string"&&n.leaseAssertion.length>0}var G="vcp:designer:trace",z="designer_trace",v="__VCP_DESIGNER_TRACE__";var J=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function H(n=globalThis){let e=n;try{if(e.localStorage?.getItem(G)==="1")return!0}catch{}try{let t=e.location?.search??"";return new URLSearchParams(t).get(z)==="1"}catch{return!1}}function l(n,e={},t=globalThis){if(!H(t))return;let i={type:n,timestamp:Date.now(),payload:Q(e)},s=t,r=s[v]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[v]=r;let c=t.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(t.console,"[designer-trace]",i)}function Q(n){return k(n,0)}function k(n,e){if(e>4)return"[truncated]";if(Array.isArray(n))return n.map(i=>k(i,e+1));if(!n||typeof n!="object")return n;let t={};for(let[i,s]of Object.entries(n)){if(J.test(i)){t[i]="[redacted]";continue}t[i]=k(s,e+1)}return t}var O=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===_&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,t)=>{let i;try{i=this.createSocket(this.options.url)}catch(a){let u=y(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),t(u);return}let s={socket:i,settled:!1,reject:t};this.connectAttempt=s,this.socket=i;let r=Math.max(0,this.options.connectTimeoutMs??Z);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(l("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,N(ee,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==i||this.connectAttempt!==s||(s.settled=!0,clearTimeout(s.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(i),e())},o=(a,u)=>{this.cleanupSocket(i,a,u)};i.onopen=()=>{if(!(this.socket!==i||this.connectAttempt!==s)){if(this.options.authKey){try{i.send(f.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(y(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=y(a,"WebSocket failed");o(u,"failed")},i.onmessage=a=>{if(this.socket===i){if(this.noteInboundMessage(i),this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(a.data,i,s,()=>{c()});return}this.handleMessage(a.data)}},i.onclose=a=>{if(this.socket!==i)return;let u=this.intentionalClose,d=new Error(oe(a,{intentional:u}));o(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let t=this.selector(e);return this.request("get-document",{composition:t})}async initializeSession(e){let t=this.selector(e.composition);return await this.request("initialize-session",{composition:t,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let t=this.selector(e);return this.request("get-style-context",{composition:t})}getObjectEditContext(e,t,i){let s=this.selector(t);return this.request("get-object-edit-context",{key:e,composition:s,...i?{selectionRef:i}:{}})}getClassNameSource(e,t){let i=this.selector(t);return this.request("get-class-name-source",{key:e,composition:i})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,t){let i=b(e),s={...e,composition:g(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:g(b(e))})}undo(e,t){return this.request("undo",{composition:this.selector(e)})}redo(e,t){return this.request("redo",{composition:this.selector(e)})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return g(e)}request(e,t){let i=this.socket;if(!i||i.readyState!==_||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${i?.readyState??"none"})`));let s=`${e}-${this.sequence+=1}`,r=ue(s,e,t);return l("bridge.request",{id:s,kind:e,routeId:typeof t.routeId=="string"?t.routeId:null,key:typeof t.key=="string"?t.key:null,operationKind:K(t.request,"kind"),documentVersion:K(t.request,"documentVersion")}),new Promise((c,o)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(s);d&&(this.pending.delete(s),l("bridge.response",{id:s,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(s,{kind:e,timeout:u,resolve:d=>c(d),reject:o});try{i.send(f.stringifyMessage(r))}catch(d){let p=y(d,"WebSocket send failed");this.clearPendingRequest(s),o(p),this.cleanupSocket(i,p,"failed")}})}handleAuthHandshakeMessage(e,t,i,s){try{if(f.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=y(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(t,c,"failed")}}handleMessage(e){let t=f.parseMessage(e);if(t.type==="event"){for(let s of this.listeners)s(t.payload.event);return}if(t.type!=="response"&&t.type!=="error")return;let i=this.pending.get(t.payload.id);if(i){if(this.clearPendingRequest(t.payload.id),t.type==="error"){l("bridge.response",{id:t.payload.id,kind:i.kind,ok:!1});let s=new Error(t.payload.message);t.payload.code&&(s.code=t.payload.code),i.reject(s);return}l("bridge.response",{id:t.payload.id,kind:i.kind,ok:!0,resultVersion:re(t.payload.result)}),i.resolve(i.kind==="get-document"?{...t.payload.result,data:U(t.payload.result.data,t.payload.result.composition)}:i.kind==="initialize-session"?ce(t.payload.result):t.payload.result)}}rejectAll(e){for(let[t,i]of[...this.pending])this.clearPendingRequest(t),i.reject(e)}clearPendingRequest(e){let t=this.pending.get(e);t&&(t.timeout&&clearTimeout(t.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let t=this.options.requestTimeoutMsByKind?.[e];return typeof t=="number"?Math.max(0,t):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):se[e]??ie}cleanupSocket(e,t,i){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let s=this.connectAttempt;this.connectAttempt=null,clearTimeout(s.deadline),s.settled||(s.settled=!0,s.reject(t))}this.connectPromise=null,this.rejectAll(t),this.setConnectionState(i,t.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===Y||e.readyState===_)&&e.close()}catch{}}startHeartbeat(e){let t=this.options.heartbeat===void 0?X:this.options.heartbeat;if(!t||t.intervalMs<=0||t.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let i=this.options.visibility===void 0?ne():this.options.visibility,s=()=>i?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!s())){try{e.send(f.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,y(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(l("bridge.heartbeat-timeout",{timeoutMs:t.timeoutMs}),this.cleanupSocket(e,N(te,`Bridge heartbeat was not answered within ${t.timeoutMs}ms`),"failed")))},t.timeoutMs)}},o=()=>{s()?c():r()};i?.addEventListener("visibilitychange",o),this.heartbeatState={socket:e,interval:setInterval(c,t.intervalMs),deadline:null,unbindVisibility:()=>i?.removeEventListener("visibilitychange",o)}}stopHeartbeat(e){let t=this.heartbeatState;!t||t.socket!==e||(clearInterval(t.interval),t.deadline&&clearTimeout(t.deadline),t.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let t=this.heartbeatState;t?.socket===e&&t.deadline&&(clearTimeout(t.deadline),t.deadline=null)}setConnectionState(e,t){if(this.connectionState===e&&!t)return;this.connectionState=e;let i={state:e,...t?{message:t}:{}};this.options.onConnectionStatus?.(i);for(let s of this.connectionStatusListeners)s(i)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},Y=0,_=1,Z=1e4,X={intervalMs:2e4,timeoutMs:1e4},ee="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",te="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ne(){let n=globalThis.document;return n&&typeof n.visibilityState=="string"&&typeof n.addEventListener=="function"&&typeof n.removeEventListener=="function"?n:null}function N(n,e){let t=new Error(`${n}: ${e}`);return t.code=n,t}var ie=15e3,se={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,undo:2e4,redo:2e4};function y(n,e){return n instanceof Error?n:new Error(e)}function oe(n,e){return e.intentional?"WebSocket disconnected":n?.code===1008?n.reason?`Bridge session authentication failed: ${n.reason}`:"Bridge session authentication failed":n?.reason?`WebSocket closed: ${n.reason}`:typeof n?.code=="number"&&n.code!==1005?`WebSocket closed with code ${n.code}`:"WebSocket closed"}function K(n,e){if(!n||typeof n!="object")return null;let i=n[e];return typeof i=="string"||typeof i=="number"?i:null}function re(n){if(!n||typeof n!="object")return null;let e=n,t=e.data?.resultVersion??e.data?.version??null;return typeof t=="number"?t:null}function Ie(n){let e="composition"in n?g(n.composition):g({routeId:n.routeId});return new q({composition:e,initialDocument:n.initialDocument,client:n.client})}var q=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,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=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=g(e.composition);let t=e.initialDocument.composition.effectiveTemplateId;if(t!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==t))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!B(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let t=B(this.currentDocument)||this.snapshotIdentityStale;return(t||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(t?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let t=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let i=await this.params.client.initializeSession({...e,composition:t});return this.currentDocument=i.data.document,this.observedDocumentVersion=i.data.document.version,this.activeCompositionContext={...i.composition},this.rememberServerConfirmedComposition(i.composition),this.sessionInitialized=!0,this.clearObjectCaches(),i}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let t=this.requireBoundComposition(e),i=S(t),s=this.styleContextCache.get(i);if(s?.generation===this.styleGeneration)return{ok:!0,data:s.value};let r=this.styleContextInFlight.get(i);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,o=this.params.client.getStyleContext(t).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(i,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(i)?.request===o&&this.styleContextInFlight.delete(i)});return this.styleContextInFlight.set(i,{generation:c,request:o}),o}async ensureDocumentVersion(e,t){this.requireBoundComposition(e);let i=await this.refreshSnapshot(t,"ensure-version");if(i.version<t)throw new Error(`Document refresh returned version ${i.version}, expected at least ${t}`);return{ok:!0,data:i}}async acknowledgeDocumentVersion(e,t){if(this.requireBoundComposition(e),t>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let i=await this.refreshSnapshot(t,"ensure-version");if(i.version<t)throw new Error(`Document refresh returned version ${i.version}, expected at least ${t}`);return{ok:!0,data:i}}this.currentDocument={...this.currentDocument,version:t},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,t),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,t,i){let s=this.requireBoundComposition(t),r=this.objectCacheKey(e,s,i),c=this.editContextCache.get(r);if(c)return{ok:!0,data:c};let o=this.editContextInFlight.get(r);if(o)return o;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,s,...i?[i]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,t){let i=this.requireBoundComposition(t),s=this.objectCacheKey(e,i),r=this.classNameSourceCache.get(s);if(r)return r;let c=this.classNameSourceInFlight.get(s);if(c)return c;let o=this.objectGeneration,a=this.params.client.getClassNameSource(e,i).then(u=>(this.objectGeneration===o&&this.classNameSourceCache.set(s,u),u)).finally(()=>{this.classNameSourceInFlight.get(s)===a&&this.classNameSourceInFlight.delete(s)});return this.classNameSourceInFlight.set(s,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,t){let i=b(e);i&&this.composition.templateId!==void 0&&this.requireBoundComposition(i);let s={...e,composition:i??this.composition};return this.params.client.execute(s)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async undo(e,t){return this.params.client.undo(this.requireBoundComposition(e))}async redo(e,t){return this.params.client.redo(this.requireBoundComposition(e))}subscribe(e){return this.params.client.subscribe(t=>{if(t.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(t.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(t);return}if(t.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(t.composition)){let i=t.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,t.version),i&&t.version>this.currentDocument.version&&this.clearObjectCaches(),e(t);return}e(t)})}async refreshSnapshot(e,t="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return l("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:t}),this.currentDocument;let i=S(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){l("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:t});let c=await s.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}l("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:t});let r=this.params.client.getDocument(this.composition).then(c=>{let o=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&I(c.data.composition)===I(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),o||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:i,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,t,i){return`${S(t)}\0${e}\0${ae(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(S(e)===S(this.composition))return!0;let t=this.serverConfirmedComposition;return t!==null&&I(t)===I(F(e))}requireBoundComposition(e){let t=e===void 0?this.composition:g(e);if(!this.isAcceptedComposition(t))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(t)}`);return g(t)}isActiveComposition(e){let t=this.activeCompositionContext??F(this.composition);return I(e)===I(t)}};function B(n){return n.version===0&&n.entries.length===0}function ce(n){let e=n;return{...e,data:{...e.data,document:U(e.data.document,e.composition)}}}function U(n,e){let t=n,i=A(t.routeId?t:{...t,routeId:e?.routeId??t.composition?.routeId});return e?{...i,composition:e}:i}function g(n){if(n&&typeof n=="object"&&typeof n.routeId=="string"){let e="effectiveTemplateId"in n?n.effectiveTemplateId:"templateId"in n?n.templateId:void 0;return{routeId:n.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function S(n){return JSON.stringify([n.routeId,n.templateId??null])}function ae(n){return n?JSON.stringify([n.key,n.instanceIndex??null,n.instanceCount??null]):""}function I(n){return JSON.stringify([n.routeId,n.effectiveTemplateId??null])}function F(n){return{routeId:n.routeId,...n.templateId?{effectiveTemplateId:n.templateId}:{}}}function b(n){if(n&&typeof n=="object"){let e=n;if(e.composition&&typeof e.composition=="object"){let t=e.composition;if(typeof t.routeId=="string")return{routeId:t.routeId,...typeof t.templateId=="string"?{templateId:t.templateId}:{}}}}}function ue(n,e,t){let i=g(e==="execute"?b(t.request):t.composition),s={id:n,kind:e,composition:i};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...s,...t.mutationContext?{mutationContext:t.mutationContext}:{}}};case"get-object-edit-context":return{type:"request",payload:{...s,key:String(t.key),...t.selectionRef?{selectionRef:t.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...s,key:String(t.key)}};case"get-source-file":return{type:"request",payload:{...s,path:String(t.path)}};case"execute":case"get-operation-result":return{type:"request",payload:{...s,request:{...t.request,composition:b(t.request)??i}}}}}export{ee as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,te as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,O as SiteEditWebSocketClient,Ie as createSiteEditBridge};
1
+ function M(t){if(!$(t)){if(t.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return t}let e=new Map,n=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],i=new Map(t.dynamicDataSummaries??[]),s=new Map(t.pageCompositionActionScopes??[]),r=c=>{let o=e.get(c);if(o)return o;let a=t.nodes[c];if(!a)throw new Error(`Missing compact document node ${c}`);let[u,d]=a,l=t.tokens[d];if(typeof l!="string")throw new Error(`Missing compact document token ${d}`);let C=`${u===null?"":r(u)}${l}`;return e.set(c,C),C};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,entries:t.entries.map((c,o)=>{let[a,u,d]=c,l=d===void 0?void 0:n[d];if(d!==void 0&&!l)throw new Error(`Missing page composition unit ${d}`);let C=t.entryParentNodeIds?.[o],w=s.get(o),R=w?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:w.siblingEntryIndexes.map(D=>{let A=t.entries[D];if(!A)throw new Error(`Missing source sibling entry ${D}`);return r(A[0])})}:w;return{key:r(a),...t.entryParentNodeIds?{parentKey:C===null?null:r(C)}:{},...l?{pageCompositionUnitKey:l}:{},...R?{pageCompositionActionScope:R}:{},operationSummary:P(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function P(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function $(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.encoding!=="segment-trie-v1"||typeof e.siteId!="string"||typeof e.snapshotId!="string"||!W(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!E(e.pageComposition)||!Array.isArray(e.tokens)||!e.tokens.every(o=>typeof o=="string")||!Array.isArray(e.nodes)||!Array.isArray(e.entries))return!1;let n=e.nodes;if(!n.every((o,a)=>Array.isArray(o)&&o.length===2&&(o[0]===null||m(o[0])&&o[0]<a)&&m(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&m(o[0])&&o[0]<n.length&&m(o[1])&&o[1]<=15&&(o.length===2||m(o[2]))))return!1;let i=e.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==e.entries.length||!i.every(o=>o===null||m(o)&&o<n.length)))return!1;let s=e.dynamicDataSummaries,r=e.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(o=>{if(!Array.isArray(o)||o.length!==2||!m(o[0])||o[0]>=e.entries.length||!E(o[1])||!["route-unit","source-siblings","unavailable"].includes(String(o[1].kind)))return!1;let a=o[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(u=>m(u)&&u<e.entries.length)&&a.siblingEntryIndexes.includes(o[0])}))&&(s===void 0||Array.isArray(s)&&s.every(o=>Array.isArray(o)&&o.length===2&&m(o[0])&&o[0]<e.entries.length&&E(o[1])))}function E(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function W(t){return!E(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function m(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}var f=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(h(e)&&h(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!h(e)||typeof e.type!="string"?!1:e.type==="request"?L(e.payload,n):e.type==="response"||e.type==="error"?h(e.payload)&&typeof e.payload.id=="string":e.type==="event"?h(e.payload)&&h(e.payload.event):e.type==="auth"?h(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?h(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&h(e.payload)&&e.payload.ok===!0}};function L(t,e){if(!h(t)||typeof t.id!="string"||!f.isRequestKind(t.kind))return!1;let n=x(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||k(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&V(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&G(t.request)&&(t.request.mutationContext===void 0||k(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&O(t.request);case"undo":case"redo":return n&&(t.request===void 0||O(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||k(t.mutationContext))}}function O(t){return h(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&x(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function V(t){if(t===void 0)return!0;if(!h(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function G(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&x(t.composition)&&typeof t.kind=="string"&&h(t.target)&&(t.target.kind!=="route"||x(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function x(t){return h(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function h(t){return typeof t=="object"&&t!==null}function k(t){return h(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}var z="vcp:designer:trace",H="designer_trace",v="__VCP_DESIGNER_TRACE__";var J=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function Q(t=globalThis){let e=t;try{if(e.localStorage?.getItem(z)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(H)==="1"}catch{return!1}}function p(t,e={},n=globalThis){if(!Q(n))return;let i={type:t,timestamp:Date.now(),payload:Y(e)},s=n,r=s[v]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[v]=r;let c=n.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",i)}function Y(t){return T(t,0)}function T(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(i=>T(i,e+1));if(!t||typeof t!="object")return t;let n={};for(let[i,s]of Object.entries(t)){if(J.test(i)){n[i]="[redacted]";continue}n[i]=T(s,e+1)}return n}var N=class{constructor(e){this.options=e,this.socket=null,this.connectPromise=null,this.connectAttempt=null,this.connectionState="idle",this.intentionalClose=!1,this.sequence=0,this.pending=new Map,this.listeners=new Set,this.heartbeatState=null,this.connectionStatusListeners=new Set}connect(){return this.socket?.readyState===q&&this.connectionState==="open"?(this.setConnectionState("open"),Promise.resolve()):this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.setConnectionState("connecting"),this.connectPromise=new Promise((e,n)=>{let i;try{i=this.createSocket(this.options.url)}catch(a){let u=y(a,"WebSocket failed");this.socket=null,this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("failed",u.message),n(u);return}let s={socket:i,settled:!1,reject:n};this.connectAttempt=s,this.socket=i;let r=Math.max(0,this.options.connectTimeoutMs??X);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(p("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,K(te,`Bridge connection did not complete within ${r}ms`),"failed"))},r));let c=()=>{this.socket!==i||this.connectAttempt!==s||(s.settled=!0,clearTimeout(s.deadline),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("open"),this.startHeartbeat(i),e())},o=(a,u)=>{this.cleanupSocket(i,a,u)};i.onopen=()=>{if(!(this.socket!==i||this.connectAttempt!==s)){if(this.options.authKey){try{i.send(f.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(y(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=y(a,"WebSocket failed");o(u,"failed")},i.onmessage=a=>{if(this.socket===i){if(this.noteInboundMessage(i),this.options.authKey&&this.connectAttempt===s&&!s.settled){this.handleAuthHandshakeMessage(a.data,i,s,()=>{c()});return}this.handleMessage(a.data)}},i.onclose=a=>{if(this.socket!==i)return;let u=this.intentionalClose,d=new Error(re(a,{intentional:u}));o(d,u?"closed":"failed")}}),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.setConnectionState("closing");let e=this.socket;if(!e){this.rejectAll(new Error("WebSocket disconnected")),this.connectAttempt=null,this.connectPromise=null,this.setConnectionState("closed");return}this.cleanupSocket(e,new Error("WebSocket disconnected"),"closed")}getConnectionState(){return this.connectionState}subscribeConnectionStatus(e){return this.connectionStatusListeners.add(e),e({state:this.connectionState}),()=>{this.connectionStatusListeners.delete(e)}}getDocument(e){let n=this.selector(e);return this.request("get-document",{composition:n})}async initializeSession(e){let n=this.selector(e.composition);return await this.request("initialize-session",{composition:n,...e.mutationContext?{mutationContext:e.mutationContext}:{}})}getHistoryStatus(e){return this.request("get-history-status",{composition:this.selector(e)})}getStyleContext(e){let n=this.selector(e);return this.request("get-style-context",{composition:n})}getObjectEditContext(e,n,i){let s=this.selector(n);return this.request("get-object-edit-context",{key:e,composition:s,...i?{selectionRef:i}:{}})}getClassNameSource(e,n){let i=this.selector(n);return this.request("get-class-name-source",{key:e,composition:i})}getSourceTree(e){return this.request("get-source-tree",{composition:this.selector(e)})}getSourceFile(e){return this.request("get-source-file",{path:e.path,composition:this.selector(e.composition)})}resolveSourceLocation(e){return this.request("resolve-source-location",{key:e.key,composition:this.selector(e.composition)})}execute(e,n){let i=b(e),s={...e,composition:g(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:g(b(e))})}getHistoryOperationResult(e){return this.request("get-history-operation-result",{request:e,composition:e.composition})}undo(e,n,i){return this.request("undo",{composition:this.selector(e),...i?{request:i}:{}})}redo(e,n,i){return this.request("redo",{composition:this.selector(e),...i?{request:i}:{}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}selector(e){return g(e)}request(e,n){let i=this.socket;if(!i||i.readyState!==q||this.connectionState!=="open")return Promise.reject(new Error(`WebSocket is not open (state: ${this.connectionState}, readyState: ${i?.readyState??"none"})`));let s=`${e}-${this.sequence+=1}`,r=de(s,e,n);return p("bridge.request",{id:s,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:B(n.request,"kind"),documentVersion:B(n.request,"documentVersion")}),new Promise((c,o)=>{let a=this.resolveRequestTimeoutMs(e),u=a>0?setTimeout(()=>{let d=this.pending.get(s);d&&(this.pending.delete(s),p("bridge.response",{id:s,kind:e,ok:!1,timedOut:!0}),d.reject(new Error(`Bridge request timed out after ${a}ms: ${e}`)))},a):null;u?.unref?.(),this.pending.set(s,{kind:e,timeout:u,resolve:d=>c(d),reject:o});try{i.send(f.stringifyMessage(r))}catch(d){let l=y(d,"WebSocket send failed");this.clearPendingRequest(s),o(l),this.cleanupSocket(i,l,"failed")}})}handleAuthHandshakeMessage(e,n,i,s){try{if(f.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=y(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=f.parseMessage(e);if(n.type==="event"){for(let s of this.listeners)s(n.payload.event);return}if(n.type!=="response"&&n.type!=="error")return;let i=this.pending.get(n.payload.id);if(i){if(this.clearPendingRequest(n.payload.id),n.type==="error"){p("bridge.response",{id:n.payload.id,kind:i.kind,ok:!1});let s=new Error(n.payload.message);n.payload.code&&(s.code=n.payload.code),i.reject(s);return}p("bridge.response",{id:n.payload.id,kind:i.kind,ok:!0,resultVersion:ce(n.payload.result)}),i.resolve(i.kind==="get-document"?{...n.payload.result,data:U(n.payload.result.data,n.payload.result.composition)}:i.kind==="initialize-session"?ae(n.payload.result):n.payload.result)}}rejectAll(e){for(let[n,i]of[...this.pending])this.clearPendingRequest(n),i.reject(e)}clearPendingRequest(e){let n=this.pending.get(e);n&&(n.timeout&&clearTimeout(n.timeout),this.pending.delete(e))}resolveRequestTimeoutMs(e){let n=this.options.requestTimeoutMsByKind?.[e];return typeof n=="number"?Math.max(0,n):typeof this.options.requestTimeoutMs=="number"?Math.max(0,this.options.requestTimeoutMs):oe[e]??se}cleanupSocket(e,n,i){if(this.socket===e&&(this.socket=null),this.stopHeartbeat(e),this.connectAttempt?.socket===e){let s=this.connectAttempt;this.connectAttempt=null,clearTimeout(s.deadline),s.settled||(s.settled=!0,s.reject(n))}this.connectPromise=null,this.rejectAll(n),this.setConnectionState(i,n.message),e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{(e.readyState===Z||e.readyState===q)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?ee:this.options.heartbeat;if(!n||n.intervalMs<=0||n.timeoutMs<=0)return;this.stopHeartbeat(this.heartbeatState?.socket??e);let i=this.options.visibility===void 0?ie():this.options.visibility,s=()=>i?.visibilityState!=="hidden",r=()=>{this.heartbeatState?.socket===e&&this.heartbeatState.deadline&&(clearTimeout(this.heartbeatState.deadline),this.heartbeatState.deadline=null)},c=()=>{let a=this.heartbeatState;if(!(a?.socket!==e||this.socket!==e||this.connectionState!=="open"||a.deadline||!s())){try{e.send(f.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,y(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(p("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,K(ne,`Bridge heartbeat was not answered within ${n.timeoutMs}ms`),"failed")))},n.timeoutMs)}},o=()=>{s()?c():r()};i?.addEventListener("visibilitychange",o),this.heartbeatState={socket:e,interval:setInterval(c,n.intervalMs),deadline:null,unbindVisibility:()=>i?.removeEventListener("visibilitychange",o)}}stopHeartbeat(e){let n=this.heartbeatState;!n||n.socket!==e||(clearInterval(n.interval),n.deadline&&clearTimeout(n.deadline),n.unbindVisibility(),this.heartbeatState=null)}noteInboundMessage(e){let n=this.heartbeatState;n?.socket===e&&n.deadline&&(clearTimeout(n.deadline),n.deadline=null)}setConnectionState(e,n){if(this.connectionState===e&&!n)return;this.connectionState=e;let i={state:e,...n?{message:n}:{}};this.options.onConnectionStatus?.(i);for(let s of this.connectionStatusListeners)s(i)}createSocket(e){if(this.options.createSocket)return this.options.createSocket(e);if(typeof WebSocket>"u")throw new Error("Site edit preview bridge requires WebSocket");return new WebSocket(e)}},Z=0,q=1,X=1e4,ee={intervalMs:2e4,timeoutMs:1e4},te="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",ne="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ie(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function K(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var se=15e3,oe={"get-source-tree":1e4,"get-source-file":1e4,"resolve-source-location":1e4,execute:6e4,"get-operation-result":6e4,"get-history-operation-result":6e4,undo:2e4,redo:2e4};function y(t,e){return t instanceof Error?t:new Error(e)}function re(t,e){return e.intentional?"WebSocket disconnected":t?.code===1008?t.reason?`Bridge session authentication failed: ${t.reason}`:"Bridge session authentication failed":t?.reason?`WebSocket closed: ${t.reason}`:typeof t?.code=="number"&&t.code!==1005?`WebSocket closed with code ${t.code}`:"WebSocket closed"}function B(t,e){if(!t||typeof t!="object")return null;let i=t[e];return typeof i=="string"||typeof i=="number"?i:null}function ce(t){if(!t||typeof t!="object")return null;let e=t,n=e.data?.resultVersion??e.data?.version??null;return typeof n=="number"?n:null}function Ce(t){let e="composition"in t?g(t.composition):g({routeId:t.routeId});return new _({composition:e,initialDocument:t.initialDocument,client:t.client})}var _=class{constructor(e){this.params=e,this.serverConfirmedComposition=null,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=new Map,this.styleContextInFlight=new Map,this.snapshotIdentityStale=!1,this.composition=g(e.composition);let n=e.initialDocument.composition.effectiveTemplateId;if(n!==void 0&&(this.composition.templateId===void 0||this.composition.templateId!==n))throw new Error(`Site edit bridge requires a matching templateId for initial document composition ${JSON.stringify(e.initialDocument.composition)}`);this.currentDocument=e.initialDocument,this.observedDocumentVersion=e.initialDocument.version,this.sessionInitialized=!F(e.initialDocument),this.activeCompositionContext=this.sessionInitialized?{...e.initialDocument.composition}:null}async getDocument(e){this.requireBoundComposition(e);let n=F(this.currentDocument)||this.snapshotIdentityStale;return(n||this.currentDocument.version<this.observedDocumentVersion)&&(this.currentDocument=await this.refreshSnapshot(n?void 0:this.observedDocumentVersion,"get-document"),this.snapshotIdentityStale=!1,this.sessionInitialized=!0),{ok:!0,data:this.currentDocument}}async initializeSession(e){let n=this.requireBoundComposition(e.composition);if(!this.params.client.initializeSession)throw new Error("Site edit bridge client does not support initialize-session");let i=await this.params.client.initializeSession({...e,composition:n});return this.currentDocument=i.data.document,this.observedDocumentVersion=i.data.document.version,this.activeCompositionContext={...i.composition},this.rememberServerConfirmedComposition(i.composition),this.sessionInitialized=!0,this.clearObjectCaches(),i}async getHistoryStatus(e){return this.params.client.getHistoryStatus(this.requireBoundComposition(e))}async getStyleContext(e){let n=this.requireBoundComposition(e),i=S(n),s=this.styleContextCache.get(i);if(s?.generation===this.styleGeneration)return{ok:!0,data:s.value};let r=this.styleContextInFlight.get(i);if(r?.generation===this.styleGeneration)return r.request;let c=this.styleGeneration,o=this.params.client.getStyleContext(n).then(a=>(this.styleGeneration===c&&this.styleContextCache.set(i,{generation:c,value:a.data}),a)).finally(()=>{this.styleContextInFlight.get(i)?.request===o&&this.styleContextInFlight.delete(i)});return this.styleContextInFlight.set(i,{generation:c,request:o}),o}async ensureDocumentVersion(e,n){this.requireBoundComposition(e);let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}async acknowledgeDocumentVersion(e,n){if(this.requireBoundComposition(e),n>this.currentDocument.version){if(this.currentDocument.pageComposition.status==="supported"){let i=await this.refreshSnapshot(n,"ensure-version");if(i.version<n)throw new Error(`Document refresh returned version ${i.version}, expected at least ${n}`);return{ok:!0,data:i}}this.currentDocument={...this.currentDocument,version:n},this.clearObjectCaches({preserveStyleContext:!0})}return this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n),{ok:!0,data:this.currentDocument}}async getObjectEditContext(e,n,i){let s=this.requireBoundComposition(n),r=this.objectCacheKey(e,s,i),c=this.editContextCache.get(r);if(c)return{ok:!0,data:c};let o=this.editContextInFlight.get(r);if(o)return o;let a=this.objectGeneration,u=this.params.client.getObjectEditContext(e,s,...i?[i]:[]).then(d=>(this.objectGeneration===a&&this.editContextCache.set(r,d.data),d)).finally(()=>{this.editContextInFlight.get(r)===u&&this.editContextInFlight.delete(r)});return this.editContextInFlight.set(r,u),u}async getClassNameSource(e,n){let i=this.requireBoundComposition(n),s=this.objectCacheKey(e,i),r=this.classNameSourceCache.get(s);if(r)return r;let c=this.classNameSourceInFlight.get(s);if(c)return c;let o=this.objectGeneration,a=this.params.client.getClassNameSource(e,i).then(u=>(this.objectGeneration===o&&this.classNameSourceCache.set(s,u),u)).finally(()=>{this.classNameSourceInFlight.get(s)===a&&this.classNameSourceInFlight.delete(s)});return this.classNameSourceInFlight.set(s,a),a}async getSourceTree(e){return this.params.client.getSourceTree(this.requireBoundComposition(e))}async getSourceFile(e){return this.params.client.getSourceFile({path:e.path,composition:this.requireBoundComposition(e.composition)})}async resolveSourceLocation(e){return this.params.client.resolveSourceLocation({key:e.key,composition:this.requireBoundComposition(e.composition)})}async execute(e,n){let i=b(e);i&&this.composition.templateId!==void 0&&this.requireBoundComposition(i);let s={...e,composition:i??this.composition};return this.params.client.execute(s)}async getOperationResult(e){return this.requireBoundComposition(e.composition),this.params.client.getOperationResult?this.params.client.getOperationResult(e):null}async getHistoryOperationResult(e){return this.requireBoundComposition(e.composition),await this.params.client.getHistoryOperationResult?.(e)??null}async undo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.undo(s,void 0,i):this.params.client.undo(s)}async redo(e,n,i){let s=this.requireBoundComposition(e);return i?this.params.client.redo(s,void 0,i):this.params.client.redo(s)}subscribe(e){return this.params.client.subscribe(n=>{if(n.type==="site-edit.snapshot.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){this.snapshotIdentityStale=!0,this.clearObjectCaches(),e(n);return}if(n.type==="site-edit.document.changed"&&this.sessionInitialized&&this.isActiveComposition(n.composition)){let i=n.version>this.observedDocumentVersion;this.observedDocumentVersion=Math.max(this.observedDocumentVersion,n.version),i&&n.version>this.currentDocument.version&&this.clearObjectCaches(),e(n);return}e(n)})}async refreshSnapshot(e,n="ensure-version"){if(typeof e=="number"&&this.currentDocument.version>=e)return p("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,skipped:!0,source:n}),this.currentDocument;let i=S(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){p("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!0,source:n});let c=await s.request;if(typeof e!="number"||c.version>=e||this.currentDocument.version>=e)return this.currentDocument}p("bridge.document-refresh",{composition:this.composition,routeId:this.composition.routeId,minVersion:e,currentVersion:this.currentDocument.version,deduped:!1,source:n});let r=this.params.client.getDocument(this.composition).then(c=>{let o=!this.snapshotIdentityStale&&c.data.snapshotId===this.currentDocument.snapshotId&&I(c.data.composition)===I(this.currentDocument.composition)&&c.data.version>this.currentDocument.version&&c.data.version===this.observedDocumentVersion;return this.currentDocument=c.data,this.activeCompositionContext={...c.data.composition},this.rememberServerConfirmedComposition(c.data.composition),this.observedDocumentVersion=Math.max(this.observedDocumentVersion,c.data.version),o||this.clearObjectCaches(),this.currentDocument});this.refreshInFlight={compositionKey:i,request:r};try{return await r}finally{this.refreshInFlight?.request===r&&(this.refreshInFlight=null)}}clearObjectCaches(e){this.objectGeneration+=1,this.editContextCache.clear(),this.editContextInFlight.clear(),this.classNameSourceCache.clear(),this.classNameSourceInFlight.clear(),!e?.preserveStyleContext&&(this.styleGeneration+=1,this.styleContextCache.clear(),this.styleContextInFlight.clear())}objectCacheKey(e,n,i){return`${S(n)}\0${e}\0${ue(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(S(e)===S(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&I(n)===I(j(e))}requireBoundComposition(e){let n=e===void 0?this.composition:g(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return g(n)}isActiveComposition(e){let n=this.activeCompositionContext??j(this.composition);return I(e)===I(n)}};function F(t){return t.version===0&&t.entries.length===0}function ae(t){let e=t;return{...e,data:{...e.data,document:U(e.data.document,e.composition)}}}function U(t,e){let n=t,i=M(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...i,composition:e}:i}function g(t){if(t&&typeof t=="object"&&typeof t.routeId=="string"){let e="effectiveTemplateId"in t?t.effectiveTemplateId:"templateId"in t?t.templateId:void 0;return{routeId:t.routeId,...typeof e=="string"?{templateId:e}:{}}}throw new Error("SITE_EDIT_COMPOSITION_SESSION_REQUIRED: a composition selector is required")}function S(t){return JSON.stringify([t.routeId,t.templateId??null])}function ue(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function I(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function j(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function b(t){if(t&&typeof t=="object"){let e=t;if(e.composition&&typeof e.composition=="object"){let n=e.composition;if(typeof n.routeId=="string")return{routeId:n.routeId,...typeof n.templateId=="string"?{templateId:n.templateId}:{}}}}}function de(t,e,n){let i=g(e==="execute"?b(n.request):n.composition),s={id:t,kind:e,composition:i};switch(e){case"initialize-session":case"get-document":case"get-history-status":case"get-style-context":case"get-source-tree":case"undo":case"redo":return{type:"request",payload:{...s,...n.mutationContext?{mutationContext:n.mutationContext}:{},...(e==="undo"||e==="redo")&&n.request?{request:n.request}:{}}};case"get-object-edit-context":return{type:"request",payload:{...s,key:String(n.key),...n.selectionRef?{selectionRef:n.selectionRef}:{}}};case"get-class-name-source":case"resolve-source-location":return{type:"request",payload:{...s,key:String(n.key)}};case"get-source-file":return{type:"request",payload:{...s,path:String(n.path)}};case"execute":case"get-operation-result":case"get-history-operation-result":return{type:"request",payload:{...s,request:{...n.request,composition:b(n.request)??i}}}}}export{te as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,ne as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,N as SiteEditWebSocketClient,Ce as createSiteEditBridge};
@@ -14,6 +14,7 @@ export const SITE_EDIT_ENGINE_WORKER_METHODS = [
14
14
  "resolveSourceLocation",
15
15
  "execute",
16
16
  "getOperationResult",
17
+ "getHistoryOperationResult",
17
18
  "undo",
18
19
  "redo",
19
20
  ];
@@ -1,4 +1,4 @@
1
- import{parentPort as nt,workerData as it}from"node:worker_threads";function H(t){let e=t&&typeof t=="object"?t:null,n=typeof e?.message=="string"&&e.message.length>0?e.message:String(t);return{name:typeof e?.name=="string"?e.name:"Error",message:n,...typeof e?.code=="string"&&e.code.length>0?{code:e.code}:{}}}import oe from"node:http";import _ from"node:fs";import{createHash as J,randomBytes as be,timingSafeEqual as xe}from"node:crypto";import m from"node:path";import{WebSocket as re,WebSocketServer as ke}from"ws";import{createPreviewSiteEditEngineRuntime as ve,openFileHistoryStore as _e,resolveManagedPageTemplateComposition as Te,scanSiteEditCompositionsFromFiles as Oe}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Ae,scanNextAppRouterRoutesFromFiles as Me}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as He}from"@vcp-dev/site-edit-engine/source-watcher";function Y(t){let e=new Map,n=[],i=new Map,s=[],o=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(o.map((c,p)=>[c,p])),a=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(c=>({placementKey:c.placementKey,placementUnitKey:c.placementUnitKey,relation:c.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},h=t.entries.flatMap((c,p)=>c.dynamicDataSummary?[[p,c.dynamicDataSummary]]:[]),d=new Map(t.entries.map((c,p)=>[c.key,p])),l=[];for(let[c,p]of t.entries.entries()){let g=p.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([c,{kind:g.kind}]);continue}let O=g.siblingKeys.map(x=>{let k=d.get(x);if(k===void 0)throw new Error("Render entry "+p.key+" references missing source sibling "+x);return k});l.push([c,{kind:"source-siblings",siblingEntryIndexes:O}])}let S=c=>{let p=e.get(c);if(typeof p=="number")return p;let g=n.length;return n.push(c),e.set(c,g),g},Q=c=>{let p=null;for(let g of le(c)){let O=`${p??"root"}\0${g}`,x=i.get(O);if(typeof x=="number"){p=x;continue}let k=s.length;s.push([p,S(g)]),i.set(O,k),p=k}if(p===null)throw new Error("Document key must not be empty");return p};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:a,tokens:n,nodes:s,entries:t.entries.map(c=>{let p=c.pageCompositionUnitKey?r.get(c.pageCompositionUnitKey)??-1:-1;if(c.pageCompositionUnitKey&&p<0)throw new Error(`Render entry ${c.key} references unknown page composition unit ${c.pageCompositionUnitKey}`);return[Q(c.key),pe(c.operationSummary),...p>=0?[p]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...t.entries.every(c=>c.parentKey!==void 0)?{entryParentNodeIds:t.entries.map(c=>c.parentKey===null?null:Q(c.parentKey))}:{},...h.length>0?{dynamicDataSummaries:h}:{}}}function pe(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function le(t){if(!t)return[];let e=[],n=0,i=G(t,n);if(i<0)return e.push(t),e;for(e.push(t.slice(0,i)),n=i;n<t.length;){if(i=G(t,n+(t.startsWith("::",n)?2:1)),i<0){e.push(t.slice(n));break}e.push(t.slice(n,i)),n=i}return e}function G(t,e){let n=t.indexOf("/",e),i=t.indexOf("::",e);return n<0?i:i<0?n:Math.min(n,i)}var Z="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",P="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var f=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(u(e)&&u(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!u(e)||typeof e.type!="string"?!1:e.type==="request"?me(e.payload,n):e.type==="response"||e.type==="error"?u(e.payload)&&typeof e.payload.id=="string":e.type==="event"?u(e.payload)&&u(e.payload.event):e.type==="auth"?u(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?u(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&u(e.payload)&&e.payload.ok===!0}},A=class{constructor(e){this.options=e,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new B,this.eventDispatcher=new V(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.handleEngineEvent(n)}),e.socket.onmessage=n=>{let i=fe(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(s){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:s instanceof Error?s.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let i=n.payload,{id:s}=i;switch(i.kind){case"initialize-session":{let o=D(i),r=await this.resolve(o),a=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:s,kind:i.kind,result:I({...a,data:{...a.data,document:ee(a.data.document)}},r.context)}});return}case"get-document":{let o=await this.resolveWireContext(i),r=await this.options.engine.getDocument(o);this.sendResult(s,i.kind,Ee(r,o));return}case"get-history-status":{let o=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(o);this.sendResult(s,i.kind,I(r,o));return}case"get-style-context":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,I(await this.options.engine.getStyleContext(o),o));return}case"get-object-edit-context":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,I(await this.options.engine.getObjectEditContext(i.key,o,i.selectionRef),o));return}case"get-class-name-source":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,I(await this.options.engine.getClassNameSource(i.key,o),o));return}case"get-source-tree":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,I(await this.options.engine.getSourceTree(o),o));return}case"get-source-file":{let o=await this.resolveWireContext(i);this.sendResult(s,i.kind,I(await this.options.engine.getSourceFile({path:i.path,composition:o}),o));return}case"resolve-source-location":{let o=await this.resolveWireContext(i),r=I(await this.options.engine.resolveSourceLocation({key:i.key,composition:o}),o);this.sendResult(s,i.kind,r);return}case"execute":case"get-operation-result":{let o=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(w(o)!==w(r))throw new C(Z,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(i.request,o);if(i.kind==="get-operation-result"){this.sendResult(s,i.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(s,i.kind,()=>this.options.engine.execute(a));return}case"undo":case"redo":{let o=await this.resolveWireContext(i);await this.handleBufferedOperation(s,i.kind,()=>i.kind==="undo"?this.options.engine.undo(o):this.options.engine.redo(o));return}}}catch(n){let i=f.extractRequestInfo(e);this.sendJson({type:"error",payload:{...i,message:K(n),code:F(n)}})}}async resolve(e){return this.options.engine.resolveComposition(e)}async resolveAndAssert(e){let n=await this.resolve(e),i=this.session.activeComposition;if(!i)throw new C(P,"Initialize a composition session before issuing this request.");if(w(i)!==w(n.context))throw new C(Z,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(e){let n=D(e);return this.resolveAndAssert(n)}async resolveOperationWireContext(e){let n=we(e);return this.resolveAndAssert(n)}activateSession(e){this.session.activeComposition=e,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(w(e))}async normalizeOperationRequest(e,n){let i={...e,composition:X(n)};if(i.target.kind==="route"){let s=i.target,o=D(s),r=await this.resolveAndAssert(o);i.target={...s,composition:X(r)}}return i}handleEngineEvent(e){let n=e?.composition;if(!Se(n))return;let i=w(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(e),e.type==="site-edit.graph.invalidated"&&i===Ce(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(e,n,i){this.sendJson({type:"response",payload:{id:e,kind:n,result:i}})}async handleRawMessage(e){try{await this.handleMessage(f.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=Re(e);this.sendJson({type:"error",payload:{...i,message:K(n),code:F(n)}})}}sendJson(e){this.options.socket.send(f.stringifyMessage(e))}async handleBufferedOperation(e,n,i){this.eventDispatcher.beginBuffering();try{let s=await i();this.sendResult(e,n,s)}catch(s){this.sendJson({type:"error",payload:{id:e,kind:n,message:K(s),code:F(s)}})}finally{this.eventDispatcher.flush()}}},ge=256;function fe(t){if(t.length>ge||!t.includes('"ping"'))return null;try{let e=JSON.parse(t);return u(e)&&e.type==="ping"&&u(e.payload)&&typeof e.payload.id=="string"?e.payload.id:null}catch{return null}}var C=class extends Error{constructor(e,n){super(n),this.code=e,this.name="BridgeProtocolError"}},V=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>this.send(n))}},B=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function me(t,e){if(!u(t)||typeof t.id!="string"||!f.isRequestKind(t.kind))return!1;let n=v(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||N(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&ye(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&Ie(t.request)&&(t.request.mutationContext===void 0||N(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"undo":case"redo":return n&&t.mutationContext===void 0||n&&N(t.mutationContext)}}function ye(t){if(t===void 0)return!0;if(!u(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function Ie(t){return u(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&v(t.composition)&&typeof t.kind=="string"&&u(t.target)&&(t.target.kind!=="route"||v(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&u(t.params)}function v(t){return u(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function Se(t){return u(t)&&typeof t.routeId=="string"&&(t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string")}function D(t){if(v(t.composition))return t.composition;throw new C(P,"A composition selector is required for this request.")}function we(t){if(u(t)&&v(t.composition))return t.composition;throw new C(P,"A composition selector is required for execute.")}function X(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function Ce(t){return t.activeComposition?w(t.activeComposition):null}function w(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function I(t,e){return u(t)&&t.ok===!0?{...t,composition:e}:t}function Ee(t,e){return!u(t)||t.ok!==!0?t:{...t,...e?{composition:e}:{},data:ee(t.data)}}function ee(t){let e=t;return Y(e.routeId?e:{...e,routeId:e.composition.routeId})}function u(t){return typeof t=="object"&&t!==null}function N(t){return u(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}function F(t){if(!(!u(t)||typeof t.code!="string"||t.code.length===0))return t.code}function K(t){return t instanceof Error||u(t)&&typeof t.message=="string"&&t.message.length>0?t.message:"Unknown websocket operation failure"}function Re(t){try{return f.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var M=class{constructor(){this.tail=Promise.resolve()}run(e){let n=this.tail.then(e,e);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as De,computeSiteEditCompositionKey as E}from"@vcp-dev/contracts";var Ne="127.0.0.1",Fe=30218,Ke="/__vcp/site-edit/bridge",ae=6*1024*1024,Ve=ae*2,Be=3e3,te=50,q=".vcp/current-snapshot.json",ne="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var j=class{constructor(e,n=oe.createServer((o,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,s={}){this.options=e,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=s,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new M,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(e={}){if(!this.isStarted){this.stopping=!1;try{_.mkdirSync(m.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let n=Le({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new He({projectRoot:this.options.projectRoot,watch_dirs:We(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??te,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,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.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=$e(),n=ze(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{e(n)}catch(s){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${s instanceof Error?s.message:String(s)}`)}}}createRuntime(e,n=null){let i=this.runtime;this.activeHistoryStore=e??null;let s=(this.dependencies.createRuntime??ve)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version,"composition"in o?o.composition:void 0);for(let r of this.eventListeners)r(o)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=s,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=qe(e.composition),s=this.getRuntime(),o=y(i);await s.initializeComposition(o);let a=s.getDocument(o).data;await this.recordRuntimeVersion(a.version,i);let h=(await s.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:h}}}),getDocument:async e=>{let n=this.getRuntime(),i=y(e);await n.initializeComposition(i);let s=n.getDocument(i);return await this.recordRuntimeVersion(s.data.version,e),{...s,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(y(e)),getObjectEditContext:async(e,n,i)=>this.getRuntime().getObjectEditContext(e,y(n),i),getClassNameSource:async(e,n)=>this.getRuntime().getClassNameSource(e,y(n)),getSourceTree:async e=>this.getRuntime().getSourceTree(y(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:y(e.composition)}),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:y(e.composition)}),execute:(e,n)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return W(i,e);let s=await this.getRuntime().executeOperation(e);return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion,s.composition),s})),getOperationResult:e=>{if(e.siteId!==this.options.siteId||e.baseSnapshotId!==this.options.snapshotId)return null;let n=this.operationReceipts.get(this.operationReceiptKey(e));return n?.fingerprint===this.operationFingerprint(e)?n.result:null},undo:e=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return W(n,void 0,e);let i=await this.getRuntime().undo();return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion,i.composition??e),i.composition?i:{...i,composition:e}}),redo:e=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return W(n,void 0,e);let i=await this.getRuntime().redo();return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion,i.composition??e),i.composition?i:{...i,composition:e}}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}operationReceiptKey(e){return JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return J("sha256").update(JSON.stringify(e)).digest("hex")}executeWithReceipt(e,n){if(e.siteId!==this.options.siteId||e.baseSnapshotId!==this.options.snapshotId)return n();let i=this.operationReceiptKey(e),s=this.operationFingerprint(e),o=this.operationReceipts.get(i);if(o)return o.fingerprint!==s?Promise.reject(new Error("Operation ID was reused with a different request.")):o.result;let r={fingerprint:s,result:n(),settled:!1};return this.operationReceipts.set(i,r),r.result.then(()=>{r.settled=!0;for(let[a,h]of this.operationReceipts){if(this.operationReceipts.size<=256)break;h.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let i=await(this.dependencies.openHistoryStore??_e)(je({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let s=i.readDocumentVersion?await i.readDocumentVersion():0,o=this.versionCheckpoints.get(i);o?o.durableVersion=Math.max(o.durableVersion,s):this.versionCheckpoints.set(i,{durableVersion:s,requestedVersion:s,pending:null});let r=this.compositions[0]?.context;if(r){let a=E(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,s))}this.createRuntime(i,e)});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(e,n){let i=n?E(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,e));let s=this.activeHistoryStore;if(!s?.writeDocumentVersion)return Promise.resolve();let o=i?this.runtimeVersionFloors.get(i)??e:e,r=this.versionCheckpoints.get(s);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(s,r)),o<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,o),r.pending)return r.pending;let a=r,h=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await s.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=h,this.versionPersistence=h,h}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let i of e)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??te;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((s,o)=>s.localeCompare(o));this.pendingChangedFiles.clear();let n=e.some(he)?this.scheduleSnapshotIdentityAdvance():!1,i=e.filter(s=>!tt(s));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let s of i)this.runtime?.notifyFileChanged(s)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=_.readFileSync(m.join(this.options.projectRoot,q),"utf8"),n=JSON.parse(e),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||$(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let s=await this.bindHistorySession(e);if(!s.ok)throw new Error(`${s.code}: ${s.message}`)}else this.createRuntime()}catch(s){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${s instanceof Error?s.message:String(s)}`);return}let i=new Date().toISOString();for(let s of this.compositions){let o={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:s.context,snapshotId:e,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(o)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,n)}catch(s){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${s instanceof Error?s.message:String(s)}`)}}refreshCompositions(e=!1){try{let n=Ue(this.options.projectRoot),i=Me(n),s=i.length>0?i:(this.options.runtime.routes??[]).map(d=>({...d})),o=Oe({files:n});if(o.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(o.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[E(d.context),d])),h=new Map(o.map(d=>[E(d.context),d]));if(this.runtime){for(let[d,l]of a){let S=h.get(d);(!S||S.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(y(l.context))}for(let[d,l]of h){let S=a.get(d);(!S||S.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=s,this.compositions=o,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,e)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Ae(e.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let s=Te({selector:{routeId:n,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),o=E(s.context);if(!this.compositions.some(r=>E(r.context)===o))throw new Error(`Composition is not registered by the preview bridge: ${o}`);return s}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let n=this.runtimeVersionFloors.get(E(e.context));return n===void 0?[]:[{composition:e.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function ce(t){let e=new j(Pe(t),oe.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function Pe(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:m.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??Ne,port:t.port??Fe,path:t.path??Ke,sessionKey:t.sessionKey??et(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function We(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function Ue(t){let e=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),s=o=>{if(!_.existsSync(o))return;let r;try{r=_.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(i.has(a.name))continue;s(m.join(o,a.name));continue}if(!a.isFile())continue;let h=m.join(o,a.name),d="";try{d=_.readFileSync(h,"utf8")}catch{}e.push({path:m.relative(t,h).replaceAll(m.sep,"/"),content:d})}};for(let o of n)s(m.join(t,o));return e.sort((o,r)=>o.path.localeCompare(r.path))}function qe(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function y(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function je(t){return m.join(m.resolve(t.root),$(t.siteId),$(t.snapshotId),J("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function $(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:J("sha256").update(t).digest("hex").slice(0,32)}function $e(){let t=globalThis;return t[ne]??=new Map,t[ne]}function ze(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function W(t,e,n){let i=n??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:i,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Le(t){let e=new ke({maxPayload:ae,noServer:!0}),n=new WeakSet,i=o=>{new A({socket:new z(o),engine:t.engine,validateOperationRequest:r=>De.safeParse(r).success})},s=(o,r,a)=>{if(!Je(o,t))return;let h=Qe(o,t);if(!h){r.write(`HTTP/1.1 401 Unauthorized\r
1
+ import{parentPort as it,workerData as st}from"node:worker_threads";function N(t){let e=t&&typeof t=="object"?t:null,n=typeof e?.message=="string"&&e.message.length>0?e.message:String(t);return{name:typeof e?.name=="string"?e.name:"Error",message:n,...typeof e?.code=="string"&&e.code.length>0?{code:e.code}:{}}}import re from"node:http";import _ from"node:fs";import{createHash as Q,randomBytes as xe,timingSafeEqual as ke}from"node:crypto";import y from"node:path";import{WebSocket as ae,WebSocketServer as ve}from"ws";import{createPreviewSiteEditEngineRuntime as _e,openFileHistoryStore as Te,resolveManagedPageTemplateComposition as Oe,scanSiteEditCompositionsFromFiles as Ae}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as He,scanNextAppRouterRoutesFromFiles as Me}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as De}from"@vcp-dev/site-edit-engine/source-watcher";function Z(t){let e=new Map,n=[],i=new Map,o=[],s=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(s.map((c,p)=>[c,p])),a=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(c=>({placementKey:c.placementKey,placementUnitKey:c.placementUnitKey,relation:c.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},h=t.entries.flatMap((c,p)=>c.dynamicDataSummary?[[p,c.dynamicDataSummary]]:[]),d=new Map(t.entries.map((c,p)=>[c.key,p])),l=[];for(let[c,p]of t.entries.entries()){let f=p.pageCompositionActionScope;if(!f)continue;if(f.kind!=="source-siblings"){l.push([c,{kind:f.kind}]);continue}let O=f.siblingKeys.map(k=>{let v=d.get(k);if(v===void 0)throw new Error("Render entry "+p.key+" references missing source sibling "+k);return v});l.push([c,{kind:"source-siblings",siblingEntryIndexes:O}])}let C=c=>{let p=e.get(c);if(typeof p=="number")return p;let f=n.length;return n.push(c),e.set(c,f),f},G=c=>{let p=null;for(let f of ge(c)){let O=`${p??"root"}\0${f}`,k=i.get(O);if(typeof k=="number"){p=k;continue}let v=o.length;o.push([p,C(f)]),i.set(O,v),p=v}if(p===null)throw new Error("Document key must not be empty");return p};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:a,tokens:n,nodes:o,entries:t.entries.map(c=>{let p=c.pageCompositionUnitKey?r.get(c.pageCompositionUnitKey)??-1:-1;if(c.pageCompositionUnitKey&&p<0)throw new Error(`Render entry ${c.key} references unknown page composition unit ${c.pageCompositionUnitKey}`);return[G(c.key),le(c.operationSummary),...p>=0?[p]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...t.entries.every(c=>c.parentKey!==void 0)?{entryParentNodeIds:t.entries.map(c=>c.parentKey===null?null:G(c.parentKey))}:{},...h.length>0?{dynamicDataSummaries:h}:{}}}function le(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function ge(t){if(!t)return[];let e=[],n=0,i=Y(t,n);if(i<0)return e.push(t),e;for(e.push(t.slice(0,i)),n=i;n<t.length;){if(i=Y(t,n+(t.startsWith("::",n)?2:1)),i<0){e.push(t.slice(n));break}e.push(t.slice(n,i)),n=i}return e}function Y(t,e){let n=t.indexOf("/",e),i=t.indexOf("::",e);return n<0?i:i<0?n:Math.min(n,i)}var A="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",W="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var m=class t{constructor(){}static parseMessage(e,n={}){let i=JSON.parse(e);if(!t.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(u(e)&&u(e.payload)){let n=typeof e.payload.id=="string"?e.payload.id:"unknown",i=this.isRequestKind(e.payload.kind)?e.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(e){return e==="initialize-session"||e==="get-document"||e==="get-history-status"||e==="get-style-context"||e==="get-object-edit-context"||e==="get-class-name-source"||e==="get-source-tree"||e==="get-source-file"||e==="resolve-source-location"||e==="execute"||e==="get-operation-result"||e==="get-history-operation-result"||e==="undo"||e==="redo"}static isMessage(e,n={}){return!u(e)||typeof e.type!="string"?!1:e.type==="request"?ye(e.payload,n):e.type==="response"||e.type==="error"?u(e.payload)&&typeof e.payload.id=="string":e.type==="event"?u(e.payload)&&u(e.payload.event):e.type==="auth"?u(e.payload)&&typeof e.payload.key=="string":e.type==="ping"||e.type==="pong"?u(e.payload)&&typeof e.payload.id=="string":e.type==="auth-ok"&&u(e.payload)&&e.payload.ok===!0}},M=class{constructor(e){this.options=e,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new q,this.eventDispatcher=new P(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.handleEngineEvent(n)}),e.socket.onmessage=n=>{let i=me(n.data);if(i!==null){this.sendJson({type:"pong",payload:{id:i}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let i=n.payload,{id:o}=i;switch(i.kind){case"initialize-session":{let s=F(i),r=await this.resolve(s),a=await this.options.engine.initializeSession({composition:r.context,...i.mutationContext?{mutationContext:i.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:i.kind,result:w({...a,data:{...a.data,document:ee(a.data.document)}},r.context)}});return}case"get-document":{let s=await this.resolveWireContext(i),r=await this.options.engine.getDocument(s);this.sendResult(o,i.kind,Re(r,s));return}case"get-history-status":{let s=await this.resolveWireContext(i),r=await this.options.engine.getHistoryStatus(s);this.sendResult(o,i.kind,w(r,s));return}case"get-style-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getStyleContext(s),s));return}case"get-object-edit-context":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getObjectEditContext(i.key,s,i.selectionRef),s));return}case"get-class-name-source":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getClassNameSource(i.key,s),s));return}case"get-source-tree":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceTree(s),s));return}case"get-source-file":{let s=await this.resolveWireContext(i);this.sendResult(o,i.kind,w(await this.options.engine.getSourceFile({path:i.path,composition:s}),s));return}case"resolve-source-location":{let s=await this.resolveWireContext(i),r=w(await this.options.engine.resolveSourceLocation({key:i.key,composition:s}),s);this.sendResult(o,i.kind,r);return}case"execute":case"get-operation-result":{let s=await this.resolveOperationWireContext(i.request),r=await this.resolveWireContext(i);if(g(s)!==g(r))throw new I(A,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(i.request,s);if(i.kind==="get-operation-result"){this.sendResult(o,i.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,i.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let s=await this.resolveWireContext(i),r=await this.resolveAndAssert(i.request.composition);if(g(s)!==g(r))throw new I(A,"History receipt composition does not match the active session.");this.sendResult(o,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:H(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(i),r=i.request;if(r){let h=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||g(s)!==g(h))throw new I(A,"History request does not match its cursor operation.")}let a=r?{...r,composition:H(s)}:void 0;await this.handleBufferedOperation(o,i.kind,()=>i.kind==="undo"?this.options.engine.undo(s,a):this.options.engine.redo(s,a));return}}}catch(n){let i=m.extractRequestInfo(e);this.sendJson({type:"error",payload:{...i,message:B(n),code:V(n)}})}}async resolve(e){return this.options.engine.resolveComposition(e)}async resolveAndAssert(e){let n=await this.resolve(e),i=this.session.activeComposition;if(!i)throw new I(W,"Initialize a composition session before issuing this request.");if(g(i)!==g(n.context))throw new I(A,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(e){let n=F(e);return this.resolveAndAssert(n)}async resolveOperationWireContext(e){let n=Ce(e);return this.resolveAndAssert(n)}activateSession(e){this.session.activeComposition=e,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(g(e))}async normalizeOperationRequest(e,n){let i={...e,composition:H(n)};if(i.target.kind==="route"){let o=i.target,s=F(o),r=await this.resolveAndAssert(s);i.target={...o,composition:H(r)}}return i}handleEngineEvent(e){let n=e?.composition;if(!we(n))return;let i=g(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(e),e.type==="site-edit.graph.invalidated"&&i===Ee(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(e,n,i){this.sendJson({type:"response",payload:{id:e,kind:n,result:i}})}async handleRawMessage(e){try{await this.handleMessage(m.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=be(e);this.sendJson({type:"error",payload:{...i,message:B(n),code:V(n)}})}}sendJson(e){this.options.socket.send(m.stringifyMessage(e))}async handleBufferedOperation(e,n,i){this.eventDispatcher.beginBuffering();try{let o=await i();this.sendResult(e,n,o)}catch(o){this.sendJson({type:"error",payload:{id:e,kind:n,message:B(o),code:V(o)}})}finally{this.eventDispatcher.flush()}}},fe=256;function me(t){if(t.length>fe||!t.includes('"ping"'))return null;try{let e=JSON.parse(t);return u(e)&&e.type==="ping"&&u(e.payload)&&typeof e.payload.id=="string"?e.payload.id:null}catch{return null}}var I=class extends Error{constructor(e,n){super(n),this.code=e,this.name="BridgeProtocolError"}},P=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>this.send(n))}},q=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function ye(t,e){if(!u(t)||typeof t.id!="string"||!m.isRequestKind(t.kind))return!1;let n=R(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||K(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&Ie(t.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof t.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof t.path=="string"&&n;case"execute":case"get-operation-result":return n&&Se(t.request)&&(t.request.mutationContext===void 0||K(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&X(t.request);case"undo":case"redo":return n&&(t.request===void 0||X(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||K(t.mutationContext))}}function X(t){return u(t)&&typeof t.request_id=="string"&&t.request_id.length>0&&t.request_id.length<=128&&typeof t.site_id=="string"&&t.site_id.length>0&&typeof t.base_snapshot_id=="string"&&t.base_snapshot_id.length>0&&(t.kind==="undo"||t.kind==="redo")&&R(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function Ie(t){if(t===void 0)return!0;if(!u(t)||typeof t.key!="string"||t.key.length===0)return!1;let e=t.instanceIndex,n=t.instanceCount;return e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof e=="number"&&typeof n=="number"&&e>=n?!1:Object.keys(t).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function Se(t){return u(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&R(t.composition)&&typeof t.kind=="string"&&u(t.target)&&(t.target.kind!=="route"||R(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&u(t.params)}function R(t){return u(t)&&typeof t.routeId=="string"&&t.routeId.length>0&&(t.templateId===void 0||typeof t.templateId=="string"&&t.templateId.length>0)&&Object.keys(t).every(e=>e==="routeId"||e==="templateId")}function we(t){return u(t)&&typeof t.routeId=="string"&&(t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string")}function F(t){if(R(t.composition))return t.composition;throw new I(W,"A composition selector is required for this request.")}function Ce(t){if(u(t)&&R(t.composition))return t.composition;throw new I(W,"A composition selector is required for execute.")}function H(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function Ee(t){return t.activeComposition?g(t.activeComposition):null}function g(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function w(t,e){return u(t)&&t.ok===!0?{...t,composition:e}:t}function Re(t,e){return!u(t)||t.ok!==!0?t:{...t,...e?{composition:e}:{},data:ee(t.data)}}function ee(t){let e=t;return Z(e.routeId?e:{...e,routeId:e.composition.routeId})}function u(t){return typeof t=="object"&&t!==null}function K(t){return u(t)&&typeof t.editingSessionId=="string"&&t.editingSessionId.length>0&&typeof t.lockId=="string"&&t.lockId.length>0&&typeof t.ownerId=="string"&&t.ownerId.length>0&&typeof t.leaseAssertion=="string"&&t.leaseAssertion.length>0}function V(t){if(!(!u(t)||typeof t.code!="string"||t.code.length===0))return t.code}function B(t){return t instanceof Error||u(t)&&typeof t.message=="string"&&t.message.length>0?t.message:"Unknown websocket operation failure"}function be(t){try{return m.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var D=class{constructor(){this.tail=Promise.resolve()}run(e){let n=this.tail.then(e,e);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Ne,computeSiteEditCompositionKey as E}from"@vcp-dev/contracts";var Fe="127.0.0.1",Ke=30218,Ve="/__vcp/site-edit/bridge",ce=6*1024*1024,Be=ce*2,Pe=3e3,te=50,j=".vcp/current-snapshot.json",ne="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var z=class{constructor(e,n=re.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,o={}){this.options=e,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new D,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(e={}){if(!this.isStarted){this.stopping=!1;try{_.mkdirSync(y.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),e.webSocket!==!1){let n=Je({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new De({projectRoot:this.options.projectRoot,watch_dirs:We(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??te,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let e=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,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.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let e=$e(),n=Le(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let e=this.options.onHealthChanged;if(!e)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{e(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(e,n=null){let i=this.runtime;this.activeHistoryStore=e??null;let o=(this.dependencies.createRuntime??_e)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:s=>{"version"in s&&typeof s.version=="number"&&this.recordRuntimeVersion(s.version,"composition"in s?s.composition:void 0);for(let r of this.eventListeners)r(s)},...e?{historyStore:e}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:e=>this.resolveComposition(e),initializeSession:e=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=je(e.composition),o=this.getRuntime(),s=S(i);await o.initializeComposition(s);let a=o.getDocument(s).data;await this.recordRuntimeVersion(a.version,i);let h=(await o.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:h}}}),getDocument:async e=>{let n=this.getRuntime(),i=S(e);await n.initializeComposition(i);let o=n.getDocument(i);return await this.recordRuntimeVersion(o.data.version,e),{...o,composition:e}},getHistoryStatus:async e=>({...await this.getRuntime().getHistoryStatus(),composition:e}),getStyleContext:async e=>this.getRuntime().getStyleContext(S(e)),getObjectEditContext:async(e,n,i)=>this.getRuntime().getObjectEditContext(e,S(n),i),getClassNameSource:async(e,n)=>this.getRuntime().getClassNameSource(e,S(n)),getSourceTree:async e=>this.getRuntime().getSourceTree(S(e)),getSourceFile:async e=>this.getRuntime().getSourceFile({path:e.path,composition:S(e.composition)}),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,composition:S(e.composition)}),execute:(e,n)=>this.executeWithReceipt(e,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return ie(i,e);let o=await this.getRuntime().executeOperation(e);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:e=>this.readOperationReceipt(e),getHistoryOperationResult:e=>this.readOperationReceipt(e),undo:(e,n)=>this.runHistoryWithReceipt("undo",e,n),redo:(e,n)=>this.runHistoryWithReceipt("redo",e,n),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}runHistoryWithReceipt(e,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==e||i.composition.routeId!==n.routeId||i.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return ie(s,void 0,n);let r=await this.getRuntime()[e]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return i?this.executeWithReceipt(i,o):o()}isActiveReceiptIdentity(e){return"request_id"in e?e.site_id===this.options.siteId&&e.base_snapshot_id===this.options.snapshotId:e.siteId===this.options.siteId&&e.baseSnapshotId===this.options.snapshotId}operationReceiptKey(e){return"request_id"in e?JSON.stringify([e.site_id,e.base_snapshot_id,"history",e.request_id]):JSON.stringify([e.siteId,e.baseSnapshotId,e.id])}operationFingerprint(e){return Q("sha256").update(JSON.stringify(e)).digest("hex")}readOperationReceipt(e){if(!this.isActiveReceiptIdentity(e))return null;let n=this.operationReceipts.get(this.operationReceiptKey(e));return n?.fingerprint===this.operationFingerprint(e)?n.result:null}executeWithReceipt(e,n){if(!this.isActiveReceiptIdentity(e))return n();let i=this.operationReceiptKey(e),o=this.operationFingerprint(e),s=this.operationReceipts.get(i);if(s)return s.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):s.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(i,r),r.result.then(()=>{r.settled=!0;for(let[a,h]of this.operationReceipts){if(this.operationReceipts.size<=256)break;h.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(e){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===e)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let i=await(this.dependencies.openHistoryStore??Te)(ze({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let o=i.readDocumentVersion?await i.readDocumentVersion():0,s=this.versionCheckpoints.get(i);s?s.durableVersion=Math.max(s.durableVersion,o):this.versionCheckpoints.set(i,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=E(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(i,e)});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(e,n){let i=n?E(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,e));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=i?this.runtimeVersionFloors.get(i)??e:e,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),s<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,s),r.pending)return r.pending;let a=r,h=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=h,this.versionPersistence=h,h}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let i of e)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??te;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let n=e.some(pe)?this.scheduleSnapshotIdentityAdvance():!1,i=e.filter(o=>!nt(o));if(!(i.length===0&&!n)&&this.refreshCompositions(!1))for(let o of i)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let e=this.readCurrentSnapshotMarker();return!e||e===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(e)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let e=_.readFileSync(y.join(this.options.projectRoot,j),"utf8"),n=JSON.parse(e),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||$(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(e){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${e instanceof Error?e.message:String(e)}`),null}}async advanceSnapshotId(e){if(this.stopping||!this.isStarted||e===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=e;try{if(this.options.historyRoot){let o=await this.bindHistorySession(e);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let i=new Date().toISOString();for(let o of this.compositions){let s={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:e,previousSnapshotId:n,at:i};for(let r of this.eventListeners)try{r(s)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(e,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(e=!1){try{let n=Ue(this.options.projectRoot),i=Me(n),o=i.length>0?i:(this.options.runtime.routes??[]).map(d=>({...d})),s=Ae({files:n});if(s.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(s.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(e&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[E(d.context),d])),h=new Map(s.map(d=>[E(d.context),d]));if(this.runtime){for(let[d,l]of a){let C=h.get(d);(!C||C.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(S(l.context))}for(let[d,l]of h){let C=a.get(d);(!C||C.entryFile!==l.entryFile)&&this.runtime.registerComposition(l.context,l.entryFile)}}return this.routes=o,this.compositions=s,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let i=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=i,e)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(e){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=He(e.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${e.routeId}`);let o=Oe({selector:{routeId:n,...e.templateId!==void 0?{templateId:e.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:i.entryFile}),s=E(o.context);if(!this.compositions.some(r=>E(r.context)===s))throw new Error(`Composition is not registered by the preview bridge: ${s}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(e=>{let n=this.runtimeVersionFloors.get(E(e.context));return n===void 0?[]:[{composition:e.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function de(t){let e=new z(qe(t),re.createServer(),!1);return e.start({listen:!1,webSocket:!1}),{engine:e.getEngine(),getHealth:()=>e.getHealth(),stop:()=>e.stop()}}function qe(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:y.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??Fe,port:t.port??Ke,path:t.path??Ve,sessionKey:t.sessionKey??tt(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{},onSnapshotIdChanged:t.onSnapshotIdChanged,onHealthChanged:t.onHealthChanged}}function We(t){let e=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...t?.length?t:e,".vcp"])]}function Ue(t){let e=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!_.existsSync(s))return;let r;try{r=_.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(i.has(a.name))continue;o(y.join(s,a.name));continue}if(!a.isFile())continue;let h=y.join(s,a.name),d="";try{d=_.readFileSync(h,"utf8")}catch{}e.push({path:y.relative(t,h).replaceAll(y.sep,"/"),content:d})}};for(let s of n)o(y.join(t,s));return e.sort((s,r)=>s.path.localeCompare(r.path))}function je(t){if(!t||typeof t!="object"||typeof t.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in t)return t;let e=t;return{routeId:e.routeId,...e.templateId?{effectiveTemplateId:e.templateId}:{}}}function S(t){return{routeId:t.routeId,...t.effectiveTemplateId?{templateId:t.effectiveTemplateId}:{}}}function ze(t){return y.join(y.resolve(t.root),$(t.siteId),$(t.snapshotId),Q("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function $(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:Q("sha256").update(t).digest("hex").slice(0,32)}function $e(){let t=globalThis;return t[ne]??=new Map,t[ne]}function Le(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function ie(t,e,n){let i=n??(e?.composition?{routeId:e.composition.routeId,...e.composition.templateId?{effectiveTemplateId:e.composition.templateId}:{}}:void 0);if(!i)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:i,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",composition:i,target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Je(t){let e=new ve({maxPayload:ce,noServer:!0}),n=new WeakSet,i=s=>{new M({socket:new L(s),engine:t.engine,validateOperationRequest:r=>Ne.safeParse(r).success})},o=(s,r,a)=>{if(!Qe(s,t))return;let h=Ge(s,t);if(!h){r.write(`HTTP/1.1 401 Unauthorized\r
2
2
  Connection: close\r
3
3
  \r
4
- `),r.destroy();return}h.authenticatedByHeader&&n.add(o),e.handleUpgrade(o,r,a,d=>{e.emit("connection",d,o)})};return t.server.on("upgrade",s),e.on("connection",(o,r)=>{if(n.has(r)){i(o);return}Ge(o,t.sessionKey,()=>{i(o)})}),e.stop=()=>{t.server.off("upgrade",s);for(let o of e.clients)o.close(1001,"bridge stopped");e.close()},e}var z=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===re.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Ve){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Je(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Qe(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=U(t.headers["x-vcp-site-edit-key"]),s=de(i,e.sessionKey),o=U(t.headers.host),r=U(t.headers.origin);return o&&!Ye(o,e.host,r)?null:r?Xe(r,o,e.allowedOrigins)?{authenticatedByHeader:s}:null:s?{authenticatedByHeader:!0}:null}function Ge(t,e,n){let i=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},Be),s,o=()=>{clearTimeout(i),t.off("message",s),t.off("close",o)},r=()=>{o(),t.close(1008,"bridge authentication failed")};s=a=>{try{let h=f.parseMessage(a.toString());if(h.type!=="auth"||!de(h.payload.key,e)){r();return}o(),t.readyState===re.OPEN&&t.send(f.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},t.on("message",s),t.on("close",o)}function de(t,e){if(!t)return!1;let n=Buffer.from(t),i=Buffer.from(e);return n.length===i.length&&xe(n,i)}function Ye(t,e,n){let i=se(t),s=se(e);return i===s||ie(s)&&ie(i)&&(!n||L(n,t))||Ze(s)&&(!n||L(n,t))}function Ze(t){return t==="0.0.0.0"||t==="::"}function ie(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Xe(t,e,n){return n.includes(t)||(e?L(t,e):!1)}function L(t,e){try{return new URL(t).host===ue(e)}catch{return!1}}function se(t){let e=ue(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function ue(t){return t.trim().toLowerCase()}function U(t){return Array.isArray(t)?t[0]:t}function et(){return be(32).toString("base64url")}function he(t){let e=t.replaceAll("\\","/");return e===q||e.endsWith(`/${q}`)}function tt(t){let e=t.replaceAll("\\","/");return he(t)||e===".vcp/workspace-state.json"||e.startsWith(".vcp/snapshot-store/")}var b=nt;if(!b)throw new Error("site edit engine worker must run inside worker_threads");var R=t=>{b.postMessage(t)},st=(t,e)=>{try{b.postMessage({type:"result",id:t,ok:!0,value:e})}catch(n){if(n instanceof Error&&n.name==="DataCloneError"){b.postMessage({type:"result",id:t,ok:!0,value:e===void 0?void 0:JSON.parse(JSON.stringify(e))});return}throw n}},{options:ot}=it,T;try{T=ce({...ot,onSnapshotIdChanged:(t,e)=>{R({type:"snapshot-id-changed",next:t,previous:e})},onHealthChanged:t=>{R({type:"health",health:t})}})}catch(t){R({type:"start-failed",error:H(t)}),process.exit(1)}T.engine.subscribe(t=>{R({type:"event",event:t})});var rt=async t=>{try{let e=T.engine[t.method],n=await e(...t.args);st(t.id,n)}catch(e){R({type:"result",id:t.id,ok:!1,error:H(e)})}};b.on("message",t=>{if(t.type==="call"){rt(t);return}t.type==="stop"&&(T.stop(),b.close())});R({type:"ready",health:T.getHealth()});
4
+ `),r.destroy();return}h.authenticatedByHeader&&n.add(s),e.handleUpgrade(s,r,a,d=>{e.emit("connection",d,s)})};return t.server.on("upgrade",o),e.on("connection",(s,r)=>{if(n.has(r)){i(s);return}Ye(s,t.sessionKey,()=>{i(s)})}),e.stop=()=>{t.server.off("upgrade",o);for(let s of e.clients)s.close(1001,"bridge stopped");e.close()},e}var L=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===ae.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Be){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Qe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ge(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=U(t.headers["x-vcp-site-edit-key"]),o=ue(i,e.sessionKey),s=U(t.headers.host),r=U(t.headers.origin);return s&&!Ze(s,e.host,r)?null:r?et(r,s,e.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Ye(t,e,n){let i=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},Pe),o,s=()=>{clearTimeout(i),t.off("message",o),t.off("close",s)},r=()=>{s(),t.close(1008,"bridge authentication failed")};o=a=>{try{let h=m.parseMessage(a.toString());if(h.type!=="auth"||!ue(h.payload.key,e)){r();return}s(),t.readyState===ae.OPEN&&t.send(m.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},t.on("message",o),t.on("close",s)}function ue(t,e){if(!t)return!1;let n=Buffer.from(t),i=Buffer.from(e);return n.length===i.length&&ke(n,i)}function Ze(t,e,n){let i=oe(t),o=oe(e);return i===o||se(o)&&se(i)&&(!n||J(n,t))||Xe(o)&&(!n||J(n,t))}function Xe(t){return t==="0.0.0.0"||t==="::"}function se(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function et(t,e,n){return n.includes(t)||(e?J(t,e):!1)}function J(t,e){try{return new URL(t).host===he(e)}catch{return!1}}function oe(t){let e=he(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function he(t){return t.trim().toLowerCase()}function U(t){return Array.isArray(t)?t[0]:t}function tt(){return xe(32).toString("base64url")}function pe(t){let e=t.replaceAll("\\","/");return e===j||e.endsWith(`/${j}`)}function nt(t){let e=t.replaceAll("\\","/");return pe(t)||e===".vcp/workspace-state.json"||e.startsWith(".vcp/snapshot-store/")}var x=it;if(!x)throw new Error("site edit engine worker must run inside worker_threads");var b=t=>{x.postMessage(t)},ot=(t,e)=>{try{x.postMessage({type:"result",id:t,ok:!0,value:e})}catch(n){if(n instanceof Error&&n.name==="DataCloneError"){x.postMessage({type:"result",id:t,ok:!0,value:e===void 0?void 0:JSON.parse(JSON.stringify(e))});return}throw n}},{options:rt}=st,T;try{T=de({...rt,onSnapshotIdChanged:(t,e)=>{b({type:"snapshot-id-changed",next:t,previous:e})},onHealthChanged:t=>{b({type:"health",health:t})}})}catch(t){b({type:"start-failed",error:N(t)}),process.exit(1)}T.engine.subscribe(t=>{b({type:"event",event:t})});var at=async t=>{try{let e=T.engine[t.method],n=await e(...t.args);ot(t.id,n)}catch(e){b({type:"result",id:t.id,ok:!1,error:N(e)})}};x.on("message",t=>{if(t.type==="call"){at(t);return}t.type==="stop"&&(T.stop(),x.close())});b({type:"ready",health:T.getHealth()});