@vcp-dev/site-edit-bridge 0.11.40 → 0.11.42

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.
@@ -13,6 +13,9 @@ export type SiteEditNextDevServerOptions = {
13
13
  siteId?: string;
14
14
  snapshotId?: string;
15
15
  historyRoot?: string;
16
+ /** Report the shared workspace preview health at the platform health path. */
17
+ workspaceDesigner?: boolean;
18
+ runtimeFingerprint?: string;
16
19
  };
17
20
  export type SiteEditNextDevBundler = "turbopack" | "webpack";
18
21
  type NextDevApp = {
@@ -81,6 +84,7 @@ export type SiteEditLaunchIdentity = {
81
84
  launchId: string;
82
85
  pid: number;
83
86
  snapshotId: string;
87
+ runtimeFingerprint?: string;
84
88
  };
85
89
  export type SiteEditBridgeHealthPayload = SiteEditBridgeHealth & {
86
90
  launch: SiteEditLaunchIdentity;
@@ -1,8 +1,8 @@
1
- import Ve from"node:http";import{existsSync as Q,readFileSync as G}from"node:fs";import{randomUUID as Ts}from"node:crypto";import{createRequire as Ht}from"node:module";import{Socket as Ot}from"node:net";import ne from"node:path";import{basename as Lt,dirname as se,join as ie}from"node:path";import{fileURLToPath as Mt}from"node:url";import{constants as qe,createGzip as Wt}from"node:zlib";function be(e,t){let n=e.write.bind(e),s=e.end.bind(e),o=!1,i,r=()=>{if(o)return;o=!0;let a=String(e.getHeader("content-type")??"");if(e.headersSent||e.statusCode!==200||e.hasHeader("content-encoding")||e.hasHeader("content-range")||/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(String(e.getHeader("cache-control")??""))||!/^(?:text\/html|(?:text|application)\/javascript)(?:;|$)/i.test(a))return;let d=String(e.getHeader("vary")??"");if(d.split(",").some(h=>["*","accept-encoding"].includes(h.trim().toLowerCase()))||e.setHeader("vary",d?`${d}, Accept-Encoding`:"Accept-Encoding"),!Vt(t))return;e.removeHeader("content-length"),e.setHeader("content-encoding","gzip"),i=Wt({level:qe.Z_BEST_SPEED,flush:qe.Z_SYNC_FLUSH}),i.on("data",h=>{n(h)||i?.pause()});let u=()=>{i?.resume()};e.on("drain",u),i.on("drain",()=>e.emit("drain")),i.on("end",()=>s()),i.on("error",h=>e.destroy(h)),e.once("close",()=>{e.off("drain",u),i?.destroy()})};return{write(a){return r(),i?i.write(a):n(a)},end(a,d){return r(),i?(d&&e.once("finish",d),i.end(a),e):d?s(a,d):s(a)},destroy(){i?.destroy(),i&&!e.headersSent&&e.removeHeader("content-encoding")}}}function Vt(e){let t=new Map;for(let s of e?.split(",")??[]){let[o,...i]=s.trim().toLowerCase().split(";"),r=1;for(let a of i){let d=/^\s*q\s*=\s*(.*?)\s*$/.exec(a);d&&(r=/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(d[1])?Number(d[1]):0)}o&&t.set(o.trim(),r)}let n=t.get("gzip")??t.get("*")??0;return n>0&&(t.get("identity")??0)<=n}import{createRequire as Ss}from"node:module";import{pathToFileURL as _s}from"node:url";import{Worker as bs}from"node:worker_threads";var Je=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function we(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import Hn from"node:http";import te from"node:fs";import{createHash as $e,randomBytes as Ln,timingSafeEqual as Mn}from"node:crypto";import O from"node:path";import{WebSocket as xt,WebSocketServer as Dn}from"ws";import{createPreviewSiteEditEngineRuntime as jn,exportPortableBlockFromSnapshot as Un,readPortableBlockLocalAssetChunk as $n,openFileHistoryStore as Kn,resolveManagedPageTemplateComposition as Fn,scanSiteEditCompositionsFromFiles as Wn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Vn,scanNextAppRouterRoutesFromFiles as zn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as qn}from"@vcp-dev/site-edit-engine/source-watcher";function Ye(e){if(e.pageBlocks!==void 0&&!qt(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((p,c)=>[p,c])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},d=e.entries.flatMap((p,c)=>p.dynamicDataSummary?[[c,p.dynamicDataSummary]]:[]),u=new Map(e.entries.map((p,c)=>[p.key,c])),h=[];for(let[p,c]of e.entries.entries()){let g=c.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){h.push([p,{kind:g.kind}]);continue}let _=g.siblingKeys.map(I=>{let E=u.get(I);if(E===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+I);return E});h.push([p,{kind:"source-siblings",siblingEntryIndexes:_}])}let l=p=>{let c=t.get(p);if(typeof c=="number")return c;let g=n.length;return n.push(p),t.set(p,g),g},f=p=>{let c=null;for(let g of nn(p)){let _=`${c??"root"}\0${g}`,I=s.get(_);if(typeof I=="number"){c=I;continue}let E=o.length;o.push([c,l(g)]),s.set(_,E),c=E}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(p=>{let c=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&c<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[f(p.key),zt(p.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:f(p.parentKey))}:{},...d.length>0?{dynamicDataSummaries:d}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function zt(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function qt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!U(n)||!V(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!oe(n.blockKey,256)||!oe(n.definitionKey,512)||!Jt(n.rootRef)||!Gt(n.source)||!Qt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>oe(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!Xt(n.capabilities)||n.unavailableReasons!==void 0&&!Yt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let o of n.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function Jt(e){return!U(e)||!V(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!Ge(e.instanceIndex)||e.instanceCount!==void 0&&(!Ge(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Gt(e){return U(e)&&V(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Zt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Qt(e){return U(e)&&V(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&oe(e.key,512)}function Xt(e){return U(e)&&V(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function Yt(e){return U(e)&&Object.entries(e).every(([t,n])=>W(t)&&U(n)&&V(n,["code","reason"])&&W(n.code)&&W(n.reason))}function Zt(e){let t=en(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function en(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Qe(r)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!tn(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Qe(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),d=Uint8Array.from(a,h=>h.charCodeAt(0)),u=new TextDecoder("utf-8",{fatal:!0}).decode(d);return u.length>0&&u.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(u)&&!u.startsWith(" ")&&!u.endsWith(" ")&&new TextEncoder().encode(u).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(u))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function Qe(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function tn(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function oe(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function V(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function nn(e){if(!e)return[];let t=[],n=0,s=Xe(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Xe(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Xe(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var z="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ke="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var P=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(S(t)&&S(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!S(t)||typeof t.type!="string"?!1:t.type==="request"?rn(t.payload,n):t.type==="response"||t.type==="error"?S(t.payload)&&typeof t.payload.id=="string":t.type==="event"?S(t.payload)&&S(t.payload.event):t.type==="auth"?S(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?S(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&S(t.payload)&&t.payload.ok===!0}},ae=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ve,this.eventDispatcher=new Ce(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=on(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let s=n.payload,{id:o}=s;switch(s.kind){case"initialize-session":{let i=Ie(s),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:D({...a,data:{...a.data,document:nt(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,pn(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,D(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!Ae(s))throw new k("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,a);return}case"export-portable-block-asset":{if(!et(s))throw new k("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(i)!==R(r))throw new k(z,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(i)!==R(r))throw new k(z,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:re(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(s),r=s.request;if(r){let d=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||R(i)!==R(d))throw new k(z,"History request does not match its cursor operation.")}let a=r?{...r,composition:re(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(n){let s=P.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:Re(n),code:xe(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new k(ke,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(z,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=Ie(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=un(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(R(t))}async normalizeOperationRequest(t,n){let s={...t,composition:re(n)};if(s.target.kind==="route"){let o=s.target,i=Ie(o),r=await this.resolveAndAssert(i);s.target={...o,composition:re(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!dn(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===ln(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(P.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=hn(t);this.sendJson({type:"error",payload:{...s,message:Re(n),code:xe(n)}})}}sendJson(t){this.options.socket.send(P.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let o=await s();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:Re(o),code:xe(o)}})}finally{this.eventDispatcher.flush()}}},sn=256;function on(e){if(e.length>sn||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return S(t)&&t.type==="ping"&&S(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},Ce=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},ve=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function rn(e,t){if(!S(e)||typeof e.id!="string"||!P.isRequestKind(e.kind))return!1;let n=j(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||Ee(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&tt(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"export-portable-block":return Ae(e);case"export-portable-block-asset":return et(e);case"execute":case"get-operation-result":return n&&cn(e.request)&&(e.request.mutationContext===void 0||Ee(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Ze(e.request);case"undo":case"redo":return n&&(e.request===void 0||Ze(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||Ee(e.mutationContext))}}function Ae(e){if(!j(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["export_schema_version","site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||t.export_schema_version!==2||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!S(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!j(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!tt(t.selection_ref)||t.cms_schema_proofs!==void 0&&!an(t.cms_schema_proofs))}function an(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!S(s)||!Reflect.ownKeys(s).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function et(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","asset_key","offset","capture_id"].includes(n))||!Ae({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.asset_key!="string"||!/^asset-[a-f0-9]{64}$/u.test(t.asset_key)||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0||t.capture_id!==void 0&&(typeof t.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)))}function Ze(e){return S(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&j(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function tt(e){if(e===void 0)return!0;if(!S(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function cn(e){return S(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&j(e.composition)&&typeof e.kind=="string"&&S(e.target)&&(e.target.kind!=="route"||j(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&S(e.params)}function j(e){return S(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function dn(e){return S(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Ie(e){if(j(e.composition))return e.composition;throw new k(ke,"A composition selector is required for this request.")}function un(e){if(S(e)&&j(e.composition))return e.composition;throw new k(ke,"A composition selector is required for execute.")}function re(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function ln(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return S(e)&&e.ok===!0?{...e,composition:t}:e}function pn(e,t){return!S(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:nt(e.data)}}function nt(e){let t=e;return Ye(t.routeId?t:{...t,routeId:t.composition.routeId})}function S(e){return typeof e=="object"&&e!==null}function Ee(e){return S(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function xe(e){if(!(!S(e)||typeof e.code!="string"||e.code.length===0))return e.code}function Re(e){return e instanceof Error||S(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function hn(e){try{return P.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var ce=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as rt}from"node:crypto";import{constants as at,promises as Te}from"node:fs";import ct from"node:path";import{createHash as fn}from"node:crypto";var de=Buffer.from(['/// <reference types="next" />','/// <reference types="next/image-types/global" />','import "./.next/types/routes.d.ts";','import "./.next/types/root-params.d.ts";',"","// NOTE: This file should not be edited","// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.",""].join(`
2
- `)),st=Buffer.from(de.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),it=e=>`sha256:${fn("sha256").update(e).digest("hex")}`,gn=it(de),mn=it(st);function Z(e,t,n){return e==="next-env.d.ts"&&t===de.byteLength&&n===gn?st.byteLength:null}function ue(e){return Z(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===mn}function ot(){return Uint8Array.from(de)}var dt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),ut=64;async function le(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||dt.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>ut||++n>t.size*ut+1)return!1;let a=await Te.readdir(ct.join(e,i),{withFileTypes:!0});for(let d of a){let u=i?`${i}/${d.name}`:d.name;if(!i&&dt.has(d.name))continue;if(d.isDirectory()){if(!await o(u,r+1))return!1;continue}if(!d.isFile())return!1;let h=t.get(u);if(h===void 0||s.has(u))return!1;s.add(u);let l=ct.join(e,u),f=await Te.lstat(l),p=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${rt("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==p&&f.size!==Z(u,p,c))return!1;let g=rt("sha256"),_=await Te.open(l,at.O_RDONLY|at.O_NOFOLLOW);try{let E=await _.stat();if(!E.isFile()||E.size!==f.size)return!1;let b=0,w=_.createReadStream({autoClose:!1});for await(let C of w){if(b+=C.byteLength,b>f.size)return w.destroy(),!1;g.update(C)}if(b!==f.size)return!1}finally{await _.close()}let I=`sha256:${g.digest("hex")}`;if((f.size!==p||I!==c)&&!ue({file:u,expectedSize:p,expectedDigest:c,actualSize:f.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as ft}from"node:crypto";import{constants as lt,promises as he}from"node:fs";import Pe from"node:path";import{GeneratedSiteCapabilitiesSchema as yn}from"@vcp-dev/contracts";var Sn=".vcp/portable-snapshot-proof.json",pt=4*1024*1024,_n=256*1024*1024,bn=1e4,wn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function gt(e){try{let t=Pe.join(e.projectRoot,Sn),n=await he.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>pt)return null;let s=JSON.parse(await he.readFile(t,"utf8"));if(!ee(s)||!pe(s,["payload"])||!xn(s.payload,pt))return null;let o=Buffer.from(s.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!ee(r)||!pe(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!ee(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>bn)return null;let d=yn.safeParse(r.host_capabilities);if(!d.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let u=new Map;for(let c of r.trusted_host_file_hashes){if(!ee(c)||!pe(c,["path","hash"])||typeof c.path!="string"||!In(c.path)||!ht(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||u.has(c.path))return null;u.set(c.path,c.hash)}let h=0,l=[],f=new Set;for(let c of a.files){if(!ee(c)||!pe(c,["path","hash","size_bytes"])||typeof c.path!="string"||!ht(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||f.has(c.path)||(f.add(c.path),h+=c.size_bytes,h>_n))return null;l.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let p=new Map;for(let c of l){let g=await En(e.projectRoot,c.path,c.size_bytes,c.hash);if(!g||`sha256:${ft("sha256").update(g).digest("hex")}`!==c.hash)return null;p.set(c.path,g)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:l},files:p},host_capabilities:d.data,trusted_host_file_hashes:u}}catch{return null}}function In(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?lib\/utils\.ts$/u.test(e)}async function En(e,t,n,s){let o=t.split("/"),i=e;for(let d of o.slice(0,-1)){i=Pe.join(i,d);let u=await he.lstat(i);if(!u.isDirectory()||u.isSymbolicLink())return null}let r=Pe.join(i,o.at(-1)),a=await he.open(r,lt.O_RDONLY|lt.O_NOFOLLOW);try{let d=await a.stat(),u=Z(t,n,s);if(!d.isFile()||d.size!==n&&d.size!==u)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let c of f){let g=c;if(l+=g.byteLength,l>d.size)return f.destroy(),null;h.push(g)}if(l!==d.size)return null;let p=Buffer.concat(h,l);return l===n?p:ue({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${ft("sha256").update(p).digest("hex")}`})?ot():null}finally{await a.close()}}function ht(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!wn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function xn(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{createHash as Rn}from"node:crypto";import Cn from"node:dns/promises";import vn from"node:http";import kn from"node:https";import{isIP as q}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Oe,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Ne}from"@vcp-dev/contracts";var v=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function mt(e){if(q(e)===4){let[t,n]=e.split(".").map(Number);return!(t===0||t===10||t===127||t>=224||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&[0,168].includes(n)||t===198&&[18,19,51].includes(n)||t===203&&n===0)}return q(e)===6&&/^[23]/u.test(e)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(e)}function Be(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.port||t.hash||n==="localhost"||!n.includes(".")&&!q(n)||/\.(?:internal|localhost|local)$/iu.test(n)||q(n)&&!mt(n))throw v();return t}function yt(e){let t=n=>n.every((s,o)=>e[o]===s);return t([137,80,78,71,13,10,26,10])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56,55,97])||t([71,73,70,56,57,97])?"image/gif":t([82,73,70,70])&&Buffer.from(e.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function An(e,t){let n=()=>{};try{return await Promise.race([e,new Promise((s,o)=>{n=()=>o(v()),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()})])}finally{t.removeEventListener("abort",n)}}async function Tn(e,t){let n=AbortSignal.any([t,AbortSignal.timeout(15e3)]),s=Be(e);for(let o=0;o<=3;o++){n.throwIfAborted();let i=s.hostname.replace(/^\[|\]$/gu,""),r=q(i)?[{address:i,family:q(i)}]:await An(Cn.lookup(i,{all:!0}),n);if(n.throwIfAborted(),!r.length||r.some(({address:u})=>!mt(u)))throw v();let a=r.find(u=>u.family===4)??r[0],d=await new Promise((u,h)=>{(s.protocol==="https:"?kn:vn).get(s,{agent:!1,signal:n,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,p,c)=>{p.all?c(null,[{address:a.address,family:a.family}]):c(null,a.address,a.family)}},u).on("error",h)});try{let u=d.statusCode??0;if([301,302,303,307,308].includes(u)){if(!d.headers.location||o===3)throw v();let g=Be(new URL(d.headers.location,s).href);if(s.protocol==="https:"&&g.protocol!=="https:")throw v();s=g;continue}let h=d.headers["content-length"];if(u!==200||d.headers["content-encoding"]&&d.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>Ne))throw v();let l=[],f=0;for await(let g of d){let _=Buffer.from(g);if(f+=_.length,f>Ne)throw v();l.push(_)}if(!f||h!==void 0&&Number(h)!==f)throw v();let p=Buffer.concat(l,f),c=yt(p);if(!c||d.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==c)throw v();return{bytes:p,mime_type:c}}finally{d.destroy()}}throw v()}var fe=class{constructor(t=Tn){this.download=t,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(t,n){let s=n.asset_catalog.filter(p=>p.asset_key===t.asset_key),o=s[0];if(this.controller.signal.aborted||t.snapshot_digest!==n.snapshot_digest||s.length!==1||o?.origin.kind!=="remote"||!t.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset%Oe)throw v();let i=o.origin.url;Be(i);let r=JSON.stringify([t.request,t.snapshot_digest,t.asset_key,t.capture_id,i]),a=this.entries.get(r);if(!a){if(t.offset||this.pending.has(r)||this.pending.size>=2||this.entries.size>=16)throw v();this.pending.add(r);try{let p=await this.download(i,this.controller.signal);if(this.controller.signal.aborted||!p.bytes.length||p.bytes.length>Ne||yt(p.bytes)!==p.mime_type||[...this.entries.values()].reduce((g,_)=>g+_.image.bytes.length,p.bytes.length)>64*1024*1024)throw v();let c=setTimeout(()=>this.remove(r),6e4);c.unref(),a={image:p,timer:c},this.entries.set(r,a)}finally{this.pending.delete(r)}}let{bytes:d,mime_type:u}=a.image;if(t.offset>=d.length)throw v();let h=Rn("sha256").update(d).digest("hex"),l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[u],f={complete:!0,snapshot_digest:t.snapshot_digest,asset_key:t.asset_key,path:`public/__portable_remote__/${h}.${l}`,mime_type:u,byte_size:d.length,digest_sha256:h,offset:t.offset,data_base64:Buffer.from(d.subarray(t.offset,t.offset+Oe)).toString("base64")};return t.offset+Oe>=d.length&&this.remove(r),f}remove(t){let n=this.entries.get(t);n&&clearTimeout(n.timer),this.entries.delete(t)}dispose(){this.controller.abort();for(let t of this.entries.keys())this.remove(t)}};import{PortableCmsSchemaEnvelopeSchema as Pn,PortableCmsSchemaStatementSchema as On}from"@vcp-dev/contracts";var Nn=3e4;function St(e){try{let t=Pn.safeParse(e.proof);if(!t.success||!Bn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),o=JSON.parse(s);if(JSON.stringify(o)!==s)return null;let i=On.safeParse(o),r=e.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>r+Nn||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Bn(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as Jn,SiteEditPortableExportRequestSchema as Gn,SiteEditPortableExportResultSchema as Qn,SiteEditPortableAssetRequestSchema as Xn,SiteEditPortableAssetResultSchema as Yn,computeSiteEditCompositionKey as $}from"@vcp-dev/contracts";var Zn="127.0.0.1",es=30218,ts="/__vcp/site-edit/bridge",Rt=6*1024*1024,ns=Rt*2,ss=3e3,_t=50,Le=".vcp/current-snapshot.json",bt="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ct(e,t,n={}){let s=new Me(kt(t),e,!1,n);return s.start({listen:!1}),s}var Me=class{constructor(t,n=Hn.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ce,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null,this.portableRemoteAssets=new fe}start(t={}){if(!this.isStarted){this.stopping=!1;try{te.mkdirSync(O.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=Ke({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new qn({projectRoot:this.options.projectRoot,watch_dirs:is(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??_t,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=cs(),n=ds(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let s=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??jn)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,s?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let s=rs(t.composition),o=this.getRuntime(),i=T(s);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,s);let d=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let o=n.getDocument(s);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return wt(s,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let o=St({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;n.push(o)}return n}async exportPortableBlock(t,n,s){let o=(w,C,A)=>({complete:!1,unresolved:[{code:w,path:C,message:A}]}),i=Gn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=T(n);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let u=()=>{let w=this.getRuntime().getDocument(a).data;return{site_id:w.siteId,snapshot_id:w.snapshotId,document_version:w.version}},h=u();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(w=>gt({...w,projectRoot:this.options.projectRoot})),p;try{p=await f({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!p)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...p.snapshot.files].map(([w,C])=>[w,typeof C=="string"?C:new Uint8Array(C)])),g={...p,snapshot:{...p.snapshot,files:c}};if(!await le(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:_,...I}=r,E=await Un({...I,...g,trusted_cms_schemas:l,read_current_identity:u}),b=Qn.safeParse(E);if(!b.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(b.data.complete&&(b.data.site_id!==r.site_id||b.data.base_snapshot_id!==r.base_snapshot_id||b.data.document_version!==r.document_version||b.data.target.blockKey!==r.target.blockKey||b.data.target.composition.routeId!==a.routeId||b.data.target.composition.templateId!==a.templateId||b.data.selection_ref.key!==r.selection_ref.key||b.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||b.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(b.data.complete||b.data.cms_candidates){if(!await le(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let w=u();if(this.options.snapshotId!==r.base_snapshot_id||w.site_id!==r.site_id||w.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(w.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");b.data.complete&&s?.(c)}return b.data}async exportPortableBlockAsset(t,n){let s=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Xn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,n,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let d=a.asset_catalog.find(l=>l.asset_key===i.asset_key),u;try{u=d?.origin.kind==="remote"?await this.portableRemoteAssets.read(i,a):$n({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,asset_key:i.asset_key,offset:i.offset})}catch{return s("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=Yn.safeParse(u);if(!h.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await le(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(T(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||l.siteId!==i.request.site_id||l.snapshotId!==i.request.base_snapshot_id||l.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?h.data:s("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return wt(i,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return s?this.executeWithReceipt(s,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return $e("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,r),r.result.then(()=>{r.settled=!0;for(let[a,d]of this.operationReceipts){if(this.operationReceipts.size<=256)break;d.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??Kn)(as({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=$(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?$(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,d=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let u=a.requestedVersion;await o.writeDocumentVersion(u),a.durableVersion=Math.max(a.durableVersion,u)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=d,this.versionPersistence=d,d}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??_t;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let n=t.some(Pt)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!ys(o));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let o of s)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=te.readFileSync(O.join(this.options.projectRoot,Le),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||De(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=os(this.options.projectRoot),s=zn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(u=>({...u})),i=Wn({files:n});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(u=>u.context.effectiveTemplateId!==void 0).map(u=>u.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(u=>[$(u.context),u])),d=new Map(i.map(u=>[$(u.context),u]));if(this.runtime){for(let[u,h]of a){let l=d.get(u);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(T(h.context))}for(let[u,h]of d){let l=a.get(u);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Vn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Fn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=$(o.context);if(!this.compositions.some(r=>$(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get($(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function vt(e){return kt(e)}function kt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:O.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Zn,port:e.port??es,path:e.path??ts,sessionKey:e.sessionKey??ms(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function is(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function os(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!te.existsSync(i))return;let r;try{r=te.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;o(O.join(i,a.name));continue}if(!a.isFile())continue;let d=O.join(i,a.name),u="";try{u=te.readFileSync(d,"utf8")}catch{}t.push({path:O.relative(e,d).replaceAll(O.sep,"/"),content:u})}};for(let i of n)o(O.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function rs(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function as(e){return O.join(O.resolve(e.root),De(e.siteId),De(e.snapshotId),$e("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function De(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:$e("sha256").update(e).digest("hex").slice(0,32)}function cs(){let e=globalThis;return e[bt]??=new Map,e[bt]}function ds(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function wt(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function Ke(e){let t=new Dn({maxPayload:Rt,noServer:!0}),n=new WeakSet,s=i=>{new ae({socket:new je(i),engine:e.engine,validateOperationRequest:r=>Jn.safeParse(r).success})},o=(i,r,a)=>{if(!us(i,e))return;let d=ls(i,e);if(!d){r.write(`HTTP/1.1 401 Unauthorized\r
1
+ import Ve from"node:http";import{existsSync as Q,readFileSync as G}from"node:fs";import{randomUUID as Ts}from"node:crypto";import{createRequire as Ht}from"node:module";import{Socket as Ot}from"node:net";import ne from"node:path";import{basename as Lt,dirname as se,join as ie}from"node:path";import{fileURLToPath as Mt}from"node:url";import{constants as qe,createGzip as Wt}from"node:zlib";function be(e,t){let n=e.write.bind(e),s=e.end.bind(e),o=!1,i,r=()=>{if(o)return;o=!0;let a=String(e.getHeader("content-type")??"");if(e.headersSent||e.statusCode!==200||e.hasHeader("content-encoding")||e.hasHeader("content-range")||/(?:^|,)\s*no-transform\s*(?:,|$)/i.test(String(e.getHeader("cache-control")??""))||!/^(?:text\/html|(?:text|application)\/javascript)(?:;|$)/i.test(a))return;let u=String(e.getHeader("vary")??"");if(u.split(",").some(h=>["*","accept-encoding"].includes(h.trim().toLowerCase()))||e.setHeader("vary",u?`${u}, Accept-Encoding`:"Accept-Encoding"),!Vt(t))return;e.removeHeader("content-length"),e.setHeader("content-encoding","gzip"),i=Wt({level:qe.Z_BEST_SPEED,flush:qe.Z_SYNC_FLUSH}),i.on("data",h=>{n(h)||i?.pause()});let d=()=>{i?.resume()};e.on("drain",d),i.on("drain",()=>e.emit("drain")),i.on("end",()=>s()),i.on("error",h=>e.destroy(h)),e.once("close",()=>{e.off("drain",d),i?.destroy()})};return{write(a){return r(),i?i.write(a):n(a)},end(a,u){return r(),i?(u&&e.once("finish",u),i.end(a),e):u?s(a,u):s(a)},destroy(){i?.destroy(),i&&!e.headersSent&&e.removeHeader("content-encoding")}}}function Vt(e){let t=new Map;for(let s of e?.split(",")??[]){let[o,...i]=s.trim().toLowerCase().split(";"),r=1;for(let a of i){let u=/^\s*q\s*=\s*(.*?)\s*$/.exec(a);u&&(r=/^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(u[1])?Number(u[1]):0)}o&&t.set(o.trim(),r)}let n=t.get("gzip")??t.get("*")??0;return n>0&&(t.get("identity")??0)<=n}import{createRequire as Ss}from"node:module";import{pathToFileURL as _s}from"node:url";import{Worker as bs}from"node:worker_threads";var Je=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function we(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import Hn from"node:http";import te from"node:fs";import{createHash as Ue,randomBytes as Ln,timingSafeEqual as Mn}from"node:crypto";import O from"node:path";import{WebSocket as xt,WebSocketServer as Dn}from"ws";import{createPreviewSiteEditEngineRuntime as jn,exportPortableBlockFromSnapshot as $n,readPortableBlockLocalAssetChunk as Un,openFileHistoryStore as Kn,resolveManagedPageTemplateComposition as Fn,scanSiteEditCompositionsFromFiles as Wn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as Vn,scanNextAppRouterRoutesFromFiles as zn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as qn}from"@vcp-dev/site-edit-engine/source-watcher";function Ye(e){if(e.pageBlocks!==void 0&&!qt(e.pageBlocks))throw new Error("Invalid page block directory");let t=new Map,n=[],s=new Map,o=[],i=e.pageComposition.status==="supported"?e.pageComposition.placementUnitKeys:[],r=new Map(i.map((p,c)=>[p,c])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(p=>({placementKey:p.placementKey,placementUnitKey:p.placementUnitKey,relation:p.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((p,c)=>p.dynamicDataSummary?[[c,p.dynamicDataSummary]]:[]),d=new Map(e.entries.map((p,c)=>[p.key,c])),h=[];for(let[p,c]of e.entries.entries()){let g=c.pageCompositionActionScope;if(!g)continue;if(g.kind!=="source-siblings"){h.push([p,{kind:g.kind}]);continue}let _=g.siblingKeys.map(I=>{let E=d.get(I);if(E===void 0)throw new Error("Render entry "+c.key+" references missing source sibling "+I);return E});h.push([p,{kind:"source-siblings",siblingEntryIndexes:_}])}let l=p=>{let c=t.get(p);if(typeof c=="number")return c;let g=n.length;return n.push(p),t.set(p,g),g},f=p=>{let c=null;for(let g of nn(p)){let _=`${c??"root"}\0${g}`,I=s.get(_);if(typeof I=="number"){c=I;continue}let E=o.length;o.push([c,l(g)]),s.set(_,E),c=E}if(c===null)throw new Error("Document key must not be empty");return c};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(p=>{let c=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&c<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[f(p.key),zt(p.operationSummary),...c>=0?[c]:[]]}),...h.length>0?{pageCompositionActionScopes:h}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:f(p.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function zt(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function qt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!$(n)||!V(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!oe(n.blockKey,256)||!oe(n.definitionKey,512)||!Jt(n.rootRef)||!Gt(n.source)||!Qt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>oe(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!W(n.placementUnitKey)||!Xt(n.capabilities)||n.unavailableReasons!==void 0&&!Yt(n.unavailableReasons)||t.has(n.blockKey))return!1;t.set(n.blockKey,n)}for(let n of e){let s=n.owner;for(let o of n.siblingBlockKeys){let i=t.get(o);if(!i)return!1;let r=i.owner;if(s.kind!==r.kind||s.key!==r.key)return!1}}return!0}function Jt(e){return!$(e)||!V(e,["key","instanceIndex","instanceCount"])||!W(e.key)||e.instanceIndex!==void 0&&!Ge(e.instanceIndex)||e.instanceCount!==void 0&&(!Ge(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Gt(e){return $(e)&&V(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Zt(e.file)&&W(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Qt(e){return $(e)&&V(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&oe(e.key,512)}function Xt(e){return $(e)&&V(e,["insert","replace","move","remove","save"])&&typeof e.insert=="boolean"&&typeof e.replace=="boolean"&&typeof e.move=="boolean"&&typeof e.remove=="boolean"&&typeof e.save=="boolean"}function Yt(e){return $(e)&&Object.entries(e).every(([t,n])=>W(t)&&$(n)&&V(n,["code","reason"])&&W(n.code)&&W(n.reason))}function Zt(e){let t=en(e),n=t?e.replace("/.vcp/","/_vcp/"):e;if(!e||e.startsWith("/")||e.includes("\\")||n.split("/").some(i=>!i||i==="."||i===".."||i.startsWith(".")||i==="node_modules"||i.toLowerCase()==="package.json"||i==="recipes"||i.startsWith(".env")))return!1;let s=e.toLowerCase();return/^(?:src\/)?app\/api(?:\/|$)/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/u.test(s)||/(^|\/)[^/]+\.server\.[cm]?[jt]sx?$/u.test(s)||/^(?:src\/)?app\/(?:.*\/)?(?:action|actions)\.[cm]?[jt]sx?$/u.test(s)||/^(?:lib|src\/lib)\/(?:server|db|cms)(?:\/|$)/u.test(s)||s.split("/").some(i=>["server","db","database","auth","secret","secrets","token","tokens","credential","credentials"].includes(i.replace(/\.[^.]+$/u,"")))?!1:["design.md","app/globals.css","src/app/globals.css"].includes(e.toLowerCase())||/^(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/iu.test(e)||["components/system/not-found-content.tsx","src/components/system/not-found-content.tsx"].includes(e)||["components/site","src/components/site","lib/generated","src/lib/generated","public"].some(i=>e===i||e.startsWith(`${i}/`))||t}function en(e){let t=/^(?:src\/)?app\/\.vcp\/page-templates\/(.+)\/page\.tsx$/u.exec(e);if(!t)return!1;let n=t[1].split("/"),s=n.some(r=>Qe(r)),o=s?n[0]:n.pop(),i=s?n.slice(1):n;if(s&&i.length===0||!/^[A-Za-z0-9_-]{1,255}$/u.test(o)||!tn(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Qe(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,h=>h.charCodeAt(0)),d=new TextDecoder("utf-8",{fatal:!0}).decode(u);return d.length>0&&d.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(d)&&!d.startsWith(" ")&&!d.endsWith(" ")&&new TextEncoder().encode(d).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(d))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function Qe(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function tn(e){return!e.startsWith("/")||e.startsWith("//")||/[?#\\\x00-\x20\x7f]/u.test(e)||e.startsWith("/.vcp")?!1:!e.split("/").some(t=>{try{let n=decodeURIComponent(t);return n==="."||n===".."||/[/\\\x00-\x1f\x7f]/u.test(n)||n.startsWith(".vcp")}catch{return!0}})}function oe(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function W(e){return typeof e=="string"&&e.length>0}function V(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function nn(e){if(!e)return[];let t=[],n=0,s=Xe(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Xe(e,n+(e.startsWith("::",n)?2:1)),s<0){t.push(e.slice(n));break}t.push(e.slice(n,s)),n=s}return t}function Xe(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var z="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",ke="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var P=class e{constructor(){}static parseMessage(t,n={}){let s=JSON.parse(t);if(!e.isMessage(s,n))throw new Error("Invalid site edit bridge message");return s}static stringifyMessage(t){return JSON.stringify(t)}static extractRequestInfo(t){if(S(t)&&S(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!S(t)||typeof t.type!="string"?!1:t.type==="request"?rn(t.payload,n):t.type==="response"||t.type==="error"?S(t.payload)&&typeof t.payload.id=="string":t.type==="event"?S(t.payload)&&S(t.payload.event):t.type==="auth"?S(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?S(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&S(t.payload)&&t.payload.ok===!0}},ae=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new ve,this.eventDispatcher=new Ce(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=on(n.data);if(s!==null){this.sendJson({type:"pong",payload:{id:s}});return}try{this.messageQueue.enqueue(()=>this.handleRawMessage(n.data))}catch(o){this.sendJson({type:"error",payload:{id:"unknown",kind:"get-document",message:o instanceof Error?o.message:"Bridge queue overflow"}}),t.socket.close(1013,"bridge busy")}},t.socket.onclose=()=>{this.unsubscribe(),this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.clear()}}async handleMessage(t){try{let n=t;if(n.type!=="request")return;let s=n.payload,{id:o}=s;switch(s.kind){case"initialize-session":{let i=Ie(s),r=await this.resolve(i),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:D({...a,data:{...a.data,document:nt(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,pn(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,D(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!Ae(s))throw new k("PORTABLE_EXPORT_REQUEST_INVALID","The portable export request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,a);return}case"export-portable-block-asset":{if(!et(s))throw new k("PORTABLE_LOCAL_ASSET_REQUEST_INVALID","The portable local image request is invalid.");let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.request.target.composition);if(R(i)!==R(r))throw new k(z,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(i)!==R(r))throw new k(z,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(i)!==R(r))throw new k(z,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:re(r)})??null);return}case"undo":case"redo":{let i=await this.resolveWireContext(s),r=s.request;if(r){let u=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||R(i)!==R(u))throw new k(z,"History request does not match its cursor operation.")}let a=r?{...r,composition:re(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(n){let s=P.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:Re(n),code:xe(n)}})}}async resolve(t){return this.options.engine.resolveComposition(t)}async resolveAndAssert(t){let n=await this.resolve(t),s=this.session.activeComposition;if(!s)throw new k(ke,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(z,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=Ie(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=un(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(R(t))}async normalizeOperationRequest(t,n){let s={...t,composition:re(n)};if(s.target.kind==="route"){let o=s.target,i=Ie(o),r=await this.resolveAndAssert(i);s.target={...o,composition:re(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!dn(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===ln(this.session)&&(this.session.activeComposition=void 0,this.session.subscribedCompositionKeys.delete(s)))}sendResult(t,n,s){this.sendJson({type:"response",payload:{id:t,kind:n,result:s}})}async handleRawMessage(t){try{await this.handleMessage(P.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=hn(t);this.sendJson({type:"error",payload:{...s,message:Re(n),code:xe(n)}})}}sendJson(t){this.options.socket.send(P.stringifyMessage(t))}async handleBufferedOperation(t,n,s){this.eventDispatcher.beginBuffering();try{let o=await s();this.sendResult(t,n,o)}catch(o){this.sendJson({type:"error",payload:{id:t,kind:n,message:Re(o),code:xe(o)}})}finally{this.eventDispatcher.flush()}}},sn=256;function on(e){if(e.length>sn||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return S(t)&&t.type==="ping"&&S(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},Ce=class{constructor(t){this.send=t,this.bufferedEvents=null}push(t){let n={type:"event",payload:{event:t}};if(this.bufferedEvents){this.bufferedEvents.push(n);return}this.send(n)}beginBuffering(){this.bufferedEvents=[]}flush(){let t=this.bufferedEvents??[];this.bufferedEvents=null,t.forEach(n=>this.send(n))}},ve=class{constructor(t=64){this.maxQueued=t,this.queue=Promise.resolve(),this.queued=0}enqueue(t){if(this.queued>=this.maxQueued)throw new Error("Bridge request queue is full");this.queued+=1;let n=async()=>{this.queued-=1,await t()},s=this.queue.then(n,n);return this.queue=s.then(()=>{},()=>{}),s}};function rn(e,t){if(!S(e)||typeof e.id!="string"||!P.isRequestKind(e.kind))return!1;let n=j(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||Ee(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&tt(e.selectionRef);case"get-class-name-source":case"resolve-source-location":return typeof e.key=="string"&&n;case"get-history-status":return n;case"get-source-tree":return n;case"get-source-file":return typeof e.path=="string"&&n;case"export-portable-block":return Ae(e);case"export-portable-block-asset":return et(e);case"execute":case"get-operation-result":return n&&cn(e.request)&&(e.request.mutationContext===void 0||Ee(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Ze(e.request);case"undo":case"redo":return n&&(e.request===void 0||Ze(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||Ee(e.mutationContext))}}function Ae(e){if(!j(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["export_schema_version","site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||t.export_schema_version!==2||typeof t.site_id!="string"||typeof t.base_snapshot_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.site_id)||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(t.base_snapshot_id)||typeof t.document_version!="number"||!Number.isSafeInteger(t.document_version)||t.document_version<0||!S(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!j(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!tt(t.selection_ref)||t.cms_schema_proofs!==void 0&&!an(t.cms_schema_proofs))}function an(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!S(s)||!Reflect.ownKeys(s).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function et(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","asset_key","offset","capture_id"].includes(n))||!Ae({id:e.id,kind:"export-portable-block",composition:e.composition,request:t.request})||typeof t.snapshot_digest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(t.snapshot_digest)||typeof t.asset_key!="string"||!/^asset-[a-f0-9]{64}$/u.test(t.asset_key)||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0||t.capture_id!==void 0&&(typeof t.capture_id!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)))}function Ze(e){return S(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&j(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function tt(e){if(e===void 0)return!0;if(!S(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function cn(e){return S(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&j(e.composition)&&typeof e.kind=="string"&&S(e.target)&&(e.target.kind!=="route"||j(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&S(e.params)}function j(e){return S(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function dn(e){return S(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function Ie(e){if(j(e.composition))return e.composition;throw new k(ke,"A composition selector is required for this request.")}function un(e){if(S(e)&&j(e.composition))return e.composition;throw new k(ke,"A composition selector is required for execute.")}function re(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function ln(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return S(e)&&e.ok===!0?{...e,composition:t}:e}function pn(e,t){return!S(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:nt(e.data)}}function nt(e){let t=e;return Ye(t.routeId?t:{...t,routeId:t.composition.routeId})}function S(e){return typeof e=="object"&&e!==null}function Ee(e){return S(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function xe(e){if(!(!S(e)||typeof e.code!="string"||e.code.length===0))return e.code}function Re(e){return e instanceof Error||S(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function hn(e){try{return P.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var ce=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as rt}from"node:crypto";import{constants as at,promises as Te}from"node:fs";import ct from"node:path";import{createHash as fn}from"node:crypto";var de=Buffer.from(['/// <reference types="next" />','/// <reference types="next/image-types/global" />','import "./.next/types/routes.d.ts";','import "./.next/types/root-params.d.ts";',"","// NOTE: This file should not be edited","// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.",""].join(`
2
+ `)),st=Buffer.from(de.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),it=e=>`sha256:${fn("sha256").update(e).digest("hex")}`,gn=it(de),mn=it(st);function Z(e,t,n){return e==="next-env.d.ts"&&t===de.byteLength&&n===gn?st.byteLength:null}function ue(e){return Z(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===mn}function ot(){return Uint8Array.from(de)}var dt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),ut=64;async function le(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||dt.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>ut||++n>t.size*ut+1)return!1;let a=await Te.readdir(ct.join(e,i),{withFileTypes:!0});for(let u of a){let d=i?`${i}/${u.name}`:u.name;if(!i&&dt.has(u.name))continue;if(u.isDirectory()){if(!await o(d,r+1))return!1;continue}if(!u.isFile())return!1;let h=t.get(d);if(h===void 0||s.has(d))return!1;s.add(d);let l=ct.join(e,d),f=await Te.lstat(l),p=typeof h=="string"?Buffer.byteLength(h,"utf8"):h.byteLength,c=`sha256:${rt("sha256").update(h).digest("hex")}`;if(!f.isFile()||f.isSymbolicLink()||f.size!==p&&f.size!==Z(d,p,c))return!1;let g=rt("sha256"),_=await Te.open(l,at.O_RDONLY|at.O_NOFOLLOW);try{let E=await _.stat();if(!E.isFile()||E.size!==f.size)return!1;let b=0,w=_.createReadStream({autoClose:!1});for await(let C of w){if(b+=C.byteLength,b>f.size)return w.destroy(),!1;g.update(C)}if(b!==f.size)return!1}finally{await _.close()}let I=`sha256:${g.digest("hex")}`;if((f.size!==p||I!==c)&&!ue({file:d,expectedSize:p,expectedDigest:c,actualSize:f.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as ft}from"node:crypto";import{constants as lt,promises as he}from"node:fs";import Pe from"node:path";import{GeneratedSiteCapabilitiesSchema as yn}from"@vcp-dev/platform-shared/contracts";var Sn=".vcp/portable-snapshot-proof.json",pt=4*1024*1024,_n=256*1024*1024,bn=1e4,wn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function gt(e){try{let t=Pe.join(e.projectRoot,Sn),n=await he.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>pt)return null;let s=JSON.parse(await he.readFile(t,"utf8"));if(!ee(s)||!pe(s,["payload"])||!xn(s.payload,pt))return null;let o=Buffer.from(s.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!ee(r)||!pe(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!ee(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>bn)return null;let u=yn.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let d=new Map;for(let c of r.trusted_host_file_hashes){if(!ee(c)||!pe(c,["path","hash"])||typeof c.path!="string"||!In(c.path)||!ht(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||d.has(c.path))return null;d.set(c.path,c.hash)}let h=0,l=[],f=new Set;for(let c of a.files){if(!ee(c)||!pe(c,["path","hash","size_bytes"])||typeof c.path!="string"||!ht(c.path)||typeof c.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.hash)||typeof c.size_bytes!="number"||!Number.isSafeInteger(c.size_bytes)||c.size_bytes<0||f.has(c.path)||(f.add(c.path),h+=c.size_bytes,h>_n))return null;l.push({path:c.path,hash:c.hash,size_bytes:c.size_bytes})}let p=new Map;for(let c of l){let g=await En(e.projectRoot,c.path,c.size_bytes,c.hash);if(!g||`sha256:${ft("sha256").update(g).digest("hex")}`!==c.hash)return null;p.set(c.path,g)}return{snapshot:{site_id:e.site_id,snapshot_id:e.base_snapshot_id,manifest:{version:1,site_id:e.site_id,snapshot_id:e.base_snapshot_id,created_at:a.created_at,files:l},files:p},host_capabilities:u.data,trusted_host_file_hashes:d}}catch{return null}}function In(e){return/^(?:src\/)?lib\/cms\/(?!generated\/)[a-zA-Z0-9_./-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?components\/ui\/[a-zA-Z0-9_-]+\.[cm]?[jt]sx?$/u.test(e)||/^(?:src\/)?lib\/utils\.ts$/u.test(e)}async function En(e,t,n,s){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=Pe.join(i,u);let d=await he.lstat(i);if(!d.isDirectory()||d.isSymbolicLink())return null}let r=Pe.join(i,o.at(-1)),a=await he.open(r,lt.O_RDONLY|lt.O_NOFOLLOW);try{let u=await a.stat(),d=Z(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==d)return null;let h=[],l=0,f=a.createReadStream({autoClose:!1});for await(let c of f){let g=c;if(l+=g.byteLength,l>u.size)return f.destroy(),null;h.push(g)}if(l!==u.size)return null;let p=Buffer.concat(h,l);return l===n?p:ue({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${ft("sha256").update(p).digest("hex")}`})?ot():null}finally{await a.close()}}function ht(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!wn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function xn(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{createHash as Rn}from"node:crypto";import Cn from"node:dns/promises";import vn from"node:http";import kn from"node:https";import{isIP as q}from"node:net";import{PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Oe,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as Ne}from"@vcp-dev/platform-shared/contracts";var v=()=>new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");function mt(e){if(q(e)===4){let[t,n]=e.split(".").map(Number);return!(t===0||t===10||t===127||t>=224||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&[0,168].includes(n)||t===198&&[18,19,51].includes(n)||t===203&&n===0)}return q(e)===6&&/^[23]/u.test(e)&&!/^(?:2001:(?:0:|db8:)|2002:)/iu.test(e)}function Be(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/gu,"").replace(/\.$/u,"");if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.port||t.hash||n==="localhost"||!n.includes(".")&&!q(n)||/\.(?:internal|localhost|local)$/iu.test(n)||q(n)&&!mt(n))throw v();return t}function yt(e){let t=n=>n.every((s,o)=>e[o]===s);return t([137,80,78,71,13,10,26,10])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56,55,97])||t([71,73,70,56,57,97])?"image/gif":t([82,73,70,70])&&Buffer.from(e.subarray(8,12)).toString()==="WEBP"?"image/webp":null}async function An(e,t){let n=()=>{};try{return await Promise.race([e,new Promise((s,o)=>{n=()=>o(v()),t.addEventListener("abort",n,{once:!0}),t.aborted&&n()})])}finally{t.removeEventListener("abort",n)}}async function Tn(e,t){let n=AbortSignal.any([t,AbortSignal.timeout(15e3)]),s=Be(e);for(let o=0;o<=3;o++){n.throwIfAborted();let i=s.hostname.replace(/^\[|\]$/gu,""),r=q(i)?[{address:i,family:q(i)}]:await An(Cn.lookup(i,{all:!0}),n);if(n.throwIfAborted(),!r.length||r.some(({address:d})=>!mt(d)))throw v();let a=r.find(d=>d.family===4)??r[0],u=await new Promise((d,h)=>{(s.protocol==="https:"?kn:vn).get(s,{agent:!1,signal:n,headers:{accept:"image/png,image/jpeg,image/gif,image/webp","accept-encoding":"identity"},lookup:(f,p,c)=>{p.all?c(null,[{address:a.address,family:a.family}]):c(null,a.address,a.family)}},d).on("error",h)});try{let d=u.statusCode??0;if([301,302,303,307,308].includes(d)){if(!u.headers.location||o===3)throw v();let g=Be(new URL(u.headers.location,s).href);if(s.protocol==="https:"&&g.protocol!=="https:")throw v();s=g;continue}let h=u.headers["content-length"];if(d!==200||u.headers["content-encoding"]&&u.headers["content-encoding"]!=="identity"||h!==void 0&&(!/^\d+$/u.test(h)||Number(h)<1||Number(h)>Ne))throw v();let l=[],f=0;for await(let g of u){let _=Buffer.from(g);if(f+=_.length,f>Ne)throw v();l.push(_)}if(!f||h!==void 0&&Number(h)!==f)throw v();let p=Buffer.concat(l,f),c=yt(p);if(!c||u.headers["content-type"]?.split(";",1)[0]?.trim().toLowerCase()!==c)throw v();return{bytes:p,mime_type:c}}finally{u.destroy()}}throw v()}var fe=class{constructor(t=Tn){this.download=t,this.entries=new Map,this.pending=new Set,this.controller=new AbortController}async read(t,n){let s=n.asset_catalog.filter(p=>p.asset_key===t.asset_key),o=s[0];if(this.controller.signal.aborted||t.snapshot_digest!==n.snapshot_digest||s.length!==1||o?.origin.kind!=="remote"||!t.capture_id||!/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(t.capture_id)||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset%Oe)throw v();let i=o.origin.url;Be(i);let r=JSON.stringify([t.request,t.snapshot_digest,t.asset_key,t.capture_id,i]),a=this.entries.get(r);if(!a){if(t.offset||this.pending.has(r)||this.pending.size>=2||this.entries.size>=16)throw v();this.pending.add(r);try{let p=await this.download(i,this.controller.signal);if(this.controller.signal.aborted||!p.bytes.length||p.bytes.length>Ne||yt(p.bytes)!==p.mime_type||[...this.entries.values()].reduce((g,_)=>g+_.image.bytes.length,p.bytes.length)>64*1024*1024)throw v();let c=setTimeout(()=>this.remove(r),6e4);c.unref(),a={image:p,timer:c},this.entries.set(r,a)}finally{this.pending.delete(r)}}let{bytes:u,mime_type:d}=a.image;if(t.offset>=u.length)throw v();let h=Rn("sha256").update(u).digest("hex"),l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[d],f={complete:!0,snapshot_digest:t.snapshot_digest,asset_key:t.asset_key,path:`public/__portable_remote__/${h}.${l}`,mime_type:d,byte_size:u.length,digest_sha256:h,offset:t.offset,data_base64:Buffer.from(u.subarray(t.offset,t.offset+Oe)).toString("base64")};return t.offset+Oe>=u.length&&this.remove(r),f}remove(t){let n=this.entries.get(t);n&&clearTimeout(n.timer),this.entries.delete(t)}dispose(){this.controller.abort();for(let t of this.entries.keys())this.remove(t)}};import{PortableCmsSchemaEnvelopeSchema as Pn,PortableCmsSchemaStatementSchema as On}from"@vcp-dev/platform-shared/contracts";var Nn=3e4;function St(e){try{let t=Pn.safeParse(e.proof);if(!t.success||!Bn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),o=JSON.parse(s);if(JSON.stringify(o)!==s)return null;let i=On.safeParse(o),r=e.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>r+Nn||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function Bn(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&/^[A-Za-z0-9_-]+$/u.test(e)&&Buffer.from(e,"base64url").toString("base64url")===e}import{SiteEditOperationRequestSchema as Jn,SiteEditPortableExportRequestSchema as Gn,SiteEditPortableExportResultSchema as Qn,SiteEditPortableAssetRequestSchema as Xn,SiteEditPortableAssetResultSchema as Yn,computeSiteEditCompositionKey as U}from"@vcp-dev/platform-shared/contracts";var Zn="127.0.0.1",es=30218,ts="/__vcp/site-edit/bridge",Rt=6*1024*1024,ns=Rt*2,ss=3e3,_t=50,Le=".vcp/current-snapshot.json",bt="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function Ct(e,t,n={}){let s=new Me(kt(t),e,!1,n);return s.start({listen:!1}),s}var Me=class{constructor(t,n=Hn.createServer((i,r)=>{r.writeHead(404),r.end("VCP site edit bridge server")}),s=!0,o={}){this.options=t,this.server=n,this.closeHttpServerOnStop=s,this.dependencies=o,this.runtime=null,this.activeHistorySessionId=null,this.historySessionTransition=Promise.resolve(),this.mutationQueue=new ce,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null,this.portableRemoteAssets=new fe}start(t={}){if(!this.isStarted){this.stopping=!1;try{te.mkdirSync(O.join(this.options.projectRoot,".vcp"),{recursive:!0})}catch(n){console.warn(`[vcp-site-edit] failed to ensure .vcp directory: ${n instanceof Error?n.message:String(n)}`)}if(this.refreshCompositions(!0),this.isStarted=!0,this.createRuntime(),this.bridgeEngine=this.createBridgeEngine(),t.webSocket!==!1){let n=Ke({server:this.server,path:this.options.path,sessionKey:this.options.sessionKey,host:this.options.host,allowedOrigins:this.options.allowedOrigins,engine:this.bridgeEngine});this.stopWebSocketServer=n.stop}this.stopWatching=new qn({projectRoot:this.options.projectRoot,watch_dirs:is(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??_t,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.portableRemoteAssets.dispose(),this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=cs(),n=ds(this.options);t.get(n)===this&&t.delete(n),this.isStarted=!1,this.notifyHealthChanged()}notifyHealthChanged(){let t=this.options.onHealthChanged;if(!t)return;let n=this.getHealth(),s=JSON.stringify(n);if(s!==this.lastNotifiedHealth){this.lastNotifiedHealth=s;try{t(n)}catch(o){console.warn(`[vcp-site-edit] onHealthChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}}createRuntime(t,n=null){let s=this.runtime;this.activeHistoryStore=t??null;let o=(this.dependencies.createRuntime??jn)({...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,projectRoot:this.options.projectRoot,compositions:this.compositions,onEvent:i=>{"version"in i&&typeof i.version=="number"&&this.recordRuntimeVersion(i.version,"composition"in i?i.composition:void 0);for(let r of this.eventListeners)r(i)},...t?{historyStore:t}:{},...this.getInitialDocumentVersions().length>0?{initialDocumentVersions:this.getInitialDocumentVersions()}:{}});this.runtime=o,this.activeHistorySessionId=n,s?.dispose(),this.notifyHealthChanged()}createBridgeEngine(){return{resolveComposition:t=>this.resolveComposition(t),initializeSession:t=>this.mutationQueue.run(async()=>{let n=await this.bindHistorySession(this.options.snapshotId);if(!n.ok)throw new Error(`${n.code}: ${n.message}`);let s=rs(t.composition),o=this.getRuntime(),i=T(s);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,s);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let o=n.getDocument(s);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return wt(s,t);let o=await this.getRuntime().executeOperation(t);return o.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(o.data.resultVersion,o.composition),o})),getOperationResult:t=>this.readOperationReceipt(t),getHistoryOperationResult:t=>this.readOperationReceipt(t),undo:(t,n)=>this.runHistoryWithReceipt("undo",t,n),redo:(t,n)=>this.runHistoryWithReceipt("redo",t,n),subscribe:t=>(this.eventListeners.add(t),()=>this.eventListeners.delete(t))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let o=St({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;n.push(o)}return n}async exportPortableBlock(t,n,s){let o=(w,C,A)=>({complete:!1,unresolved:[{code:w,path:C,message:A}]}),i=Gn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=T(n);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let d=()=>{let w=this.getRuntime().getDocument(a).data;return{site_id:w.siteId,snapshot_id:w.snapshotId,document_version:w.version}},h=d();if(h.site_id!==r.site_id||h.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(h.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let f=this.dependencies.loadTrustedPortableSnapshot??(w=>gt({...w,projectRoot:this.options.projectRoot})),p;try{p=await f({site_id:r.site_id,base_snapshot_id:r.base_snapshot_id})}catch{return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","The trusted Snapshot proof could not be obtained.")}if(!p)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let c=new Map([...p.snapshot.files].map(([w,C])=>[w,typeof C=="string"?C:new Uint8Array(C)])),g={...p,snapshot:{...p.snapshot,files:c}};if(!await le(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:_,...I}=r,E=await $n({...I,...g,trusted_cms_schemas:l,read_current_identity:d}),b=Qn.safeParse(E);if(!b.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(b.data.complete&&(b.data.site_id!==r.site_id||b.data.base_snapshot_id!==r.base_snapshot_id||b.data.document_version!==r.document_version||b.data.target.blockKey!==r.target.blockKey||b.data.target.composition.routeId!==a.routeId||b.data.target.composition.templateId!==a.templateId||b.data.selection_ref.key!==r.selection_ref.key||b.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||b.data.selection_ref.instanceCount!==r.selection_ref.instanceCount))return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result does not match the selected block.");if(b.data.complete||b.data.cms_candidates){if(!await le(this.options.projectRoot,c))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let w=d();if(this.options.snapshotId!==r.base_snapshot_id||w.site_id!==r.site_id||w.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(w.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document changed during export.")}catch{return o("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live document identity could not be verified.")}if(!this.verifyCmsSchemaProofs(r))return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof expired during export.");b.data.complete&&s?.(c)}return b.data}async exportPortableBlockAsset(t,n){let s=l=>({complete:!1,unresolved:[{code:l,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Xn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,n,l=>{r=l});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=a.asset_catalog.find(l=>l.asset_key===i.asset_key),d;try{d=u?.origin.kind==="remote"?await this.portableRemoteAssets.read(i,a):Un({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,asset_key:i.asset_key,offset:i.offset})}catch{return s("PORTABLE_STATIC_ASSET_UNAVAILABLE")}let h=Yn.safeParse(d);if(!h.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!h.data.complete)return h.data;if(!await le(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let l=this.getRuntime().getDocument(T(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||l.siteId!==i.request.site_id||l.snapshotId!==i.request.base_snapshot_id||l.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?h.data:s("PORTABLE_CMS_SCHEMA_PROOF_INVALID")}runHistoryWithReceipt(t,n,s){if(s&&(!this.isActiveReceiptIdentity(s)||s.kind!==t||s.composition.routeId!==n.routeId||s.composition.templateId!==n.effectiveTemplateId))return Promise.reject(new Error("History request identity does not match the active editing session."));let o=()=>this.mutationQueue.run(async()=>{let i=await this.bindHistorySession(this.options.snapshotId);if(!i.ok)return wt(i,void 0,n);let r=await this.getRuntime()[t]();return r.data?.resultVersion!==void 0&&await this.recordRuntimeVersion(r.data.resultVersion,r.composition??n),r.composition?r:{...r,composition:n}});return s?this.executeWithReceipt(s,o):o()}isActiveReceiptIdentity(t){return"request_id"in t?t.site_id===this.options.siteId&&t.base_snapshot_id===this.options.snapshotId:t.siteId===this.options.siteId&&t.baseSnapshotId===this.options.snapshotId}operationReceiptKey(t){return"request_id"in t?JSON.stringify([t.site_id,t.base_snapshot_id,"history",t.request_id]):JSON.stringify([t.siteId,t.baseSnapshotId,t.id])}operationFingerprint(t){return Ue("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??Kn)(as({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=U(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?U(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let d=a.requestedVersion;await o.writeDocumentVersion(d),a.durableVersion=Math.max(a.durableVersion,d)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let s of t)this.pendingChangedFiles.add(s);this.fileChangeTimer&&clearTimeout(this.fileChangeTimer);let n=this.options.runtime.watch_debounce_ms??_t;this.fileChangeTimer=setTimeout(()=>{this.fileChangeTimer=null,this.flushChangedFiles()},n),this.fileChangeTimer?.unref?.()}flushChangedFiles(){if(this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.pendingChangedFiles.size===0)return;let t=[...this.pendingChangedFiles].sort((o,i)=>o.localeCompare(i));this.pendingChangedFiles.clear();let n=t.some(Pt)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!ys(o));if(!(s.length===0&&!n)&&this.refreshCompositions(!1))for(let o of s)this.runtime?.notifyFileChanged(o)}scheduleSnapshotIdentityAdvance(){if(this.stopping||!this.isStarted)return!1;let t=this.readCurrentSnapshotMarker();return!t||t===this.options.snapshotId?!1:(this.mutationQueue.run(()=>this.advanceSnapshotId(t)).catch(n=>{console.warn(`[vcp-site-edit] snapshot identity advance failed: ${n instanceof Error?n.message:String(n)}`)}),!0)}readCurrentSnapshotMarker(){try{let t=te.readFileSync(O.join(this.options.projectRoot,Le),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||De(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=os(this.options.projectRoot),s=zn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(d=>({...d})),i=Wn({files:n});if(i.length===0)throw new Error("No canonical App Router composition is indexed by the preview bridge.");let r=JSON.stringify(i.filter(d=>d.context.effectiveTemplateId!==void 0).map(d=>d.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(d=>[U(d.context),d])),u=new Map(i.map(d=>[U(d.context),d]));if(this.runtime){for(let[d,h]of a){let l=u.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.unregisterComposition(T(h.context))}for(let[d,h]of u){let l=a.get(d);(!l||l.entryFile!==h.entryFile)&&this.runtime.registerComposition(h.context,h.entryFile)}}return this.routes=o,this.compositions=i,this.compositionFiles=n,this.compositionResolutionError=null,this.notifyHealthChanged(),!0}catch(n){let s=n instanceof Error?n:new Error(String(n));if(this.compositionResolutionError=s,t)throw s;return this.notifyHealthChanged(),!1}}resolveComposition(t){if(this.compositionResolutionError)throw this.compositionResolutionError;let n=Vn(t.routeId,this.routes,this.options.basePath);if(!n)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let s=this.routes.find(r=>r.routeId===n);if(!s)throw new Error(`Route is not indexed by the preview bridge: ${t.routeId}`);let o=Fn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=U(o.context);if(!this.compositions.some(r=>U(r.context)===i))throw new Error(`Composition is not registered by the preview bridge: ${i}`);return o}getInitialDocumentVersions(){return this.compositions.flatMap(t=>{let n=this.runtimeVersionFloors.get(U(t.context));return n===void 0?[]:[{composition:t.context,version:n}]})}getRuntime(){if(!this.runtime)throw new Error("VCP site edit preview bridge runtime is not ready");return this.runtime}};function vt(e){return kt(e)}function kt(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:O.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Zn,port:e.port??es,path:e.path??ts,sessionKey:e.sessionKey??ms(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function is(e){let t=["app","src/app","components/site","src/components/site","lib/generated","src/lib/generated","public"];return[...new Set([...e?.length?e:t,".vcp"])]}function os(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!te.existsSync(i))return;let r;try{r=te.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;o(O.join(i,a.name));continue}if(!a.isFile())continue;let u=O.join(i,a.name),d="";try{d=te.readFileSync(u,"utf8")}catch{}t.push({path:O.relative(e,u).replaceAll(O.sep,"/"),content:d})}};for(let i of n)o(O.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function rs(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function as(e){return O.join(O.resolve(e.root),De(e.siteId),De(e.snapshotId),Ue("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function De(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ue("sha256").update(e).digest("hex").slice(0,32)}function cs(){let e=globalThis;return e[bt]??=new Map,e[bt]}function ds(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function wt(e,t,n){let s=n??(t?.composition?{routeId:t.composition.routeId,...t.composition.templateId?{effectiveTemplateId:t.composition.templateId}:{}}:void 0);if(!s)throw new Error("A normalized composition is required to construct a mutation result.");return{ok:!1,composition:s,error:{code:e.code,message:e.message},data:{requestId:t?.id??"mutation-context",kind:t?.kind??"update-text",composition:s,target:t?.target??{kind:"node",key:""},resultVersion:t?.documentVersion??0}}}function Ke(e){let t=new Dn({maxPayload:Rt,noServer:!0}),n=new WeakSet,s=i=>{new ae({socket:new je(i),engine:e.engine,validateOperationRequest:r=>Jn.safeParse(r).success})},o=(i,r,a)=>{if(!us(i,e))return;let u=ls(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
3
3
  Connection: close\r
4
4
  \r
5
- `),r.destroy();return}d.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,r,a,u=>{t.emit("connection",u,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}ps(i,e.sessionKey,()=>{s(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var je=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===xt.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ns){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function us(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function ls(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=He(e.headers["x-vcp-site-edit-key"]),o=At(s,t.sessionKey),i=He(e.headers.host),r=He(e.headers.origin);return i&&!hs(i,t.host,r)?null:r?gs(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ps(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ss),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=a=>{try{let d=P.parseMessage(a.toString());if(d.type!=="auth"||!At(d.payload.key,t)){r();return}i(),e.readyState===xt.OPEN&&e.send(P.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function At(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&Mn(n,s)}function hs(e,t,n){let s=Et(e),o=Et(t);return s===o||It(o)&&It(s)&&(!n||Ue(n,e))||fs(o)&&(!n||Ue(n,e))}function fs(e){return e==="0.0.0.0"||e==="::"}function It(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function gs(e,t,n){return n.includes(e)||(t?Ue(e,t):!1)}function Ue(e,t){try{return new URL(e).host===Tt(t)}catch{return!1}}function Et(e){let t=Tt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Tt(e){return e.trim().toLowerCase()}function He(e){return Array.isArray(e)?e[0]:e}function ms(){return Ln(32).toString("base64url")}function Pt(e){let t=e.replaceAll("\\","/");return t===Le||t.endsWith(`/${Le}`)}function ys(e){let t=e.replaceAll("\\","/");return Pt(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var ws="SITE_EDIT_ENGINE_UNAVAILABLE",Is=5e3,Es=1024,xs="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",Rs=3,Cs=10*6e4,vs=1012;function Fe(e,t,n={}){let s=vt(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,a={options:r},d=n.maxHeapMb??As(process.env[xs])??Es,u=n.maxRestarts??Rs,h=n.restartWindowMs??Cs,l="starting",f,p=0,c=[],g=null,_=0,I=new Map,E=new Set,b,w,C=new Promise((m,y)=>{b=m,w=y});C.catch(()=>{});let A=m=>{let y=new Error(`VCP site edit preview bridge runtime is not ready: ${m}`);return y.code=ws,y},X=m=>{for(let y of I.values())y.reject(m);I.clear()},B=m=>{switch(m.type){case"ready":g=m.health,l==="starting"?(l="ready",b()):l==="restarting"&&(l="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":l==="starting"&&H(we(m.error));return;case"result":{let y=I.get(m.id);if(!y)return;I.delete(m.id),m.ok?y.resolve(m.value):y.reject(we(m.error));return}case"event":for(let y of E)try{y(m.event)}catch(x){console.warn(`[vcp-site-edit] engine event listener failed: ${x instanceof Error?x.message:String(x)}`)}return;case"health":g=m.health;return;case"snapshot-id-changed":a.options.snapshotId=m.next;try{o?.(m.next,m.previous)}catch(y){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${y instanceof Error?y.message:String(y)}`)}return}},K=()=>{let m=p+=1,y=n.workerUrl??new URL("./engine-worker.js",import.meta.url),x=new bs(ks(y),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:d},...n.execArgv?{execArgv:n.execArgv}:{}});x.unref();let M=()=>m===p;x.on("message",N=>{M()&&B(N)}),x.on("error",N=>{M()&&H(N instanceof Error?N:new Error(String(N)))}),x.on("exit",N=>{M()&&H(new Error(`engine worker exited with code ${N}`))}),f=x,n.onWorker?.(x)},H=m=>{if(l==="stopped"||l==="failed")return;if(X(A(m.message)),g=null,l==="starting"){l="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${m.message}`),w(m);return}let y=Date.now();for(;c.length>0&&y-c[0]>h;)c.shift();if(c.length>=u){l="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${u} restarts: ${m.message}`);return}c.push(y),l="restarting";for(let x of L.clients)x.close(vs,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${c.length}/${u}): ${m.message}`),K()},Y=(m,y)=>{if(l==="failed"||l==="stopped"||l==="restarting")return Promise.reject(A(l));let x=_+=1;return new Promise((M,N)=>{I.set(x,{resolve:M,reject:N});let Ft={type:"call",id:x,method:m,args:y};f.postMessage(Ft)})},F=Object.fromEntries(Je.map(m=>[m,(...y)=>Y(m,y)])),L=Ke({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...F,subscribe(m){return E.add(m),()=>E.delete(m)}}});return K(),{getHealth(){return l==="ready"&&g?g:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:g?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(l==="stopped")return;let m=l==="starting";l="stopped",L.stop(),m&&w(A("bridge stopped")),X(A("bridge stopped")),E.clear();let y=f,x={type:"stop"};y.postMessage(x);let M=setTimeout(()=>{y.terminate()},Is);M.unref(),y.once("exit",()=>clearTimeout(M))},whenReady(){return C},eventListeners:E}}function ks(e){if(!e.pathname.endsWith(".ts"))return e;let t=_s(Ss(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
6
- `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function As(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var Ps="next",Os="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Dt="127.0.0.1",Ns=3e3,Se="/__vcp/site-edit/bridge",jt="/__vcp/site-edit/health",Bs="probe",Hs="render",Nt="/_error",_e="/__vcp/site-edit/client/",Ls=`${_e}auto-bootstrap.js`,Ut='data-vcp-site-edit-bootstrap="true"',Ms=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ds="@vcp-dev/site-edit-engine/webpack-loader",js=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Us=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],$s=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-block-thumbnail.js","frame-block-thumbnail-renderer.js","frame-layout-outline.js","frame-text-commit-preview.js","property-preview.js","portable-thumbnail-assets.js","protocol.js","window-message.js"]);async function Lo(e={},t={}){let n=t.process??process,s=t.createServer??Ve.createServer,o=t.attachBridgeServer??(n.env[Os]==="1"?Ct:Fe),i=t.loadNext??Si,r=ne.resolve(e.projectRoot??process.cwd()),a=e.host??Dt,d=e.port??Ii(n.env.PORT)??Ns,u=e.bridgePath??Se,h=Js(u),l=hi(),f=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",p=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,c=await i(r),g=Ks(r),_=c({dev:!0,dir:r,hostname:a,port:d,...Fs(g)}),I=_.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",b=e.snapshotId??n.env.VCP_SNAPSHOT_ID??wi(r),w=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=w?.trim()?ne.resolve(w):void 0,A=null,X={launchId:Ts(),pid:process.pid,snapshotId:b},B=s((L,m)=>{ti({basePath:f,bridgePath:u,bridgeHealthPath:h,bridgeSessionKey:l,getBridgeHealth:()=>A?.getHealth()??ai(u),launch:X,runRenderProbe:()=>ii(_),handle:I,request:L,response:m}).catch(y=>{console.error(y),m.headersSent||(m.statusCode=500),m.end("site edit preview request failed")})}),K=null,H=null,Y=()=>H||(ye(()=>n.off("SIGINT",F)),ye(()=>n.off("SIGTERM",F)),ye(()=>K?.()),K=null,ye(()=>A?.stop()),A=null,H=Promise.allSettled([xi(B),Ri(()=>_.close())]).then(()=>{}),H),F=()=>{Y()};try{return await _.prepare(),A=o(B,{...p?{tenantId:p}:{},siteId:E,snapshotId:b,projectRoot:r,basePath:f,host:a,port:d,path:u,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:L=>{X.snapshotId=L}}),K=zs({server:B,bridgePath:u,handleUpgrade:_.getUpgradeHandler()}),n.on("SIGINT",F),n.on("SIGTERM",F),await A.whenReady?.(),await Ei(B,d,a),{bundler:g,close:Y,host:a,port:Ci(B,d),server:B}}catch(L){throw await Y(),L}}function Ks(e){let t=Ws(e);return t&&Vs(t)?"webpack":"turbopack"}function Fs(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Ws(e){for(let t of Ms){let n=ie(e,t);if(Q(n))return G(n,"utf8")}return null}function Vs(e){return e.includes(Ds)?!0:js.test(e)&&Us.some(t=>t.test(e))}function zs(e){let t=(n,s,o)=>{qs(n.url,e.bridgePath)||e.handleUpgrade(n,s,o).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function qs(e,t){return new URL(e??"/","http://localhost").pathname===t}function Js(e=Se){if(e===Se)return jt;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Gs(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Qs()});return`<script type="module" ${Ut}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ls)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Qs(){return{bridge:We("@vcp-dev/site-edit-bridge"),contracts:We("@vcp-dev/contracts"),engine:We("@vcp-dev/site-edit-engine")}}function We(e){let t=Ht(import.meta.url);try{let n=t.resolve(e),s=Xs(n,e);if(!s)return;let o=JSON.parse(G(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Xs(e,t){let n=ne.parse(e).root,s=se(e);for(;s&&s!==n;){let o=ie(s,"package.json");if(Q(o))try{if(JSON.parse(G(o,"utf8")).name===t)return o}catch{return}s=se(s)}}function Ys(e,t){if(e.includes(Ut))return e;let n=Gs(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function Mo(e,t=se(Mt(import.meta.url)),n=Q){return $t(e,t,n)?.path??null}function $t(e,t=se(Mt(import.meta.url)),n=Q){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(_e))return null;let o=s.slice(_e.length);if(!$s.has(o))return null;let i=ze(_i(t),o);if(Lt(t)!=="src")return{path:i,requiresTranspile:!1};let r=ze(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Zs(e,t){let n=$t(e.url);if(!n)return!1;if(!Q(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await ei(G(n.path,"utf8")):G(n.path);return t.setHeader("cache-control","no-store"),t.setHeader("content-type","text/javascript; charset=utf-8"),be(t,e.method==="GET"?e.headers["accept-encoding"]:void 0).end(Buffer.isBuffer(s)?s:Buffer.from(s)),!0}async function ei(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function ti({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:a,request:d,response:u}){if(ni(d.url,e)){u.statusCode=404,u.end();return}if(await ri(d,u,n,o,i,r)||await Zs(d,u))return;let h=d.headers["accept-encoding"],l=ci(d),f=di(d),p=l||f?pi(u,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:f,acceptEncoding:h,launch:{...i}}):()=>{};try{await a(d,u)}catch(c){if(p(),u.headersSent){u.destroy(c instanceof Error?c:void 0);return}throw c}}function ni(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(s,"http://namespace.invalid").pathname,i=t.replace(/\/+$/,"");return(i&&(o===i||o.startsWith(i+"/"))?o.slice(i.length)||"/":o).startsWith("/.vcp")}function si(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function ii(e){let t=new Ve.IncomingMessage(new Ot);t.method="GET",t.url=Nt,t.headers={host:Dt};let n=new Ve.ServerResponse(t);n.assignSocket(new Ot);try{return await e.renderToHTML(t,n,Nt,{}),{verdict:"ok"}}catch(s){return si(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function oi(e){return new URL(e??"/","http://localhost").searchParams.get(Bs)===Hs}async function ri(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=s(),d=oi(e.url)?await i():void 0,u={...a,launch:o,...d?{render:d}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(u)),!0}function ai(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function ci(e){return ui(e)?(e.headers["accept-encoding"]="identity",!0):!1}function di(e){return li(e)?(e.headers["accept-encoding"]="identity",!0):!1}function ui(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(_e)||n===Se||n===jt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function li(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function pi(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),a=e.writeHead.bind(e),d=be(e,t.acceptEncoding),u=!1;s.flushHeaders=()=>{},e.writeHead=((l,f,p)=>{e.statusCode=l,typeof f=="string"&&(e.statusMessage=f);let c=typeof f=="string"?p:f;if(Array.isArray(c))for(let g=0;g<c.length;g+=2)e.appendHeader(String(c[g]),String(c[g+1]));else if(c)for(let[g,_]of Object.entries(c))_!==void 0&&e.setHeader(g,_);return e});let h=()=>{if(t.patchNextDevChunk||u)return!1;let l=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(l.toString("utf8")))return!1;let f=Bt(e,l,t);return f!==l&&!e.headersSent&&e.removeHeader("content-length"),e.writeHead=a,d.write(f),n.length=0,u=!0,!0};return s.write=(l,f,p)=>{if(u){if(l!==void 0){let c=d.write(ge(l,me(f)));return J(f),J(p),c}return J(f),J(p),!0}return l!==void 0&&(n.push(ge(l,me(f))),h()),J(f),J(p),!0},s.end=(l,f,p)=>{let c=typeof l=="function"?void 0:l;if(u){s.write=i,s.end=r,s.flushHeaders=o;let E=typeof l=="function"?l:typeof f=="function"?f:typeof p=="function"?p:void 0;return d.end(c===void 0?void 0:ge(c,me(f)),E)}c!==void 0&&n.push(ge(c,me(f))),s.write=i,s.end=r,s.flushHeaders=o,e.writeHead=a;let g=Buffer.concat(n),_=Bt(e,g,t);_!==g&&!e.headersSent&&e.removeHeader("content-length");let I=typeof l=="function"?l:typeof f=="function"?f:typeof p=="function"?p:void 0;return d.end(_,I)},()=>{s.write=i,s.end=r,s.flushHeaders=o,e.writeHead=a,d.destroy()}}function Bt(e,t,n){if(fi(e,t))return Buffer.from(Ys(t.toString("utf8"),n));if(n.patchNextDevChunk&&gi(e)){let s=t.toString("utf8"),o=mi(s);if(o!==s)return Buffer.from(o)}return t}function hi(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function fi(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function gi(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function mi(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
5
+ `),r.destroy();return}u.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,r,a,d=>{t.emit("connection",d,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}ps(i,e.sessionKey,()=>{s(i)})}),t.stop=()=>{e.server.off("upgrade",o);for(let i of t.clients)i.close(1001,"bridge stopped");t.close()},t}var je=class{constructor(t){this.socket=t,this.onmessage=null,this.onclose=null,t.on("error",()=>{}),t.on("message",n=>{this.onmessage?.({data:n.toString()})}),t.on("close",()=>{this.onclose?.()})}send(t){if(this.socket.readyState===xt.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>ns){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function us(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function ls(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=He(e.headers["x-vcp-site-edit-key"]),o=At(s,t.sessionKey),i=He(e.headers.host),r=He(e.headers.origin);return i&&!hs(i,t.host,r)?null:r?gs(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function ps(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},ss),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=a=>{try{let u=P.parseMessage(a.toString());if(u.type!=="auth"||!At(u.payload.key,t)){r();return}i(),e.readyState===xt.OPEN&&e.send(P.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function At(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&Mn(n,s)}function hs(e,t,n){let s=Et(e),o=Et(t);return s===o||It(o)&&It(s)&&(!n||$e(n,e))||fs(o)&&(!n||$e(n,e))}function fs(e){return e==="0.0.0.0"||e==="::"}function It(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function gs(e,t,n){return n.includes(e)||(t?$e(e,t):!1)}function $e(e,t){try{return new URL(e).host===Tt(t)}catch{return!1}}function Et(e){let t=Tt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function Tt(e){return e.trim().toLowerCase()}function He(e){return Array.isArray(e)?e[0]:e}function ms(){return Ln(32).toString("base64url")}function Pt(e){let t=e.replaceAll("\\","/");return t===Le||t.endsWith(`/${Le}`)}function ys(e){let t=e.replaceAll("\\","/");return Pt(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var ws="SITE_EDIT_ENGINE_UNAVAILABLE",Is=5e3,Es=1024,xs="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",Rs=3,Cs=10*6e4,vs=1012;function Fe(e,t,n={}){let s=vt(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,a={options:r},u=n.maxHeapMb??As(process.env[xs])??Es,d=n.maxRestarts??Rs,h=n.restartWindowMs??Cs,l="starting",f,p=0,c=[],g=null,_=0,I=new Map,E=new Set,b,w,C=new Promise((m,y)=>{b=m,w=y});C.catch(()=>{});let A=m=>{let y=new Error(`VCP site edit preview bridge runtime is not ready: ${m}`);return y.code=ws,y},X=m=>{for(let y of I.values())y.reject(m);I.clear()},B=m=>{switch(m.type){case"ready":g=m.health,l==="starting"?(l="ready",b()):l==="restarting"&&(l="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":l==="starting"&&H(we(m.error));return;case"result":{let y=I.get(m.id);if(!y)return;I.delete(m.id),m.ok?y.resolve(m.value):y.reject(we(m.error));return}case"event":for(let y of E)try{y(m.event)}catch(x){console.warn(`[vcp-site-edit] engine event listener failed: ${x instanceof Error?x.message:String(x)}`)}return;case"health":g=m.health;return;case"snapshot-id-changed":a.options.snapshotId=m.next;try{o?.(m.next,m.previous)}catch(y){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${y instanceof Error?y.message:String(y)}`)}return}},K=()=>{let m=p+=1,y=n.workerUrl??new URL("./engine-worker.js",import.meta.url),x=new bs(ks(y),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:u},...n.execArgv?{execArgv:n.execArgv}:{}});x.unref();let M=()=>m===p;x.on("message",N=>{M()&&B(N)}),x.on("error",N=>{M()&&H(N instanceof Error?N:new Error(String(N)))}),x.on("exit",N=>{M()&&H(new Error(`engine worker exited with code ${N}`))}),f=x,n.onWorker?.(x)},H=m=>{if(l==="stopped"||l==="failed")return;if(X(A(m.message)),g=null,l==="starting"){l="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${m.message}`),w(m);return}let y=Date.now();for(;c.length>0&&y-c[0]>h;)c.shift();if(c.length>=d){l="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${d} restarts: ${m.message}`);return}c.push(y),l="restarting";for(let x of L.clients)x.close(vs,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${c.length}/${d}): ${m.message}`),K()},Y=(m,y)=>{if(l==="failed"||l==="stopped"||l==="restarting")return Promise.reject(A(l));let x=_+=1;return new Promise((M,N)=>{I.set(x,{resolve:M,reject:N});let Ft={type:"call",id:x,method:m,args:y};f.postMessage(Ft)})},F=Object.fromEntries(Je.map(m=>[m,(...y)=>Y(m,y)])),L=Ke({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...F,subscribe(m){return E.add(m),()=>E.delete(m)}}});return K(),{getHealth(){return l==="ready"&&g?g:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:g?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(l==="stopped")return;let m=l==="starting";l="stopped",L.stop(),m&&w(A("bridge stopped")),X(A("bridge stopped")),E.clear();let y=f,x={type:"stop"};y.postMessage(x);let M=setTimeout(()=>{y.terminate()},Is);M.unref(),y.once("exit",()=>clearTimeout(M))},whenReady(){return C},eventListeners:E}}function ks(e){if(!e.pathname.endsWith(".ts"))return e;let t=_s(Ss(import.meta.url).resolve("tsx/esm/api")).href,n=[`import { tsImport } from ${JSON.stringify(t)};`,`await tsImport(${JSON.stringify(e.href)}, ${JSON.stringify(e.href)});`].join(`
6
+ `);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function As(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var Ps="next",Os="VCP_SITE_EDIT_ENGINE_IN_PROCESS",Dt="127.0.0.1",Ns=3e3,Se="/__vcp/site-edit/bridge",jt="/__vcp/site-edit/health",Bs="probe",Hs="render",Nt="/_error",_e="/__vcp/site-edit/client/",Ls=`${_e}auto-bootstrap.js`,$t='data-vcp-site-edit-bootstrap="true"',Ms=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],Ds="@vcp-dev/site-edit-engine/webpack-loader",js=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,$s=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],Us=new Set(["auto-bootstrap.js","client.js","cms-preview-identity-registry.js","composition-key.js","designer-trace.js","document-codec.js","frame-scroll-session.js","frame-block-thumbnail.js","frame-block-thumbnail-renderer.js","frame-layout-outline.js","frame-text-commit-preview.js","property-preview.js","portable-thumbnail-assets.js","protocol.js","window-message.js"]);async function Lo(e={},t={}){let n=t.process??process,s=t.createServer??Ve.createServer,o=t.attachBridgeServer??(n.env[Os]==="1"?Ct:Fe),i=t.loadNext??Si,r=ne.resolve(e.projectRoot??process.cwd()),a=e.host??Dt,u=e.port??Ii(n.env.PORT)??Ns,d=e.bridgePath??Se,h=Js(d),l=hi(),f=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",p=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,c=await i(r),g=Ks(r),_=c({dev:!0,dir:r,hostname:a,port:u,...Fs(g)}),I=_.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",b=e.snapshotId??n.env.VCP_SNAPSHOT_ID??wi(r),w=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=w?.trim()?ne.resolve(w):void 0,A=null,X={launchId:Ts(),pid:process.pid,snapshotId:b,...e.runtimeFingerprint?{runtimeFingerprint:e.runtimeFingerprint}:{}},B=s((L,m)=>{ti({basePath:f,bridgePath:d,bridgeHealthPath:h,bridgeSessionKey:l,workspaceDesigner:e.workspaceDesigner===!0,getBridgeHealth:()=>A?.getHealth()??ai(d),launch:X,runRenderProbe:()=>ii(_),handle:I,request:L,response:m}).catch(y=>{console.error(y),m.headersSent||(m.statusCode=500),m.end("site edit preview request failed")})}),K=null,H=null,Y=()=>H||(ye(()=>n.off("SIGINT",F)),ye(()=>n.off("SIGTERM",F)),ye(()=>K?.()),K=null,ye(()=>A?.stop()),A=null,H=Promise.allSettled([xi(B),Ri(()=>_.close())]).then(()=>{}),H),F=()=>{Y()};try{await _.prepare();let L={...p?{tenantId:p}:{},siteId:E,snapshotId:b,projectRoot:r,basePath:f,host:a,port:u,path:d,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:m=>{X.snapshotId=m}};return A=o(B,L),K=zs({server:B,bridgePath:d,handleUpgrade:_.getUpgradeHandler()}),n.on("SIGINT",F),n.on("SIGTERM",F),await A.whenReady?.(),await Ei(B,u,a),{bundler:g,close:Y,host:a,port:Ci(B,u),server:B}}catch(L){throw await Y(),L}}function Ks(e){let t=Ws(e);return t&&Vs(t)?"webpack":"turbopack"}function Fs(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Ws(e){for(let t of Ms){let n=ie(e,t);if(Q(n))return G(n,"utf8")}return null}function Vs(e){return e.includes(Ds)?!0:js.test(e)&&$s.some(t=>t.test(e))}function zs(e){let t=(n,s,o)=>{qs(n.url,e.bridgePath)||e.handleUpgrade(n,s,o).catch(i=>{console.error(i),s.destroyed||s.destroy()})};return e.server.on("upgrade",t),()=>e.server.off("upgrade",t)}function qs(e,t){return new URL(e??"/","http://localhost").pathname===t}function Js(e=Se){if(e===Se)return jt;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Gs(e){let t=JSON.stringify({basePath:e.basePath,launch_id:e.launch?.launchId,snapshot_id:e.launch?.snapshotId,wsPath:e.bridgePath,bridge_session_key:e.bridgeSessionKey,defer_initial_sync:!0,runtime_versions:e.runtimeVersions??Qs()});return`<script type="module" ${$t}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ls)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Qs(){return{bridge:We("@vcp-dev/site-edit-bridge"),contracts:We("@vcp-dev/platform-shared/contracts","@vcp-dev/platform-shared"),engine:We("@vcp-dev/site-edit-engine")}}function We(e,t=e){let n=Ht(import.meta.url);try{let s=n.resolve(e),o=Xs(s,t);if(!o)return;let i=JSON.parse(G(o,"utf8"));return typeof i.version=="string"?i.version:void 0}catch{return}}function Xs(e,t){let n=ne.parse(e).root,s=se(e);for(;s&&s!==n;){let o=ie(s,"package.json");if(Q(o))try{if(JSON.parse(G(o,"utf8")).name===t)return o}catch{return}s=se(s)}}function Ys(e,t){if(e.includes($t))return e;let n=Gs(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function Mo(e,t=se(Mt(import.meta.url)),n=Q){return Ut(e,t,n)?.path??null}function Ut(e,t=se(Mt(import.meta.url)),n=Q){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(_e))return null;let o=s.slice(_e.length);if(!Us.has(o))return null;let i=ze(_i(t),o);if(Lt(t)!=="src")return{path:i,requiresTranspile:!1};let r=ze(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Zs(e,t){let n=Ut(e.url);if(!n)return!1;if(!Q(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await ei(G(n.path,"utf8")):G(n.path);return t.setHeader("cache-control","no-store"),t.setHeader("content-type","text/javascript; charset=utf-8"),be(t,e.method==="GET"?e.headers["accept-encoding"]:void 0).end(Buffer.isBuffer(s)?s:Buffer.from(s)),!0}async function ei(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function ti({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,workspaceDesigner:o,getBridgeHealth:i,launch:r,runRenderProbe:a,handle:u,request:d,response:h}){if(ni(d.url,e)){h.statusCode=404,h.end();return}if(await ri(d,h,n,i,r,a,o?e:void 0)||await Zs(d,h))return;let l=d.headers["accept-encoding"],f=ci(d),p=di(d),c=f||p?pi(h,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:p,acceptEncoding:l,launch:{...r}}):()=>{};try{await u(d,h)}catch(g){if(c(),h.headersSent){h.destroy(g instanceof Error?g:void 0);return}throw g}}function ni(e,t){let n=(e??"/").split(/[?#]/,1)[0]??"/";if(!/(\\|\/\/)/.test(n))return!1;let s;try{s=decodeURIComponent(n).replace(/\\/g,"/").replace(/\/{2,}/g,"/")}catch{return!1}let o=new URL(s,"http://namespace.invalid").pathname,i=t.replace(/\/+$/,"");return(i&&(o===i||o.startsWith(i+"/"))?o.slice(i.length)||"/":o).startsWith("/.vcp")}function si(e){let t=e instanceof Error?e.message:String(e),n=e&&typeof e=="object"&&"code"in e?e.code:void 0;return/\.next[/\\]/.test(t)||/chunks[/\\]ssr[/\\]/.test(t)?n==="ENOENT"||n==="MODULE_NOT_FOUND"?{verdict:"artifact_broken",detail:t}:t.includes("Cannot find module")?{verdict:"artifact_broken",detail:t}:{verdict:"inconclusive",detail:t}:{verdict:"inconclusive",detail:t}}async function ii(e){let t=new Ve.IncomingMessage(new Ot);t.method="GET",t.url=Nt,t.headers={host:Dt};let n=new Ve.ServerResponse(t);n.assignSocket(new Ot);try{return await e.renderToHTML(t,n,Nt,{}),{verdict:"ok"}}catch(s){return si(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function oi(e){return new URL(e??"/","http://localhost").searchParams.get(Bs)===Hs}async function ri(e,t,n,s,o,i,r){if(e.method!=="GET")return!1;let a=new URL(e.url??"/","http://localhost").pathname,u="/__vcp/preview/health",d=r!==void 0&&(a===u||a===r.replace(/\/$/,"")+u);if(a!==n&&!d)return!1;let h=s(),l=oi(e.url)?await i():void 0,f={...h,...d?{framework:"next",mode:"designer"}:{},launch:o,...l?{render:l}:{}};return t.writeHead(h.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(f)),!0}function ai(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function ci(e){return ui(e)?(e.headers["accept-encoding"]="identity",!0):!1}function di(e){return li(e)?(e.headers["accept-encoding"]="identity",!0):!1}function ui(e){if(e.method!=="GET")return!1;let t=new URL(e.url??"/","http://localhost");if(e.headers["x-template-id"]!==void 0&&!t.searchParams.has("template_id"))return!1;let n=t.pathname;if(n.startsWith("/_next/")||n.startsWith(_e)||n===Se||n===jt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function li(e){if(e.method!=="GET"||!String(e.headers["user-agent"]??"").includes("Firefox"))return!1;let n=new URL(e.url??"/","http://localhost").pathname;return n.startsWith("/_next/static/chunks/")&&n.endsWith(".js")}function pi(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),a=e.writeHead.bind(e),u=be(e,t.acceptEncoding),d=!1;s.flushHeaders=()=>{},e.writeHead=((l,f,p)=>{e.statusCode=l,typeof f=="string"&&(e.statusMessage=f);let c=typeof f=="string"?p:f;if(Array.isArray(c))for(let g=0;g<c.length;g+=2)e.appendHeader(String(c[g]),String(c[g+1]));else if(c)for(let[g,_]of Object.entries(c))_!==void 0&&e.setHeader(g,_);return e});let h=()=>{if(t.patchNextDevChunk||d)return!1;let l=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(l.toString("utf8")))return!1;let f=Bt(e,l,t);return f!==l&&!e.headersSent&&e.removeHeader("content-length"),e.writeHead=a,u.write(f),n.length=0,d=!0,!0};return s.write=(l,f,p)=>{if(d){if(l!==void 0){let c=u.write(ge(l,me(f)));return J(f),J(p),c}return J(f),J(p),!0}return l!==void 0&&(n.push(ge(l,me(f))),h()),J(f),J(p),!0},s.end=(l,f,p)=>{let c=typeof l=="function"?void 0:l;if(d){s.write=i,s.end=r,s.flushHeaders=o;let E=typeof l=="function"?l:typeof f=="function"?f:typeof p=="function"?p:void 0;return u.end(c===void 0?void 0:ge(c,me(f)),E)}c!==void 0&&n.push(ge(c,me(f))),s.write=i,s.end=r,s.flushHeaders=o,e.writeHead=a;let g=Buffer.concat(n),_=Bt(e,g,t);_!==g&&!e.headersSent&&e.removeHeader("content-length");let I=typeof l=="function"?l:typeof f=="function"?f:typeof p=="function"?p:void 0;return u.end(_,I)},()=>{s.write=i,s.end=r,s.flushHeaders=o,e.writeHead=a,u.destroy()}}function Bt(e,t,n){if(fi(e,t))return Buffer.from(Ys(t.toString("utf8"),n));if(n.patchNextDevChunk&&gi(e)){let s=t.toString("utf8"),o=mi(s);if(o!==s)return Buffer.from(o)}return t}function hi(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function fi(e,t){if(e.statusCode<200||e.statusCode>=300)return!1;let n=e.getHeader("content-type"),s=Array.isArray(n)?n.join(";"):String(n??"");return t.toString("utf8",0,256).includes("<html")&&(s===""||s.includes("text/html"))}function gi(e){if(e.statusCode<200||e.statusCode>=300)return!1;let t=e.getHeader("content-type"),n=Array.isArray(t)?t.join(";"):String(t??"");return n===""||n.includes("javascript")||n.includes("ecmascript")}function mi(e){return[["debugChannel = createDebugChannel(undefined);","debugChannel = undefined;"],["if (isStreamErrorOrUnfinished(ctr)) {","if (false) {"],["return ctr.desiredSize === null || ctr.desiredSize < 0;","return false;"],[["findSourceMapURL: _appfindsourcemapurl.findSourceMapURL,"," debugChannel,"," startTime: 0"].join(`
7
7
  `),["unstable_allowPartialStream: true,"," debugChannel,"," startTime: 0"].join(`
8
- `)],[["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,o])=>yi(n,s,o),e)}function yi(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function ge(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function me(e){return typeof e=="string"?e:void 0}function J(e){typeof e=="function"&&e()}async function Si(e){let n=Ht(ie(e,"package.json"))(Ps);return n.default??n}function _i(e){return Lt(e)!=="src"?e:ze(bi(e),"dist")}function bi(e){return Kt(e)?ne.posix.dirname(e):se(e)}function ze(e,t){return Kt(e)?ne.posix.join(e,t):ie(e,t)}function Kt(e){return e.includes("/")&&!e.includes("\\")}function wi(e){let t=ie(e,".vcp/current-snapshot.json");if(!Q(t))return"sandbox_worktree";try{let n=JSON.parse(G(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Ii(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Ei(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function xi(e){return new Promise(t=>{e.close(()=>t())})}function ye(e){try{e()}catch{}}function Ri(e){try{return e()}catch(t){return Promise.reject(t)}}function Ci(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{zs as attachNextDevUpgradeHandler,Fe as attachSiteEditBridgeServerInWorker,si as classifySiteEditRenderProbeError,Gs as createSiteEditAutoBootstrapHtmlSnippet,Ys as injectSiteEditAutoBootstrap,oi as isSiteEditRenderProbeRequested,mi as patchNextFirefoxDevChunk,di as prepareFirefoxNextDevChunkPatchRequest,ci as prepareSiteEditHtmlInjectionRequest,Js as resolveSiteEditBridgeHealthPath,$t as resolveSiteEditClientAsset,Mo as resolveSiteEditClientAssetPath,Ks as resolveSiteEditNextDevBundler,ii as runSiteEditRenderProbe,Lo as startSiteEditNextDevServer,ei as transpileSiteEditClientSource};
8
+ `)],[["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,o])=>yi(n,s,o),e)}function yi(e,t,n){if(n.length>t.length)throw new Error("Replacement must not be longer than the search string.");return e.replaceAll(t,n.padEnd(t.length," "))}function ge(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function me(e){return typeof e=="string"?e:void 0}function J(e){typeof e=="function"&&e()}async function Si(e){let n=Ht(ie(e,"package.json"))(Ps);return n.default??n}function _i(e){return Lt(e)!=="src"?e:ze(bi(e),"dist")}function bi(e){return Kt(e)?ne.posix.dirname(e):se(e)}function ze(e,t){return Kt(e)?ne.posix.join(e,t):ie(e,t)}function Kt(e){return e.includes("/")&&!e.includes("\\")}function wi(e){let t=ie(e,".vcp/current-snapshot.json");if(!Q(t))return"sandbox_worktree";try{let n=JSON.parse(G(t,"utf8"));return typeof n.snapshot_id=="string"&&n.snapshot_id?n.snapshot_id:typeof n.snapshotId=="string"&&n.snapshotId?n.snapshotId:"sandbox_worktree"}catch{return"sandbox_worktree"}}function Ii(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function Ei(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function xi(e){return new Promise(t=>{e.close(()=>t())})}function ye(e){try{e()}catch{}}function Ri(e){try{return e()}catch(t){return Promise.reject(t)}}function Ci(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{zs as attachNextDevUpgradeHandler,Fe as attachSiteEditBridgeServerInWorker,si as classifySiteEditRenderProbeError,Gs as createSiteEditAutoBootstrapHtmlSnippet,Ys as injectSiteEditAutoBootstrap,oi as isSiteEditRenderProbeRequested,mi as patchNextFirefoxDevChunk,di as prepareFirefoxNextDevChunkPatchRequest,ci as prepareSiteEditHtmlInjectionRequest,Js as resolveSiteEditBridgeHealthPath,Ut as resolveSiteEditClientAsset,Mo as resolveSiteEditClientAssetPath,Ks as resolveSiteEditNextDevBundler,ii as runSiteEditRenderProbe,Lo as startSiteEditNextDevServer,ei as transpileSiteEditClientSource};
@@ -1,4 +1,4 @@
1
- import { PortableCmsSchemaEnvelopeSchema, PortableCmsSchemaStatementSchema, } from "@vcp-dev/contracts";
1
+ import { PortableCmsSchemaEnvelopeSchema, PortableCmsSchemaStatementSchema, } from "@vcp-dev/platform-shared/contracts";
2
2
  const MAX_CLOCK_SKEW_MS = 30_000;
3
3
  /** Check schema format and identity without authenticating its origin. */
4
4
  export function verifyPortableCmsSchemaProof(input) {
@@ -3,7 +3,7 @@ import dns from "node:dns/promises";
3
3
  import http from "node:http";
4
4
  import https from "node:https";
5
5
  import { isIP } from "node:net";
6
- import { PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as CHUNK, PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as MAX, } from "@vcp-dev/contracts";
6
+ import { PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as CHUNK, PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as MAX, } from "@vcp-dev/platform-shared/contracts";
7
7
  const unavailable = () => new Error("PORTABLE_STATIC_ASSET_UNAVAILABLE");
8
8
  /** No private, metadata, loopback, multicast or IPv4-mapped IPv6 destinations. */
9
9
  export function isPublicPortableAssetAddress(address) {
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { constants, promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
- import { GeneratedSiteCapabilitiesSchema, } from "@vcp-dev/contracts";
4
+ import { GeneratedSiteCapabilitiesSchema, } from "@vcp-dev/platform-shared/contracts";
5
5
  import { isPortableNextEnvDevRewrite, portableNextEnvBuildBytes, portableNextEnvDevSize, } from "./portable-next-env.js";
6
6
  const PROOF_FILE = ".vcp/portable-snapshot-proof.json";
7
7
  const MAX_PROOF_BYTES = 4 * 1024 * 1024;
@@ -20,8 +20,7 @@ const RUNTIME_DIRECTORIES = new Set([
20
20
  "dist",
21
21
  "coverage",
22
22
  ]);
23
- /** Read the preview's unsigned Snapshot metadata, then read only files whose
24
- * bytes match its manifest. Metadata authenticity is not verified. */
23
+ /** Verify source hashes against the preview's unsigned Snapshot metadata. */
25
24
  export async function readVerifiedPortableSnapshot(input) {
26
25
  try {
27
26
  const proofPath = path.join(input.projectRoot, PROOF_FILE);
@@ -1,4 +1,4 @@
1
- import type { SiteEditPropertyChange } from "@vcp-dev/contracts";
1
+ import type { SiteEditPropertyChange } from "@vcp-dev/platform-shared/contracts";
2
2
  import type { SiteEditFrameRuntimeNodePatch } from "./window-message.js";
3
3
  export type SiteEditPropertyPreviewElement = {
4
4
  kind: "host" | "component";
@@ -1,4 +1,4 @@
1
- import type { SiteEditClassNameSourceStyleContext, SiteEditCommandSuccess, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditMutationContext, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/contracts";
1
+ import type { SiteEditClassNameSourceStyleContext, SiteEditCommandSuccess, SiteEditCompositionContext, SiteEditCompositionSelector, SiteEditEvent, SiteEditGetClassNameSourceCommandResult, SiteEditHistoryRequest, SiteEditMutationContext, SiteEditObjectEditContext, SiteEditOperationSelectionRef, SiteEditOperationCommandResult, SiteEditOperationRequest, SiteEditPortableExportRequest, SiteEditPortableExportResult, SiteEditPortableAssetRequest, SiteEditPortableAssetResult, SiteEditRenderDocument, SiteEditResolveSourceLocationInput, SiteEditSourceFileResponse, SiteEditSourceLocation, SiteEditSourceTreeResponse } from "@vcp-dev/platform-shared/contracts";
2
2
  type Awaitable<T> = T | Promise<T>;
3
3
  /** The Bridge keeps this old shape at its boundary for compatibility with the
4
4
  * durable history adapter. The selected composition is carried beside it. */