@vcp-dev/site-edit-bridge 0.10.70 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-bootstrap.d.ts +1 -1
- package/dist/auto-bootstrap.js +15 -15
- package/dist/client.d.ts +34 -0
- package/dist/client.js +1 -1
- package/dist/document-codec.d.ts +1 -0
- package/dist/document-codec.js +1 -1
- package/dist/engine-worker.js +2 -2
- package/dist/index.js +18 -18
- package/dist/next-dev-server.js +4 -4
- package/dist/server.js +2 -2
- package/dist/window-message.d.ts +4 -1
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
package/dist/client.d.ts
CHANGED
|
@@ -132,6 +132,40 @@ export declare class SiteEditWebSocketClient implements SiteEditBridgeClient {
|
|
|
132
132
|
message: string;
|
|
133
133
|
}[];
|
|
134
134
|
};
|
|
135
|
+
pageBlocks?: readonly {
|
|
136
|
+
blockKey: string;
|
|
137
|
+
rootRef: {
|
|
138
|
+
key: string;
|
|
139
|
+
instanceIndex?: number | undefined;
|
|
140
|
+
instanceCount?: number | undefined;
|
|
141
|
+
};
|
|
142
|
+
definitionKey: string;
|
|
143
|
+
source: {
|
|
144
|
+
file: string;
|
|
145
|
+
structuralPath: string;
|
|
146
|
+
contentHash: string;
|
|
147
|
+
};
|
|
148
|
+
owner: {
|
|
149
|
+
kind: "route-member";
|
|
150
|
+
key: string;
|
|
151
|
+
} | {
|
|
152
|
+
kind: "component-definition";
|
|
153
|
+
key: string;
|
|
154
|
+
};
|
|
155
|
+
siblingBlockKeys: readonly string[];
|
|
156
|
+
capabilities: {
|
|
157
|
+
insert: boolean;
|
|
158
|
+
replace: boolean;
|
|
159
|
+
move: boolean;
|
|
160
|
+
remove: boolean;
|
|
161
|
+
save: boolean;
|
|
162
|
+
};
|
|
163
|
+
placementUnitKey?: string | undefined;
|
|
164
|
+
unavailableReasons?: Readonly<Record<string, {
|
|
165
|
+
code: string;
|
|
166
|
+
reason: string;
|
|
167
|
+
}>> | undefined;
|
|
168
|
+
}[] | undefined;
|
|
135
169
|
}>>;
|
|
136
170
|
initializeSession(input: SiteEditBridgeInitializeInput): Promise<SiteEditCommandSuccess<{
|
|
137
171
|
document: SiteEditRenderDocument;
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
function N(t){if(!V(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,m=t.tokens[d];if(typeof m!="string")throw new Error(`Missing compact document token ${d}`);let x=`${u===null?"":r(u)}${m}`;return e.set(c,x),x};return{siteId:t.siteId,snapshotId:t.snapshotId,composition:{...t.composition},routeId:t.composition.routeId,version:t.version,pageComposition:t.pageComposition,...t.pageBlocks!==void 0?{pageBlocks:t.pageBlocks}:{},entries:t.entries.map((c,o)=>{let[a,u,d]=c,m=d===void 0?void 0:n[d];if(d!==void 0&&!m)throw new Error(`Missing page composition unit ${d}`);let x=t.entryParentNodeIds?.[o],_=s.get(o),O=_?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:_.siblingEntryIndexes.map(M=>{let B=t.entries[M];if(!B)throw new Error(`Missing source sibling entry ${M}`);return r(B[0])})}:_;return{key:r(a),...t.entryParentNodeIds?{parentKey:x===null?null:r(x)}:{},...m?{pageCompositionUnitKey:m}:{},...O?{pageCompositionActionScope:O}:{},operationSummary:z(u),...i.get(o)?{dynamicDataSummary:i.get(o)}:{}}})}}function z(t){return{canUpdateText:(t&1)!==0,canInsertChild:(t&2)!==0,canMove:(t&4)!==0,canRemove:(t&8)!==0}}function V(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"||!H(e.composition)||typeof e.routeId!="string"||e.routeId!==e.composition.routeId||!Number.isInteger(e.version)||e.version<0||!l(e.pageComposition)||e.pageBlocks!==void 0&&!G(e.pageBlocks)||!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||p(o[0])&&o[0]<a)&&p(o[1])&&o[1]<e.tokens.length)||!e.entries.every(o=>Array.isArray(o)&&(o.length===2||o.length===3)&&p(o[0])&&o[0]<n.length&&p(o[1])&&o[1]<=15&&(o.length===2||p(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||p(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||!p(o[0])||o[0]>=e.entries.length||!l(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=>p(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&&p(o[0])&&o[0]<e.entries.length&&l(o[1])))}function l(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function H(t){return!l(t)||typeof t.routeId!="string"?!1:t.effectiveTemplateId===void 0||typeof t.effectiveTemplateId=="string"}function p(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0}function G(t){if(!Array.isArray(t))return!1;let e=new Map;for(let n of t){if(!l(n)||!b(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!w(n.blockKey,256)||!w(n.definitionKey,512)||!J(n.rootRef)||!Q(n.source)||!Y(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>w(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!I(n.placementUnitKey)||!Z(n.capabilities)||n.unavailableReasons!==void 0&&!X(n.unavailableReasons)||e.has(n.blockKey))return!1;e.set(n.blockKey,n)}for(let n of t){let i=n.owner;for(let s of n.siblingBlockKeys){let r=e.get(s);if(!r)return!1;let c=r.owner;if(i.kind!==c.kind||i.key!==c.key)return!1}}return!0}function J(t){return!l(t)||!b(t,["key","instanceIndex","instanceCount"])||!I(t.key)||t.instanceIndex!==void 0&&!p(t.instanceIndex)||t.instanceCount!==void 0&&(!p(t.instanceCount)||t.instanceCount<1)?!1:!(t.instanceIndex!==void 0&&t.instanceCount!==void 0&&t.instanceIndex>=t.instanceCount)}function Q(t){return l(t)&&b(t,["file","structuralPath","contentHash"])&&typeof t.file=="string"&&ee(t.file)&&I(t.structuralPath)&&typeof t.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)}function Y(t){return l(t)&&b(t,["kind","key"])&&(t.kind==="route-member"||t.kind==="component-definition")&&w(t.key,512)}function Z(t){return l(t)&&b(t,["insert","replace","move","remove","save"])&&typeof t.insert=="boolean"&&typeof t.replace=="boolean"&&typeof t.move=="boolean"&&typeof t.remove=="boolean"&&typeof t.save=="boolean"}function X(t){return l(t)&&Object.entries(t).every(([e,n])=>I(e)&&l(n)&&b(n,["code","reason"])&&I(n.code)&&I(n.reason))}function ee(t){let e=te(t),n=e?t.replace("/.vcp/","/_vcp/"):t;if(!t||t.startsWith("/")||t.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let i=t.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(t.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(t)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(t)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>t===r||t.startsWith(`${r}/`))||e}function te(t){let e=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(t);if(!e)return!1;let n=e[1].split("/"),i=n.some(c=>K(c)),s=i?n[0]:n.pop(),r=i?n.slice(1):n;if(i&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(s)||!ne(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!K(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=s.replace(/-/gu,"+").replace(/_/gu,"/"),o=atob(c),a=Uint8Array.from(o,d=>d.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(a);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===s}catch{return!1}}function K(t){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(t)||/^\[[^\[\]]+\]$/u.test(t)}function ne(t){return!t.startsWith("/")||t.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(t)||t.startsWith("/.vcp")?!1:!t.split("/").some(e=>{try{let n=decodeURIComponent(e);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function w(t,e){return typeof t=="string"&&t.length>0&&t.length<=e}function I(t){return typeof t=="string"&&t.length>0}function b(t,e){let n=new Set(e);return Object.keys(t).every(i=>n.has(i))}var g=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"?ie(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 ie(t,e){if(!h(t)||typeof t.id!="string"||!g.isRequestKind(t.kind))return!1;let n=T(t.composition);switch(t.kind){case"initialize-session":return n&&(t.mutationContext===void 0||q(t.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof t.key=="string"&&n&&se(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&&oe(t.request)&&(t.request.mutationContext===void 0||q(t.request.mutationContext))&&(e.validateOperationRequest?.(t.request)??!0);case"get-history-operation-result":return n&&v(t.request);case"undo":case"redo":return n&&(t.request===void 0||v(t.request)&&t.request.kind===t.kind)&&(t.mutationContext===void 0||q(t.mutationContext))}}function v(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")&&T(t.composition)&&Object.keys(t).every(e=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(e))}function se(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 oe(t){return h(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&T(t.composition)&&typeof t.kind=="string"&&h(t.target)&&(t.target.kind!=="route"||T(t.target.composition))&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&h(t.params)}function T(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 q(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 re="vcp:designer:trace",ce="designer_trace",P="__VCP_DESIGNER_TRACE__";var ae=/(authorization|cookie|token|secret|providerTrace|headers?|sourceCode|rawSource|fullSource)/i;function ue(t=globalThis){let e=t;try{if(e.localStorage?.getItem(re)==="1")return!0}catch{}try{let n=e.location?.search??"";return new URLSearchParams(n).get(ce)==="1"}catch{return!1}}function f(t,e={},n=globalThis){if(!ue(n))return;let i={type:t,timestamp:Date.now(),payload:de(e)},s=n,r=s[P]??[];r.push(i),r.length>1e3&&r.splice(0,r.length-1e3),s[P]=r;let c=n.console?.debug;i.payload.diagnosticOnly!==!0&&typeof c=="function"&&c.call(n.console,"[designer-trace]",i)}function de(t){return R(t,0)}function R(t,e){if(e>4)return"[truncated]";if(Array.isArray(t))return t.map(i=>R(i,e+1));if(!t||typeof t!="object")return t;let n={};for(let[i,s]of Object.entries(t)){if(ae.test(i)){n[i]="[redacted]";continue}n[i]=R(s,e+1)}return n}var j=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===D&&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=C(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??pe);r>0&&(s.deadline=setTimeout(()=>{this.connectAttempt!==s||s.settled||(f("bridge.connect-timeout",{connectTimeoutMs:r}),this.cleanupSocket(i,U(fe,`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(g.stringifyMessage({type:"auth",payload:{key:this.options.authKey}}))}catch(a){o(C(a,"WebSocket auth failed"),"failed")}return}c()}},i.onerror=a=>{if(this.socket!==i)return;let u=C(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(be(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=E(e),s={...e,composition:y(i)};return this.request("execute",{request:s})}getOperationResult(e){return this.request("get-operation-result",{request:e,composition:y(E(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 y(e)}request(e,n){let i=this.socket;if(!i||i.readyState!==D||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=ke(s,e,n);return f("bridge.request",{id:s,kind:e,routeId:typeof n.routeId=="string"?n.routeId:null,key:typeof n.key=="string"?n.key:null,operationKind:$(n.request,"kind"),documentVersion:$(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),f("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(g.stringifyMessage(r))}catch(d){let m=C(d,"WebSocket send failed");this.clearPendingRequest(s),o(m),this.cleanupSocket(i,m,"failed")}})}handleAuthHandshakeMessage(e,n,i,s){try{if(g.parseMessage(e).type==="auth-ok"){s();return}throw new Error("Bridge authentication failed")}catch(r){let c=C(r,"Bridge authentication failed");this.connectAttempt===i&&this.cleanupSocket(n,c,"failed")}}handleMessage(e){let n=g.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"){f("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}f("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:L(n.payload.result.data,n.payload.result.composition)}:i.kind==="initialize-session"?Se(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):Ie[e]??ye}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===he||e.readyState===D)&&e.close()}catch{}}startHeartbeat(e){let n=this.options.heartbeat===void 0?le: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?ge():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(g.stringifyMessage({type:"ping",payload:{id:`ping-${this.sequence+=1}`}}))}catch(u){this.cleanupSocket(e,C(u,"WebSocket heartbeat send failed"),"failed");return}a.deadline=setTimeout(()=>{this.heartbeatState?.socket===e&&(this.heartbeatState.deadline=null,s()&&(f("bridge.heartbeat-timeout",{timeoutMs:n.timeoutMs}),this.cleanupSocket(e,U(me,`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)}},he=0,D=1,pe=1e4,le={intervalMs:2e4,timeoutMs:1e4},fe="SITE_EDIT_BRIDGE_CONNECT_TIMEOUT",me="SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT";function ge(){let t=globalThis.document;return t&&typeof t.visibilityState=="string"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"?t:null}function U(t,e){let n=new Error(`${t}: ${e}`);return n.code=t,n}var ye=15e3,Ie={"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 C(t,e){return t instanceof Error?t:new Error(e)}function be(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 $(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 Oe(t){let e="composition"in t?y(t.composition):y({routeId:t.routeId});return new A({composition:e,initialDocument:t.initialDocument,client:t.client})}var A=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=y(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=k(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=E(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 f("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=k(this.composition),s=this.refreshInFlight;if(s?.compositionKey===i){f("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}f("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&&S(c.data.composition)===S(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`${k(n)}\0${e}\0${xe(i)}`}rememberServerConfirmedComposition(e){!e||typeof e.routeId!="string"||(this.serverConfirmedComposition={...e})}isAcceptedComposition(e){if(k(e)===k(this.composition))return!0;let n=this.serverConfirmedComposition;return n!==null&&S(n)===S(W(e))}requireBoundComposition(e){let n=e===void 0?this.composition:y(e);if(!this.isAcceptedComposition(n))throw new Error(`Site edit bridge is bound to composition ${JSON.stringify(this.composition)}, received ${JSON.stringify(n)}`);return y(n)}isActiveComposition(e){let n=this.activeCompositionContext??W(this.composition);return S(e)===S(n)}};function F(t){return t.version===0&&t.entries.length===0}function Se(t){let e=t;return{...e,data:{...e.data,document:L(e.data.document,e.composition)}}}function L(t,e){let n=t,i=N(n.routeId?n:{...n,routeId:e?.routeId??n.composition?.routeId});return e?{...i,composition:e}:i}function y(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 k(t){return JSON.stringify([t.routeId,t.templateId??null])}function xe(t){return t?JSON.stringify([t.key,t.instanceIndex??null,t.instanceCount??null]):""}function S(t){return JSON.stringify([t.routeId,t.effectiveTemplateId??null])}function W(t){return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function E(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 ke(t,e,n){let i=y(e==="execute"?E(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:E(n.request)??i}}}}}export{fe as SITE_EDIT_BRIDGE_CONNECT_TIMEOUT,me as SITE_EDIT_BRIDGE_HEARTBEAT_TIMEOUT,j as SiteEditWebSocketClient,Oe as createSiteEditBridge};
|
package/dist/document-codec.d.ts
CHANGED
package/dist/document-codec.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function U(e){let t=new Map,o=[],r=new Map,u=[],g=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],l=new Map(g.map((i,s)=>[i,s])),n=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(i=>({placementKey:i.placementKey,placementUnitKey:i.placementUnitKey,relation:i.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},a=e.entries.flatMap((i,s)=>i.dynamicDataSummary?[[s,i.dynamicDataSummary]]:[]),d=new Map(e.entries.map((i,s)=>[i.key,s])),c=[];for(let[i,s]of e.entries.entries()){let p=s.pageCompositionActionScope;if(!p)continue;if(p.kind!=="source-siblings"){c.push([i,{kind:p.kind}]);continue}let h=p.siblingKeys.map(I=>{let C=d.get(I);if(C===void 0)throw new Error("Render entry "+s.key+" references missing source sibling "+I);return C});c.push([i,{kind:"source-siblings",siblingEntryIndexes:h}])}let y=i=>{let s=t.get(i);if(typeof s=="number")return s;let p=o.length;return o.push(i),t.set(i,p),p},f=i=>{let s=null;for(let p of v(i)){let h=`${s??"root"}\0${p}`,I=r.get(h);if(typeof I=="number"){s=I;continue}let C=u.length;u.push([s,y(p)]),r.set(h,C),s=C}if(s===null)throw new Error("Document key must not be empty");return s};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:n,tokens:o,nodes:u,entries:e.entries.map(i=>{let s=i.pageCompositionUnitKey?l.get(i.pageCompositionUnitKey)??-1:-1;if(i.pageCompositionUnitKey&&s<0)throw new Error(`Render entry ${i.key} references unknown page composition unit ${i.pageCompositionUnitKey}`);return[f(i.key),K(i.operationSummary),...s>=0?[s]:[]]}),...c.length>0?{pageCompositionActionScopes:c}:{},...e.entries.every(i=>i.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(i=>i.parentKey===null?null:f(i.parentKey))}:{},...a.length>0?{dynamicDataSummaries:a}:{}}}function k(e){if(!x(e)){if(e.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return e}let t=new Map,o=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(e.dynamicDataSummaries??[]),u=new Map(e.pageCompositionActionScopes??[]),g=l=>{let n=t.get(l);if(n)return n;let a=e.nodes[l];if(!a)throw new Error(`Missing compact document node ${l}`);let[d,c]=a,y=e.tokens[c];if(typeof y!="string")throw new Error(`Missing compact document token ${c}`);let f=`${d===null?"":g(d)}${y}`;return t.set(l,f),f};return{siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:e.pageComposition,entries:e.entries.map((l,n)=>{let[a,d,c]=l,y=c===void 0?void 0:o[c];if(c!==void 0&&!y)throw new Error(`Missing page composition unit ${c}`);let f=e.entryParentNodeIds?.[n],i=u.get(n),s=i?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:i.siblingEntryIndexes.map(p=>{let h=e.entries[p];if(!h)throw new Error(`Missing source sibling entry ${p}`);return g(h[0])})}:i;return{key:g(a),...e.entryParentNodeIds?{parentKey:f===null?null:g(f)}:{},...y?{pageCompositionUnitKey:y}:{},...s?{pageCompositionActionScope:s}:{},operationSummary:w(d),...r.get(n)?{dynamicDataSummary:r.get(n)}:{}}})}}function K(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function w(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function x(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||!S(t.composition)||typeof t.routeId!="string"||t.routeId!==t.composition.routeId||!Number.isInteger(t.version)||t.version<0||!A(t.pageComposition)||!Array.isArray(t.tokens)||!t.tokens.every(n=>typeof n=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let o=t.nodes;if(!o.every((n,a)=>Array.isArray(n)&&n.length===2&&(n[0]===null||m(n[0])&&n[0]<a)&&m(n[1])&&n[1]<t.tokens.length)||!t.entries.every(n=>Array.isArray(n)&&(n.length===2||n.length===3)&&m(n[0])&&n[0]<o.length&&m(n[1])&&n[1]<=15&&(n.length===2||m(n[2]))))return!1;let r=t.entryParentNodeIds;if(r!==void 0&&(!Array.isArray(r)||r.length!==t.entries.length||!r.every(n=>n===null||m(n)&&n<o.length)))return!1;let u=t.dynamicDataSummaries,g=t.pageCompositionActionScopes;return(g===void 0||Array.isArray(g)&&g.every(n=>{if(!Array.isArray(n)||n.length!==2||!m(n[0])||n[0]>=t.entries.length||!A(n[1])||!["route-unit","source-siblings","unavailable"].includes(String(n[1].kind)))return!1;let a=n[1];return a.kind!=="source-siblings"||Array.isArray(a.siblingEntryIndexes)&&a.siblingEntryIndexes.length>=2&&a.siblingEntryIndexes.every(d=>m(d)&&d<t.entries.length)&&a.siblingEntryIndexes.includes(n[0])}))&&(u===void 0||Array.isArray(u)&&u.every(n=>Array.isArray(n)&&n.length===2&&m(n[0])&&n[0]<t.entries.length&&A(n[1])))}function A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function S(e){return!A(e)||typeof e.routeId!="string"?!1:e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string"}function m(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function v(e){if(!e)return[];let t=[],o=0,r=b(e,o);if(r<0)return t.push(e),t;for(t.push(e.slice(0,r)),o=r;o<e.length;){if(r=b(e,o+(e.startsWith("::",o)?2:1)),r<0){t.push(e.slice(o));break}t.push(e.slice(o,r)),o=r}return t}function b(e,t){let o=e.indexOf("/",t),r=e.indexOf("::",t);return o<0?r:r<0?o:Math.min(o,r)}export{k as decodeRenderDocument,U as encodeRenderDocument,x as isCompactRenderDocument};
|
|
1
|
+
function L(e){if(e.pageBlocks!==void 0&&!S(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],i=new Map,d=[],r=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],c=new Map(r.map((o,a)=>[o,a])),s=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(o=>({placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,relation:o.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},p=e.entries.flatMap((o,a)=>o.dynamicDataSummary?[[a,o.dynamicDataSummary]]:[]),l=new Map(e.entries.map((o,a)=>[o.key,a])),f=[];for(let[o,a]of e.entries.entries()){let g=a.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){f.push([o,{kind:g.kind}]);continue}let b=g.siblingKeys.map(x=>{let K=l.get(x);if(K===void 0)throw new Error("Render entry "+a.key+" references missing source sibling "+x);return K});f.push([o,{kind:"source-siblings",siblingEntryIndexes:b}])}let m=o=>{let a=t.get(o);if(typeof a=="number")return a;let g=n.length;return n.push(o),t.set(o,g),g},h=o=>{let a=null;for(let g of O(o)){let b=`${a??"root"}\0${g}`,x=i.get(b);if(typeof x=="number"){a=x;continue}let K=d.length;d.push([a,m(g)]),i.set(b,K),a=K}if(a===null)throw new Error("Document key must not be empty");return a};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:s,tokens:n,nodes:d,entries:e.entries.map(o=>{let a=o.pageCompositionUnitKey?c.get(o.pageCompositionUnitKey)??-1:-1;if(o.pageCompositionUnitKey&&a<0)throw new Error(`Render entry ${o.key} references unknown page composition unit ${o.pageCompositionUnitKey}`);return[h(o.key),B(o.operationSummary),...a>=0?[a]:[]]}),...f.length>0?{pageCompositionActionScopes:f}:{},...e.entries.every(o=>o.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(o=>o.parentKey===null?null:h(o.parentKey))}:{},...p.length>0?{dynamicDataSummaries:p}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function _(e){if(!U(e)){if(e.encoding==="segment-trie-v1")throw new Error("Invalid compact render document");return e}let t=new Map,n=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],i=new Map(e.dynamicDataSummaries??[]),d=new Map(e.pageCompositionActionScopes??[]),r=c=>{let s=t.get(c);if(s)return s;let p=e.nodes[c];if(!p)throw new Error(`Missing compact document node ${c}`);let[l,f]=p,m=e.tokens[f];if(typeof m!="string")throw new Error(`Missing compact document token ${f}`);let h=`${l===null?"":r(l)}${m}`;return t.set(c,h),h};return{siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:e.pageComposition,...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{},entries:e.entries.map((c,s)=>{let[p,l,f]=c,m=f===void 0?void 0:n[f];if(f!==void 0&&!m)throw new Error(`Missing page composition unit ${f}`);let h=e.entryParentNodeIds?.[s],o=d.get(s),a=o?.kind==="source-siblings"?{kind:"source-siblings",siblingKeys:o.siblingEntryIndexes.map(g=>{let b=e.entries[g];if(!b)throw new Error(`Missing source sibling entry ${g}`);return r(b[0])})}:o;return{key:r(p),...e.entryParentNodeIds?{parentKey:h===null?null:r(h)}:{},...m?{pageCompositionUnitKey:m}:{},...a?{pageCompositionActionScope:a}:{},operationSummary:$(l),...i.get(s)?{dynamicDataSummary:i.get(s)}:{}}})}}function B(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function $(e){return{canUpdateText:(e&1)!==0,canInsertChild:(e&2)!==0,canMove:(e&4)!==0,canRemove:(e&8)!==0}}function U(e){if(typeof e!="object"||e===null)return!1;let t=e;if(t.encoding!=="segment-trie-v1"||typeof t.siteId!="string"||typeof t.snapshotId!="string"||!E(t.composition)||typeof t.routeId!="string"||t.routeId!==t.composition.routeId||!Number.isInteger(t.version)||t.version<0||!y(t.pageComposition)||t.pageBlocks!==void 0&&!S(t.pageBlocks)||!Array.isArray(t.tokens)||!t.tokens.every(s=>typeof s=="string")||!Array.isArray(t.nodes)||!Array.isArray(t.entries))return!1;let n=t.nodes;if(!n.every((s,p)=>Array.isArray(s)&&s.length===2&&(s[0]===null||u(s[0])&&s[0]<p)&&u(s[1])&&s[1]<t.tokens.length)||!t.entries.every(s=>Array.isArray(s)&&(s.length===2||s.length===3)&&u(s[0])&&s[0]<n.length&&u(s[1])&&s[1]<=15&&(s.length===2||u(s[2]))))return!1;let i=t.entryParentNodeIds;if(i!==void 0&&(!Array.isArray(i)||i.length!==t.entries.length||!i.every(s=>s===null||u(s)&&s<n.length)))return!1;let d=t.dynamicDataSummaries,r=t.pageCompositionActionScopes;return(r===void 0||Array.isArray(r)&&r.every(s=>{if(!Array.isArray(s)||s.length!==2||!u(s[0])||s[0]>=t.entries.length||!y(s[1])||!["route-unit","source-siblings","unavailable"].includes(String(s[1].kind)))return!1;let p=s[1];return p.kind!=="source-siblings"||Array.isArray(p.siblingEntryIndexes)&&p.siblingEntryIndexes.length>=2&&p.siblingEntryIndexes.every(l=>u(l)&&l<t.entries.length)&&p.siblingEntryIndexes.includes(s[0])}))&&(d===void 0||Array.isArray(d)&&d.every(s=>Array.isArray(s)&&s.length===2&&u(s[0])&&s[0]<t.entries.length&&y(s[1])))}function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function E(e){return!y(e)||typeof e.routeId!="string"?!1:e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string"}function u(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function S(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!y(n)||!I(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!C(n.blockKey,256)||!C(n.definitionKey,512)||!M(n.rootRef)||!P(n.source)||!R(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>C(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!k(n.placementUnitKey)||!D(n.capabilities)||n.unavailableReasons!==void 0&&!N(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let i=n.owner;for(let d of n.siblingBlockKeys){let r=t.get(d);if(!r)return!1;let c=r.owner;if(i.kind!==c.kind||i.key!==c.key)return!1}}return!0}function M(e){return!y(e)||!I(e,["key","instanceIndex","instanceCount"])||!k(e.key)||e.instanceIndex!==void 0&&!u(e.instanceIndex)||e.instanceCount!==void 0&&(!u(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function P(e){return y(e)&&I(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&W(e.file)&&k(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function R(e){return y(e)&&I(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&C(e.key,512)}function D(e){return y(e)&&I(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function N(e){return y(e)&&Object.entries(e).every(([t,n])=>k(t)&&y(n)&&I(n,["code","reason"])&&k(n.code)&&k(n.reason))}function W(e){let t=T(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(r=>!r||r==="."||r===".."||r.startsWith(".")||r==="node_modules"||r.toLowerCase()==="package.json"||r==="recipes"||r.startsWith(".env")))return!1;let i=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(r=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(r.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(r=>e===r||e.startsWith(`${r}/`))||t}function T(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),i=n.some(c=>w(c)),d=i?n[0]:n.pop(),r=i?n.slice(1):n;if(i&&r.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(d)||!j(`/${r.join("/")}`)||r.some(c=>c.includes("[")||c.includes("]")?!w(c):/[\[\]()%]/u.test(c)||c.startsWith("_")||c.startsWith("@")))return!1;try{let c=d.replace(/-/gu,"+").replace(/_/gu,"/"),s=atob(c),p=Uint8Array.from(s,f=>f.charCodeAt(0)),l=new TextDecoder("utf-8",{fatal:!0}).decode(p);return l.length>0&&l.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(l)&&!l.startsWith(" ")&&!l.endsWith(" ")&&new TextEncoder().encode(l).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(l))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===d}catch{return!1}}function w(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function j(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function C(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function k(e){return typeof e=="string"&&e.length>0}function I(e,t){let n=new Set(t);return Object.keys(e).every(i=>n.has(i))}function O(e){if(!e)return[];let t=[],n=0,i=A(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=A(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function A(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}export{_ as decodeRenderDocument,L as encodeRenderDocument,U as isCompactRenderDocument};
|
package/dist/engine-worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
|
|
1
|
+
import{parentPort as It,workerData as St}from"node:worker_threads";function F(e){let t=e&&typeof e=="object"?e:null,n=typeof t?.message=="string"&&t.message.length>0?t.message:String(e);return{name:typeof t?.name=="string"?t.name:"Error",message:n,...typeof t?.code=="string"&&t.code.length>0?{code:t.code}:{}}}import he from"node:http";import A from"node:fs";import{createHash as X,randomBytes as We,timingSafeEqual as Ve}from"node:crypto";import y from"node:path";import{WebSocket as le,WebSocketServer as $e}from"ws";import{createPreviewSiteEditEngineRuntime as qe,openFileHistoryStore as je,resolveManagedPageTemplateComposition as Ue,scanSiteEditCompositionsFromFiles as ze}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Le,scanNextAppRouterRoutesFromFiles as Je}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Qe}from"@vcp-dev/site-edit-engine/source-watcher";function se(e){if(e.pageBlocks!==void 0&&!we(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],i=new Map,o=[],s=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(s.map((d,h)=>[d,h])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(d=>({placementKey:d.placementKey,placementUnitKey:d.placementUnitKey,relation:d.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((d,h)=>d.dynamicDataSummary?[[h,d.dynamicDataSummary]]:[]),c=new Map(e.entries.map((d,h)=>[d.key,h])),l=[];for(let[d,h]of e.entries.entries()){let g=h.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){l.push([d,{kind:g.kind}]);continue}let K=g.siblingKeys.map(T=>{let O=c.get(T);if(O===void 0)throw new Error("Render entry "+h.key+" references missing source sibling "+T);return O});l.push([d,{kind:"source-siblings",siblingEntryIndexes:K}])}let C=d=>{let h=t.get(d);if(typeof h=="number")return h;let g=n.length;return n.push(d),t.set(d,g),g},ee=d=>{let h=null;for(let g of Te(d)){let K=`${h??"root"}\0${g}`,T=i.get(K);if(typeof T=="number"){h=T;continue}let O=o.length;o.push([h,C(g)]),i.set(K,O),h=O}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(d=>{let h=d.pageCompositionUnitKey?r.get(d.pageCompositionUnitKey)??-1:-1;if(d.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${d.key} references unknown page composition unit ${d.pageCompositionUnitKey}`);return[ee(d.key),Se(d.operationSummary),...h>=0?[h]:[]]}),...l.length>0?{pageCompositionActionScopes:l}:{},...e.entries.every(d=>d.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(d=>d.parentKey===null?null:ee(d.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Se(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function te(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function we(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!b(n)||!x(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!B(n.blockKey,256)||!B(n.definitionKey,512)||!Ce(n.rootRef)||!be(n.source)||!Ee(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(i=>B(i,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!k(n.placementUnitKey)||!ke(n.capabilities)||n.unavailableReasons!==void 0&&!xe(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let i=n.owner;for(let o of n.siblingBlockKeys){let s=t.get(o);if(!s)return!1;let r=s.owner;if(i.kind!==r.kind||i.key!==r.key)return!1}}return!0}function Ce(e){return!b(e)||!x(e,["key","instanceIndex","instanceCount"])||!k(e.key)||e.instanceIndex!==void 0&&!te(e.instanceIndex)||e.instanceCount!==void 0&&(!te(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function be(e){return b(e)&&x(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Re(e.file)&&k(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Ee(e){return b(e)&&x(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&B(e.key,512)}function ke(e){return b(e)&&x(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function xe(e){return b(e)&&Object.entries(e).every(([t,n])=>k(t)&&b(n)&&x(n,["code","reason"])&&k(n.code)&&k(n.reason))}function Re(e){let t=_e(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(s=>!s||s==="."||s===".."||s.startsWith(".")||s==="node_modules"||s.toLowerCase()==="package.json"||s==="recipes"||s.startsWith(".env")))return!1;let i=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(i)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(i)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(i)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(i)||i.split("/").some(s=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(s.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(s=>e===s||e.startsWith(`${s}/`))||t}function _e(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),i=n.some(r=>ne(r)),o=i?n[0]:n.pop(),s=i?n.slice(1):n;if(i&&s.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!ve(`/${s.join("/")}`)||s.some(r=>r.includes("[")||r.includes("]")?!ne(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,l=>l.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function ne(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function ve(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function B(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function k(e){return typeof e=="string"&&e.length>0}function x(e,t){let n=new Set(t);return Object.keys(e).every(i=>n.has(i))}function Te(e){if(!e)return[];let t=[],n=0,i=ie(e,n);if(i<0)return t.push(e),t;for(t.push(e.slice(0,i)),n=i;n<e.length;){if(i=ie(e,n+(e.startsWith("::",n)?2:1)),i<0){t.push(e.slice(n));break}t.push(e.slice(n,i)),n=i}return t}function ie(e,t){let n=e.indexOf("/",t),i=e.indexOf("::",t);return n<0?i:i<0?n:Math.min(n,i)}var M="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",z="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var m=class e{constructor(){}static parseMessage(t,n={}){let i=JSON.parse(t);if(!e.isMessage(i,n))throw new Error("Invalid site edit bridge message");return i}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(p(t)&&p(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",i=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:i}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!p(t)||typeof t.type!="string"?!1:t.type==="request"?He(t.payload,n):t.type==="response"||t.type==="error"?p(t.payload)&&typeof t.payload.id=="string":t.type==="event"?p(t.payload)&&p(t.payload.event):t.type==="auth"?p(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?p(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&p(t.payload)&&t.payload.ok===!0}},P=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new U,this.eventDispatcher=new j(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let i=Ae(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"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let i=n.payload,{id:o}=i;switch(i.kind){case"initialize-session":{let s=W(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:re(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,Ne(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(f(s)!==f(r))throw new I(M,"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(f(s)!==f(r))throw new I(M,"History receipt composition does not match the active session.");this.sendResult(o,i.kind,await this.options.engine.getHistoryOperationResult?.({...i.request,composition:D(r)})??null);return}case"undo":case"redo":{let s=await this.resolveWireContext(i),r=i.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==i.kind||f(s)!==f(u))throw new I(M,"History request does not match its cursor operation.")}let a=r?{...r,composition:D(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(t);this.sendJson({type:"error",payload:{...i,message:q(n),code:$(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),i=this.session.activeComposition;if(!i)throw new I(z,"Initialize a composition session before issuing this request.");if(f(i)!==f(n.context))throw new I(M,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=W(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=De(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(f(t))}async normalizeOperationRequest(t,n){let i={...t,composition:D(n)};if(i.target.kind==="route"){let o=i.target,s=W(o),r=await this.resolveAndAssert(s);i.target={...o,composition:D(r)}}return i}handleEngineEvent(t){let n=t?.composition;if(!Me(n))return;let i=f(n);this.session.subscribedCompositionKeys.has(i)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&i===Pe(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(i)))}sendResult(t,n,i){this.sendJson({type:"response",payload:{id:t,kind:n,result:i}})}async handleRawMessage(t){try{await this.handleMessage(m.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let i=Fe(t);this.sendJson({type:"error",payload:{...i,message:q(n),code:$(n)}})}}sendJson(t){this.options.socket.send(m.stringifyMessage(t))}async handleBufferedOperation(t,n,i){this.eventDispatcher.beginBuffering();try{let o=await i();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:q(o),code:$(o)}})}finally{this.eventDispatcher.flush()}}},Oe=256;function Ae(e){if(e.length>Oe||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return p(t)&&t.type==="ping"&&p(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var I=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},j=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},U=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},i=this.queue.then(n,n);return this.queue=i.then(()=>{},()=>{}),i}};function He(e,t){if(!p(e)||typeof e.id!="string"||!m.isRequestKind(e.kind))return!1;let n=R(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||V(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ke(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"execute":case"get-operation-result":return n&&Be(e.request)&&(e.request.mutationContext===void 0||V(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&oe(e.request);case"undo":case"redo":return n&&(e.request===void 0||oe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||V(e.mutationContext))}}function oe(e){return p(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&R(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ke(e){if(e===void 0)return!0;if(!p(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(i=>i==="key"||i==="instanceIndex"||i==="instanceCount")}function Be(e){return p(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&R(e.composition)&&typeof e.kind=="string"&&p(e.target)&&(e.target.kind!=="route"||R(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&p(e.params)}function R(e){return p(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Me(e){return p(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function W(e){if(R(e.composition))return e.composition;throw new I(z,"A composition selector is required for this request.")}function De(e){if(p(e)&&R(e.composition))return e.composition;throw new I(z,"A composition selector is required for execute.")}function D(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Pe(e){return e.activeComposition?f(e.activeComposition):null}function f(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function w(e,t){return p(e)&&e.ok===!0?{...e,composition:t}:e}function Ne(e,t){return!p(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:re(e.data)}}function re(e){let t=e;return se(t.routeId?t:{...t,routeId:t.composition.routeId})}function p(e){return typeof e=="object"&&e!==null}function V(e){return p(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function $(e){if(!(!p(e)||typeof e.code!="string"||e.code.length===0))return e.code}function q(e){return e instanceof Error||p(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function Fe(e){try{return m.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var N=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Ge,computeSiteEditCompositionKey as E}from"@vcp-dev/contracts";var Ye="127.0.0.1",Ze=30218,Xe="/__vcp/site-edit/bridge",fe=6*1024*1024,et=fe*2,tt=3e3,ae=50,J=".vcp/current-snapshot.json",ce="__VCP_SITE_EDIT_BRIDGE_SERVERS__";var Q=class{constructor(t,n=he.createServer((s,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),i=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=i,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new N,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(t={}){if(!this.isStarted){this.stopping=!1;try{A.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(),t.webSocket!==!1){let n=dt({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 Qe({projectRoot:this.options.projectRoot,watch_dirs:it(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??ae,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(),t.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 t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,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 t=at(),n=ct(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),i=JSON.stringify(n);if(i!==this.lastNotifiedHealth){this.lastNotifiedHealth=i;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let i=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??qe)({...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)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,i?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let i=ot(t.composition),o=this.getRuntime(),s=S(i);await o.initializeComposition(s);let a=o.getDocument(s).data;await this.recordRuntimeVersion(a.version,i);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:i,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),i=S(t);await n.initializeComposition(i);let o=n.getDocument(i);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(S(t)),getObjectEditContext:async(t,n,i)=>this.getRuntime().getObjectEditContext(t,S(n),i),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,S(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(S(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:S(t.composition)}),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:S(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return de(i,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}runHistoryWithReceipt(t,n,i){if(i&&(!this.isActiveReceiptIdentity(i)||i.kind!==t||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 de(s,void 0,n);let r=await this.getRuntime()[t]();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(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return X("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let i=this.operationReceiptKey(t),o=this.operationFingerprint(t),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,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(i)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let i=await(this.dependencies.openHistoryStore??je)(rt({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));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,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let i=n?E(n):null;i&&this.runtimeVersionFloors.set(i,Math.max(this.runtimeVersionFloors.get(i)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let s=i?this.runtimeVersionFloors.get(i)??t:t,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,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let i of t)this.pendingChangedFiles.add(i);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??ae;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,s)=>o.localeCompare(s));this.pendingChangedFiles.clear();let n=t.some(Ie)?this.scheduleSnapshotIdentityAdvance():!1,i=t.filter(o=>!yt(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 t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=A.readFileSync(y.join(this.options.projectRoot,J),"utf8"),n=JSON.parse(t),i=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!i||G(i)!==i?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):i}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);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:t,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?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=st(this.options.projectRoot),i=Je(n),o=i.length>0?i:(this.options.runtime.routes??[]).map(c=>({...c})),s=ze({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(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(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(c=>[E(c.context),c])),u=new Map(s.map(c=>[E(c.context),c]));if(this.runtime){for(let[c,l]of a){let C=u.get(c);(!C||C.entryFile!==l.entryFile)&&this.runtime.unregisterComposition(S(l.context))}for(let[c,l]of u){let C=a.get(c);(!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,t)throw i;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Le(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let i=this.routes.find(r=>r.routeId===n);if(!i)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Ue({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.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(t=>{let n=this.runtimeVersionFloors.get(E(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function ge(e){let t=new Q(nt(e),he.createServer(),!1);return t.start({listen:!1,webSocket:!1}),{engine:t.getEngine(),getHealth:()=>t.getHealth(),stop:()=>t.stop()}}function nt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:y.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Ye,port:e.port??Ze,path:e.path??Xe,sessionKey:e.sessionKey??mt(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function it(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function st(e){let t=[],n=["app","src/app",".vcp"],i=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=s=>{if(!A.existsSync(s))return;let r;try{r=A.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 u=y.join(s,a.name),c="";try{c=A.readFileSync(u,"utf8")}catch{}t.push({path:y.relative(e,u).replaceAll(y.sep,"/"),content:c})}};for(let s of n)o(y.join(e,s));return t.sort((s,r)=>s.path.localeCompare(r.path))}function ot(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function S(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function rt(e){return y.join(y.resolve(e.root),G(e.siteId),G(e.snapshotId),X("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function G(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:X("sha256").update(e).digest("hex").slice(0,32)}function at(){let e=globalThis;return e[ce]??=new Map,e[ce]}function ct(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function de(e,t,n){let i=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.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:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:i,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function dt(e){let t=new $e({maxPayload:fe,noServer:!0}),n=new WeakSet,i=s=>{new P({socket:new Y(s),engine:e.engine,validateOperationRequest:r=>Ge.safeParse(r).success})},o=(s,r,a)=>{if(!ut(s,e))return;let u=pt(s,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),r.destroy();return}
|
|
4
|
+
`),r.destroy();return}u.authenticatedByHeader&&n.add(s),t.handleUpgrade(s,r,a,c=>{t.emit("connection",c,s)})};return e.server.on("upgrade",o),t.on("connection",(s,r)=>{if(n.has(r)){i(s);return}ht(s,e.sessionKey,()=>{i(s)})}),t.stop=()=>{e.server.off("upgrade",o);for(let s of t.clients)s.close(1001,"bridge stopped");t.close()},t}var Y=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===le.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>et){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function ut(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function pt(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let i=L(e.headers["x-vcp-site-edit-key"]),o=me(i,t.sessionKey),s=L(e.headers.host),r=L(e.headers.origin);return s&&!lt(s,t.host,r)?null:r?gt(r,s,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ht(e,t,n){let i=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},tt),o,s=()=>{clearTimeout(i),e.off("message",o),e.off("close",s)},r=()=>{s(),e.close(1008,"bridge authentication failed")};o=a=>{try{let u=m.parseMessage(a.toString());if(u.type!=="auth"||!me(u.payload.key,t)){r();return}s(),e.readyState===le.OPEN&&e.send(m.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",s)}function me(e,t){if(!e)return!1;let n=Buffer.from(e),i=Buffer.from(t);return n.length===i.length&&Ve(n,i)}function lt(e,t,n){let i=pe(e),o=pe(t);return i===o||ue(o)&&ue(i)&&(!n||Z(n,e))||ft(o)&&(!n||Z(n,e))}function ft(e){return e==="0.0.0.0"||e==="::"}function ue(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function gt(e,t,n){return n.includes(e)||(t?Z(e,t):!1)}function Z(e,t){try{return new URL(e).host===ye(t)}catch{return!1}}function pe(e){let t=ye(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function ye(e){return e.trim().toLowerCase()}function L(e){return Array.isArray(e)?e[0]:e}function mt(){return We(32).toString("base64url")}function Ie(e){let t=e.replaceAll("\\","/");return t===J||t.endsWith(`/${J}`)}function yt(e){let t=e.replaceAll("\\","/");return Ie(e)||t===".vcp/workspace-state.json"||t.startsWith(".vcp/snapshot-store/")}var v=It;if(!v)throw new Error("site edit engine worker must run inside worker_threads");var _=e=>{v.postMessage(e)},wt=(e,t)=>{try{v.postMessage({type:"result",id:e,ok:!0,value:t})}catch(n){if(n instanceof Error&&n.name==="DataCloneError"){v.postMessage({type:"result",id:e,ok:!0,value:t===void 0?void 0:JSON.parse(JSON.stringify(t))});return}throw n}},{options:Ct}=St,H;try{H=ge({...Ct,onSnapshotIdChanged:(e,t)=>{_({type:"snapshot-id-changed",next:e,previous:t})},onHealthChanged:e=>{_({type:"health",health:e})}})}catch(e){_({type:"start-failed",error:F(e)}),process.exit(1)}H.engine.subscribe(e=>{_({type:"event",event:e})});var bt=async e=>{try{let t=H.engine[e.method],n=await t(...e.args);wt(e.id,n)}catch(t){_({type:"result",id:e.id,ok:!1,error:F(t)})}};v.on("message",e=>{if(e.type==="call"){bt(e);return}e.type==="stop"&&(H.stop(),v.close())});_({type:"ready",health:H.getHealth()});
|