@vcp-dev/site-edit-bridge 0.11.24 → 0.11.25

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,7 @@ export type SiteEditNextDevServerOptions = {
13
13
  siteId?: string;
14
14
  snapshotId?: string;
15
15
  portableSnapshotPublicKey?: string;
16
+ portableCmsSchemaPublicKey?: string;
16
17
  historyRoot?: string;
17
18
  };
18
19
  export type SiteEditNextDevBundler = "turbopack" | "webpack";
@@ -1,8 +1,8 @@
1
- import je from"node:http";import{existsSync as z,readFileSync as q}from"node:fs";import{randomUUID as cs}from"node:crypto";import{createRequire as Rt}from"node:module";import{Socket as Et}from"node:net";import Y from"node:path";import{basename as kt,dirname as Z,join as ee}from"node:path";import{fileURLToPath as Ct}from"node:url";import{createRequire as Qn}from"node:module";import{pathToFileURL as Xn}from"node:url";import{Worker as Yn}from"node:worker_threads";var Ue=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function ge(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 X from"node:fs";import{createHash as Ne,randomBytes as fn,timingSafeEqual as gn}from"node:crypto";import v from"node:path";import{WebSocket as ft,WebSocketServer as mn}from"ws";import{createPreviewSiteEditEngineRuntime as yn,exportPortableBlockFromSnapshot as Sn,readPortableBlockLocalAssetChunk as bn,openFileHistoryStore as _n,resolveManagedPageTemplateComposition as In,scanSiteEditCompositionsFromFiles as En}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as wn,scanNextAppRouterRoutesFromFiles as xn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Rn}from"@vcp-dev/site-edit-engine/source-watcher";function Ve(e){if(e.pageBlocks!==void 0&&!Ht(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,f)=>[p,f])),c=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,f)=>p.dynamicDataSummary?[[f,p.dynamicDataSummary]]:[]),a=new Map(e.entries.map((p,f)=>[p.key,f])),u=[];for(let[p,f]of e.entries.entries()){let b=f.pageCompositionActionScope;if(!b)continue;if(b.kind!=="source-siblings"){u.push([p,{kind:b.kind}]);continue}let l=b.siblingKeys.map(y=>{let I=a.get(y);if(I===void 0)throw new Error("Render entry "+f.key+" references missing source sibling "+y);return I});u.push([p,{kind:"source-siblings",siblingEntryIndexes:l}])}let h=p=>{let f=t.get(p);if(typeof f=="number")return f;let b=n.length;return n.push(p),t.set(p,b),b},m=p=>{let f=null;for(let b of $t(p)){let l=`${f??"root"}\0${b}`,y=s.get(l);if(typeof y=="number"){f=y;continue}let I=o.length;o.push([f,h(b)]),s.set(l,I),f=I}if(f===null)throw new Error("Document key must not be empty");return f};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:c,tokens:n,nodes:o,entries:e.entries.map(p=>{let f=p.pageCompositionUnitKey?r.get(p.pageCompositionUnitKey)??-1:-1;if(p.pageCompositionUnitKey&&f<0)throw new Error(`Render entry ${p.key} references unknown page composition unit ${p.pageCompositionUnitKey}`);return[m(p.key),Bt(p.operationSummary),...f>=0?[f]:[]]}),...u.length>0?{pageCompositionActionScopes:u}:{},...e.entries.every(p=>p.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(p=>p.parentKey===null?null:m(p.parentKey))}:{},...d.length>0?{dynamicDataSummaries:d}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Bt(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function We(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ht(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!K(n)||!$(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!ne(n.blockKey,256)||!ne(n.definitionKey,512)||!Mt(n.rootRef)||!Lt(n.source)||!Dt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>ne(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!F(n.placementUnitKey)||!jt(n.capabilities)||n.unavailableReasons!==void 0&&!Kt(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 Mt(e){return!K(e)||!$(e,["key","instanceIndex","instanceCount"])||!F(e.key)||e.instanceIndex!==void 0&&!We(e.instanceIndex)||e.instanceCount!==void 0&&(!We(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Lt(e){return K(e)&&$(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Ut(e.file)&&F(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Dt(e){return K(e)&&$(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&ne(e.key,512)}function jt(e){return K(e)&&$(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 Kt(e){return K(e)&&Object.entries(e).every(([t,n])=>F(t)&&K(n)&&$(n,["code","reason"])&&F(n.code)&&F(n.reason))}function Ut(e){let t=Wt(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 Wt(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=>Fe(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)||!Ft(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!Fe(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),c=atob(r),d=Uint8Array.from(c,u=>u.charCodeAt(0)),a=new TextDecoder("utf-8",{fatal:!0}).decode(d);return a.length>0&&a.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(a)&&!a.startsWith(" ")&&!a.endsWith(" ")&&new TextEncoder().encode(a).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(a))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function Fe(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function Ft(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 ne(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function F(e){return typeof e=="string"&&e.length>0}function $(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function $t(e){if(!e)return[];let t=[],n=0,s=$e(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=$e(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 $e(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var V="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",Ee="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var C=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(_(t)&&_(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!_(t)||typeof t.type!="string"?!1:t.type==="request"?zt(t.payload,n):t.type==="response"||t.type==="error"?_(t.payload)&&typeof t.payload.id=="string":t.type==="event"?_(t.payload)&&_(t.payload.event):t.type==="auth"?_(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?_(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&_(t.payload)&&t.payload.ok===!0}},ie=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Ie,this.eventDispatcher=new _e(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=qt(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=me(s),r=await this.resolve(i),c=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:H({...c,data:{...c.data,document:Ge(c.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,Yt(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,H(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(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,H(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,H(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!we(s))throw new x("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(w(i)!==w(r))throw new x(V,"The portable export target does not match the active composition.");let c=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,c);return}case"export-portable-block-asset":{if(!ze(s))throw new x("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(w(i)!==w(r))throw new x(V,"The portable asset target does not match the active composition.");let c=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,c);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=H(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(w(i)!==w(r))throw new x(V,"The execute request composition does not match its operation composition.");let c=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(c)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(c));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(w(i)!==w(r))throw new x(V,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:se(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||w(i)!==w(d))throw new x(V,"History request does not match its cursor operation.")}let c=r?{...r,composition:se(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,c):this.options.engine.redo(i,c));return}}}catch(n){let s=C.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:be(n),code:Se(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 x(Ee,"Initialize a composition session before issuing this request.");if(w(s)!==w(n.context))throw new x(V,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=me(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=Qt(t);return this.resolveAndAssert(n)}activateSession(t){this.session.activeComposition=t,this.session.subscribedCompositionKeys.clear(),this.session.subscribedCompositionKeys.add(w(t))}async normalizeOperationRequest(t,n){let s={...t,composition:se(n)};if(s.target.kind==="route"){let o=s.target,i=me(o),r=await this.resolveAndAssert(i);s.target={...o,composition:se(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Gt(n))return;let s=w(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===Xt(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(C.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=Zt(t);this.sendJson({type:"error",payload:{...s,message:be(n),code:Se(n)}})}}sendJson(t){this.options.socket.send(C.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:be(o),code:Se(o)}})}finally{this.eventDispatcher.flush()}}},Vt=256;function qt(e){if(e.length>Vt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return _(t)&&t.type==="ping"&&_(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var x=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},_e=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))}},Ie=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 zt(e,t){if(!_(e)||typeof e.id!="string"||!C.isRequestKind(e.kind))return!1;let n=M(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||ye(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Je(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 we(e);case"export-portable-block-asset":return ze(e);case"execute":case"get-operation-result":return n&&Jt(e.request)&&(e.request.mutationContext===void 0||ye(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&qe(e.request);case"undo":case"redo":return n&&(e.request===void 0||qe(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||ye(e.mutationContext))}}function we(e){if(!M(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref"].includes(n))||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||!_(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))||!M(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!Je(t.selection_ref))}function ze(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!_(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!we({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.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function qe(e){return _(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")&&M(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Je(e){if(e===void 0)return!0;if(!_(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 Jt(e){return _(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&M(e.composition)&&typeof e.kind=="string"&&_(e.target)&&(e.target.kind!=="route"||M(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&_(e.params)}function M(e){return _(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 Gt(e){return _(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function me(e){if(M(e.composition))return e.composition;throw new x(Ee,"A composition selector is required for this request.")}function Qt(e){if(_(e)&&M(e.composition))return e.composition;throw new x(Ee,"A composition selector is required for execute.")}function se(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Xt(e){return e.activeComposition?w(e.activeComposition):null}function w(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function H(e,t){return _(e)&&e.ok===!0?{...e,composition:t}:e}function Yt(e,t){return!_(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Ge(e.data)}}function Ge(e){let t=e;return Ve(t.routeId?t:{...t,routeId:t.composition.routeId})}function _(e){return typeof e=="object"&&e!==null}function ye(e){return _(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 Se(e){if(!(!_(e)||typeof e.code!="string"||e.code.length===0))return e.code}function be(e){return e instanceof Error||_(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function Zt(e){try{return C.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var oe=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as Ze}from"node:crypto";import{constants as et,promises as xe}from"node:fs";import tt from"node:path";import{createHash as en}from"node:crypto";var re=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
- `)),Qe=Buffer.from(re.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Xe=e=>`sha256:${en("sha256").update(e).digest("hex")}`,tn=Xe(re),nn=Xe(Qe);function G(e,t,n){return e==="next-env.d.ts"&&t===re.byteLength&&n===tn?Qe.byteLength:null}function ae(e){return G(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===nn}function Ye(){return Uint8Array.from(re)}var nt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),st=64;async function ce(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(c=>!c||c==="."||c==="..")||nt.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>st||++n>t.size*st+1)return!1;let c=await xe.readdir(tt.join(e,i),{withFileTypes:!0});for(let d of c){let a=i?`${i}/${d.name}`:d.name;if(!i&&nt.has(d.name))continue;if(d.isDirectory()){if(!await o(a,r+1))return!1;continue}if(!d.isFile())return!1;let u=t.get(a);if(u===void 0||s.has(a))return!1;s.add(a);let h=tt.join(e,a),m=await xe.lstat(h),p=typeof u=="string"?Buffer.byteLength(u,"utf8"):u.byteLength,f=`sha256:${Ze("sha256").update(u).digest("hex")}`;if(!m.isFile()||m.isSymbolicLink()||m.size!==p&&m.size!==G(a,p,f))return!1;let b=Ze("sha256"),l=await xe.open(h,et.O_RDONLY|et.O_NOFOLLOW);try{let I=await l.stat();if(!I.isFile()||I.size!==m.size)return!1;let k=0,T=l.createReadStream({autoClose:!1});for await(let O of T){if(k+=O.byteLength,k>m.size)return T.destroy(),!1;b.update(O)}if(k!==m.size)return!1}finally{await l.close()}let y=`sha256:${b.digest("hex")}`;if((m.size!==p||y!==f)&&!ae({file:a,expectedSize:p,expectedDigest:f,actualSize:m.size,actualDigest:y}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as at,createPublicKey as sn,verify as on}from"node:crypto";import{constants as it,promises as ue}from"node:fs";import ke from"node:path";import{GeneratedSiteCapabilitiesSchema as rn}from"@vcp-dev/contracts";var an=".vcp/portable-snapshot-proof.json",ot=4*1024*1024,cn=256*1024*1024,dn=1e4,un=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function ct(e){try{if(!e.publicKey||!Re(e.publicKey,256))return null;let t=sn({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let n=ke.join(e.projectRoot,an),s=await ue.lstat(n);if(!s.isFile()||s.isSymbolicLink()||s.size>ot)return null;let o=JSON.parse(await ue.readFile(n,"utf8"));if(!Q(o)||!de(o,["payload","signature"])||!Re(o.payload,ot)||!Re(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!on(null,i,t,r))return null;let c=new TextDecoder("utf-8",{fatal:!0}).decode(i),d=JSON.parse(c);if(JSON.stringify(d)!==c||!Q(d)||!de(d,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||d.kind!=="vcp-portable-snapshot-v1"||!Q(d.manifest))return null;let a=d.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>dn)return null;let u=rn.safeParse(d.host_capabilities);if(!u.success||!Array.isArray(d.trusted_host_file_hashes)||d.trusted_host_file_hashes.length>512)return null;let h=new Map;for(let l of d.trusted_host_file_hashes){if(!Q(l)||!de(l,["path","hash"])||typeof l.path!="string"||!pn(l.path)||!rt(l.path)||typeof l.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(l.hash)||h.has(l.path))return null;h.set(l.path,l.hash)}let m=0,p=[],f=new Set;for(let l of a.files){if(!Q(l)||!de(l,["path","hash","size_bytes"])||typeof l.path!="string"||!rt(l.path)||typeof l.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(l.hash)||typeof l.size_bytes!="number"||!Number.isSafeInteger(l.size_bytes)||l.size_bytes<0||f.has(l.path)||(f.add(l.path),m+=l.size_bytes,m>cn))return null;p.push({path:l.path,hash:l.hash,size_bytes:l.size_bytes})}let b=new Map;for(let l of p){let y=await ln(e.projectRoot,l.path,l.size_bytes,l.hash);if(!y||`sha256:${at("sha256").update(y).digest("hex")}`!==l.hash)return null;b.set(l.path,y)}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:p},files:b},host_capabilities:u.data,trusted_host_file_hashes:h}}catch{return null}}function pn(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 ln(e,t,n,s){let o=t.split("/"),i=e;for(let d of o.slice(0,-1)){i=ke.join(i,d);let a=await ue.lstat(i);if(!a.isDirectory()||a.isSymbolicLink())return null}let r=ke.join(i,o.at(-1)),c=await ue.open(r,it.O_RDONLY|it.O_NOFOLLOW);try{let d=await c.stat(),a=G(t,n,s);if(!d.isFile()||d.size!==n&&d.size!==a)return null;let u=[],h=0,m=c.createReadStream({autoClose:!1});for await(let f of m){let b=f;if(h+=b.byteLength,h>d.size)return m.destroy(),null;u.push(b)}if(h!==d.size)return null;let p=Buffer.concat(u,h);return h===n?p:ae({file:t,expectedSize:n,expectedDigest:s,actualSize:h,actualDigest:`sha256:${at("sha256").update(p).digest("hex")}`})?Ye():null}finally{await c.close()}}function rt(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!un.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Re(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 kn,SiteEditPortableExportRequestSchema as Cn,SiteEditPortableExportResultSchema as vn,SiteEditPortableAssetRequestSchema as Tn,SiteEditPortableAssetResultSchema as An,computeSiteEditCompositionKey as U}from"@vcp-dev/contracts";var Pn="127.0.0.1",On=30218,Nn="/__vcp/site-edit/bridge",gt=6*1024*1024,Bn=gt*2,Hn=3e3,dt=50,ve=".vcp/current-snapshot.json",ut="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function mt(e,t,n={}){let s=new Te(St(t),e,!1,n);return s.start({listen:!1}),s}var Te=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 oe,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{X.mkdirSync(v.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=Be({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 Rn({projectRoot:this.options.projectRoot,watch_dirs:Mn(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??dt,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=Kn(),n=Un(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??yn)({...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=Dn(t.composition),o=this.getRuntime(),i=R(s);await o.initializeComposition(i);let c=o.getDocument(i).data;await this.recordRuntimeVersion(c.version,s);let d=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:c,historyStatus:d}}}),getDocument:async t=>{let n=this.getRuntime(),s=R(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(R(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,R(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,R(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(R(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:R(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:R(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return pt(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))}}async exportPortableBlock(t,n,s){let o=(y,I,k)=>({complete:!1,unresolved:[{code:y,path:I,message:k}]}),i=Cn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,c=R(n);if(r.target.composition.routeId!==c.routeId||r.target.composition.templateId!==c.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(c);let a=()=>{let y=this.getRuntime().getDocument(c).data;return{site_id:y.siteId,snapshot_id:y.snapshotId,document_version:y.version}},u=a();if(u.site_id!==r.site_id||u.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(u.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let h=this.dependencies.loadTrustedPortableSnapshot??(y=>ct({...y,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),m;try{m=await h({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(!m)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let p=new Map([...m.snapshot.files].map(([y,I])=>[y,typeof I=="string"?I:new Uint8Array(I)])),f={...m,snapshot:{...m.snapshot,files:p}};if(!await ce(this.options.projectRoot,p))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let b=await Sn({...r,...f,read_current_identity:a}),l=vn.safeParse(b);if(!l.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(l.data.complete&&(l.data.site_id!==r.site_id||l.data.base_snapshot_id!==r.base_snapshot_id||l.data.document_version!==r.document_version||l.data.target.blockKey!==r.target.blockKey||l.data.target.composition.routeId!==c.routeId||l.data.target.composition.templateId!==c.templateId||l.data.selection_ref.key!==r.selection_ref.key||l.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||l.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(l.data.complete){if(!await ce(this.options.projectRoot,p))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let y=a();if(this.options.snapshotId!==r.base_snapshot_id||y.site_id!==r.site_id||y.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(y.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.")}s?.(p)}return l.data}async exportPortableBlockAsset(t,n){let s=u=>({complete:!1,unresolved:[{code:u,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Tn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,c=await this.exportPortableBlock(i.request,n,u=>{r=u});if(!c.complete)return c;if(c.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let d=bn({exported:c,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),a=An.safeParse(d);if(!a.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!a.data.complete)return a.data;if(!await ce(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let u=this.getRuntime().getDocument(R(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||u.siteId!==i.request.site_id||u.snapshotId!==i.request.base_snapshot_id||u.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return a.data}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 pt(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 Ne("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[c,d]of this.operationReceipts){if(this.operationReceipts.size<=256)break;d.settled&&this.operationReceipts.delete(c)}},()=>{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??_n)(jn({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 c=U(r);this.runtimeVersionFloors.set(c,Math.max(this.runtimeVersionFloors.get(c)??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 c=r,d=this.versionPersistence.then(async()=>{try{for(;c.requestedVersion>c.durableVersion;){let a=c.requestedVersion;await o.writeDocumentVersion(a),c.durableVersion=Math.max(c.durableVersion,a)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{c.pending=null}});return c.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??dt;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(It)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!Gn(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=X.readFileSync(v.join(this.options.projectRoot,ve),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Ae(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(c){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${c instanceof Error?c.message:String(c)}`)}}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=Ln(this.options.projectRoot),s=xn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(a=>({...a})),i=En({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(a=>a.context.effectiveTemplateId!==void 0).map(a=>a.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 c=new Map(this.compositions.map(a=>[U(a.context),a])),d=new Map(i.map(a=>[U(a.context),a]));if(this.runtime){for(let[a,u]of c){let h=d.get(a);(!h||h.entryFile!==u.entryFile)&&this.runtime.unregisterComposition(R(u.context))}for(let[a,u]of d){let h=c.get(a);(!h||h.entryFile!==u.entryFile)&&this.runtime.registerComposition(u.context,u.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=wn(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=In({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 yt(e){return St(e)}function St(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:v.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Pn,port:e.port??On,path:e.path??Nn,sessionKey:e.sessionKey??Jn(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Mn(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 Ln(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!X.existsSync(i))return;let r;try{r=X.readdirSync(i,{withFileTypes:!0})}catch{return}for(let c of r){if(c.name.startsWith(".")&&c.name!==".vcp")continue;if(c.isDirectory()){if(s.has(c.name))continue;o(v.join(i,c.name));continue}if(!c.isFile())continue;let d=v.join(i,c.name),a="";try{a=X.readFileSync(d,"utf8")}catch{}t.push({path:v.relative(e,d).replaceAll(v.sep,"/"),content:a})}};for(let i of n)o(v.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function Dn(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 R(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function jn(e){return v.join(v.resolve(e.root),Ae(e.siteId),Ae(e.snapshotId),Ne("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Ae(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Ne("sha256").update(e).digest("hex").slice(0,32)}function Kn(){let e=globalThis;return e[ut]??=new Map,e[ut]}function Un(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function pt(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 Be(e){let t=new mn({maxPayload:gt,noServer:!0}),n=new WeakSet,s=i=>{new ie({socket:new Pe(i),engine:e.engine,validateOperationRequest:r=>kn.safeParse(r).success})},o=(i,r,c)=>{if(!Wn(i,e))return;let d=Fn(i,e);if(!d){r.write(`HTTP/1.1 401 Unauthorized\r
1
+ import je from"node:http";import{existsSync as q,readFileSync as V}from"node:fs";import{randomUUID as ms}from"node:crypto";import{createRequire as vt}from"node:module";import{Socket as Rt}from"node:net";import Z from"node:path";import{basename as Tt,dirname as ee,join as te}from"node:path";import{fileURLToPath as Pt}from"node:url";import{createRequire as is}from"node:module";import{pathToFileURL as os}from"node:url";import{Worker as rs}from"node:worker_threads";var $e=["resolveComposition","initializeSession","getDocument","getHistoryStatus","getStyleContext","getObjectEditContext","getClassNameSource","getSourceTree","getSourceFile","exportPortableBlock","exportPortableBlockAsset","resolveSourceLocation","execute","getOperationResult","getHistoryOperationResult","undo","redo"];function me(e){let t=new Error(e.message);return t.name=e.name,e.code!==void 0&&(t.code=e.code),t}import In from"node:http";import Y from"node:fs";import{createHash as Be,randomBytes as En,timingSafeEqual as wn}from"node:crypto";import O from"node:path";import{WebSocket as yt,WebSocketServer as xn}from"ws";import{createPreviewSiteEditEngineRuntime as Rn,exportPortableBlockFromSnapshot as Cn,readPortableBlockLocalAssetChunk as kn,openFileHistoryStore as vn,resolveManagedPageTemplateComposition as Tn,scanSiteEditCompositionsFromFiles as Pn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as An,scanNextAppRouterRoutesFromFiles as On}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Nn}from"@vcp-dev/site-edit-engine/source-watcher";function qe(e){if(e.pageBlocks!==void 0&&!Kt(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((l,h)=>[l,h])),c=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(l=>({placementKey:l.placementKey,placementUnitKey:l.placementUnitKey,relation:l.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((l,h)=>l.dynamicDataSummary?[[h,l.dynamicDataSummary]]:[]),a=new Map(e.entries.map((l,h)=>[l.key,h])),d=[];for(let[l,h]of e.entries.entries()){let S=h.pageCompositionActionScope;if(!S)continue;if(S.kind!=="source-siblings"){d.push([l,{kind:S.kind}]);continue}let f=S.siblingKeys.map(I=>{let E=a.get(I);if(E===void 0)throw new Error("Render entry "+h.key+" references missing source sibling "+I);return E});d.push([l,{kind:"source-siblings",siblingEntryIndexes:f}])}let p=l=>{let h=t.get(l);if(typeof h=="number")return h;let S=n.length;return n.push(l),t.set(l,S),S},m=l=>{let h=null;for(let S of zt(l)){let f=`${h??"root"}\0${S}`,I=s.get(f);if(typeof I=="number"){h=I;continue}let E=o.length;o.push([h,p(S)]),s.set(f,E),h=E}if(h===null)throw new Error("Document key must not be empty");return h};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:c,tokens:n,nodes:o,entries:e.entries.map(l=>{let h=l.pageCompositionUnitKey?r.get(l.pageCompositionUnitKey)??-1:-1;if(l.pageCompositionUnitKey&&h<0)throw new Error(`Render entry ${l.key} references unknown page composition unit ${l.pageCompositionUnitKey}`);return[m(l.key),Lt(l.operationSummary),...h>=0?[h]:[]]}),...d.length>0?{pageCompositionActionScopes:d}:{},...e.entries.every(l=>l.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(l=>l.parentKey===null?null:m(l.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{}}}function Lt(e){return(e.canUpdateText?1:0)|(e.canInsertChild?2:0)|(e.canMove?4:0)|(e.canRemove?8:0)}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Kt(e){if(!Array.isArray(e))return!1;let t=new Map;for(let n of e){if(!K(n)||!F(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!ne(n.blockKey,256)||!ne(n.definitionKey,512)||!Dt(n.rootRef)||!jt(n.source)||!Ut(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>ne(s,256))||new Set(n.siblingBlockKeys).size!==n.siblingBlockKeys.length||n.siblingBlockKeys.includes(n.blockKey)||n.placementUnitKey!==void 0&&!$(n.placementUnitKey)||!$t(n.capabilities)||n.unavailableReasons!==void 0&&!Ft(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 Dt(e){return!K(e)||!F(e,["key","instanceIndex","instanceCount"])||!$(e.key)||e.instanceIndex!==void 0&&!Fe(e.instanceIndex)||e.instanceCount!==void 0&&(!Fe(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function jt(e){return K(e)&&F(e,["file","structuralPath","contentHash"])&&typeof e.file=="string"&&Wt(e.file)&&$(e.structuralPath)&&typeof e.contentHash=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e.contentHash)}function Ut(e){return K(e)&&F(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&ne(e.key,512)}function $t(e){return K(e)&&F(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 Ft(e){return K(e)&&Object.entries(e).every(([t,n])=>$(t)&&K(n)&&F(n,["code","reason"])&&$(n.code)&&$(n.reason))}function Wt(e){let t=Vt(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 Vt(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=>We(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)||!qt(`/${i.join("/")}`)||i.some(r=>r.includes("[")||r.includes("]")?!We(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),c=atob(r),u=Uint8Array.from(c,d=>d.charCodeAt(0)),a=new TextDecoder("utf-8",{fatal:!0}).decode(u);return a.length>0&&a.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(a)&&!a.startsWith(" ")&&!a.endsWith(" ")&&new TextEncoder().encode(a).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(a))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function We(e){return/^\[\[\.\.\.[^\[\]]+\]\]$/u.test(e)||/^\[[^\[\]]+\]$/u.test(e)}function qt(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 ne(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function $(e){return typeof e=="string"&&e.length>0}function F(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function zt(e){if(!e)return[];let t=[],n=0,s=Ve(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Ve(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 Ve(e,t){let n=e.indexOf("/",t),s=e.indexOf("::",t);return n<0?s:s<0?n:Math.min(n,s)}var W="SITE_EDIT_COMPOSITION_SESSION_MISMATCH",we="SITE_EDIT_COMPOSITION_SESSION_REQUIRED";var A=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(b(t)&&b(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!b(t)||typeof t.type!="string"?!1:t.type==="request"?Qt(t.payload,n):t.type==="response"||t.type==="error"?b(t.payload)&&typeof t.payload.id=="string":t.type==="event"?b(t.payload)&&b(t.payload.event):t.type==="auth"?b(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?b(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&b(t.payload)&&t.payload.ok===!0}},ie=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Ee,this.eventDispatcher=new Ie(n=>{this.sendJson(n)}),this.unsubscribe=t.engine.subscribe(n=>{this.handleEngineEvent(n)}),t.socket.onmessage=n=>{let s=Gt(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=ye(s),r=await this.resolve(i),c=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:H({...c,data:{...c.data,document:Qe(c.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,nn(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,H(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(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,H(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,H(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,H(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!xe(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(W,"The portable export target does not match the active composition.");let c=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,c);return}case"export-portable-block-asset":{if(!Je(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(W,"The portable asset target does not match the active composition.");let c=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,c);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=H(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(W,"The execute request composition does not match its operation composition.");let c=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(c)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(c));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(W,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:se(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(W,"History request does not match its cursor operation.")}let c=r?{...r,composition:se(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,c):this.options.engine.redo(i,c));return}}}catch(n){let s=A.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:_e(n),code:be(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(we,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(W,"The request composition does not match the active socket session.");return n.context}async resolveWireContext(t){let n=ye(t);return this.resolveAndAssert(n)}async resolveOperationWireContext(t){let n=en(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:se(n)};if(s.target.kind==="route"){let o=s.target,i=ye(o),r=await this.resolveAndAssert(i);s.target={...o,composition:se(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Zt(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===tn(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(A.parseMessage(t,{validateOperationRequest:this.options.validateOperationRequest}))}catch(n){let s=sn(t);this.sendJson({type:"error",payload:{...s,message:_e(n),code:be(n)}})}}sendJson(t){this.options.socket.send(A.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:_e(o),code:be(o)}})}finally{this.eventDispatcher.flush()}}},Jt=256;function Gt(e){if(e.length>Jt||!e.includes('"ping"'))return null;try{let t=JSON.parse(e);return b(t)&&t.type==="ping"&&b(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"}},Ie=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))}},Ee=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 Qt(e,t){if(!b(e)||typeof e.id!="string"||!A.isRequestKind(e.kind))return!1;let n=M(e.composition);switch(e.kind){case"initialize-session":return n&&(e.mutationContext===void 0||Se(e.mutationContext));case"get-document":case"get-style-context":return n;case"get-object-edit-context":return typeof e.key=="string"&&n&&Ge(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 xe(e);case"export-portable-block-asset":return Je(e);case"execute":case"get-operation-result":return n&&Yt(e.request)&&(e.request.mutationContext===void 0||Se(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||Se(e.mutationContext))}}function xe(e){if(!M(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["site_id","base_snapshot_id","document_version","target","selection_ref","cms_schema_proofs"].includes(n))||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||!b(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))||!M(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!Ge(t.selection_ref)||t.cms_schema_proofs!==void 0&&!Xt(t.cms_schema_proofs))}function Xt(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(!b(s)||!Reflect.ownKeys(s).every(r=>typeof r=="string"&&["payload","signature"].includes(r)))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload"),i=Object.getOwnPropertyDescriptor(s,"signature");if(!o||!("value"in o)||!i||!("value"in i)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value)||typeof i.value!="string"||!/^[A-Za-z0-9_-]{86}$/u.test(i.value))return!1}return!0}function Je(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!b(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","file_path","occurrence","offset"].includes(n))||!xe({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.file_path!="string"||!t.file_path.length||t.file_path.length>1024||t.file_path.startsWith("/")||/[\\\0%]/u.test(t.file_path)||t.file_path.split("/").some(n=>!n||n.startsWith(".")||n==="node_modules")||typeof t.occurrence!="number"||!Number.isSafeInteger(t.occurrence)||t.occurrence<0||t.occurrence>4095||typeof t.offset!="number"||!Number.isSafeInteger(t.offset)||t.offset<0||t.offset>50*1024*1024||t.offset%(1024*1024)!==0)}function ze(e){return b(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")&&M(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function Ge(e){if(e===void 0)return!0;if(!b(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 Yt(e){return b(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&M(e.composition)&&typeof e.kind=="string"&&b(e.target)&&(e.target.kind!=="route"||M(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&b(e.params)}function M(e){return b(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 Zt(e){return b(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function ye(e){if(M(e.composition))return e.composition;throw new k(we,"A composition selector is required for this request.")}function en(e){if(b(e)&&M(e.composition))return e.composition;throw new k(we,"A composition selector is required for execute.")}function se(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function tn(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function H(e,t){return b(e)&&e.ok===!0?{...e,composition:t}:e}function nn(e,t){return!b(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Qe(e.data)}}function Qe(e){let t=e;return qe(t.routeId?t:{...t,routeId:t.composition.routeId})}function b(e){return typeof e=="object"&&e!==null}function Se(e){return b(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 be(e){if(!(!b(e)||typeof e.code!="string"||e.code.length===0))return e.code}function _e(e){return e instanceof Error||b(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function sn(e){try{return A.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var oe=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as et}from"node:crypto";import{constants as tt,promises as Re}from"node:fs";import nt from"node:path";import{createHash as on}from"node:crypto";var re=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
+ `)),Xe=Buffer.from(re.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Ye=e=>`sha256:${on("sha256").update(e).digest("hex")}`,rn=Ye(re),an=Ye(Xe);function Q(e,t,n){return e==="next-env.d.ts"&&t===re.byteLength&&n===rn?Xe.byteLength:null}function ae(e){return Q(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===an}function Ze(){return Uint8Array.from(re)}var st=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),it=64;async function ce(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(c=>!c||c==="."||c==="..")||st.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>it||++n>t.size*it+1)return!1;let c=await Re.readdir(nt.join(e,i),{withFileTypes:!0});for(let u of c){let a=i?`${i}/${u.name}`:u.name;if(!i&&st.has(u.name))continue;if(u.isDirectory()){if(!await o(a,r+1))return!1;continue}if(!u.isFile())return!1;let d=t.get(a);if(d===void 0||s.has(a))return!1;s.add(a);let p=nt.join(e,a),m=await Re.lstat(p),l=typeof d=="string"?Buffer.byteLength(d,"utf8"):d.byteLength,h=`sha256:${et("sha256").update(d).digest("hex")}`;if(!m.isFile()||m.isSymbolicLink()||m.size!==l&&m.size!==Q(a,l,h))return!1;let S=et("sha256"),f=await Re.open(p,tt.O_RDONLY|tt.O_NOFOLLOW);try{let E=await f.stat();if(!E.isFile()||E.size!==m.size)return!1;let _=0,w=f.createReadStream({autoClose:!1});for await(let C of w){if(_+=C.byteLength,_>m.size)return w.destroy(),!1;S.update(C)}if(_!==m.size)return!1}finally{await f.close()}let I=`sha256:${S.digest("hex")}`;if((m.size!==l||I!==h)&&!ae({file:a,expectedSize:l,expectedDigest:h,actualSize:m.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as ct,createPublicKey as cn,verify as un}from"node:crypto";import{constants as ot,promises as de}from"node:fs";import ke from"node:path";import{GeneratedSiteCapabilitiesSchema as dn}from"@vcp-dev/contracts";var ln=".vcp/portable-snapshot-proof.json",rt=4*1024*1024,pn=256*1024*1024,hn=1e4,fn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function ut(e){try{if(!e.publicKey||!Ce(e.publicKey,256))return null;let t=cn({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"});if(t.asymmetricKeyType!=="ed25519")return null;let n=ke.join(e.projectRoot,ln),s=await de.lstat(n);if(!s.isFile()||s.isSymbolicLink()||s.size>rt)return null;let o=JSON.parse(await de.readFile(n,"utf8"));if(!X(o)||!ue(o,["payload","signature"])||!Ce(o.payload,rt)||!Ce(o.signature,128))return null;let i=Buffer.from(o.payload,"base64url"),r=Buffer.from(o.signature,"base64url");if(r.byteLength!==64||!un(null,i,t,r))return null;let c=new TextDecoder("utf-8",{fatal:!0}).decode(i),u=JSON.parse(c);if(JSON.stringify(u)!==c||!X(u)||!ue(u,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||u.kind!=="vcp-portable-snapshot-v1"||!X(u.manifest))return null;let a=u.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>hn)return null;let d=dn.safeParse(u.host_capabilities);if(!d.success||!Array.isArray(u.trusted_host_file_hashes)||u.trusted_host_file_hashes.length>512)return null;let p=new Map;for(let f of u.trusted_host_file_hashes){if(!X(f)||!ue(f,["path","hash"])||typeof f.path!="string"||!gn(f.path)||!at(f.path)||typeof f.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(f.hash)||p.has(f.path))return null;p.set(f.path,f.hash)}let m=0,l=[],h=new Set;for(let f of a.files){if(!X(f)||!ue(f,["path","hash","size_bytes"])||typeof f.path!="string"||!at(f.path)||typeof f.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(f.hash)||typeof f.size_bytes!="number"||!Number.isSafeInteger(f.size_bytes)||f.size_bytes<0||h.has(f.path)||(h.add(f.path),m+=f.size_bytes,m>pn))return null;l.push({path:f.path,hash:f.hash,size_bytes:f.size_bytes})}let S=new Map;for(let f of l){let I=await mn(e.projectRoot,f.path,f.size_bytes,f.hash);if(!I||`sha256:${ct("sha256").update(I).digest("hex")}`!==f.hash)return null;S.set(f.path,I)}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:S},host_capabilities:d.data,trusted_host_file_hashes:p}}catch{return null}}function gn(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 mn(e,t,n,s){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=ke.join(i,u);let a=await de.lstat(i);if(!a.isDirectory()||a.isSymbolicLink())return null}let r=ke.join(i,o.at(-1)),c=await de.open(r,ot.O_RDONLY|ot.O_NOFOLLOW);try{let u=await c.stat(),a=Q(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==a)return null;let d=[],p=0,m=c.createReadStream({autoClose:!1});for await(let h of m){let S=h;if(p+=S.byteLength,p>u.size)return m.destroy(),null;d.push(S)}if(p!==u.size)return null;let l=Buffer.concat(d,p);return p===n?l:ae({file:t,expectedSize:n,expectedDigest:s,actualSize:p,actualDigest:`sha256:${ct("sha256").update(l).digest("hex")}`})?Ze():null}finally{await c.close()}}function at(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!fn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function X(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ue(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Ce(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{createPublicKey as dt,verify as yn}from"node:crypto";import{PortableCmsSchemaEnvelopeSchema as Sn,PortableCmsSchemaStatementSchema as bn}from"@vcp-dev/contracts";var _n=3e4;function lt(e){try{let t=Sn.safeParse(e.proof);if(!t.success||!le(e.publicKey,256)||!le(e.snapshotPublicKey,256)||e.publicKey===e.snapshotPublicKey||!le(t.data.payload,262144)||!le(t.data.signature,86))return null;let n=dt({key:Buffer.from(e.publicKey,"base64url"),type:"spki",format:"der"}),s=dt({key:Buffer.from(e.snapshotPublicKey,"base64url"),type:"spki",format:"der"});if(n.asymmetricKeyType!=="ed25519"||s.asymmetricKeyType!=="ed25519"||s.export({type:"spki",format:"der"}).toString("base64url")!==e.snapshotPublicKey||n.export({type:"spki",format:"der"}).toString("base64url")!==e.publicKey)return null;let o=Buffer.from(t.data.payload,"base64url"),i=Buffer.from(t.data.signature,"base64url");if(i.byteLength!==64||!yn(null,o,n,i))return null;let r=new TextDecoder("utf-8",{fatal:!0}).decode(o),c=JSON.parse(r);if(JSON.stringify(c)!==r)return null;let u=bn.safeParse(c),a=e.now??Date.now();return!u.success||!Number.isSafeInteger(a)||u.data.site_id!==e.site_id||u.data.base_snapshot_id!==e.base_snapshot_id||u.data.issued_at>a+_n||u.data.expires_at<=a?null:{source_slug:u.data.slug,evidence_path:`trusted-cms-schema:${u.data.slug}`,fields:u.data.fields}}catch{return null}}function le(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 Bn,SiteEditPortableExportRequestSchema as Hn,SiteEditPortableExportResultSchema as Mn,SiteEditPortableAssetRequestSchema as Ln,SiteEditPortableAssetResultSchema as Kn,computeSiteEditCompositionKey as D}from"@vcp-dev/contracts";var Dn="127.0.0.1",jn=30218,Un="/__vcp/site-edit/bridge",St=6*1024*1024,$n=St*2,Fn=3e3,pt=50,Te=".vcp/current-snapshot.json",ht="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function bt(e,t,n={}){let s=new Pe(It(t),e,!1,n);return s.start({listen:!1}),s}var Pe=class{constructor(t,n=In.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 oe,this.operationReceipts=new Map,this.eventListeners=new Set,this.routes=[],this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.launchCandidateEntries=null,this.stopWatching=null,this.stopWebSocketServer=null,this.pendingChangedFiles=new Set,this.fileChangeTimer=null,this.isStarted=!1,this.stopping=!1,this.runtimeVersionFloors=new Map,this.activeHistoryStore=null,this.versionPersistence=Promise.resolve(),this.versionCheckpoints=new WeakMap,this.bridgeEngine=null,this.lastNotifiedHealth=null}start(t={}){if(!this.isStarted){this.stopping=!1;try{Y.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=He({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 Nn({projectRoot:this.options.projectRoot,watch_dirs:Wn(this.options.runtime.watch_dirs),interval_ms:this.options.runtime.watch_interval_ms,debounce_ms:this.options.runtime.watch_debounce_ms??pt,max_dirs:this.options.runtime.watch_max_dirs,max_files:this.options.runtime.watch_max_files,max_depth:this.options.runtime.watch_max_depth,max_startup_ms:this.options.runtime.watch_max_startup_ms,on_change:n=>this.handleFileChanged(n),on_batch_change:n=>this.handleFilesChanged(n)}).start(),t.listen!==!1&&this.server.listen(this.options.port,this.options.host),this.notifyHealthChanged()}}getEngine(){if(!this.bridgeEngine)throw new Error("VCP site edit preview bridge runtime is not ready");return this.bridgeEngine}getHealth(){let t=!!this.runtime&&!this.compositionResolutionError;return{ok:this.isStarted&&t,bridgePath:this.options.path,runtimeReady:t,routesIndexed:this.routes.length,sessionRequired:!!this.options.sessionKey}}stop(){this.stopping=!0,this.stopWatching?.(),this.stopWatching=null,this.flushChangedFiles(),this.fileChangeTimer&&(clearTimeout(this.fileChangeTimer),this.fileChangeTimer=null),this.stopWebSocketServer?.(),this.stopWebSocketServer=null,this.runtime?.dispose(),this.runtime=null,this.compositions=[],this.compositionFiles=[],this.compositionResolutionError=null,this.closeHttpServerOnStop&&this.server.close();let t=Jn(),n=Gn(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??Rn)({...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=qn(t.composition),o=this.getRuntime(),i=v(s);await o.initializeComposition(i);let c=o.getDocument(i).data;await this.recordRuntimeVersion(c.version,s);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:c,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=v(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(v(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,v(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,v(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(v(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:v(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:v(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return ft(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=lt({proof:s,publicKey:this.options.portableCmsSchemaPublicKey,snapshotPublicKey:this.options.portableSnapshotPublicKey,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,N)=>({complete:!1,unresolved:[{code:w,path:C,message:N}]}),i=Hn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,c=v(n);if(r.target.composition.routeId!==c.routeId||r.target.composition.templateId!==c.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(c);let a=()=>{let w=this.getRuntime().getDocument(c).data;return{site_id:w.siteId,snapshot_id:w.snapshotId,document_version:w.version}},d=a();if(d.site_id!==r.site_id||d.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(d.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let p=this.verifyCmsSchemaProofs(r);if(!p)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let m=this.dependencies.loadTrustedPortableSnapshot??(w=>ut({...w,projectRoot:this.options.projectRoot,publicKey:this.options.portableSnapshotPublicKey})),l;try{l=await m({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(!l)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let h=new Map([...l.snapshot.files].map(([w,C])=>[w,typeof C=="string"?C:new Uint8Array(C)])),S={...l,snapshot:{...l.snapshot,files:h}};if(!await ce(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:f,...I}=r,E=await Cn({...I,...S,trusted_cms_schemas:p,read_current_identity:a}),_=Mn.safeParse(E);if(!_.success)return o("PORTABLE_EXPORT_RESULT_INVALID","<selection>","The Engine export result did not satisfy its contract.");if(_.data.complete&&(_.data.site_id!==r.site_id||_.data.base_snapshot_id!==r.base_snapshot_id||_.data.document_version!==r.document_version||_.data.target.blockKey!==r.target.blockKey||_.data.target.composition.routeId!==c.routeId||_.data.target.composition.templateId!==c.templateId||_.data.selection_ref.key!==r.selection_ref.key||_.data.selection_ref.instanceIndex!==r.selection_ref.instanceIndex||_.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(_.data.complete||_.data.cms_candidates){if(!await ce(this.options.projectRoot,h))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let w=a();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.");_.data.complete&&s?.(h)}return _.data}async exportPortableBlockAsset(t,n){let s=d=>({complete:!1,unresolved:[{code:d,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Ln.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,c=await this.exportPortableBlock(i.request,n,d=>{r=d});if(!c.complete)return{complete:!1,unresolved:c.unresolved};if(c.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=kn({exported:c,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),a=Kn.safeParse(u);if(!a.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!a.data.complete)return a.data;if(!await ce(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let d=this.getRuntime().getDocument(v(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||d.siteId!==i.request.site_id||d.snapshotId!==i.request.base_snapshot_id||d.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?a.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 ft(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 Be("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[c,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(c)}},()=>{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??vn)(zn({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 c=D(r);this.runtimeVersionFloors.set(c,Math.max(this.runtimeVersionFloors.get(c)??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?D(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 c=r,u=this.versionPersistence.then(async()=>{try{for(;c.requestedVersion>c.durableVersion;){let a=c.requestedVersion;await o.writeDocumentVersion(a),c.durableVersion=Math.max(c.durableVersion,a)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{c.pending=null}});return c.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??pt;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(xt)?this.scheduleSnapshotIdentityAdvance():!1,s=t.filter(o=>!ss(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=Y.readFileSync(O.join(this.options.projectRoot,Te),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Ae(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(c){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${c instanceof Error?c.message:String(c)}`)}}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=Vn(this.options.projectRoot),s=On(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(a=>({...a})),i=Pn({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(a=>a.context.effectiveTemplateId!==void 0).map(a=>a.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 c=new Map(this.compositions.map(a=>[D(a.context),a])),u=new Map(i.map(a=>[D(a.context),a]));if(this.runtime){for(let[a,d]of c){let p=u.get(a);(!p||p.entryFile!==d.entryFile)&&this.runtime.unregisterComposition(v(d.context))}for(let[a,d]of u){let p=c.get(a);(!p||p.entryFile!==d.entryFile)&&this.runtime.registerComposition(d.context,d.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=An(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=Tn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=D(o.context);if(!this.compositions.some(r=>D(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(D(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 _t(e){return It(e)}function It(e){return{tenantId:e.tenantId,siteId:e.siteId,snapshotId:e.snapshotId,projectRoot:O.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Dn,port:e.port??jn,path:e.path??Un,sessionKey:e.sessionKey??ns(),portableSnapshotPublicKey:e.portableSnapshotPublicKey,portableCmsSchemaPublicKey:e.portableCmsSchemaPublicKey,historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Wn(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 Vn(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!Y.existsSync(i))return;let r;try{r=Y.readdirSync(i,{withFileTypes:!0})}catch{return}for(let c of r){if(c.name.startsWith(".")&&c.name!==".vcp")continue;if(c.isDirectory()){if(s.has(c.name))continue;o(O.join(i,c.name));continue}if(!c.isFile())continue;let u=O.join(i,c.name),a="";try{a=Y.readFileSync(u,"utf8")}catch{}t.push({path:O.relative(e,u).replaceAll(O.sep,"/"),content:a})}};for(let i of n)o(O.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function qn(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 v(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function zn(e){return O.join(O.resolve(e.root),Ae(e.siteId),Ae(e.snapshotId),Be("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Ae(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Be("sha256").update(e).digest("hex").slice(0,32)}function Jn(){let e=globalThis;return e[ht]??=new Map,e[ht]}function Gn(e){return`${e.projectRoot}:${e.host}:${e.port}:${e.path}:${e.historyRoot??""}`}function ft(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 He(e){let t=new xn({maxPayload:St,noServer:!0}),n=new WeakSet,s=i=>{new ie({socket:new Oe(i),engine:e.engine,validateOperationRequest:r=>Bn.safeParse(r).success})},o=(i,r,c)=>{if(!Qn(i,e))return;let u=Xn(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,c,a=>{t.emit("connection",a,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}$n(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 Pe=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===ft.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>Bn){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Wn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Fn(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=Ce(e.headers["x-vcp-site-edit-key"]),o=bt(s,t.sessionKey),i=Ce(e.headers.host),r=Ce(e.headers.origin);return i&&!Vn(i,t.host,r)?null:r?zn(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function $n(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Hn),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let d=C.parseMessage(c.toString());if(d.type!=="auth"||!bt(d.payload.key,t)){r();return}i(),e.readyState===ft.OPEN&&e.send(C.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function bt(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&gn(n,s)}function Vn(e,t,n){let s=ht(e),o=ht(t);return s===o||lt(o)&&lt(s)&&(!n||Oe(n,e))||qn(o)&&(!n||Oe(n,e))}function qn(e){return e==="0.0.0.0"||e==="::"}function lt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function zn(e,t,n){return n.includes(e)||(t?Oe(e,t):!1)}function Oe(e,t){try{return new URL(e).host===_t(t)}catch{return!1}}function ht(e){let t=_t(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function _t(e){return e.trim().toLowerCase()}function Ce(e){return Array.isArray(e)?e[0]:e}function Jn(){return fn(32).toString("base64url")}function It(e){let t=e.replaceAll("\\","/");return t===ve||t.endsWith(`/${ve}`)}function Gn(e){let t=e.replaceAll("\\","/");return It(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var Zn="SITE_EDIT_ENGINE_UNAVAILABLE",es=5e3,ts=1024,ns="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",ss=3,is=10*6e4,os=1012;function He(e,t,n={}){let s=yt(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,c={options:r},d=n.maxHeapMb??as(process.env[ns])??ts,a=n.maxRestarts??ss,u=n.restartWindowMs??is,h="starting",m,p=0,f=[],b=null,l=0,y=new Map,I=new Set,k,T,O=new Promise((g,S)=>{k=g,T=S});O.catch(()=>{});let L=g=>{let S=new Error(`VCP site edit preview bridge runtime is not ready: ${g}`);return S.code=Zn,S},N=g=>{for(let S of y.values())S.reject(g);y.clear()},te=g=>{switch(g.type){case"ready":b=g.health,h==="starting"?(h="ready",k()):h==="restarting"&&(h="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":h==="starting"&&D(ge(g.error));return;case"result":{let S=y.get(g.id);if(!S)return;y.delete(g.id),g.ok?S.resolve(g.value):S.reject(ge(g.error));return}case"event":for(let S of I)try{S(g.event)}catch(E){console.warn(`[vcp-site-edit] engine event listener failed: ${E instanceof Error?E.message:String(E)}`)}return;case"health":b=g.health;return;case"snapshot-id-changed":c.options.snapshotId=g.next;try{o?.(g.next,g.previous)}catch(S){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${S instanceof Error?S.message:String(S)}`)}return}},A=()=>{let g=p+=1,S=n.workerUrl??new URL("./engine-worker.js",import.meta.url),E=new Yn(rs(S),{workerData:c,resourceLimits:{maxOldGenerationSizeMb:d},...n.execArgv?{execArgv:n.execArgv}:{}});E.unref();let B=()=>g===p;E.on("message",P=>{B()&&te(P)}),E.on("error",P=>{B()&&D(P instanceof Error?P:new Error(String(P)))}),E.on("exit",P=>{B()&&D(new Error(`engine worker exited with code ${P}`))}),m=E,n.onWorker?.(E)},D=g=>{if(h==="stopped"||h==="failed")return;if(N(L(g.message)),b=null,h==="starting"){h="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${g.message}`),T(g);return}let S=Date.now();for(;f.length>0&&S-f[0]>u;)f.shift();if(f.length>=a){h="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${a} restarts: ${g.message}`);return}f.push(S),h="restarting";for(let E of j.clients)E.close(os,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${f.length}/${a}): ${g.message}`),A()},W=(g,S)=>{if(h==="failed"||h==="stopped"||h==="restarting")return Promise.reject(L(h));let E=l+=1;return new Promise((B,P)=>{y.set(E,{resolve:B,reject:P});let Nt={type:"call",id:E,method:g,args:S};m.postMessage(Nt)})},J=Object.fromEntries(Ue.map(g=>[g,(...S)=>W(g,S)])),j=Be({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...J,subscribe(g){return I.add(g),()=>I.delete(g)}}});return A(),{getHealth(){return h==="ready"&&b?b:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:b?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(h==="stopped")return;let g=h==="starting";h="stopped",j.stop(),g&&T(L("bridge stopped")),N(L("bridge stopped")),I.clear();let S=m,E={type:"stop"};S.postMessage(E);let B=setTimeout(()=>{S.terminate()},es);B.unref(),S.once("exit",()=>clearTimeout(B))},whenReady(){return O},eventListeners:I}}function rs(e){if(!e.pathname.endsWith(".ts"))return e;let t=Xn(Qn(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 ds="next",us="VCP_SITE_EDIT_ENGINE_IN_PROCESS",vt="127.0.0.1",ps=3e3,he="/__vcp/site-edit/bridge",Tt="/__vcp/site-edit/health",ls="probe",hs="render",wt="/_error",fe="/__vcp/site-edit/client/",fs=`${fe}auto-bootstrap.js`,At='data-vcp-site-edit-bootstrap="true"',gs=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],ms="@vcp-dev/site-edit-engine/webpack-loader",ys=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Ss=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],bs=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-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function Zi(e={},t={}){let n=t.process??process,s=t.createServer??je.createServer,o=t.attachBridgeServer??(n.env[us]==="1"?mt:He),i=t.loadNext??Qs,r=Y.resolve(e.projectRoot??process.cwd()),c=e.host??vt,d=e.port??ei(n.env.PORT)??ps,a=e.bridgePath??he,u=ks(a),h=Vs(),m=e.portableSnapshotPublicKey??n.env.VCP_PORTABLE_SNAPSHOT_PUBLIC_KEY,p=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",f=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,b=await i(r),l=_s(r),y=b({dev:!0,dir:r,hostname:c,port:d,...Is(l)}),I=y.getRequestHandler(),k=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",T=e.snapshotId??n.env.VCP_SNAPSHOT_ID??Zs(r),O=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,L=O?.trim()?Y.resolve(O):void 0,N=null,te={launchId:cs(),pid:process.pid,snapshotId:T},A=s((g,S)=>{Ns({basePath:p,bridgePath:a,bridgeHealthPath:u,bridgeSessionKey:h,getBridgeHealth:()=>N?.getHealth()??js(a),launch:te,runRenderProbe:()=>Ms(y),handle:I,request:g,response:S}).catch(E=>{console.error(E),S.headersSent||(S.statusCode=500),S.end("site edit preview request failed")})}),D=null,W=null,J=()=>W||(le(()=>n.off("SIGINT",j)),le(()=>n.off("SIGTERM",j)),le(()=>D?.()),D=null,le(()=>N?.stop()),N=null,W=Promise.allSettled([ni(A),si(()=>y.close())]).then(()=>{}),W),j=()=>{J()};try{return await y.prepare(),N=o(A,{...f?{tenantId:f}:{},siteId:k,snapshotId:T,projectRoot:r,basePath:p,host:c,port:d,path:a,sessionKey:h,...m?{portableSnapshotPublicKey:m}:{},...L?{historyRoot:L}:{},onSnapshotIdChanged:g=>{te.snapshotId=g}}),D=xs({server:A,bridgePath:a,handleUpgrade:y.getUpgradeHandler()}),n.on("SIGINT",j),n.on("SIGTERM",j),await N.whenReady?.(),await ti(A,d,c),{bundler:l,close:J,host:c,port:ii(A,d),server:A}}catch(g){throw await J(),g}}function _s(e){let t=Es(e);return t&&ws(t)?"webpack":"turbopack"}function Is(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Es(e){for(let t of gs){let n=ee(e,t);if(z(n))return q(n,"utf8")}return null}function ws(e){return e.includes(ms)?!0:ys.test(e)&&Ss.some(t=>t.test(e))}function xs(e){let t=(n,s,o)=>{Rs(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 Rs(e,t){return new URL(e??"/","http://localhost").pathname===t}function ks(e=he){if(e===he)return Tt;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Cs(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??vs()});return`<script type="module" ${At}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(fs)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function vs(){return{bridge:Me("@vcp-dev/site-edit-bridge"),contracts:Me("@vcp-dev/contracts"),engine:Me("@vcp-dev/site-edit-engine")}}function Me(e){let t=Rt(import.meta.url);try{let n=t.resolve(e),s=Ts(n,e);if(!s)return;let o=JSON.parse(q(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Ts(e,t){let n=Y.parse(e).root,s=Z(e);for(;s&&s!==n;){let o=ee(s,"package.json");if(z(o))try{if(JSON.parse(q(o,"utf8")).name===t)return o}catch{return}s=Z(s)}}function As(e,t){if(e.includes(At))return e;let n=Cs(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function eo(e,t=Z(Ct(import.meta.url)),n=z){return Pt(e,t,n)?.path??null}function Pt(e,t=Z(Ct(import.meta.url)),n=z){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(fe))return null;let o=s.slice(fe.length);if(!bs.has(o))return null;let i=Ke(Xs(t),o);if(kt(t)!=="src")return{path:i,requiresTranspile:!1};let r=Ke(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Ps(e,t){let n=Pt(e.url);if(!n)return!1;if(!z(n.path))return t.writeHead(404),t.end("site edit client asset not found"),!0;let s=n.requiresTranspile?await Os(q(n.path,"utf8")):q(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function Os(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Ns({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:c,request:d,response:a}){if(Bs(d.url,e)){a.statusCode=404,a.end();return}if(await Ds(d,a,n,o,i,r)||await Ps(d,a))return;let u=Ks(d),h=Us(d),m=u||h?$s(a,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:h,launch:{...i}}):()=>{};try{await c(d,a)}catch(p){throw m(),p}}function Bs(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 Hs(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 Ms(e){let t=new je.IncomingMessage(new Et);t.method="GET",t.url=wt,t.headers={host:vt};let n=new je.ServerResponse(t);n.assignSocket(new Et);try{return await e.renderToHTML(t,n,wt,{}),{verdict:"ok"}}catch(s){return Hs(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Ls(e){return new URL(e??"/","http://localhost").searchParams.get(ls)===hs}async function Ds(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let c=s(),d=Ls(e.url)?await i():void 0,a={...c,launch:o,...d?{render:d}:{}};return t.writeHead(c.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(a)),!0}function js(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ks(e){return Ws(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Us(e){return Fs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Ws(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(fe)||n===he||n===Tt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function Fs(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 $s(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),c=!1;s.flushHeaders=()=>{};let d=()=>{if(t.patchNextDevChunk||c)return!1;let a=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(a.toString("utf8")))return!1;let u=xt(e,a,t);return u!==a&&!e.headersSent&&e.removeHeader("content-length"),i(u),n.length=0,c=!0,!0};return s.write=(a,u,h)=>c?(a!==void 0&&i(Le(a,De(u))),pe(u),pe(h),!0):(a!==void 0&&(n.push(Le(a,De(u))),d()),pe(u),pe(h),!0),s.end=(a,u,h)=>{let m=typeof a=="function"?void 0:a;if(c)return s.write=i,s.end=r,s.flushHeaders=o,m===void 0?typeof a=="function"?r(a):typeof u=="function"?r(u):typeof h=="function"?r(h):r():typeof u=="function"?r(m,u):typeof h=="function"?r(m,u,h):r(m,u);m!==void 0&&n.push(Le(m,De(u))),s.write=i,s.end=r,s.flushHeaders=o;let p=Buffer.concat(n),f=xt(e,p,t);f!==p&&!e.headersSent&&e.removeHeader("content-length");let b=typeof a=="function"?a:typeof u=="function"?u:typeof h=="function"?h:void 0;return b?r(f,b):r(f)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function xt(e,t,n){if(qs(e,t))return Buffer.from(As(t.toString("utf8"),n));if(n.patchNextDevChunk&&zs(e)){let s=t.toString("utf8"),o=Js(s);if(o!==s)return Buffer.from(o)}return t}function Vs(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function qs(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 zs(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 Js(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,c,a=>{t.emit("connection",a,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}Yn(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 Oe=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===yt.OPEN){if(this.socket.bufferedAmount+Buffer.byteLength(t,"utf8")>$n){this.socket.close(1013,"bridge backpressure");return}this.socket.send(t)}}close(t,n){this.socket.close(t,n)}};function Qn(e,t){return new URL(e.url??"/","http://localhost").pathname===t.path}function Xn(e,t){if(new URL(e.url??"/","http://localhost").searchParams.has("vcp_bridge_key"))return null;let s=ve(e.headers["x-vcp-site-edit-key"]),o=Et(s,t.sessionKey),i=ve(e.headers.host),r=ve(e.headers.origin);return i&&!Zn(i,t.host,r)?null:r?ts(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Yn(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},Fn),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=c=>{try{let u=A.parseMessage(c.toString());if(u.type!=="auth"||!Et(u.payload.key,t)){r();return}i(),e.readyState===yt.OPEN&&e.send(A.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function Et(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&wn(n,s)}function Zn(e,t,n){let s=mt(e),o=mt(t);return s===o||gt(o)&&gt(s)&&(!n||Ne(n,e))||es(o)&&(!n||Ne(n,e))}function es(e){return e==="0.0.0.0"||e==="::"}function gt(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ts(e,t,n){return n.includes(e)||(t?Ne(e,t):!1)}function Ne(e,t){try{return new URL(e).host===wt(t)}catch{return!1}}function mt(e){let t=wt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function wt(e){return e.trim().toLowerCase()}function ve(e){return Array.isArray(e)?e[0]:e}function ns(){return En(32).toString("base64url")}function xt(e){let t=e.replaceAll("\\","/");return t===Te||t.endsWith(`/${Te}`)}function ss(e){let t=e.replaceAll("\\","/");return xt(e)||t===".vcp/workspace-state.json"||t===".vcp/portable-snapshot-proof.json"||t.startsWith(".vcp/snapshot-store/")}var as="SITE_EDIT_ENGINE_UNAVAILABLE",cs=5e3,us=1024,ds="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",ls=3,ps=10*6e4,hs=1012;function Me(e,t,n={}){let s=_t(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,c={options:r},u=n.maxHeapMb??gs(process.env[ds])??us,a=n.maxRestarts??ls,d=n.restartWindowMs??ps,p="starting",m,l=0,h=[],S=null,f=0,I=new Map,E=new Set,_,w,C=new Promise((g,y)=>{_=g,w=y});C.catch(()=>{});let N=g=>{let y=new Error(`VCP site edit preview bridge runtime is not ready: ${g}`);return y.code=as,y},z=g=>{for(let y of I.values())y.reject(g);I.clear()},L=g=>{switch(g.type){case"ready":S=g.health,p==="starting"?(p="ready",_()):p==="restarting"&&(p="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":p==="starting"&&T(me(g.error));return;case"result":{let y=I.get(g.id);if(!y)return;I.delete(g.id),g.ok?y.resolve(g.value):y.reject(me(g.error));return}case"event":for(let y of E)try{y(g.event)}catch(x){console.warn(`[vcp-site-edit] engine event listener failed: ${x instanceof Error?x.message:String(x)}`)}return;case"health":S=g.health;return;case"snapshot-id-changed":c.options.snapshotId=g.next;try{o?.(g.next,g.previous)}catch(y){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${y instanceof Error?y.message:String(y)}`)}return}},J=()=>{let g=l+=1,y=n.workerUrl??new URL("./engine-worker.js",import.meta.url),x=new rs(fs(y),{workerData:c,resourceLimits:{maxOldGenerationSizeMb:u},...n.execArgv?{execArgv:n.execArgv}:{}});x.unref();let P=()=>g===l;x.on("message",B=>{P()&&L(B)}),x.on("error",B=>{P()&&T(B instanceof Error?B:new Error(String(B)))}),x.on("exit",B=>{P()&&T(new Error(`engine worker exited with code ${B}`))}),m=x,n.onWorker?.(x)},T=g=>{if(p==="stopped"||p==="failed")return;if(z(N(g.message)),S=null,p==="starting"){p="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${g.message}`),w(g);return}let y=Date.now();for(;h.length>0&&y-h[0]>d;)h.shift();if(h.length>=a){p="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${a} restarts: ${g.message}`);return}h.push(y),p="restarting";for(let x of U.clients)x.close(hs,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${h.length}/${a}): ${g.message}`),J()},G=(g,y)=>{if(p==="failed"||p==="stopped"||p==="restarting")return Promise.reject(N(p));let x=f+=1;return new Promise((P,B)=>{I.set(x,{resolve:P,reject:B});let Mt={type:"call",id:x,method:g,args:y};m.postMessage(Mt)})},j=Object.fromEntries($e.map(g=>[g,(...y)=>G(g,y)])),U=He({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...j,subscribe(g){return E.add(g),()=>E.delete(g)}}});return J(),{getHealth(){return p==="ready"&&S?S:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:S?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(p==="stopped")return;let g=p==="starting";p="stopped",U.stop(),g&&w(N("bridge stopped")),z(N("bridge stopped")),E.clear();let y=m,x={type:"stop"};y.postMessage(x);let P=setTimeout(()=>{y.terminate()},cs);P.unref(),y.once("exit",()=>clearTimeout(P))},whenReady(){return C},eventListeners:E}}function fs(e){if(!e.pathname.endsWith(".ts"))return e;let t=os(is(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 gs(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var ys="next",Ss="VCP_SITE_EDIT_ENGINE_IN_PROCESS",At="127.0.0.1",bs=3e3,fe="/__vcp/site-edit/bridge",Ot="/__vcp/site-edit/health",_s="probe",Is="render",Ct="/_error",ge="/__vcp/site-edit/client/",Es=`${ge}auto-bootstrap.js`,Nt='data-vcp-site-edit-bootstrap="true"',ws=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],xs="@vcp-dev/site-edit-engine/webpack-loader",Rs=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Cs=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ks=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-text-commit-preview.js","property-preview.js","protocol.js","window-message.js"]);async function po(e={},t={}){let n=t.process??process,s=t.createServer??je.createServer,o=t.attachBridgeServer??(n.env[Ss]==="1"?bt:Me),i=t.loadNext??ii,r=Z.resolve(e.projectRoot??process.cwd()),c=e.host??At,u=e.port??ci(n.env.PORT)??bs,a=e.bridgePath??fe,d=Bs(a),p=Zs(),m=e.portableSnapshotPublicKey??n.env.VCP_PORTABLE_SNAPSHOT_PUBLIC_KEY,l=e.portableCmsSchemaPublicKey??n.env.VCP_PORTABLE_CMS_SCHEMA_PUBLIC_KEY,h=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",S=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,f=await i(r),I=vs(r),E=f({dev:!0,dir:r,hostname:c,port:u,...Ts(I)}),_=E.getRequestHandler(),w=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",C=e.snapshotId??n.env.VCP_SNAPSHOT_ID??ai(r),N=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,z=N?.trim()?Z.resolve(N):void 0,L=null,J={launchId:ms(),pid:process.pid,snapshotId:C},T=s((y,x)=>{Us({basePath:h,bridgePath:a,bridgeHealthPath:d,bridgeSessionKey:p,getBridgeHealth:()=>L?.getHealth()??zs(a),launch:J,runRenderProbe:()=>Ws(E),handle:_,request:y,response:x}).catch(P=>{console.error(P),x.headersSent||(x.statusCode=500),x.end("site edit preview request failed")})}),G=null,j=null,U=()=>j||(he(()=>n.off("SIGINT",g)),he(()=>n.off("SIGTERM",g)),he(()=>G?.()),G=null,he(()=>L?.stop()),L=null,j=Promise.allSettled([di(T),li(()=>E.close())]).then(()=>{}),j),g=()=>{U()};try{return await E.prepare(),L=o(T,{...S?{tenantId:S}:{},siteId:w,snapshotId:C,projectRoot:r,basePath:h,host:c,port:u,path:a,sessionKey:p,...m?{portableSnapshotPublicKey:m}:{},...l?{portableCmsSchemaPublicKey:l}:{},...z?{historyRoot:z}:{},onSnapshotIdChanged:y=>{J.snapshotId=y}}),G=Os({server:T,bridgePath:a,handleUpgrade:E.getUpgradeHandler()}),n.on("SIGINT",g),n.on("SIGTERM",g),await L.whenReady?.(),await ui(T,u,c),{bundler:I,close:U,host:c,port:pi(T,u),server:T}}catch(y){throw await U(),y}}function vs(e){let t=Ps(e);return t&&As(t)?"webpack":"turbopack"}function Ts(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Ps(e){for(let t of ws){let n=te(e,t);if(q(n))return V(n,"utf8")}return null}function As(e){return e.includes(xs)?!0:Rs.test(e)&&Cs.some(t=>t.test(e))}function Os(e){let t=(n,s,o)=>{Ns(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 Ns(e,t){return new URL(e??"/","http://localhost").pathname===t}function Bs(e=fe){if(e===fe)return Ot;let t=(e.startsWith("/")?e:`/${e}`).replace(/\/+$/,"");return t.endsWith("/bridge")?`${t.slice(0,-7)}/health`:t?`${t}/health`:"/health"}function Hs(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??Ms()});return`<script type="module" ${Nt}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Es)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Ms(){return{bridge:Le("@vcp-dev/site-edit-bridge"),contracts:Le("@vcp-dev/contracts"),engine:Le("@vcp-dev/site-edit-engine")}}function Le(e){let t=vt(import.meta.url);try{let n=t.resolve(e),s=Ls(n,e);if(!s)return;let o=JSON.parse(V(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Ls(e,t){let n=Z.parse(e).root,s=ee(e);for(;s&&s!==n;){let o=te(s,"package.json");if(q(o))try{if(JSON.parse(V(o,"utf8")).name===t)return o}catch{return}s=ee(s)}}function Ks(e,t){if(e.includes(Nt))return e;let n=Hs(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function ho(e,t=ee(Pt(import.meta.url)),n=q){return Bt(e,t,n)?.path??null}function Bt(e,t=ee(Pt(import.meta.url)),n=q){let s=new URL(e??"/","http://localhost").pathname;if(!s.startsWith(ge))return null;let o=s.slice(ge.length);if(!ks.has(o))return null;let i=Ue(oi(t),o);if(Tt(t)!=="src")return{path:i,requiresTranspile:!1};let r=Ue(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Ds(e,t){let n=Bt(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 js(V(n.path,"utf8")):V(n.path);return t.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript; charset=utf-8"}),t.end(s),!0}async function js(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Us({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:c,request:u,response:a}){if($s(u.url,e)){a.statusCode=404,a.end();return}if(await qs(u,a,n,o,i,r)||await Ds(u,a))return;let d=Js(u),p=Gs(u),m=d||p?Ys(a,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:p,launch:{...i}}):()=>{};try{await c(u,a)}catch(l){throw m(),l}}function $s(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 Fs(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 Ws(e){let t=new je.IncomingMessage(new Rt);t.method="GET",t.url=Ct,t.headers={host:At};let n=new je.ServerResponse(t);n.assignSocket(new Rt);try{return await e.renderToHTML(t,n,Ct,{}),{verdict:"ok"}}catch(s){return Fs(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Vs(e){return new URL(e??"/","http://localhost").searchParams.get(_s)===Is}async function qs(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let c=s(),u=Vs(e.url)?await i():void 0,a={...c,launch:o,...u?{render:u}:{}};return t.writeHead(c.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(a)),!0}function zs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Js(e){return Qs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Gs(e){return Xs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Qs(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(ge)||n===fe||n===Ot)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function Xs(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 Ys(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),c=!1;s.flushHeaders=()=>{};let u=()=>{if(t.patchNextDevChunk||c)return!1;let a=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(a.toString("utf8")))return!1;let d=kt(e,a,t);return d!==a&&!e.headersSent&&e.removeHeader("content-length"),i(d),n.length=0,c=!0,!0};return s.write=(a,d,p)=>c?(a!==void 0&&i(Ke(a,De(d))),pe(d),pe(p),!0):(a!==void 0&&(n.push(Ke(a,De(d))),u()),pe(d),pe(p),!0),s.end=(a,d,p)=>{let m=typeof a=="function"?void 0:a;if(c)return s.write=i,s.end=r,s.flushHeaders=o,m===void 0?typeof a=="function"?r(a):typeof d=="function"?r(d):typeof p=="function"?r(p):r():typeof d=="function"?r(m,d):typeof p=="function"?r(m,d,p):r(m,d);m!==void 0&&n.push(Ke(m,De(d))),s.write=i,s.end=r,s.flushHeaders=o;let l=Buffer.concat(n),h=kt(e,l,t);h!==l&&!e.headersSent&&e.removeHeader("content-length");let S=typeof a=="function"?a:typeof d=="function"?d:typeof p=="function"?p:void 0;return S?r(h,S):r(h)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function kt(e,t,n){if(ei(e,t))return Buffer.from(Ks(t.toString("utf8"),n));if(n.patchNextDevChunk&&ti(e)){let s=t.toString("utf8"),o=ni(s);if(o!==s)return Buffer.from(o)}return t}function Zs(){let e=new Uint8Array(32);return globalThis.crypto.getRandomValues(e),Buffer.from(e).toString("base64url")}function ei(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 ti(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 ni(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])=>Gs(n,s,o),e)}function Gs(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 Le(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function De(e){return typeof e=="string"?e:void 0}function pe(e){typeof e=="function"&&e()}async function Qs(e){let n=Rt(ee(e,"package.json"))(ds);return n.default??n}function Xs(e){return kt(e)!=="src"?e:Ke(Ys(e),"dist")}function Ys(e){return Ot(e)?Y.posix.dirname(e):Z(e)}function Ke(e,t){return Ot(e)?Y.posix.join(e,t):ee(e,t)}function Ot(e){return e.includes("/")&&!e.includes("\\")}function Zs(e){let t=ee(e,".vcp/current-snapshot.json");if(!z(t))return"sandbox_worktree";try{let n=JSON.parse(q(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 ei(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function ti(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function ni(e){return new Promise(t=>{e.close(()=>t())})}function le(e){try{e()}catch{}}function si(e){try{return e()}catch(t){return Promise.reject(t)}}function ii(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{xs as attachNextDevUpgradeHandler,He as attachSiteEditBridgeServerInWorker,Hs as classifySiteEditRenderProbeError,Cs as createSiteEditAutoBootstrapHtmlSnippet,As as injectSiteEditAutoBootstrap,Ls as isSiteEditRenderProbeRequested,Js as patchNextFirefoxDevChunk,Us as prepareFirefoxNextDevChunkPatchRequest,Ks as prepareSiteEditHtmlInjectionRequest,ks as resolveSiteEditBridgeHealthPath,Pt as resolveSiteEditClientAsset,eo as resolveSiteEditClientAssetPath,_s as resolveSiteEditNextDevBundler,Ms as runSiteEditRenderProbe,Zi as startSiteEditNextDevServer,Os 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])=>si(n,s,o),e)}function si(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 Ke(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),t)}function De(e){return typeof e=="string"?e:void 0}function pe(e){typeof e=="function"&&e()}async function ii(e){let n=vt(te(e,"package.json"))(ys);return n.default??n}function oi(e){return Tt(e)!=="src"?e:Ue(ri(e),"dist")}function ri(e){return Ht(e)?Z.posix.dirname(e):ee(e)}function Ue(e,t){return Ht(e)?Z.posix.join(e,t):te(e,t)}function Ht(e){return e.includes("/")&&!e.includes("\\")}function ai(e){let t=te(e,".vcp/current-snapshot.json");if(!q(t))return"sandbox_worktree";try{let n=JSON.parse(V(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 ci(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function ui(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function di(e){return new Promise(t=>{e.close(()=>t())})}function he(e){try{e()}catch{}}function li(e){try{return e()}catch(t){return Promise.reject(t)}}function pi(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{Os as attachNextDevUpgradeHandler,Me as attachSiteEditBridgeServerInWorker,Fs as classifySiteEditRenderProbeError,Hs as createSiteEditAutoBootstrapHtmlSnippet,Ks as injectSiteEditAutoBootstrap,Vs as isSiteEditRenderProbeRequested,ni as patchNextFirefoxDevChunk,Gs as prepareFirefoxNextDevChunkPatchRequest,Js as prepareSiteEditHtmlInjectionRequest,Bs as resolveSiteEditBridgeHealthPath,Bt as resolveSiteEditClientAsset,ho as resolveSiteEditClientAssetPath,vs as resolveSiteEditNextDevBundler,Ws as runSiteEditRenderProbe,po as startSiteEditNextDevServer,js as transpileSiteEditClientSource};
@@ -0,0 +1,69 @@
1
+ import { createPublicKey, verify } from "node:crypto";
2
+ import { PortableCmsSchemaEnvelopeSchema, PortableCmsSchemaStatementSchema, } from "@vcp-dev/contracts";
3
+ const MAX_CLOCK_SKEW_MS = 30_000;
4
+ /** The verifier key is captured at trusted preview startup, not supplied by a
5
+ * browser or a writable Snapshot. A valid statement proves only CMS data
6
+ * provenance; Engine must independently prove the selected source and calls. */
7
+ export function verifyPortableCmsSchemaProof(input) {
8
+ try {
9
+ const envelope = PortableCmsSchemaEnvelopeSchema.safeParse(input.proof);
10
+ if (!envelope.success ||
11
+ !isBase64Url(input.publicKey, 256) ||
12
+ !isBase64Url(input.snapshotPublicKey, 256) ||
13
+ input.publicKey === input.snapshotPublicKey)
14
+ return null;
15
+ if (!isBase64Url(envelope.data.payload, 262_144) ||
16
+ !isBase64Url(envelope.data.signature, 86))
17
+ return null;
18
+ const key = createPublicKey({
19
+ key: Buffer.from(input.publicKey, "base64url"),
20
+ type: "spki",
21
+ format: "der",
22
+ });
23
+ const snapshotKey = createPublicKey({
24
+ key: Buffer.from(input.snapshotPublicKey, "base64url"),
25
+ type: "spki",
26
+ format: "der",
27
+ });
28
+ if (key.asymmetricKeyType !== "ed25519" ||
29
+ snapshotKey.asymmetricKeyType !== "ed25519" ||
30
+ snapshotKey
31
+ .export({ type: "spki", format: "der" })
32
+ .toString("base64url") !== input.snapshotPublicKey ||
33
+ key.export({ type: "spki", format: "der" }).toString("base64url") !==
34
+ input.publicKey)
35
+ return null;
36
+ const bytes = Buffer.from(envelope.data.payload, "base64url");
37
+ const signature = Buffer.from(envelope.data.signature, "base64url");
38
+ if (signature.byteLength !== 64 || !verify(null, bytes, key, signature))
39
+ return null;
40
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
41
+ const raw = JSON.parse(text);
42
+ if (JSON.stringify(raw) !== text)
43
+ return null;
44
+ const statement = PortableCmsSchemaStatementSchema.safeParse(raw);
45
+ const now = input.now ?? Date.now();
46
+ if (!statement.success ||
47
+ !Number.isSafeInteger(now) ||
48
+ statement.data.site_id !== input.site_id ||
49
+ statement.data.base_snapshot_id !== input.base_snapshot_id ||
50
+ statement.data.issued_at > now + MAX_CLOCK_SKEW_MS ||
51
+ statement.data.expires_at <= now)
52
+ return null;
53
+ return {
54
+ source_slug: statement.data.slug,
55
+ evidence_path: `trusted-cms-schema:${statement.data.slug}`,
56
+ fields: statement.data.fields,
57
+ };
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ function isBase64Url(value, maxLength) {
64
+ return (typeof value === "string" &&
65
+ value.length > 0 &&
66
+ value.length <= maxLength &&
67
+ /^[A-Za-z0-9_-]+$/u.test(value) &&
68
+ Buffer.from(value, "base64url").toString("base64url") === value);
69
+ }
package/dist/protocol.js CHANGED
@@ -539,6 +539,7 @@ function isPortableExportPayload(payload) {
539
539
  "document_version",
540
540
  "target",
541
541
  "selection_ref",
542
+ "cms_schema_proofs",
542
543
  ].includes(key)) ||
543
544
  typeof request.site_id !== "string" ||
544
545
  typeof request.base_snapshot_id !== "string" ||
@@ -557,10 +558,48 @@ function isPortableExportPayload(payload) {
557
558
  request.target.composition.routeId !== payload.composition.routeId ||
558
559
  request.target.composition.templateId !== payload.composition.templateId ||
559
560
  request.selection_ref === undefined ||
560
- !isSelectionRefLike(request.selection_ref))
561
+ !isSelectionRefLike(request.selection_ref) ||
562
+ (request.cms_schema_proofs !== undefined &&
563
+ !isPortableCmsSchemaEnvelopes(request.cms_schema_proofs)))
561
564
  return false;
562
565
  return true;
563
566
  }
567
+ // Protocol is served as browser JS, so keep its transport budget in sync with
568
+ // the shared Zod envelope. Signature and authority are verified server-side.
569
+ function isPortableCmsSchemaEnvelopes(value) {
570
+ if (!Array.isArray(value) || value.length > 16)
571
+ return false;
572
+ if (!Reflect.ownKeys(value).every((key) => key === "length" ||
573
+ (typeof key === "string" &&
574
+ /^(0|[1-9][0-9]*)$/u.test(key) &&
575
+ Number(key) < value.length)))
576
+ return false;
577
+ for (let index = 0; index < value.length; index++) {
578
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
579
+ if (!descriptor || !("value" in descriptor))
580
+ return false;
581
+ const proof = descriptor.value;
582
+ if (!isRecord(proof) ||
583
+ !Reflect.ownKeys(proof).every((key) => typeof key === "string" && ["payload", "signature"].includes(key)))
584
+ return false;
585
+ const payload = Object.getOwnPropertyDescriptor(proof, "payload");
586
+ const signature = Object.getOwnPropertyDescriptor(proof, "signature");
587
+ if (!payload ||
588
+ !("value" in payload) ||
589
+ !signature ||
590
+ !("value" in signature))
591
+ return false;
592
+ if (typeof payload.value !== "string" ||
593
+ payload.value.length < 1 ||
594
+ payload.value.length > 262_144 ||
595
+ !/^[A-Za-z0-9_-]+$/u.test(payload.value))
596
+ return false;
597
+ if (typeof signature.value !== "string" ||
598
+ !/^[A-Za-z0-9_-]{86}$/u.test(signature.value))
599
+ return false;
600
+ }
601
+ return true;
602
+ }
564
603
  function isPortableAssetPayload(payload) {
565
604
  if (!Object.keys(payload).every((key) => ["id", "kind", "composition", "request"].includes(key)) ||
566
605
  !isRecord(payload.request))
package/dist/server.d.ts CHANGED
@@ -26,6 +26,8 @@ export type SiteEditBridgeServerOptions = {
26
26
  sessionKey?: string;
27
27
  /** Public verifier supplied by the trusted preview launcher, never the browser. */
28
28
  portableSnapshotPublicKey?: string;
29
+ /** Separate CMS schema verifier supplied by the trusted preview launcher. */
30
+ portableCmsSchemaPublicKey?: string;
29
31
  /** Private runtime directory for the durable, server-side undo/redo store. */
30
32
  historyRoot?: string;
31
33
  allowedOrigins?: string[];
@@ -110,6 +112,7 @@ export declare class SiteEditBridgeServer {
110
112
  private notifyHealthChanged;
111
113
  private createRuntime;
112
114
  private createBridgeEngine;
115
+ private verifyCmsSchemaProofs;
113
116
  private exportPortableBlock;
114
117
  private exportPortableBlockAsset;
115
118
  private runHistoryWithReceipt;
@@ -153,6 +156,7 @@ export declare function normalizeSiteEditBridgeServerOptions(options: SiteEditBr
153
156
  path: string;
154
157
  sessionKey: string;
155
158
  portableSnapshotPublicKey: string | undefined;
159
+ portableCmsSchemaPublicKey: string | undefined;
156
160
  historyRoot: string | undefined;
157
161
  allowedOrigins: string[];
158
162
  runtime: SiteEditBridgeRuntimeOptions;
@@ -170,6 +174,7 @@ declare function normalizeOptions(options: SiteEditBridgeServerOptions): {
170
174
  path: string;
171
175
  sessionKey: string;
172
176
  portableSnapshotPublicKey: string | undefined;
177
+ portableCmsSchemaPublicKey: string | undefined;
173
178
  historyRoot: string | undefined;
174
179
  allowedOrigins: string[];
175
180
  runtime: SiteEditBridgeRuntimeOptions;