@vcp-dev/site-edit-bridge 0.6.5 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-bootstrap.js +31 -1
- package/dist/client.js +1 -1
- package/dist/designer-trace.js +1 -1
- package/dist/index.js +33 -3
- package/dist/next-dev-server.js +3 -3
- package/dist/server.d.ts +1 -0
- package/dist/server.js +1 -1
- package/dist/window-message.d.ts +121 -1
- package/dist/window-message.js +1 -1
- package/package.json +4 -4
package/dist/next-dev-server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import st from"node:http";import{existsSync as w,readFileSync as S}from"node:fs";import{createRequire as pe}from"node:module";import R from"node:path";import{basename as ge,dirname as x,join as b}from"node:path";import{fileURLToPath as me}from"node:url";import Te from"node:http";import{createHash as ie,randomBytes as He,timingSafeEqual as Be}from"node:crypto";import L from"node:path";import{WebSocket as oe,WebSocketServer as je}from"ws";import{createPreviewSiteEditEngineRuntime as Ae,openFileHistoryStore as De}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Me,scanNextAppRouterRoutes as Ue}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ne}from"@vcp-dev/site-edit-engine/source-watcher";function U(t){let e=new Map,n=[],s=new Map,r=[],i=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],o=new Map(i.map((a,u)=>[a,u])),c=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(a=>({placementKey:a.placementKey,placementUnitKey:a.placementUnitKey,relation:a.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},d=t.entries.flatMap((a,u)=>a.dynamicDataSummary?[[u,a.dynamicDataSummary]]:[]),h=a=>{let u=e.get(a);if(typeof u=="number")return u;let l=n.length;return n.push(a),e.set(a,l),l},g=a=>{let u=null;for(let l of Ce(a)){let k=`${u??"root"}\0${l}`,I=s.get(k);if(typeof I=="number"){u=I;continue}let m=r.length;r.push([u,h(l)]),s.set(k,m),u=m}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,pageComposition:c,tokens:n,nodes:r,entries:t.entries.map(a=>{let u=a.pageCompositionUnitKey?o.get(a.pageCompositionUnitKey)??-1:-1;if(a.pageCompositionUnitKey&&u<0)throw new Error(`Render entry ${a.key} references unknown page composition unit ${a.pageCompositionUnitKey}`);return[g(a.key),ve(a.operationSummary),...u>=0?[u]:[]]}),...d.length>0?{dynamicDataSummaries:d}:{}}}function ve(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function Ce(t){if(!t)return[];let e=[],n=0,s=Y(t,n);if(s<0)return e.push(t),e;for(e.push(t.slice(0,s)),n=s;n<t.length;){if(s=Y(t,n+(t.startsWith("::",n)?2:1)),s<0){e.push(t.slice(n));break}e.push(t.slice(n,s)),n=s}return e}function Y(t,e){let n=t.indexOf("/",e),s=t.indexOf("::",e);return n<0?s:s<0?n:Math.min(n,s)}var p=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let n=e.payload,s=typeof n.id=="string"?n.id:"unknown",r=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:s,kind:r}}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==="undo"||e==="redo"}static isMessage(e,n={}){return!f(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?f(e.payload)&&typeof e.payload.id=="string":e.type==="event"?f(e.payload)&&f(e.payload.event):e.type==="auth"?f(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?f(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,n={}){if(!f(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"initialize-session":return typeof e.routeId=="string"&&(e.mutationContext===void 0||N(e.mutationContext));case"get-document":case"get-style-context":return typeof e.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-history-status":return e.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return Ee(e.request)&&(e.request.mutationContext===void 0||N(e.request.mutationContext))&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return e.mutationContext===void 0||N(e.mutationContext)}}},P=class{constructor(e){this.options=e,this.messageQueue=new V,this.eventDispatcher=new O(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.eventDispatcher.push(n)}),e.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(s){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:s instanceof Error?s.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let s=n.payload,{id:r}=s;switch(s.kind){case"initialize-session":{let i=await this.options.engine.initializeSession({routeId:s.routeId,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:{document:U(i.data.document),historyStatus:i.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:U((await this.options.engine.getDocument(s.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getStyleContext(s.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getObjectEditContext(s.key,s.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getClassNameSource(s.key,s.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceFile({path:s.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.resolveSourceLocation({key:s.key,routeId:s.routeId})}});return;case"execute":{await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.execute(s.request));return}case"undo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.redo());return}}catch(n){let s=p.extractRequestInfo(e);this.sendJson({type:"error",payload:{...s,message:X(n),code:Z(n)}})}}async handleRawMessage(e){try{await this.handleMessage(p.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=n instanceof Error?n.message:"Invalid websocket message",r=Pe(e);this.sendJson({type:"error",payload:{...r,message:s}})}}sendJson(e){this.options.socket.send(p.stringifyMessage(e))}async handleBufferedOperation(e,n,s){this.eventDispatcher.beginBuffering();try{let r=await s();this.sendJson({type:"response",payload:{id:e,kind:n,result:r}}),this.eventDispatcher.flush()}catch(r){this.sendJson({type:"error",payload:{id:e,kind:n,message:X(r),code:Z(r)}}),this.eventDispatcher.flush()}}},O=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},V=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function f(t){return typeof t=="object"&&t!==null}function Ee(t){return f(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&f(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&f(t.params)}function N(t){return _e(t)}function Z(t){if(!t||typeof t!="object")return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function X(t){if(t instanceof Error)return t.message;if(!t||typeof t!="object")return"Unknown websocket operation failure";let e=t.message;return typeof e=="string"&&e.length>0?e:"Unknown websocket operation failure"}function _e(t){return f(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:!1}function Pe(t){try{return p.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var T=class{constructor(){this.tail=Promise.resolve()}run(e){let n=this.tail.then(e,e);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Oe}from"@vcp-dev/contracts";var Ve="127.0.0.1",Fe=30218,Ke="/__vcp/site-edit/bridge",ae=6*1024*1024,Le=ae*2,qe=3e3,ee=50,te="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function ue(t,e,n={}){let s=new q($e(e),t,!1,n);return s.start({listen:!1}),s}var q=class{constructor(e,n=Te.createServer((i,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),s=!0,r={}){this.options=e,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=r,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new T,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=Ge({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new Ne({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??ee,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:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let e=!!this.runtime;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=We(),n=ze(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createRuntime(e,n=null){let s=this.runtime;this.activeHistoryStore=e??null;let r=(this.dependencies.createRuntime??Ae)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let o of this.eventListeners)o(i)},...e?{historyStore:e}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=r,this.activeHistorySessionId=n,s?.dispose()}createBridgeEngine(){return{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{runtime:s,resolvedRouteId:r}=await this.activateRoute(e.routeId),i=s.getDocument(r).data;await this.recordRuntimeVersion(i.version);let o=(await s.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:o}}}),getDocument:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e),r=n.getDocument(s);return await this.recordRuntimeVersion(r.data.version),r},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e);return n.getStyleContext(s)},getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let s=this.getRuntime(),r=n?this.resolveRouteId(n):void 0;return s.getClassNameSource(e,r)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute:(e,n)=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return F(s,e);let r=await this.getRuntime().executeOperation(this.normalizeRequest(e));return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion),r}),undo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}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 s=await(this.dependencies.openHistoryStore??De)(Je({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let r=s.readDocumentVersion?await s.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,r),this.createRuntime(s,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){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,e);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(e){let n=this.getRuntime(),s=this.resolveRouteId(e);return await n.setActiveRoute(s),{runtime:n,resolvedRouteId:s}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let s of e)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??ee;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((n,s)=>n.localeCompare(s));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of e)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:Ue(this.options.projectRoot),n=new Map(this.routes.map(r=>[r.routeId,r.entryFile])),s=new Set(e.map(r=>r.routeId));this.routes=e;for(let r of e)n.get(r.routeId)!==r.entryFile&&this.runtime?.registerRoute(r.routeId,r.entryFile);for(let r of n.keys())s.has(r)||this.runtime?.unregisterRoute(r)}resolveRouteId(e){let n=Me(e,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function $e(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:L.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??Ve,port:t.port??Fe,path:t.path??Ke,sessionKey:t.sessionKey??nt(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function Je(t){return L.join(L.resolve(t.root),ne(t.siteId),ne(t.snapshotId),ie("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function ne(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:ie("sha256").update(t).digest("hex").slice(0,32)}function We(){let t=globalThis;return t[te]??=new Map,t[te]}function ze(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function F(t,e){return{ok:!1,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ge(t){let e=new je({maxPayload:ae,noServer:!0}),n=new WeakSet,s=i=>{new P({socket:new $(i),engine:t.engine,validateOperationRequest:o=>Oe.safeParse(o).success})},r=(i,o,c)=>{if(!Qe(i,t))return;let d=Ye(i,t);if(!d){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import st from"node:http";import{existsSync as w,readFileSync as S}from"node:fs";import{createRequire as pe}from"node:module";import R from"node:path";import{basename as ge,dirname as x,join as b}from"node:path";import{fileURLToPath as me}from"node:url";import Te from"node:http";import{createHash as ie,randomBytes as He,timingSafeEqual as Be}from"node:crypto";import L from"node:path";import{WebSocket as oe,WebSocketServer as je}from"ws";import{createPreviewSiteEditEngineRuntime as Ae,openFileHistoryStore as De}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Me,scanNextAppRouterRoutes as Ue}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Ne}from"@vcp-dev/site-edit-engine/source-watcher";function U(t){let e=new Map,n=[],s=new Map,r=[],i=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],o=new Map(i.map((a,u)=>[a,u])),c=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(a=>({placementKey:a.placementKey,placementUnitKey:a.placementUnitKey,relation:a.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},d=t.entries.flatMap((a,u)=>a.dynamicDataSummary?[[u,a.dynamicDataSummary]]:[]),h=a=>{let u=e.get(a);if(typeof u=="number")return u;let l=n.length;return n.push(a),e.set(a,l),l},g=a=>{let u=null;for(let l of Ce(a)){let v=`${u??"root"}\0${l}`,I=s.get(v);if(typeof I=="number"){u=I;continue}let m=r.length;r.push([u,h(l)]),s.set(v,m),u=m}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,pageComposition:c,tokens:n,nodes:r,entries:t.entries.map(a=>{let u=a.pageCompositionUnitKey?o.get(a.pageCompositionUnitKey)??-1:-1;if(a.pageCompositionUnitKey&&u<0)throw new Error(`Render entry ${a.key} references unknown page composition unit ${a.pageCompositionUnitKey}`);return[g(a.key),ke(a.operationSummary),...u>=0?[u]:[]]}),...d.length>0?{dynamicDataSummaries:d}:{}}}function ke(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function Ce(t){if(!t)return[];let e=[],n=0,s=Y(t,n);if(s<0)return e.push(t),e;for(e.push(t.slice(0,s)),n=s;n<t.length;){if(s=Y(t,n+(t.startsWith("::",n)?2:1)),s<0){e.push(t.slice(n));break}e.push(t.slice(n,s)),n=s}return e}function Y(t,e){let n=t.indexOf("/",e),s=t.indexOf("::",e);return n<0?s:s<0?n:Math.min(n,s)}var p=class t{constructor(){}static parseMessage(e,n={}){let s=JSON.parse(e);if(!t.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let n=e.payload,s=typeof n.id=="string"?n.id:"unknown",r=t.isRequestKind(n.kind)?n.kind:"get-document";return{id:s,kind:r}}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==="undo"||e==="redo"}static isMessage(e,n={}){return!f(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,n):e.type==="response"||e.type==="error"?f(e.payload)&&typeof e.payload.id=="string":e.type==="event"?f(e.payload)&&f(e.payload.event):e.type==="auth"?f(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?f(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,n={}){if(!f(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"initialize-session":return typeof e.routeId=="string"&&(e.mutationContext===void 0||N(e.mutationContext));case"get-document":case"get-style-context":return typeof e.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-history-status":return e.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return Ee(e.request)&&(e.request.mutationContext===void 0||N(e.request.mutationContext))&&(n.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return e.mutationContext===void 0||N(e.mutationContext)}}},P=class{constructor(e){this.options=e,this.messageQueue=new V,this.eventDispatcher=new O(n=>{this.sendJson(n)}),this.unsubscribe=e.engine.subscribe(n=>{this.eventDispatcher.push(n)}),e.socket.onmessage=n=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(s){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:s instanceof Error?s.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let n=e;if(n.type!=="request")return;let s=n.payload,{id:r}=s;switch(s.kind){case"initialize-session":{let i=await this.options.engine.initializeSession({routeId:s.routeId,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:{document:U(i.data.document),historyStatus:i.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:{ok:!0,data:U((await this.options.engine.getDocument(s.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getStyleContext(s.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getObjectEditContext(s.key,s.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getClassNameSource(s.key,s.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.getSourceFile({path:s.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:r,kind:s.kind,result:await this.options.engine.resolveSourceLocation({key:s.key,routeId:s.routeId})}});return;case"execute":{await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.execute(s.request));return}case"undo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(r,s.kind,()=>this.options.engine.redo());return}}catch(n){let s=p.extractRequestInfo(e);this.sendJson({type:"error",payload:{...s,message:X(n),code:Z(n)}})}}async handleRawMessage(e){try{await this.handleMessage(p.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=n instanceof Error?n.message:"Invalid websocket message",r=Pe(e);this.sendJson({type:"error",payload:{...r,message:s}})}}sendJson(e){this.options.socket.send(p.stringifyMessage(e))}async handleBufferedOperation(e,n,s){this.eventDispatcher.beginBuffering();try{let r=await s();this.sendJson({type:"response",payload:{id:e,kind:n,result:r}}),this.eventDispatcher.flush()}catch(r){this.sendJson({type:"error",payload:{id:e,kind:n,message:X(r),code:Z(r)}}),this.eventDispatcher.flush()}}},O=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let n={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(n=>{this.send(n)})}},V=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await e()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function f(t){return typeof t=="object"&&t!==null}function Ee(t){return f(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&f(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&f(t.params)}function N(t){return _e(t)}function Z(t){if(!t||typeof t!="object")return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function X(t){if(t instanceof Error)return t.message;if(!t||typeof t!="object")return"Unknown websocket operation failure";let e=t.message;return typeof e=="string"&&e.length>0?e:"Unknown websocket operation failure"}function _e(t){return f(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:!1}function Pe(t){try{return p.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var T=class{constructor(){this.tail=Promise.resolve()}run(e){let n=this.tail.then(e,e);return this.tail=n.then(()=>{},()=>{}),n}};import{SiteEditOperationRequestSchema as Oe}from"@vcp-dev/contracts";var Ve="127.0.0.1",Fe=30218,Ke="/__vcp/site-edit/bridge",ae=6*1024*1024,Le=ae*2,qe=3e3,ee=50,te="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function ue(t,e,n={}){let s=new q($e(e),t,!1,n);return s.start({listen:!1}),s}var q=class{constructor(e,n=Te.createServer((i,o)=>{o.writeHead(404),o.end("VCP site edit bridge server")}),s=!0,r={}){this.options=e,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=r,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new T,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let n=Ge({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=n.stop,this.stopWatching=new Ne({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??ee,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:s=>this.handleFileChanged(s),on_batch_change:s=>this.handleFilesChanged(s)}).start(),e.listen!==!1&&this.server.listen(this.options.port,this.options.host)}getHealth(){let e=!!this.runtime;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=We(),n=ze(this.options);e.get(n)===this&&e.delete(n),this.isStarted=!1}createRuntime(e,n=null){let s=this.runtime;this.activeHistoryStore=e??null;let r=(this.dependencies.createRuntime??Ae)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version);for(let o of this.eventListeners)o(i)},...e?{historyStore:e}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=r,this.activeHistorySessionId=n,s?.dispose()}createBridgeEngine(){return{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{runtime:s,resolvedRouteId:r}=await this.activateRoute(e.routeId),i=s.getDocument(r).data;await this.recordRuntimeVersion(i.version);let o=(await s.getHistoryStatus()).data;return{ok:!0,data:{document:i,historyStatus:o}}}),getDocument:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e),r=n.getDocument(s);return await this.recordRuntimeVersion(r.data.version),r},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async e=>{let{runtime:n,resolvedRouteId:s}=await this.activateRoute(e);return n.getStyleContext(s)},getObjectEditContext:async(e,n)=>this.getRuntime().getObjectEditContext(e,n?this.resolveRouteId(n):void 0),getClassNameSource:async(e,n)=>{let s=this.getRuntime(),r=n?this.resolveRouteId(n):void 0;return s.getClassNameSource(e,r)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute:(e,n)=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return F(s,e);let r=await this.getRuntime().executeOperation(this.normalizeRequest(e));return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion),r}),undo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().undo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),redo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return F(e);let n=await this.getRuntime().redo();return n.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(n.data.resultVersion),n}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}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 s=await(this.dependencies.openHistoryStore??De)(Je({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let r=s.readDocumentVersion?await s.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,r),this.createRuntime(s,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){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,e);let n=this.activeHistoryStore;return n?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>n.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(e){let n=this.getRuntime(),s=this.resolveRouteId(e);return await n.setActiveRoute(s),{runtime:n,resolvedRouteId:s}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let s of e)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??ee;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((n,s)=>n.localeCompare(s));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let n of e)this.runtime?.notifyFileChanged(n)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:Ue(this.options.projectRoot),n=new Map(this.routes.map(r=>[r.routeId,r.entryFile])),s=new Set(e.map(r=>r.routeId));this.routes=e;for(let r of e)n.get(r.routeId)!==r.entryFile&&this.runtime?.registerRoute(r.routeId,r.entryFile);for(let r of n.keys())s.has(r)||this.runtime?.unregisterRoute(r)}resolveRouteId(e){let n=Me(e,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return n}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function $e(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:L.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??Ve,port:t.port??Fe,path:t.path??Ke,sessionKey:t.sessionKey??nt(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function Je(t){return L.join(L.resolve(t.root),ne(t.siteId),ne(t.snapshotId),ie("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function ne(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:ie("sha256").update(t).digest("hex").slice(0,32)}function We(){let t=globalThis;return t[te]??=new Map,t[te]}function ze(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function F(t,e){return{ok:!1,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function Ge(t){let e=new je({maxPayload:ae,noServer:!0}),n=new WeakSet,s=i=>{new P({socket:new $(i),engine:t.engine,validateOperationRequest:o=>Oe.safeParse(o).success})},r=(i,o,c)=>{if(!Qe(i,t))return;let d=Ye(i,t);if(!d){o.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
|
-
`),o.destroy();return}d.authenticatedByHeader&&n.add(i),e.handleUpgrade(i,o,c,h=>{e.emit("connection",h,i)})};return t.server.on("upgrade",r),e.on("connection",(i,o)=>{if(n.has(o)){s(i);return}Ze(i,t.sessionKey,()=>{s(i)})}),e.stop=()=>{t.server.off("upgrade",r);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var $=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===oe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Le){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Qe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ye(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=K(t.headers["x-vcp-site-edit-key"]),r=ce(s,e.sessionKey),i=K(t.headers.host),o=K(t.headers.origin);return i&&!Xe(i,e.host,o)?null:o?tt(o,i,e.allowedOrigins)?{authenticatedByHeader:r}:null:r?{authenticatedByHeader:!0}:null}function Ze(t,e,n){let s=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},qe),r,i=()=>{clearTimeout(s),t.off("message",r),t.off("close",i)},o=()=>{i(),t.close(1008,"bridge authentication failed")};r=c=>{try{let d=p.parseMessage(c.toString());if(d.type!=="auth"||!ce(d.payload.key,e)){o();return}i(),t.readyState===oe.OPEN&&t.send(p.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{o()}},t.on("message",r),t.on("close",i)}function ce(t,e){if(!t)return!1;let n=Buffer.from(t),s=Buffer.from(e);return n.length===s.length&&Be(n,s)}function Xe(t,e,n){let s=re(t),r=re(e);return s===r||se(r)&&se(s)&&(!n||J(n,t))||et(r)&&(!n||J(n,t))}function et(t){return t==="0.0.0.0"||t==="::"}function se(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function tt(t,e,n){return n.includes(t)||(e?J(t,e):!1)}function J(t,e){try{return new URL(t).host===de(e)}catch{return!1}}function re(t){let e=de(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function de(t){return t.trim().toLowerCase()}function K(t){return Array.isArray(t)?t[0]:t}function nt(){return He(32).toString("base64url")}var rt="next",it="127.0.0.1",ot=3e3,B="/__vcp/site-edit/bridge",ye="/__vcp/site-edit/health",j="/__vcp/site-edit/client/",at=`${j}auto-bootstrap.js`,Se='data-vcp-site-edit-bootstrap="true"',ut=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ct="@vcp-dev/site-edit-engine/webpack-loader",dt=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ht=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],lt=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Sn(t={},e={}){let n=e.process??process,s=e.createServer??st.createServer,r=e.attachBridgeServer??ue,i=e.loadNext??Vt,o=R.resolve(t.projectRoot??process.cwd()),c=t.host??it,d=t.port??qt(n.env.PORT)??ot,h=t.bridgePath??B,g=wt(h),a=Dt(),u=t.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",l=(t.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,
|
|
4
|
+
`),o.destroy();return}d.authenticatedByHeader&&n.add(i),e.handleUpgrade(i,o,c,h=>{e.emit("connection",h,i)})};return t.server.on("upgrade",r),e.on("connection",(i,o)=>{if(n.has(o)){s(i);return}Ze(i,t.sessionKey,()=>{s(i)})}),e.stop=()=>{t.server.off("upgrade",r);for(let i of e.clients)i.close(1001,"bridge stopped");e.close()},e}var $=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",n=>{this.onmessage?.({data:n.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===oe.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>Le){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,n){this.socket.close(e,n)}};function Qe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function Ye(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=K(t.headers["x-vcp-site-edit-key"]),r=ce(s,e.sessionKey),i=K(t.headers.host),o=K(t.headers.origin);return i&&!Xe(i,e.host,o)?null:o?tt(o,i,e.allowedOrigins)?{authenticatedByHeader:r}:null:r?{authenticatedByHeader:!0}:null}function Ze(t,e,n){let s=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},qe),r,i=()=>{clearTimeout(s),t.off("message",r),t.off("close",i)},o=()=>{i(),t.close(1008,"bridge authentication failed")};r=c=>{try{let d=p.parseMessage(c.toString());if(d.type!=="auth"||!ce(d.payload.key,e)){o();return}i(),t.readyState===oe.OPEN&&t.send(p.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{o()}},t.on("message",r),t.on("close",i)}function ce(t,e){if(!t)return!1;let n=Buffer.from(t),s=Buffer.from(e);return n.length===s.length&&Be(n,s)}function Xe(t,e,n){let s=re(t),r=re(e);return s===r||se(r)&&se(s)&&(!n||J(n,t))||et(r)&&(!n||J(n,t))}function et(t){return t==="0.0.0.0"||t==="::"}function se(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function tt(t,e,n){return n.includes(t)||(e?J(t,e):!1)}function J(t,e){try{return new URL(t).host===de(e)}catch{return!1}}function re(t){let e=de(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function de(t){return t.trim().toLowerCase()}function K(t){return Array.isArray(t)?t[0]:t}function nt(){return He(32).toString("base64url")}var rt="next",it="127.0.0.1",ot=3e3,B="/__vcp/site-edit/bridge",ye="/__vcp/site-edit/health",j="/__vcp/site-edit/client/",at=`${j}auto-bootstrap.js`,Se='data-vcp-site-edit-bootstrap="true"',ut=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ct="@vcp-dev/site-edit-engine/webpack-loader",dt=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,ht=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],lt=new Set(["auto-bootstrap.js","client.js","designer-trace.js","document-codec.js","protocol.js","window-message.js"]);async function Sn(t={},e={}){let n=e.process??process,s=e.createServer??st.createServer,r=e.attachBridgeServer??ue,i=e.loadNext??Vt,o=R.resolve(t.projectRoot??process.cwd()),c=t.host??it,d=t.port??qt(n.env.PORT)??ot,h=t.bridgePath??B,g=wt(h),a=Dt(),u=t.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",l=(t.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,v=await i(o),I=ft(o),m=v({dev:!0,dir:o,hostname:c,port:d,...pt(I)}),Re=m.getRequestHandler(),xe=t.siteId??n.env.VCP_SITE_ID??"site_preview",be=t.snapshotId??n.env.VCP_SNAPSHOT_ID??Lt(o),G=t.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,Q=G?.trim()?R.resolve(G):void 0,k=null,y=s((M,_)=>{Ct({basePath:u,bridgePath:h,bridgeHealthPath:g,bridgeSessionKey:a,getBridgeHealth:()=>k?.getHealth()??_t(h),handle:Re,request:M,response:_}).catch(ve=>{console.error(ve),_.headersSent||(_.statusCode=500),_.end("site edit preview request failed")})}),A=null,C=null,D=()=>C||(H(()=>n.off("SIGINT",E)),H(()=>n.off("SIGTERM",E)),H(()=>A?.()),A=null,H(()=>k?.stop()),k=null,C=Promise.allSettled([Jt(y),Wt(()=>m.close())]).then(()=>{}),C),E=()=>{D()};try{return await m.prepare(),k=r(y,{...l?{tenantId:l}:{},siteId:xe,snapshotId:be,projectRoot:o,basePath:u,host:c,port:d,path:h,sessionKey:a,...Q?{historyRoot:Q}:{}}),A=yt({server:y,bridgePath:h,handleUpgrade:m.getUpgradeHandler()}),n.on("SIGINT",E),n.on("SIGTERM",E),await $t(y,d,c),{bundler:I,close:D,host:c,port:zt(y,d),server:y}}catch(M){throw await D(),M}}function ft(t){let e=gt(t);return e&&mt(e)?"webpack":"turbopack"}function pt(t){return t==="webpack"?{webpack:!0}:{turbopack:!0}}function gt(t){for(let e of ut){let n=b(t,e);if(w(n))return S(n,"utf8")}return null}function mt(t){return t.includes(ct)?!0:dt.test(t)&&ht.some(e=>e.test(t))}function yt(t){let e=(n,s,r)=>{St(n.url,t.bridgePath)||t.handleUpgrade(n,s,r).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return t.server.on("upgrade",e),()=>t.server.off("upgrade",e)}function St(t,e){return new URL(t??"/","http://localhost").pathname===e}function wt(t=B){if(t===B)return ye;let e=(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"");return e.endsWith("/bridge")?`${e.slice(0,-7)}/health`:e?`${e}/health`:"/health"}function It(t){let e=JSON.stringify({basePath:t.basePath,wsPath:t.bridgePath,bridge_session_key:t.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:t.runtimeVersions??Rt()});return`<script type="module" ${Se}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(at)};void startSiteEditAutoBootstrap(window, ${e}).catch(() => undefined);</script>`}function Rt(){return{bridge:W("@vcp-dev/site-edit-bridge"),contracts:W("@vcp-dev/contracts"),engine:W("@vcp-dev/site-edit-engine")}}function W(t){let e=pe(import.meta.url);try{let n=e.resolve(t),s=xt(n,t);if(!s)return;let r=JSON.parse(S(s,"utf8"));return typeof r.version=="string"?r.version:void 0}catch{return}}function xt(t,e){let n=R.parse(t).root,s=x(t);for(;s&&s!==n;){let r=b(s,"package.json");if(w(r))try{if(JSON.parse(S(r,"utf8")).name===e)return r}catch{return}s=x(s)}}function bt(t,e){if(t.includes(Se))return t;let n=It(e),s=/<\/body\s*>/i.exec(t);return s?`${t.slice(0,s.index)}${n}${t.slice(s.index)}`:`${t}${n}`}function wn(t,e=x(me(import.meta.url)),n=w){return we(t,e,n)?.path??null}function we(t,e=x(me(import.meta.url)),n=w){let s=new URL(t??"/","http://localhost").pathname;if(!s.startsWith(j))return null;let r=s.slice(j.length);if(!lt.has(r))return null;let i=z(Ft(e),r);if(ge(e)!=="src")return{path:i,requiresTranspile:!1};let o=z(e,r.replace(/\.js$/,".ts"));return n(o)?{path:o,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function vt(t,e){let n=we(t.url);if(!n)return!1;if(!w(n.path))return e.writeHead(404),e.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await kt(S(n.path,"utf8")):S(n.path);return e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),e.end(s),!0}async function kt(t){let e=await import("typescript");return e.transpileModule(t,{compilerOptions:{module:e.ModuleKind.ES2022,target:e.ScriptTarget.ES2022}}).outputText}async function Ct({basePath:t,bridgePath:e,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:r,handle:i,request:o,response:c}){if(Et(o,c,n,r)||await vt(o,c))return;let d=Pt(o),h=Tt(o),g=d||h?jt(c,{basePath:t,bridgePath:e,bridgeSessionKey:s,patchNextDevChunk:h}):()=>{};try{await i(o,c)}catch(a){throw g(),a}}function Et(t,e,n,s){if(t.method!=="GET"||new URL(t.url??"/","http://localhost").pathname!==n)return!1;let i=s();return e.writeHead(i.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(i)),!0}function _t(t){return{ok:!1,bridgePath:t,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Pt(t){return Ht(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Tt(t){return Bt(t)?(t.headers["accept-encoding"]="identity",!0):!1}function Ht(t){if(t.method!=="GET")return!1;let e=new URL(t.url??"/","http://localhost").pathname;if(e.startsWith("/_next/")||e.startsWith(j)||e===B||e===ye)return!1;let n=t.headers.accept??"";return n===""||n.includes("text/html")}function Bt(t){if(t.method!=="GET"||!String(t.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(t.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function jt(t,e){let n=[],s=t,r=s.flushHeaders.bind(t),i=s.write.bind(t),o=s.end.bind(t);return s.flushHeaders=()=>{},s.write=(c,d,h)=>(c!==void 0&&n.push(he(c,le(d))),fe(d),fe(h),!0),s.end=(c,d,h)=>{let g=typeof c=="function"?void 0:c;g!==void 0&&n.push(he(g,le(d))),s.write=i,s.end=o,s.flushHeaders=r;let a=Buffer.concat(n),u=At(t,a,e);u!==a&&!t.headersSent&&t.removeHeader("content-length");let l=typeof c=="function"?c:typeof d=="function"?d:typeof h=="function"?h:void 0;return l?o(u,l):o(u)},()=>{s.write=i,s.end=o,s.flushHeaders=r}}function At(t,e,n){if(Mt(t,e))return Buffer.from(bt(e.toString("utf8"),n));if(n.patchNextDevChunk&&Ut(t)){let s=e.toString("utf8"),r=Nt(s);if(r!==s)return Buffer.from(r)}return e}function Dt(){let t=new Uint8Array(32);return globalThis.crypto.getRandomValues(t),Buffer.from(t).toString("base64url")}function Mt(t,e){if(t.statusCode<200||t.statusCode>=300)return!1;let n=t.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return e.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function Ut(t){if(t.statusCode<200||t.statusCode>=300)return!1;let e=t.getHeader("content-type"),n=Array.isArray(e)?e.join(";"):String(e??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function Nt(t){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
|
|
5
5
|
`),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
|
|
6
|
-
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[s,r])=>Ot(n,s,r),t)}function Ot(t,e,n){if(n.length>e.length)throw new Error("Replacement must not be longer than the search string.");return t.replaceAll(e,n.padEnd(e.length," "))}function he(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function le(t){return typeof t=="string"?t:void 0}function fe(t){typeof t=="function"&&t()}async function Vt(t){let n=pe(b(t,"package.json"))(rt);return n.default??n}function Ft(t){return ge(t)!=="src"?t:z(Kt(t),"dist")}function Kt(t){return Ie(t)?R.posix.dirname(t):x(t)}function z(t,e){return Ie(t)?R.posix.join(t,e):b(t,e)}function Ie(t){return t.includes("/")&&!t.includes("\\")}function Lt(t){let e=b(t,".vcp/current-snapshot.json");if(!w(e))return"sandbox_worktree";try{let n=JSON.parse(S(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function qt(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function $t(t,e,n){return new Promise((s,r)=>{t.once("error",r),t.listen(e,n,()=>{t.off("error",r),s()})})}function Jt(t){return new Promise(e=>{t.close(()=>e())})}function H(t){try{t()}catch{}}function Wt(t){try{return t()}catch(e){return Promise.reject(e)}}function zt(t,e){let n=t.address();return typeof n=="object"&&n?n.port:e}export{yt as attachNextDevUpgradeHandler,It as createSiteEditAutoBootstrapHtmlSnippet,bt as injectSiteEditAutoBootstrap,Nt as patchNextFirefoxDevChunk,Tt as prepareFirefoxNextDevChunkPatchRequest,Pt as prepareSiteEditHtmlInjectionRequest,wt as resolveSiteEditBridgeHealthPath,we as resolveSiteEditClientAsset,wn as resolveSiteEditClientAssetPath,ft as resolveSiteEditNextDevBundler,Sn as startSiteEditNextDevServer,
|
|
6
|
+
`)],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join("\\n"),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join("\\n")],["debugChannel: createDebugChannel && createDebugChannel(requestHeaders)","debugChannel: undefined"],["debugChannel: createDebugChannel && createDebugChannel(headers)","debugChannel: undefined"]].reduce((n,[s,r])=>Ot(n,s,r),t)}function Ot(t,e,n){if(n.length>e.length)throw new Error("Replacement must not be longer than the search string.");return t.replaceAll(e,n.padEnd(e.length," "))}function he(t,e){return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):Buffer.from(String(t),e)}function le(t){return typeof t=="string"?t:void 0}function fe(t){typeof t=="function"&&t()}async function Vt(t){let n=pe(b(t,"package.json"))(rt);return n.default??n}function Ft(t){return ge(t)!=="src"?t:z(Kt(t),"dist")}function Kt(t){return Ie(t)?R.posix.dirname(t):x(t)}function z(t,e){return Ie(t)?R.posix.join(t,e):b(t,e)}function Ie(t){return t.includes("/")&&!t.includes("\\")}function Lt(t){let e=b(t,".vcp/current-snapshot.json");if(!w(e))return"sandbox_worktree";try{let n=JSON.parse(S(e,"utf8"));return typeof n.snapshotId=="string"?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function qt(t){if(!t)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0&&e<=65535?e:null}function $t(t,e,n){return new Promise((s,r)=>{t.once("error",r),t.listen(e,n,()=>{t.off("error",r),s()})})}function Jt(t){return new Promise(e=>{t.close(()=>e())})}function H(t){try{t()}catch{}}function Wt(t){try{return t()}catch(e){return Promise.reject(e)}}function zt(t,e){let n=t.address();return typeof n=="object"&&n?n.port:e}export{yt as attachNextDevUpgradeHandler,It as createSiteEditAutoBootstrapHtmlSnippet,bt as injectSiteEditAutoBootstrap,Nt as patchNextFirefoxDevChunk,Tt as prepareFirefoxNextDevChunkPatchRequest,Pt as prepareSiteEditHtmlInjectionRequest,wt as resolveSiteEditBridgeHealthPath,we as resolveSiteEditClientAsset,wn as resolveSiteEditClientAssetPath,ft as resolveSiteEditNextDevBundler,Sn as startSiteEditNextDevServer,kt as transpileSiteEditClientSource};
|
package/dist/server.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { type SiteEditBridgeEngine } from "./protocol.js";
|
|
|
7
7
|
export type SiteEditBridgeRuntimeOptions = {
|
|
8
8
|
routes?: SiteEditNextRouteConfig[];
|
|
9
9
|
watch_dirs?: string[];
|
|
10
|
+
watch_interval_ms?: number;
|
|
10
11
|
watch_debounce_ms?: number;
|
|
11
12
|
watch_max_dirs?: number;
|
|
12
13
|
watch_max_files?: number;
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import X from"node:http";import{createHash as F,randomBytes as Z,timingSafeEqual as ee}from"node:crypto";import C from"node:path";import{WebSocket as U,WebSocketServer as te}from"ws";import{createPreviewSiteEditEngineRuntime as se,openFileHistoryStore as ne}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as ie,scanNextAppRouterRoutes as oe}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as re}from"@vcp-dev/site-edit-engine/source-watcher";function I(t){let e=new Map,s=[],n=new Map,i=[],o=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(o.map((a,u)=>[a,u])),p=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(a=>({placementKey:a.placementKey,placementUnitKey:a.placementUnitKey,relation:a.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},h=t.entries.flatMap((a,u)=>a.dynamicDataSummary?[[u,a.dynamicDataSummary]]:[]),y=a=>{let u=e.get(a);if(typeof u=="number")return u;let l=s.length;return s.push(a),e.set(a,l),l},$=a=>{let u=null;for(let l of z(a)){let E=`${u??"root"}\0${l}`,_=n.get(E);if(typeof _=="number"){u=_;continue}let T=i.length;i.push([u,y(l)]),n.set(E,T),u=T}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,pageComposition:p,tokens:s,nodes:i,entries:t.entries.map(a=>{let u=a.pageCompositionUnitKey?r.get(a.pageCompositionUnitKey)??-1:-1;if(a.pageCompositionUnitKey&&u<0)throw new Error(`Render entry ${a.key} references unknown page composition unit ${a.pageCompositionUnitKey}`);return[$(a.key),W(a.operationSummary),...u>=0?[u]:[]]}),...h.length>0?{dynamicDataSummaries:h}:{}}}function W(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function z(t){if(!t)return[];let e=[],s=0,n=B(t,s);if(n<0)return e.push(t),e;for(e.push(t.slice(0,n)),s=n;s<t.length;){if(n=B(t,s+(t.startsWith("::",s)?2:1)),n<0){e.push(t.slice(s));break}e.push(t.slice(s,n)),s=n}return e}function B(t,e){let s=t.indexOf("/",e),n=t.indexOf("::",e);return s<0?n:n<0?s:Math.min(s,n)}var d=class t{constructor(){}static parseMessage(e,s={}){let n=JSON.parse(e);if(!t.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let s=e.payload,n=typeof s.id=="string"?s.id:"unknown",i=t.isRequestKind(s.kind)?s.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==="undo"||e==="redo"}static isMessage(e,s={}){return!c(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,s):e.type==="response"||e.type==="error"?c(e.payload)&&typeof e.payload.id=="string":e.type==="event"?c(e.payload)&&c(e.payload.event):e.type==="auth"?c(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?c(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,s={}){if(!c(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"initialize-session":return typeof e.routeId=="string"&&(e.mutationContext===void 0||R(e.mutationContext));case"get-document":case"get-style-context":return typeof e.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-history-status":return e.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return Q(e.request)&&(e.request.mutationContext===void 0||R(e.request.mutationContext))&&(s.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return e.mutationContext===void 0||R(e.mutationContext)}}},g=class{constructor(e){this.options=e,this.messageQueue=new w,this.eventDispatcher=new S(s=>{this.sendJson(s)}),this.unsubscribe=e.engine.subscribe(s=>{this.eventDispatcher.push(s)}),e.socket.onmessage=s=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(n){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:n instanceof Error?n.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let s=e;if(s.type!=="request")return;let n=s.payload,{id:i}=n;switch(n.kind){case"initialize-session":{let o=await this.options.engine.initializeSession({routeId:n.routeId,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:{ok:!0,data:{document:I(o.data.document),historyStatus:o.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:{ok:!0,data:I((await this.options.engine.getDocument(n.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getStyleContext(n.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getObjectEditContext(n.key,n.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getClassNameSource(n.key,n.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getSourceFile({path:n.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.resolveSourceLocation({key:n.key,routeId:n.routeId})}});return;case"execute":{await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.execute(n.request));return}case"undo":await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.redo());return}}catch(s){let n=d.extractRequestInfo(e);this.sendJson({type:"error",payload:{...n,message:H(s),code:D(s)}})}}async handleRawMessage(e){try{await this.handleMessage(d.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=s instanceof Error?s.message:"Invalid websocket message",i=Y(e);this.sendJson({type:"error",payload:{...i,message:n}})}}sendJson(e){this.options.socket.send(d.stringifyMessage(e))}async handleBufferedOperation(e,s,n){this.eventDispatcher.beginBuffering();try{let i=await n();this.sendJson({type:"response",payload:{id:e,kind:s,result:i}}),this.eventDispatcher.flush()}catch(i){this.sendJson({type:"error",payload:{id:e,kind:s,message:H(i),code:D(i)}}),this.eventDispatcher.flush()}}},S=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let s={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(s=>{this.send(s)})}},w=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await e()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function c(t){return typeof t=="object"&&t!==null}function Q(t){return c(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&c(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&c(t.params)}function R(t){return G(t)}function D(t){if(!t||typeof t!="object")return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function H(t){if(t instanceof Error)return t.message;if(!t||typeof t!="object")return"Unknown websocket operation failure";let e=t.message;return typeof e=="string"&&e.length>0?e:"Unknown websocket operation failure"}function G(t){return c(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:!1}function Y(t){try{return d.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var f=class{constructor(){this.tail=Promise.resolve()}run(e){let s=this.tail.then(e,e);return this.tail=s.then(()=>{},()=>{}),s}};import{SiteEditOperationRequestSchema as ae}from"@vcp-dev/contracts";var ue="127.0.0.1",ce=30218,de="/__vcp/site-edit/bridge",P=6*1024*1024,he=P*2,pe=3e3,M=50,O="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ae(t){let e=q(t),s=J(e),n=j(),i=n.get(s);if(i)return i;let o=new m(e);n.set(s,o);try{o.start()}catch(r){throw n.delete(s),o.stop(),r}return o}function Ke(t,e,s={}){let n=new m(q(e),t,!1,s);return n.start({listen:!1}),n}var m=class{constructor(e,s=X.createServer((o,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,i={}){this.options=e,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new f,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let s=ge({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=s.stop,this.stopWatching=new re({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,debounce_ms:this.options.runtime.watch_debounce_ms??M,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)}getHealth(){let e=!!this.runtime;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=j(),s=J(this.options);e.get(s)===this&&e.delete(s),this.isStarted=!1}createRuntime(e,s=null){let n=this.runtime;this.activeHistoryStore=e??null;let i=(this.dependencies.createRuntime??se)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version);for(let r of this.eventListeners)r(o)},...e?{historyStore:e}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=i,this.activeHistorySessionId=s,n?.dispose()}createBridgeEngine(){return{initializeSession:e=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let{runtime:n,resolvedRouteId:i}=await this.activateRoute(e.routeId),o=n.getDocument(i).data;await this.recordRuntimeVersion(o.version);let r=(await n.getHistoryStatus()).data;return{ok:!0,data:{document:o,historyStatus:r}}}),getDocument:async e=>{let{runtime:s,resolvedRouteId:n}=await this.activateRoute(e),i=s.getDocument(n);return await this.recordRuntimeVersion(i.data.version),i},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async e=>{let{runtime:s,resolvedRouteId:n}=await this.activateRoute(e);return s.getStyleContext(n)},getObjectEditContext:async(e,s)=>this.getRuntime().getObjectEditContext(e,s?this.resolveRouteId(s):void 0),getClassNameSource:async(e,s)=>{let n=this.getRuntime(),i=s?this.resolveRouteId(s):void 0;return n.getClassNameSource(e,i)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute:(e,s)=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return k(n,e);let i=await this.getRuntime().executeOperation(this.normalizeRequest(e));return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),undo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return k(e);let s=await this.getRuntime().undo();return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion),s}),redo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return k(e);let s=await this.getRuntime().redo();return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion),s}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}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 s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??ne)(le({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let i=n.readDocumentVersion?await n.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,i),this.createRuntime(n,e)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,e);let s=this.activeHistoryStore;return s?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>s.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(e){let s=this.getRuntime(),n=this.resolveRouteId(e);return await s.setActiveRoute(n),{runtime:s,resolvedRouteId:n}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??M;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((s,n)=>s.localeCompare(n));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let s of e)this.runtime?.notifyFileChanged(s)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:oe(this.options.projectRoot),s=new Map(this.routes.map(i=>[i.routeId,i.entryFile])),n=new Set(e.map(i=>i.routeId));this.routes=e;for(let i of e)s.get(i.routeId)!==i.entryFile&&this.runtime?.registerRoute(i.routeId,i.entryFile);for(let i of s.keys())n.has(i)||this.runtime?.unregisterRoute(i)}resolveRouteId(e){let s=ie(e,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return s}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function q(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:C.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??ue,port:t.port??ce,path:t.path??de,sessionKey:t.sessionKey??we(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function le(t){return C.join(C.resolve(t.root),V(t.siteId),V(t.snapshotId),F("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function V(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:F("sha256").update(t).digest("hex").slice(0,32)}function j(){let t=globalThis;return t[O]??=new Map,t[O]}function J(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function k(t,e){return{ok:!1,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function ge(t){let e=new te({maxPayload:P,noServer:!0}),s=new WeakSet,n=o=>{new g({socket:new b(o),engine:t.engine,validateOperationRequest:r=>ae.safeParse(r).success})},i=(o,r,p)=>{if(!fe(o,t))return;let h=me(o,t);if(!h){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import X from"node:http";import{createHash as F,randomBytes as Z,timingSafeEqual as ee}from"node:crypto";import C from"node:path";import{WebSocket as U,WebSocketServer as te}from"ws";import{createPreviewSiteEditEngineRuntime as se,openFileHistoryStore as ne}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as ie,scanNextAppRouterRoutes as oe}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as re}from"@vcp-dev/site-edit-engine/source-watcher";function I(t){let e=new Map,s=[],n=new Map,i=[],o=t.pageComposition.status==="supported"?t.pageComposition.placementUnitKeys:[],r=new Map(o.map((a,u)=>[a,u])),p=t.pageComposition.status==="supported"?{status:"supported",containerKey:t.pageComposition.containerKey,hasBusinessMembers:t.pageComposition.hasBusinessMembers,placementUnitKeys:t.pageComposition.placementUnitKeys,placements:t.pageComposition.placements.map(a=>({placementKey:a.placementKey,placementUnitKey:a.placementUnitKey,relation:a.relation}))}:{status:"unsupported",reason:t.pageComposition.reason,diagnostics:t.pageComposition.diagnostics},h=t.entries.flatMap((a,u)=>a.dynamicDataSummary?[[u,a.dynamicDataSummary]]:[]),y=a=>{let u=e.get(a);if(typeof u=="number")return u;let l=s.length;return s.push(a),e.set(a,l),l},$=a=>{let u=null;for(let l of z(a)){let E=`${u??"root"}\0${l}`,_=n.get(E);if(typeof _=="number"){u=_;continue}let T=i.length;i.push([u,y(l)]),n.set(E,T),u=T}if(u===null)throw new Error("Document key must not be empty");return u};return{encoding:"segment-trie-v1",siteId:t.siteId,snapshotId:t.snapshotId,routeId:t.routeId,version:t.version,pageComposition:p,tokens:s,nodes:i,entries:t.entries.map(a=>{let u=a.pageCompositionUnitKey?r.get(a.pageCompositionUnitKey)??-1:-1;if(a.pageCompositionUnitKey&&u<0)throw new Error(`Render entry ${a.key} references unknown page composition unit ${a.pageCompositionUnitKey}`);return[$(a.key),W(a.operationSummary),...u>=0?[u]:[]]}),...h.length>0?{dynamicDataSummaries:h}:{}}}function W(t){return(t.canUpdateText?1:0)|(t.canInsertChild?2:0)|(t.canMove?4:0)|(t.canRemove?8:0)}function z(t){if(!t)return[];let e=[],s=0,n=B(t,s);if(n<0)return e.push(t),e;for(e.push(t.slice(0,n)),s=n;s<t.length;){if(n=B(t,s+(t.startsWith("::",s)?2:1)),n<0){e.push(t.slice(s));break}e.push(t.slice(s,n)),s=n}return e}function B(t,e){let s=t.indexOf("/",e),n=t.indexOf("::",e);return s<0?n:n<0?s:Math.min(s,n)}var d=class t{constructor(){}static parseMessage(e,s={}){let n=JSON.parse(e);if(!t.isMessage(n,s))throw new Error("Invalid site edit bridge message");return n}static stringifyMessage(e){return JSON.stringify(e)}static extractRequestInfo(e){if(typeof e=="object"&&e!==null&&"payload"in e&&typeof e.payload=="object"&&e.payload!==null){let s=e.payload,n=typeof s.id=="string"?s.id:"unknown",i=t.isRequestKind(s.kind)?s.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==="undo"||e==="redo"}static isMessage(e,s={}){return!c(e)||typeof e.type!="string"?!1:e.type==="request"?t.isRequestPayload(e.payload,s):e.type==="response"||e.type==="error"?c(e.payload)&&typeof e.payload.id=="string":e.type==="event"?c(e.payload)&&c(e.payload.event):e.type==="auth"?c(e.payload)&&typeof e.payload.key=="string":e.type==="auth-ok"?c(e.payload)&&e.payload.ok===!0:!1}static isRequestPayload(e,s={}){if(!c(e)||typeof e.id!="string"||!t.isRequestKind(e.kind))return!1;switch(e.kind){case"initialize-session":return typeof e.routeId=="string"&&(e.mutationContext===void 0||R(e.mutationContext));case"get-document":case"get-style-context":return typeof e.routeId=="string";case"get-object-edit-context":case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&(e.routeId===void 0||typeof e.routeId=="string");case"get-history-status":return e.mutationContext===void 0;case"get-source-tree":return!0;case"get-source-file":return typeof e.path=="string";case"execute":return Q(e.request)&&(e.request.mutationContext===void 0||R(e.request.mutationContext))&&(s.validateOperationRequest?.(e.request)??!0);case"undo":case"redo":return e.mutationContext===void 0||R(e.mutationContext)}}},g=class{constructor(e){this.options=e,this.messageQueue=new w,this.eventDispatcher=new S(s=>{this.sendJson(s)}),this.unsubscribe=e.engine.subscribe(s=>{this.eventDispatcher.push(s)}),e.socket.onmessage=s=>{try{this.messageQueue.enqueue(()=>this.handleRawMessage(s.data))}catch(n){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:n instanceof Error?n.message:"Bridge queue overflow"}}),e.socket.close(1013,"bridge busy")}},e.socket.onclose=()=>{this.unsubscribe()}}async handleMessage(e){try{let s=e;if(s.type!=="request")return;let n=s.payload,{id:i}=n;switch(n.kind){case"initialize-session":{let o=await this.options.engine.initializeSession({routeId:n.routeId,...n.mutationContext?{mutationContext:n.mutationContext}:{}});this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:{ok:!0,data:{document:I(o.data.document),historyStatus:o.data.historyStatus}}}});return}case"get-document":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:{ok:!0,data:I((await this.options.engine.getDocument(n.routeId)).data)}}});return;case"get-history-status":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getHistoryStatus()}});return;case"get-style-context":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getStyleContext(n.routeId)}});return;case"get-object-edit-context":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getObjectEditContext(n.key,n.routeId)}});return;case"get-class-name-source":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getClassNameSource(n.key,n.routeId)}});return;case"get-source-tree":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getSourceTree()}});return;case"get-source-file":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.getSourceFile({path:n.path})}});return;case"resolve-source-location":this.sendJson({type:"response",payload:{id:i,kind:n.kind,result:await this.options.engine.resolveSourceLocation({key:n.key,routeId:n.routeId})}});return;case"execute":{await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.execute(n.request));return}case"undo":await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.undo());return;case"redo":await this.handleBufferedOperation(i,n.kind,()=>this.options.engine.redo());return}}catch(s){let n=d.extractRequestInfo(e);this.sendJson({type:"error",payload:{...n,message:H(s),code:D(s)}})}}async handleRawMessage(e){try{await this.handleMessage(d.parseMessage(e,{validateOperationRequest:this.options.validateOperationRequest}))}catch(s){let n=s instanceof Error?s.message:"Invalid websocket message",i=Y(e);this.sendJson({type:"error",payload:{...i,message:n}})}}sendJson(e){this.options.socket.send(d.stringifyMessage(e))}async handleBufferedOperation(e,s,n){this.eventDispatcher.beginBuffering();try{let i=await n();this.sendJson({type:"response",payload:{id:e,kind:s,result:i}}),this.eventDispatcher.flush()}catch(i){this.sendJson({type:"error",payload:{id:e,kind:s,message:H(i),code:D(i)}}),this.eventDispatcher.flush()}}},S=class{constructor(e){this.send=e,this.bufferedEvents=null}push(e){let s={type:"event",payload:{event:e}};if(this.bufferedEvents){this.bufferedEvents.push(s);return}this.send(s)}beginBuffering(){this.bufferedEvents=[]}flush(){let e=this.bufferedEvents??[];this.bufferedEvents=null,e.forEach(s=>{this.send(s)})}},w=class{constructor(e=64){this.maxQueued=e,this.queue=Promise.resolve(),this.queued=0}enqueue(e){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let s=async()=>{this.queued-=1,await e()},n=this.queue.then(s,s);return this.queue=n.then(()=>{},()=>{}),n}};function c(t){return typeof t=="object"&&t!==null}function Q(t){return c(t)&&typeof t.id=="string"&&typeof t.siteId=="string"&&typeof t.baseSnapshotId=="string"&&(t.routeId===void 0||typeof t.routeId=="string")&&typeof t.kind=="string"&&c(t.target)&&typeof t.documentVersion=="number"&&Number.isInteger(t.documentVersion)&&t.documentVersion>=0&&c(t.params)}function R(t){return G(t)}function D(t){if(!t||typeof t!="object")return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function H(t){if(t instanceof Error)return t.message;if(!t||typeof t!="object")return"Unknown websocket operation failure";let e=t.message;return typeof e=="string"&&e.length>0?e:"Unknown websocket operation failure"}function G(t){return c(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:!1}function Y(t){try{return d.extractRequestInfo(JSON.parse(t))}catch{return{id:"unknown",kind:"get-document"}}}var f=class{constructor(){this.tail=Promise.resolve()}run(e){let s=this.tail.then(e,e);return this.tail=s.then(()=>{},()=>{}),s}};import{SiteEditOperationRequestSchema as ae}from"@vcp-dev/contracts";var ue="127.0.0.1",ce=30218,de="/__vcp/site-edit/bridge",P=6*1024*1024,he=P*2,pe=3e3,M=50,O="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ae(t){let e=q(t),s=J(e),n=j(),i=n.get(s);if(i)return i;let o=new m(e);n.set(s,o);try{o.start()}catch(r){throw n.delete(s),o.stop(),r}return o}function Ke(t,e,s={}){let n=new m(q(e),t,!1,s);return n.start({listen:!1}),n}var m=class{constructor(e,s=X.createServer((o,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),n=!0,i={}){this.options=e,this.server=s,this.closeHttpServerOnStop=n,this.dependencies=i,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new f,this.eventListeners=new Set,this.routes=[],this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.runtimeVersionFloor=0,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve()}start(e={}){if(this.isStarted)return;this.refreshRoutes(),this.isStarted=!0,this.createRuntime();let s=ge({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.createBridgeEngine()});this.stopWebSocketServer=s.stop,this.stopWatching=new re({projectRoot:this.options.projectRoot,watch_dirs:this.options.runtime.watch_dirs,interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??M,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)}getHealth(){let e=!!this.runtime;return{ok:this.isStarted&&e,bridgePath:this.options.path,runtimeReady:e,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.closeHttpServerOnStop&&this.server.close();let e=j(),s=J(this.options);e.get(s)===this&&e.delete(s),this.isStarted=!1}createRuntime(e,s=null){let n=this.runtime;this.activeHistoryStore=e??null;let i=(this.dependencies.createRuntime??se)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,routes:this.routes,onEvent:o=>{"version"in o&&typeof o.version=="number"&&this.recordRuntimeVersion(o.version);for(let r of this.eventListeners)r(o)},...e?{historyStore:e}:{},initialDocumentVersion:this.runtimeVersionFloor});this.runtime=i,this.activeHistorySessionId=s,n?.dispose()}createBridgeEngine(){return{initializeSession:e=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)throw new Error(`${s.code}: ${s.message}`);let{runtime:n,resolvedRouteId:i}=await this.activateRoute(e.routeId),o=n.getDocument(i).data;await this.recordRuntimeVersion(o.version);let r=(await n.getHistoryStatus()).data;return{ok:!0,data:{document:o,historyStatus:r}}}),getDocument:async e=>{let{runtime:s,resolvedRouteId:n}=await this.activateRoute(e),i=s.getDocument(n);return await this.recordRuntimeVersion(i.data.version),i},getHistoryStatus:async()=>this.getRuntime().getHistoryStatus(),getStyleContext:async e=>{let{runtime:s,resolvedRouteId:n}=await this.activateRoute(e);return s.getStyleContext(n)},getObjectEditContext:async(e,s)=>this.getRuntime().getObjectEditContext(e,s?this.resolveRouteId(s):void 0),getClassNameSource:async(e,s)=>{let n=this.getRuntime(),i=s?this.resolveRouteId(s):void 0;return n.getClassNameSource(e,i)},getSourceTree:async()=>this.getRuntime().getSourceTree(),getSourceFile:async e=>this.getRuntime().getSourceFile(e),resolveSourceLocation:async e=>this.getRuntime().resolveSourceLocation({key:e.key,routeId:e.routeId?this.resolveRouteId(e.routeId):void 0}),execute:(e,s)=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)return k(n,e);let i=await this.getRuntime().executeOperation(this.normalizeRequest(e));return i.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(i.data.resultVersion),i}),undo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return k(e);let s=await this.getRuntime().undo();return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion),s}),redo:()=>this.mutationQueue.run(async()=>{let e=await this.bindHistorySession(this.options.snapshotId);if(!e.ok)return k(e);let s=await this.getRuntime().redo();return s.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(s.data.resultVersion),s}),subscribe:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e))}}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 s=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===e)return;let n=await(this.dependencies.openHistoryStore??ne)(le({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:e}));if(!this.isStarted)return;let i=n.readDocumentVersion?await n.readDocumentVersion():0;this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,i),this.createRuntime(n,e)});this.historySessionTransition=s.catch(()=>{});try{return await s,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(e){this.runtimeVersionFloor=Math.max(this.runtimeVersionFloor,e);let s=this.activeHistoryStore;return s?.writeDocumentVersion?(this.versionPersistence=this.versionPersistence.then(()=>s.writeDocumentVersion(this.runtimeVersionFloor)).catch(()=>{}),this.versionPersistence):Promise.resolve()}async activateRoute(e){let s=this.getRuntime(),n=this.resolveRouteId(e);return await s.setActiveRoute(n),{runtime:s,resolvedRouteId:n}}normalizeRequest(e){return e.target.kind!=="route"?e.routeId?{...e,routeId:this.resolveRouteId(e.routeId)}:e:{...e,target:{...e.target,routeId:this.resolveRouteId(e.target.routeId)}}}handleFileChanged(e){this.handleFilesChanged([e])}handleFilesChanged(e){for(let n of e)this.pendingChangedFiles.add(n);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let s=this.options.runtime.watch_debounce_ms??M;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},s),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let e=[...this.pendingChangedFiles].sort((s,n)=>s.localeCompare(n));this.pendingChangedFiles.clear(),this.refreshRoutes();for(let s of e)this.runtime?.notifyFileChanged(s)}refreshRoutes(){let e=this.options.runtime.routes?.length?this.options.runtime.routes:oe(this.options.projectRoot),s=new Map(this.routes.map(i=>[i.routeId,i.entryFile])),n=new Set(e.map(i=>i.routeId));this.routes=e;for(let i of e)s.get(i.routeId)!==i.entryFile&&this.runtime?.registerRoute(i.routeId,i.entryFile);for(let i of s.keys())n.has(i)||this.runtime?.unregisterRoute(i)}resolveRouteId(e){let s=ie(e,this.routes,this.options.basePath);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${e}`);return s}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function q(t){return{tenantId:t.tenantId,siteId:t.siteId,snapshotId:t.snapshotId,projectRoot:C.resolve(t.projectRoot??process.cwd()),basePath:t.basePath??"",host:t.host??ue,port:t.port??ce,path:t.path??de,sessionKey:t.sessionKey??we(),historyRoot:t.historyRoot,allowedOrigins:t.allowedOrigins??[],runtime:t.runtime??{}}}function le(t){return C.join(C.resolve(t.root),V(t.siteId),V(t.snapshotId),F("sha256").update(t.editingSessionId).digest("hex").slice(0,32))}function V(t){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(t)&&t!=="."&&t!==".."?t:F("sha256").update(t).digest("hex").slice(0,32)}function j(){let t=globalThis;return t[O]??=new Map,t[O]}function J(t){return`${t.projectRoot}:${t.host}:${t.port}:${t.path}:${t.historyRoot??""}`}function k(t,e){return{ok:!1,error:{code:t.code,message:t.message},data:{requestId:e?.id??"mutation-context",kind:e?.kind??"update-text",target:e?.target??{kind:"node",key:""},resultVersion:e?.documentVersion??0}}}function ge(t){let e=new te({maxPayload:P,noServer:!0}),s=new WeakSet,n=o=>{new g({socket:new b(o),engine:t.engine,validateOperationRequest:r=>ae.safeParse(r).success})},i=(o,r,p)=>{if(!fe(o,t))return;let h=me(o,t);if(!h){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
2
2
|
Connection: close\r
|
|
3
3
|
\r
|
|
4
4
|
`),r.destroy();return}h.authenticatedByHeader&&s.add(o),e.handleUpgrade(o,r,p,y=>{e.emit("connection",y,o)})};return t.server.on("upgrade",i),e.on("connection",(o,r)=>{if(s.has(r)){n(o);return}ye(o,t.sessionKey,()=>{n(o)})}),e.stop=()=>{t.server.off("upgrade",i);for(let o of e.clients)o.close(1001,"bridge stopped");e.close()},e}var b=class{constructor(e){this.socket=e,this.onmessage=null,this.onclose=null,e.on("error",()=>{}),e.on("message",s=>{this.onmessage?.({data:s.toString()})}),e.on("close",()=>{this.onclose?.()})}send(e){if(this.socket.readyState===U.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(e,"utf8")>he){this.socket.close(1013,"bridge backpressure");return}this.socket.send(e)}}close(e,s){this.socket.close(e,s)}};function fe(t,e){return new URL(t.url??"/","http://localhost").pathname===e.path}function me(t,e){if(new URL(t.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let n=x(t.headers["x-vcp-site-edit-key"]),i=L(n,e.sessionKey),o=x(t.headers.host),r=x(t.headers.origin);return o&&!Ie(o,e.host,r)?null:r?Se(r,o,e.allowedOrigins)?{authenticatedByHeader:i}:null:i?{authenticatedByHeader:!0}:null}function ye(t,e,s){let n=setTimeout(()=>{t.close(1008,"bridge authentication timeout")},pe),i,o=()=>{clearTimeout(n),t.off("message",i),t.off("close",o)},r=()=>{o(),t.close(1008,"bridge authentication failed")};i=p=>{try{let h=d.parseMessage(p.toString());if(h.type!=="auth"||!L(h.payload.key,e)){r();return}o(),t.readyState===U.OPEN&&t.send(d.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),s()}catch{r()}},t.on("message",i),t.on("close",o)}function L(t,e){if(!t)return!1;let s=Buffer.from(t),n=Buffer.from(e);return s.length===n.length&&ee(s,n)}function Ie(t,e,s){let n=K(t),i=K(e);return n===i||A(i)&&A(n)&&(!s||v(s,t))||Re(i)&&(!s||v(s,t))}function Re(t){return t==="0.0.0.0"||t==="::"}function A(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"}function Se(t,e,s){return s.includes(t)||(e?v(t,e):!1)}function v(t,e){try{return new URL(t).host===N(e)}catch{return!1}}function K(t){let e=N(t);return e.startsWith("[")?e.slice(1,e.indexOf("]")):e.split(":").length-1===1?e.split(":",1)[0]??"":e}function N(t){return t.trim().toLowerCase()}function x(t){return Array.isArray(t)?t[0]:t}function we(){return Z(32).toString("base64url")}export{he as SITE_EDIT_BRIDGE_MAX_BUFFERED_BYTES,P as SITE_EDIT_BRIDGE_MAX_PAYLOAD_BYTES,m as SiteEditBridgeServer,Ke as attachSiteEditBridgeServer,ge as attachSiteEditWebSocketServer,Ae as ensureSiteEditBridgeServerStarted};
|
package/dist/window-message.d.ts
CHANGED
|
@@ -19,6 +19,10 @@ export declare function createVcpWindowMessageEnvelope<TNamespace extends string
|
|
|
19
19
|
export declare function isVcpWindowMessageEnvelope(value: unknown): value is VcpWindowMessageEnvelope;
|
|
20
20
|
export declare const SITE_EDIT_WINDOW_MESSAGE_NAMESPACE = "site-edit";
|
|
21
21
|
export declare const SITE_EDIT_FRAME_RUNTIME_CHANNEL = "frame-runtime";
|
|
22
|
+
export declare const SITE_EDIT_FRAME_RUNTIME_LAYOUT_SNAPSHOT_VERSION = 1;
|
|
23
|
+
export declare const SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION = 1;
|
|
24
|
+
export declare const SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION = 1;
|
|
25
|
+
export declare const SITE_EDIT_FRAME_SECTION_GAP_RADIUS_PX = 24;
|
|
22
26
|
export type SiteEditFrameRuntimeRef = {
|
|
23
27
|
key: string;
|
|
24
28
|
instanceIndex?: number;
|
|
@@ -28,6 +32,14 @@ export type SiteEditFrameRuntimeRef = {
|
|
|
28
32
|
export type SiteEditFrameRuntimeStarted = {
|
|
29
33
|
ref: SiteEditFrameRuntimeRef;
|
|
30
34
|
};
|
|
35
|
+
export type SiteEditFrameRuntimeSelectionVisualAck = {
|
|
36
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION;
|
|
37
|
+
active: boolean;
|
|
38
|
+
};
|
|
39
|
+
export type SiteEditFrameRuntimeResizeVisualAck = {
|
|
40
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION;
|
|
41
|
+
active: boolean;
|
|
42
|
+
};
|
|
31
43
|
export type SiteEditFrameRuntimeHitDetailLevel = "summary" | "full";
|
|
32
44
|
export type SiteEditFrameRuntimeScrollMetrics = {
|
|
33
45
|
scrollX: number;
|
|
@@ -38,6 +50,19 @@ export type SiteEditFrameRuntimeScrollMetrics = {
|
|
|
38
50
|
viewportHeight: number;
|
|
39
51
|
};
|
|
40
52
|
export type SiteEditFrameRuntimePointerEventKind = "pointer-down" | "pointer-move" | "pointer-leave" | "pointer-up" | "pointer-cancel" | "pointer-click" | "pointer-double-click";
|
|
53
|
+
export type SiteEditFrameRuntimeResizeEdge = "e" | "s" | "se";
|
|
54
|
+
export type SiteEditFrameRuntimeResizeSession = {
|
|
55
|
+
version: 1;
|
|
56
|
+
phase: "start" | "commit" | "cancel";
|
|
57
|
+
sessionId: string;
|
|
58
|
+
pointerId: number;
|
|
59
|
+
edge: SiteEditFrameRuntimeResizeEdge;
|
|
60
|
+
ref: SiteEditFrameRuntimeRef;
|
|
61
|
+
startWidth: number;
|
|
62
|
+
startHeight: number;
|
|
63
|
+
width: number;
|
|
64
|
+
height: number;
|
|
65
|
+
};
|
|
41
66
|
export type SiteEditFrameRuntimeNodePatch = {
|
|
42
67
|
attributes?: Record<string, string | null>;
|
|
43
68
|
className?: string;
|
|
@@ -151,6 +176,38 @@ export type SiteEditFrameRuntimeRequestBody = {
|
|
|
151
176
|
payload: {
|
|
152
177
|
enabled: boolean;
|
|
153
178
|
};
|
|
179
|
+
} | {
|
|
180
|
+
type: "request";
|
|
181
|
+
id: string;
|
|
182
|
+
kind: "set-selection-visual";
|
|
183
|
+
payload: {
|
|
184
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION;
|
|
185
|
+
ref: SiteEditFrameRuntimeRef;
|
|
186
|
+
visible: true;
|
|
187
|
+
};
|
|
188
|
+
} | {
|
|
189
|
+
type: "request";
|
|
190
|
+
id: string;
|
|
191
|
+
kind: "clear-selection-visual";
|
|
192
|
+
payload: {
|
|
193
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION;
|
|
194
|
+
};
|
|
195
|
+
} | {
|
|
196
|
+
type: "request";
|
|
197
|
+
id: string;
|
|
198
|
+
kind: "set-resize-visual";
|
|
199
|
+
payload: {
|
|
200
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION;
|
|
201
|
+
ref: SiteEditFrameRuntimeRef;
|
|
202
|
+
visible: true;
|
|
203
|
+
};
|
|
204
|
+
} | {
|
|
205
|
+
type: "request";
|
|
206
|
+
id: string;
|
|
207
|
+
kind: "clear-resize-visual";
|
|
208
|
+
payload: {
|
|
209
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION;
|
|
210
|
+
};
|
|
154
211
|
} | {
|
|
155
212
|
type: "request";
|
|
156
213
|
id: string;
|
|
@@ -288,6 +345,42 @@ export type SiteEditFrameRuntimeRect = {
|
|
|
288
345
|
width: number;
|
|
289
346
|
height: number;
|
|
290
347
|
};
|
|
348
|
+
export type SiteEditFrameRuntimeContainingBlock = {
|
|
349
|
+
kind: "viewport" | "document";
|
|
350
|
+
} | {
|
|
351
|
+
kind: "element";
|
|
352
|
+
runtimeNodeId: string;
|
|
353
|
+
};
|
|
354
|
+
export type SiteEditFrameRuntimeScrollContainer = {
|
|
355
|
+
runtimeNodeId: string;
|
|
356
|
+
scrollLeft: number;
|
|
357
|
+
scrollTop: number;
|
|
358
|
+
};
|
|
359
|
+
/**
|
|
360
|
+
* Runtime-owned geometry for projecting a preview node into the designer.
|
|
361
|
+
* `runtimeNodeId` is opaque and only identifies a live DOM node; it is not a
|
|
362
|
+
* source key or component identity.
|
|
363
|
+
*/
|
|
364
|
+
export type SiteEditFrameRuntimeLayoutSnapshot = {
|
|
365
|
+
version: typeof SITE_EDIT_FRAME_RUNTIME_LAYOUT_SNAPSHOT_VERSION;
|
|
366
|
+
runtimeNodeId: string;
|
|
367
|
+
rect: {
|
|
368
|
+
viewport: SiteEditFrameRuntimeRect;
|
|
369
|
+
document: SiteEditFrameRuntimeRect;
|
|
370
|
+
};
|
|
371
|
+
layout: {
|
|
372
|
+
position: string;
|
|
373
|
+
transform: string;
|
|
374
|
+
containingBlock: SiteEditFrameRuntimeContainingBlock;
|
|
375
|
+
};
|
|
376
|
+
scrollContext: {
|
|
377
|
+
scrollX: number;
|
|
378
|
+
scrollY: number;
|
|
379
|
+
viewportWidth: number;
|
|
380
|
+
viewportHeight: number;
|
|
381
|
+
scrollContainers: SiteEditFrameRuntimeScrollContainer[];
|
|
382
|
+
};
|
|
383
|
+
};
|
|
291
384
|
export type SiteEditFrameRuntimeChildBox = {
|
|
292
385
|
rect: SiteEditFrameRuntimeRect;
|
|
293
386
|
margin: SiteEditFrameRuntimeMargin;
|
|
@@ -328,6 +421,7 @@ export type SiteEditFrameRuntimeHit = {
|
|
|
328
421
|
textEditable: boolean;
|
|
329
422
|
container: boolean;
|
|
330
423
|
};
|
|
424
|
+
layoutSnapshot?: SiteEditFrameRuntimeLayoutSnapshot;
|
|
331
425
|
layout?: {
|
|
332
426
|
display: string;
|
|
333
427
|
flexDirection?: string;
|
|
@@ -339,6 +433,23 @@ export type SiteEditFrameRuntimeHit = {
|
|
|
339
433
|
childRects?: SiteEditFrameRuntimeRect[];
|
|
340
434
|
spacing?: SiteEditFrameRuntimeSpacing;
|
|
341
435
|
};
|
|
436
|
+
export type SiteEditFrameRuntimeGeometryReason = "scroll" | "resize" | "mutation";
|
|
437
|
+
export type SiteEditFrameRuntimeGeometrySnapshot = {
|
|
438
|
+
ref: SiteEditFrameRuntimeRef;
|
|
439
|
+
layoutSnapshot: SiteEditFrameRuntimeLayoutSnapshot;
|
|
440
|
+
childBoxes?: SiteEditFrameRuntimeChildBox[];
|
|
441
|
+
childRects?: SiteEditFrameRuntimeRect[];
|
|
442
|
+
layout?: SiteEditFrameRuntimeHit["layout"];
|
|
443
|
+
spacing?: SiteEditFrameRuntimeSpacing;
|
|
444
|
+
};
|
|
445
|
+
export type SiteEditFrameRuntimeGeometryBatch = {
|
|
446
|
+
sequence: number;
|
|
447
|
+
sourceEventAt: number;
|
|
448
|
+
captureStartedAt: number;
|
|
449
|
+
capturedAt: number;
|
|
450
|
+
reason: SiteEditFrameRuntimeGeometryReason;
|
|
451
|
+
snapshots: SiteEditFrameRuntimeGeometrySnapshot[];
|
|
452
|
+
};
|
|
342
453
|
export type SiteEditFrameRuntimeResponseBody = {
|
|
343
454
|
type: "response";
|
|
344
455
|
id: string;
|
|
@@ -350,7 +461,7 @@ export type SiteEditFrameRuntimeResponseBody = {
|
|
|
350
461
|
scrolled: true;
|
|
351
462
|
}) | {
|
|
352
463
|
interactionEnabled: boolean;
|
|
353
|
-
} | {
|
|
464
|
+
} | SiteEditFrameRuntimeSelectionVisualAck | {
|
|
354
465
|
themeOverrideApplied: true;
|
|
355
466
|
} | {
|
|
356
467
|
themeOverrideCleared: true;
|
|
@@ -381,6 +492,10 @@ export type SiteEditFrameRuntimeEventBody = {
|
|
|
381
492
|
payload: {
|
|
382
493
|
hit: SiteEditFrameRuntimeHit;
|
|
383
494
|
};
|
|
495
|
+
} | {
|
|
496
|
+
type: "event";
|
|
497
|
+
kind: "geometry-batch";
|
|
498
|
+
payload: SiteEditFrameRuntimeGeometryBatch;
|
|
384
499
|
} | {
|
|
385
500
|
type: "event";
|
|
386
501
|
kind: "bridge-event";
|
|
@@ -395,6 +510,10 @@ export type SiteEditFrameRuntimeEventBody = {
|
|
|
395
510
|
clientX: number;
|
|
396
511
|
clientY: number;
|
|
397
512
|
buttons?: number;
|
|
513
|
+
pointerId?: number;
|
|
514
|
+
hoverVisualOwned?: boolean;
|
|
515
|
+
resizeEdge?: SiteEditFrameRuntimeResizeEdge;
|
|
516
|
+
resizeSession?: SiteEditFrameRuntimeResizeSession;
|
|
398
517
|
hit: SiteEditFrameRuntimeHit | null;
|
|
399
518
|
section: SiteEditFrameRuntimeSectionContext | null;
|
|
400
519
|
sectionGap: SiteEditFrameRuntimeSectionGapCandidate | null;
|
|
@@ -432,3 +551,4 @@ export declare function createSiteEditFrameRuntimeMessage(body: SiteEditFrameRun
|
|
|
432
551
|
sessionKey?: string;
|
|
433
552
|
}): SiteEditFrameRuntimeMessage;
|
|
434
553
|
export declare function isSiteEditFrameRuntimeMessage(value: unknown): value is SiteEditFrameRuntimeMessage;
|
|
554
|
+
export declare function isSiteEditFrameRuntimeLayoutSnapshot(value: unknown): value is SiteEditFrameRuntimeLayoutSnapshot;
|
package/dist/window-message.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var l="vcp-window-message",q=1;function I(e){return{source:l,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function R(e){try{return i(e)?d(e,"source",l)&&d(e,"version",1)&&s(e,"namespace")&&s(e,"channel")&&a(e,"body")&&(!u(e,"sessionKey")||s(e,"sessionKey")):!1}catch{return!1}}var h="site-edit",w="frame-runtime";function L(e,r={}){return I({namespace:h,channel:w,sessionKey:r.sessionKey,body:e})}function H(e){try{return!R(e)||e.namespace!==h||e.channel!==w?!1:B(e.body)}catch{return!1}}var u=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function a(e,r){let t=Object.getOwnPropertyDescriptor(e,r);return t!==void 0&&"value"in t}function n(e,r){return Object.getOwnPropertyDescriptor(e,r)?.value}function d(e,r,t){return a(e,r)&&n(e,r)===t}function s(e,r){return a(e,r)&&typeof n(e,r)=="string"}function m(e,r){return a(e,r)&&typeof n(e,r)=="boolean"}function o(e,r){let t=n(e,r);return a(e,r)&&typeof t=="number"&&Number.isFinite(t)}function g(e,r){return!u(e,r)||n(e,r)===void 0||s(e,r)}function y(e,r){return!u(e,r)||n(e,r)===void 0||o(e,r)}function b(e,r){let t=n(e,r);return!u(e,r)||t===void 0||a(e,r)&&typeof t=="number"&&Number.isInteger(t)&&t>=0}function c(e,r){return!u(e,r)||n(e,r)===void 0}function i(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function x(e){return i(e)&&Reflect.ownKeys(e).length===0}function S(e){if(!Array.isArray(e))return!1;for(let r=0;r<e.length;r+=1){let t=Object.getOwnPropertyDescriptor(e,String(r));if(t===void 0||!("value"in t)||typeof t.value!="string")return!1}return!0}function p(e){return i(e)&&s(e,"key")&&b(e,"instanceIndex")&&b(e,"instanceCount")&&b(e,"textSegmentIndex")}function N(e){return i(e)&&o(e,"top")&&o(e,"left")&&o(e,"width")&&o(e,"height")}function _(e){return i(e)&&s(e,"blockId")&&p(n(e,"ref"))&&N(n(e,"rect"))&&m(e,"targetIsSectionRoot")}function A(e){if(!i(e))return!1;let r=n(e,"placement"),t=n(e,"boundary");return s(e,"anchorBlockId")&&p(n(e,"anchorRef"))&&(r==="before"||r==="after")&&i(t)&&o(t,"top")&&o(t,"left")&&o(t,"width")}function P(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&(typeof n(e,r)=="string"||n(e,r)===null))}function E(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function D(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&a(e,r)&&E(n(e,r)))}function V(e){if(!i(e))return!1;let r=n(e,"priority");return s(e,"property")&&a(e,"value")&&E(n(e,"value"))&&(!u(e,"priority")||r===void 0||r==="important")}function K(e){return i(e)?(c(e,"attributes")||P(n(e,"attributes")))&&g(e,"className")&&(c(e,"style")||D(n(e,"style")))&&(c(e,"styleDeclarations")||Array.isArray(n(e,"styleDeclarations"))&&n(e,"styleDeclarations").every(V)):!1}function W(e){return i(e)&&o(e,"x")&&o(e,"y")&&(c(e,"detailLevel")||d(e,"detailLevel","summary")||d(e,"detailLevel","full"))}function M(e){return i(e)&&p(n(e,"ref"))}function F(e){if(!i(e)||!i(n(e,"variables")))return!1;let r=n(e,"variables");return Reflect.ownKeys(r).every(t=>typeof t=="string"&&s(r,t))?c(e,"stylesheets")||S(n(e,"stylesheets")):!1}function C(e){if(!d(e,"type","request")||!s(e,"id")||!s(e,"kind")||!a(e,"payload"))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"hit-test-at-point":case"start-text-edit-at-point":return W(t);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return x(t);case"bridge-get-source-file":return i(t)&&s(t,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return i(t)&&s(t,"key")&&g(t,"routeId");case"scroll-to":return i(t)&&o(t,"x")&&o(t,"y");case"scroll-by":return i(t)&&o(t,"deltaX")&&o(t,"deltaY");case"set-interaction-mode":return i(t)&&m(t,"enabled");case"set-theme-override":return F(t);case"get-theme-variables":return i(t)&&S(n(t,"names"));case"compute-drop-target-at-point":return i(t)&&o(t,"x")&&o(t,"y")&&(d(t,"dragKind","insert")||d(t,"dragKind","move"))&&(c(t,"movingRef")||p(n(t,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return i(t)&&(c(t,"ref")||p(n(t,"ref")));case"apply-node-patch":return i(t)&&p(n(t,"ref"))&&K(n(t,"patch"))&&(c(t,"preview")||i(n(t,"preview"))&&s(n(t,"preview"),"sessionId")&&b(n(t,"preview"),"revision")&&u(n(t,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return M(t);case"bridge-initialize-session":case"bridge-get-style-context":return i(t)&&s(t,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return i(t)&&s(t,"routeId")&&y(t,"minVersion")&&y(t,"version");case"bridge-execute":return i(t)&&i(n(t,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return i(t)&&s(t,"subscriptionId");default:return!1}}function j(e){return d(e,"type","response")&&s(e,"id")&&m(e,"ok")&&(c(e,"error")||s(e,"error"))}var G=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]);function T(e){if(!d(e,"type","event")||!s(e,"kind")||!i(n(e,"payload")))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return p(n(t,"ref"))&&g(t,"value")&&(c(t,"hit")||i(n(t,"hit")));case"node-bounds-change":return i(n(t,"hit"));case"bridge-event":return s(t,"subscriptionId")&&i(n(t,"event"));case"route-ready":return s(t,"routeId")&&y(t,"version");case"bridge-status":{let f=n(t,"state");return(f==="connecting"||f==="ready"||f==="reconnecting"||f==="failed"||f==="reload-required")&&g(t,"routeId")&&y(t,"attempt")&&y(t,"retryInMs")&&g(t,"messageKey")}case"scroll":{let f=n(t,"metrics");return i(f)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(O=>o(f,O))}default:return G.has(r)&&o(t,"clientX")&&o(t,"clientY")&&y(t,"buttons")&&(n(t,"hit")===null||i(n(t,"hit")))&&(n(t,"section")===null||_(n(t,"section")))&&(n(t,"sectionGap")===null||A(n(t,"sectionGap")))}}function B(e){if(!i(e))return!1;switch(n(e,"type")){case"request":return C(e);case"response":return j(e);case"event":return T(e);default:return!1}}export{w as SITE_EDIT_FRAME_RUNTIME_CHANNEL,h as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,l as VCP_WINDOW_MESSAGE_SOURCE,q as VCP_WINDOW_MESSAGE_VERSION,L as createSiteEditFrameRuntimeMessage,I as createVcpWindowMessageEnvelope,H as isSiteEditFrameRuntimeMessage,R as isVcpWindowMessageEnvelope};
|
|
1
|
+
var _="vcp-window-message",ce=1;function M(e){return{source:_,version:1,namespace:e.namespace,channel:e.channel,...e.sessionKey?{sessionKey:e.sessionKey}:{},body:e.body}}function W(e){try{return i(e)?d(e,"source",_)&&d(e,"version",1)&&s(e,"namespace")&&s(e,"channel")&&u(e,"body")&&(!l(e,"sessionKey")||s(e,"sessionKey")):!1}catch{return!1}}var O="site-edit",N="frame-runtime",C=1,R=1,w=1,ae=24;function de(e,r={}){return M({namespace:O,channel:N,sessionKey:r.sessionKey,body:e})}function ue(e){try{return!W(e)||e.namespace!==O||e.channel!==N?!1:oe(e.body)}catch{return!1}}var l=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);function u(e,r){let t=Object.getOwnPropertyDescriptor(e,r);return t!==void 0&&"value"in t}function n(e,r){return Object.getOwnPropertyDescriptor(e,r)?.value}function d(e,r,t){return u(e,r)&&n(e,r)===t}function s(e,r){return u(e,r)&&typeof n(e,r)=="string"}function S(e,r){return u(e,r)&&typeof n(e,r)=="boolean"}function o(e,r){let t=n(e,r);return u(e,r)&&typeof t=="number"&&Number.isFinite(t)}function K(e,r){let t=n(e,r);return u(e,r)&&typeof t=="number"&&Number.isInteger(t)&&t>0}function g(e,r){return!l(e,r)||n(e,r)===void 0||s(e,r)}function y(e,r){return!l(e,r)||n(e,r)===void 0||o(e,r)}function b(e,r){let t=n(e,r);return!l(e,r)||t===void 0||u(e,r)&&typeof t=="number"&&Number.isInteger(t)&&t>=0}function a(e,r){return!l(e,r)||n(e,r)===void 0}function i(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function G(e){return i(e)&&Reflect.ownKeys(e).length===0}function A(e){if(!Array.isArray(e))return!1;for(let r=0;r<e.length;r+=1){let t=Object.getOwnPropertyDescriptor(e,String(r));if(t===void 0||!("value"in t)||typeof t.value!="string")return!1}return!0}function p(e){return i(e)&&s(e,"key")&&b(e,"instanceIndex")&&b(e,"instanceCount")&&b(e,"textSegmentIndex")}function B(e){return i(e)&&s(e,"blockId")&&p(n(e,"ref"))&&h(n(e,"rect"))&&S(e,"targetIsSectionRoot")}function L(e){if(!i(e))return!1;let r=n(e,"placement"),t=n(e,"boundary");return s(e,"anchorBlockId")&&p(n(e,"anchorRef"))&&(r==="before"||r==="after")&&i(t)&&o(t,"top")&&o(t,"left")&&o(t,"width")}function h(e){return i(e)&&["top","left","width","height"].every(r=>o(e,r))}function x(e){if(!i(e))return!1;let r=n(e,"rect"),t=n(e,"layout"),c=i(t)?n(t,"containingBlock"):null,f=n(e,"scrollContext"),E=i(c)&&(d(c,"kind","viewport")&&Reflect.ownKeys(c).length===1||d(c,"kind","document")&&Reflect.ownKeys(c).length===1||d(c,"kind","element")&&s(c,"runtimeNodeId"));return d(e,"version",C)&&s(e,"runtimeNodeId")&&i(r)&&h(n(r,"viewport"))&&h(n(r,"document"))&&i(t)&&s(t,"position")&&s(t,"transform")&&E&&i(f)&&["scrollX","scrollY","viewportWidth","viewportHeight"].every(m=>o(f,m))&&u(f,"scrollContainers")&&z(n(f,"scrollContainers"))}function z(e){return Array.isArray(e)&&e.every(r=>i(r)&&s(r,"runtimeNodeId")&&o(r,"scrollLeft")&&o(r,"scrollTop"))}function I(e){return i(e)&&(a(e,"layoutSnapshot")||x(n(e,"layoutSnapshot")))}function U(e){return i(e)&&p(n(e,"ref"))&&u(e,"layoutSnapshot")&&x(n(e,"layoutSnapshot"))&&(a(e,"childBoxes")||H(n(e,"childBoxes")))&&(a(e,"childRects")||q(n(e,"childRects")))&&(a(e,"layout")||j(n(e,"layout")))&&(a(e,"spacing")||X(n(e,"spacing")))}function j(e){if(!i(e))return!1;let r=n(e,"indicatorOrientation");return s(e,"display")&&(r==="horizontal"||r==="vertical")&&g(e,"flexDirection")&&g(e,"gridAutoFlow")}function q(e){return Array.isArray(e)&&e.every(r=>h(r))}function H(e){return Array.isArray(e)&&e.every(r=>i(r)&&h(n(r,"rect"))&&T(n(r,"margin")))}function T(e){return i(e)&&["marginTop","marginRight","marginBottom","marginLeft"].every(r=>o(e,r))}function X(e){return T(e)&&["paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","columnGap","rowGap"].every(r=>o(e,r))}function Y(e){if(!Array.isArray(e))return!1;for(let r=0;r<e.length;r+=1){let t=Object.getOwnPropertyDescriptor(e,String(r));if(t===void 0||!("value"in t)||!U(t.value))return!1}return!0}function Z(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&u(e,r)&&(typeof n(e,r)=="string"||n(e,r)===null))}function V(e){return e==null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function k(e){return i(e)&&Reflect.ownKeys(e).every(r=>typeof r=="string"&&u(e,r)&&V(n(e,r)))}function J(e){if(!i(e))return!1;let r=n(e,"priority");return s(e,"property")&&u(e,"value")&&V(n(e,"value"))&&(!l(e,"priority")||r===void 0||r==="important")}function Q(e){return i(e)?(a(e,"attributes")||Z(n(e,"attributes")))&&g(e,"className")&&(a(e,"style")||k(n(e,"style")))&&(a(e,"styleDeclarations")||Array.isArray(n(e,"styleDeclarations"))&&n(e,"styleDeclarations").every(J)):!1}function $(e){return i(e)&&o(e,"x")&&o(e,"y")&&(a(e,"detailLevel")||d(e,"detailLevel","summary")||d(e,"detailLevel","full"))}function v(e){return i(e)&&p(n(e,"ref"))}function ee(e){if(!i(e)||!i(n(e,"variables")))return!1;let r=n(e,"variables");return Reflect.ownKeys(r).every(t=>typeof t=="string"&&s(r,t))?a(e,"stylesheets")||A(n(e,"stylesheets")):!1}function te(e){if(!d(e,"type","request")||!s(e,"id")||!s(e,"kind")||!u(e,"payload"))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"hit-test-at-point":case"start-text-edit-at-point":return $(t);case"bridge-get-source-tree":case"get-scroll-metrics":case"clear-theme-override":case"bridge-get-history-status":case"bridge-undo":case"bridge-redo":return G(t);case"bridge-get-source-file":return i(t)&&s(t,"path");case"bridge-resolve-source-location":case"bridge-get-object-edit-context":case"bridge-get-class-name-source":return i(t)&&s(t,"key")&&g(t,"routeId");case"scroll-to":return i(t)&&o(t,"x")&&o(t,"y");case"scroll-by":return i(t)&&o(t,"deltaX")&&o(t,"deltaY");case"set-interaction-mode":return i(t)&&S(t,"enabled");case"set-selection-visual":return i(t)&&d(t,"version",R)&&p(n(t,"ref"))&&d(t,"visible",!0);case"clear-selection-visual":return i(t)&&d(t,"version",R);case"set-resize-visual":return i(t)&&d(t,"version",w)&&p(n(t,"ref"))&&d(t,"visible",!0);case"clear-resize-visual":return i(t)&&d(t,"version",w);case"set-theme-override":return ee(t);case"get-theme-variables":return i(t)&&A(n(t,"names"));case"compute-drop-target-at-point":return i(t)&&o(t,"x")&&o(t,"y")&&(d(t,"dragKind","insert")||d(t,"dragKind","move"))&&(a(t,"movingRef")||p(n(t,"movingRef")));case"observe-node-bounds":case"clear-node-bounds-observer":return i(t)&&(a(t,"ref")||p(n(t,"ref")));case"apply-node-patch":return i(t)&&p(n(t,"ref"))&&Q(n(t,"patch"))&&(a(t,"preview")||i(n(t,"preview"))&&s(n(t,"preview"),"sessionId")&&b(n(t,"preview"),"revision")&&l(n(t,"preview"),"revision"));case"get-hit-by-ref":case"get-path-by-ref":case"restore-text-edit":case"clear-text-edit-rollback":return v(t);case"bridge-initialize-session":case"bridge-get-style-context":return i(t)&&s(t,"routeId");case"bridge-get-document":case"bridge-ensure-document-version":case"bridge-acknowledge-document-version":return i(t)&&s(t,"routeId")&&y(t,"minVersion")&&y(t,"version");case"bridge-execute":return i(t)&&i(n(t,"request"));case"bridge-subscribe":case"bridge-unsubscribe":return i(t)&&s(t,"subscriptionId");default:return!1}}function re(e){return d(e,"type","response")&&s(e,"id")&&S(e,"ok")&&(a(e,"error")||s(e,"error"))}var ne=new Set(["pointer-down","pointer-move","pointer-leave","pointer-up","pointer-cancel","pointer-click","pointer-double-click"]),F=new Set(["e","s","se"]);function ie(e,r){if(a(e,"resizeSession"))return!0;let t=n(e,"resizeSession");if(!i(t))return!1;let c=n(e,"pointerId"),f=n(t,"pointerId"),E=n(t,"phase"),m=n(t,"edge"),D=r==="pointer-down"?"start":r==="pointer-up"?"commit":r==="pointer-cancel"?"cancel":null;return n(t,"version")===1&&E===D&&s(t,"sessionId")&&String(n(t,"sessionId")).length>0&&typeof c=="number"&&Number.isInteger(c)&&typeof f=="number"&&Number.isInteger(f)&&c===f&&typeof m=="string"&&F.has(m)&&n(e,"resizeEdge")===m&&p(n(t,"ref"))&&["startWidth","startHeight","width","height"].every(P=>o(t,P))}function se(e){if(!d(e,"type","event")||!s(e,"kind")||!i(n(e,"payload")))return!1;let r=n(e,"kind"),t=n(e,"payload");switch(r){case"text-edit-commit":case"text-edit-cancel":case"text-edit-exit":case"text-edit-input":return p(n(t,"ref"))&&g(t,"value")&&(a(t,"hit")||I(n(t,"hit")));case"node-bounds-change":return I(n(t,"hit"));case"geometry-batch":{let c=n(t,"reason");return K(t,"sequence")&&o(t,"sourceEventAt")&&o(t,"captureStartedAt")&&o(t,"capturedAt")&&(c==="scroll"||c==="resize"||c==="mutation")&&Y(n(t,"snapshots"))}case"bridge-event":return s(t,"subscriptionId")&&i(n(t,"event"));case"route-ready":return s(t,"routeId")&&y(t,"version");case"bridge-status":{let c=n(t,"state");return(c==="connecting"||c==="ready"||c==="reconnecting"||c==="failed"||c==="reload-required")&&g(t,"routeId")&&y(t,"attempt")&&y(t,"retryInMs")&&g(t,"messageKey")}case"scroll":{let c=n(t,"metrics");return i(c)&&["scrollX","scrollY","scrollWidth","scrollHeight","viewportWidth","viewportHeight"].every(f=>o(c,f))}default:return ne.has(r)&&o(t,"clientX")&&o(t,"clientY")&&y(t,"buttons")&&y(t,"pointerId")&&(a(t,"hoverVisualOwned")||S(t,"hoverVisualOwned"))&&(a(t,"resizeEdge")||s(t,"resizeEdge")&&F.has(n(t,"resizeEdge")))&&ie(t,r)&&(n(t,"hit")===null||I(n(t,"hit")))&&(a(t,"section")||n(t,"section")===null||B(n(t,"section")))&&(a(t,"sectionGap")||n(t,"sectionGap")===null||L(n(t,"sectionGap")))}}function oe(e){if(!i(e))return!1;switch(n(e,"type")){case"request":return te(e);case"response":return re(e);case"event":return se(e);default:return!1}}export{N as SITE_EDIT_FRAME_RUNTIME_CHANNEL,C as SITE_EDIT_FRAME_RUNTIME_LAYOUT_SNAPSHOT_VERSION,w as SITE_EDIT_FRAME_RUNTIME_RESIZE_VISUAL_VERSION,R as SITE_EDIT_FRAME_RUNTIME_SELECTION_VISUAL_VERSION,ae as SITE_EDIT_FRAME_SECTION_GAP_RADIUS_PX,O as SITE_EDIT_WINDOW_MESSAGE_NAMESPACE,_ as VCP_WINDOW_MESSAGE_SOURCE,ce as VCP_WINDOW_MESSAGE_VERSION,de as createSiteEditFrameRuntimeMessage,M as createVcpWindowMessageEnvelope,x as isSiteEditFrameRuntimeLayoutSnapshot,ue as isSiteEditFrameRuntimeMessage,W as isVcpWindowMessageEnvelope};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vcp-dev/site-edit-bridge",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
@@ -69,13 +69,13 @@
|
|
|
69
69
|
"node": ">=24.0.0"
|
|
70
70
|
},
|
|
71
71
|
"scripts": {
|
|
72
|
-
"build": "
|
|
72
|
+
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
|
|
73
73
|
"test": "vitest run --root ../.. packages/site-edit-bridge/src --maxWorkers=2",
|
|
74
74
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@vcp-dev/contracts": "0.6.
|
|
78
|
-
"@vcp-dev/site-edit-engine": "0.6.
|
|
77
|
+
"@vcp-dev/contracts": "0.6.6",
|
|
78
|
+
"@vcp-dev/site-edit-engine": "0.6.6",
|
|
79
79
|
"@types/ws": "^8.18.1",
|
|
80
80
|
"ws": "^8.20.1"
|
|
81
81
|
},
|