@vcp-dev/site-edit-bridge 0.11.28 → 0.11.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-bootstrap.js +3 -3
- package/dist/client.js +1 -1
- package/dist/engine-worker.js +3 -3
- package/dist/index.js +10 -10
- package/dist/next-dev-server.js +4 -4
- package/dist/portable-snapshot-proof.js +1 -2
- package/dist/protocol.js +2 -9
- package/dist/server.js +3 -3
- package/dist/window-message.js +1 -1
- package/package.json +3 -3
package/dist/next-dev-server.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import Le from"node:http";import{existsSync as z,readFileSync as q}from"node:fs";import{randomUUID as ls}from"node:crypto";import{createRequire as Rt}from"node:module";import{Socket as Et}from"node:net";import ee from"node:path";import{basename as Ct,dirname as te,join as ne}from"node:path";import{fileURLToPath as kt}from"node:url";import{createRequire as es}from"node:module";import{pathToFileURL as ts}from"node:url";import{Worker as ns}from"node:worker_threads";var Ke=["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 yn from"node:http";import Z from"node:fs";import{createHash as Oe,randomBytes as Sn,timingSafeEqual as _n}from"node:crypto";import P from"node:path";import{WebSocket as ft,WebSocketServer as bn}from"ws";import{createPreviewSiteEditEngineRuntime as In,exportPortableBlockFromSnapshot as En,readPortableBlockLocalAssetChunk as wn,openFileHistoryStore as xn,resolveManagedPageTemplateComposition as Rn,scanSiteEditCompositionsFromFiles as Cn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as kn,scanNextAppRouterRoutesFromFiles as vn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Tn}from"@vcp-dev/site-edit-engine/source-watcher";function We(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((h,d)=>[h,d])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(h=>({placementKey:h.placementKey,placementUnitKey:h.placementUnitKey,relation:h.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((h,d)=>h.dynamicDataSummary?[[d,h.dynamicDataSummary]]:[]),c=new Map(e.entries.map((h,d)=>[h.key,d])),p=[];for(let[h,d]of e.entries.entries()){let m=d.pageCompositionActionScope;if(!m)continue;if(m.kind!=="source-siblings"){p.push([h,{kind:m.kind}]);continue}let w=m.siblingKeys.map(I=>{let E=c.get(I);if(E===void 0)throw new Error("Render entry "+d.key+" references missing source sibling "+I);return E});p.push([h,{kind:"source-siblings",siblingEntryIndexes:w}])}let l=h=>{let d=t.get(h);if(typeof d=="number")return d;let m=n.length;return n.push(h),t.set(h,m),m},g=h=>{let d=null;for(let m of Wt(h)){let w=`${d??"root"}\0${m}`,I=s.get(w);if(typeof I=="number"){d=I;continue}let E=o.length;o.push([d,l(m)]),s.set(w,E),d=E}if(d===null)throw new Error("Document key must not be empty");return d};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(h=>{let d=h.pageCompositionUnitKey?r.get(h.pageCompositionUnitKey)??-1:-1;if(h.pageCompositionUnitKey&&d<0)throw new Error(`Render entry ${h.key} references unknown page composition unit ${h.pageCompositionUnitKey}`);return[g(h.key),Bt(h.operationSummary),...d>=0?[d]:[]]}),...p.length>0?{pageCompositionActionScopes:p}:{},...e.entries.every(h=>h.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(h=>h.parentKey===null?null:g(h.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...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 j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(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(!j(n)||!W(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!se(n.blockKey,256)||!se(n.definitionKey,512)||!Mt(n.rootRef)||!Dt(n.source)||!Lt(n.owner)||!Array.isArray(n.siblingBlockKeys)||!n.siblingBlockKeys.every(s=>se(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!j(e)||!W(e,["key","instanceIndex","instanceCount"])||!F(e.key)||e.instanceIndex!==void 0&&!Ue(e.instanceIndex)||e.instanceCount!==void 0&&(!Ue(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Dt(e){return j(e)&&W(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 Lt(e){return j(e)&&W(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&se(e.key,512)}function jt(e){return j(e)&&W(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 j(e)&&Object.entries(e).every(([t,n])=>F(t)&&j(n)&&W(n,["code","reason"])&&F(n.code)&&F(n.reason))}function Ut(e){let t=$t(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 $t(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=>$e(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("]")?!$e(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,p=>p.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function $e(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 se(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function F(e){return typeof e=="string"&&e.length>0}function W(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Wt(e){if(!e)return[];let t=[],n=0,s=Fe(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Fe(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 Fe(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 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(S(t)&&S(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!S(t)||typeof t.type!="string"?!1:t.type==="request"?zt(t.payload,n):t.type==="response"||t.type==="error"?S(t.payload)&&typeof t.payload.id=="string":t.type==="event"?S(t.payload)&&S(t.payload.event):t.type==="auth"?S(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?S(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&S(t.payload)&&t.payload.ok===!0}},oe=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Ie,this.eventDispatcher=new be(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),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:D({...a,data:{...a.data,document:Je(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,Zt(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,D(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!we(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(V,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,a);return}case"export-portable-block-asset":{if(!qe(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(V,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(i)!==R(r))throw new k(V,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(i)!==R(r))throw new k(V,"History receipt composition does not match the active session.");this.sendResult(o,s.kind,await this.options.engine.getHistoryOperationResult?.({...s.request,composition:ie(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(V,"History request does not match its cursor operation.")}let a=r?{...r,composition:ie(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(n){let s=A.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:_e(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 k(Ee,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(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=Xt(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:ie(n)};if(s.target.kind==="route"){let o=s.target,i=me(o),r=await this.resolveAndAssert(i);s.target={...o,composition:ie(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Qt(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===Yt(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=en(t);this.sendJson({type:"error",payload:{...s,message:_e(n),code:Se(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: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 S(t)&&t.type==="ping"&&S(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},be=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(!S(e)||typeof e.id!="string"||!A.isRequestKind(e.kind))return!1;let n=L(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&&ze(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 qe(e);case"execute":case"get-operation-result":return n&&Gt(e.request)&&(e.request.mutationContext===void 0||ye(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Ve(e.request);case"undo":case"redo":return n&&(e.request===void 0||Ve(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||ye(e.mutationContext))}}function we(e){if(!L(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["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||!S(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!L(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!ze(t.selection_ref)||t.cms_schema_proofs!==void 0&&!Jt(t.cms_schema_proofs))}function Jt(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!S(s)||!Reflect.ownKeys(s).every(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 qe(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","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 Ve(e){return S(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&L(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function ze(e){if(e===void 0)return!0;if(!S(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function Gt(e){return S(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&L(e.composition)&&typeof e.kind=="string"&&S(e.target)&&(e.target.kind!=="route"||L(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&S(e.params)}function L(e){return S(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Qt(e){return S(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function me(e){if(L(e.composition))return e.composition;throw new k(Ee,"A composition selector is required for this request.")}function Xt(e){if(S(e)&&L(e.composition))return e.composition;throw new k(Ee,"A composition selector is required for execute.")}function ie(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Yt(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return S(e)&&e.ok===!0?{...e,composition:t}:e}function Zt(e,t){return!S(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Je(e.data)}}function Je(e){let t=e;return We(t.routeId?t:{...t,routeId:t.composition.routeId})}function S(e){return typeof e=="object"&&e!==null}function ye(e){return S(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function Se(e){if(!(!S(e)||typeof e.code!="string"||e.code.length===0))return e.code}function _e(e){return e instanceof Error||S(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function en(e){try{return A.extractRequestInfo(JSON.parse(e))}catch{return{id:"unknown",kind:"get-document"}}}var re=class{constructor(){this.tail=Promise.resolve()}run(t){let n=this.tail.then(t,t);return this.tail=n.then(()=>{},()=>{}),n}};import{createHash as Ye}from"node:crypto";import{constants as Ze,promises as xe}from"node:fs";import et from"node:path";import{createHash as tn}from"node:crypto";var ae=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
|
-
`)),Ge=Buffer.from(ae.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Qe=e=>`sha256:${tn("sha256").update(e).digest("hex")}`,nn=Qe(ae),sn=Qe(Ge);function Q(e,t,n){return e==="next-env.d.ts"&&t===ae.byteLength&&n===nn?Ge.byteLength:null}function ce(e){return Q(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===sn}function Xe(){return Uint8Array.from(ae)}var tt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),nt=64;async function de(e,t){try{if(!t.size)return!1;for(let[i,r]of t)if(!i||i.startsWith("/")||i.includes("\\")||i.includes("\0")||i.split("/").some(a=>!a||a==="."||a==="..")||tt.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>nt||++n>t.size*nt+1)return!1;let a=await xe.readdir(et.join(e,i),{withFileTypes:!0});for(let u of a){let c=i?`${i}/${u.name}`:u.name;if(!i&&tt.has(u.name))continue;if(u.isDirectory()){if(!await o(c,r+1))return!1;continue}if(!u.isFile())return!1;let p=t.get(c);if(p===void 0||s.has(c))return!1;s.add(c);let l=et.join(e,c),g=await xe.lstat(l),h=typeof p=="string"?Buffer.byteLength(p,"utf8"):p.byteLength,d=`sha256:${Ye("sha256").update(p).digest("hex")}`;if(!g.isFile()||g.isSymbolicLink()||g.size!==h&&g.size!==Q(c,h,d))return!1;let m=Ye("sha256"),w=await xe.open(l,Ze.O_RDONLY|Ze.O_NOFOLLOW);try{let E=await w.stat();if(!E.isFile()||E.size!==g.size)return!1;let _=0,b=w.createReadStream({autoClose:!1});for await(let C of b){if(_+=C.byteLength,_>g.size)return b.destroy(),!1;m.update(C)}if(_!==g.size)return!1}finally{await w.close()}let I=`sha256:${m.digest("hex")}`;if((g.size!==h||I!==d)&&!ce({file:c,expectedSize:h,expectedDigest:d,actualSize:g.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as rt}from"node:crypto";import{constants as st,promises as ue}from"node:fs";import Re from"node:path";import{GeneratedSiteCapabilitiesSchema as on}from"@vcp-dev/contracts";var rn=".vcp/portable-snapshot-proof.json",it=4*1024*1024,an=256*1024*1024,cn=1e4,dn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function at(e){try{let t=Re.join(e.projectRoot,rn),n=await ue.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>it)return null;let s=JSON.parse(await ue.readFile(t,"utf8"));if(!X(s)||!(Y(s,["payload"])||Y(s,["payload","signature"]))||!ln(s.payload,it))return null;let o=Buffer.from(s.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!X(r)||!Y(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!X(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>cn)return null;let u=on.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let c=new Map;for(let d of r.trusted_host_file_hashes){if(!X(d)||!Y(d,["path","hash"])||typeof d.path!="string"||!un(d.path)||!ot(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||c.has(d.path))return null;c.set(d.path,d.hash)}let p=0,l=[],g=new Set;for(let d of a.files){if(!X(d)||!Y(d,["path","hash","size_bytes"])||typeof d.path!="string"||!ot(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||typeof d.size_bytes!="number"||!Number.isSafeInteger(d.size_bytes)||d.size_bytes<0||g.has(d.path)||(g.add(d.path),p+=d.size_bytes,p>an))return null;l.push({path:d.path,hash:d.hash,size_bytes:d.size_bytes})}let h=new Map;for(let d of l){let m=await pn(e.projectRoot,d.path,d.size_bytes,d.hash);if(!m||`sha256:${rt("sha256").update(m).digest("hex")}`!==d.hash)return null;h.set(d.path,m)}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:h},host_capabilities:u.data,trusted_host_file_hashes:c}}catch{return null}}function un(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 pn(e,t,n,s){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=Re.join(i,u);let c=await ue.lstat(i);if(!c.isDirectory()||c.isSymbolicLink())return null}let r=Re.join(i,o.at(-1)),a=await ue.open(r,st.O_RDONLY|st.O_NOFOLLOW);try{let u=await a.stat(),c=Q(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==c)return null;let p=[],l=0,g=a.createReadStream({autoClose:!1});for await(let d of g){let m=d;if(l+=m.byteLength,l>u.size)return g.destroy(),null;p.push(m)}if(l!==u.size)return null;let h=Buffer.concat(p,l);return l===n?h:ce({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${rt("sha256").update(h).digest("hex")}`})?Xe():null}finally{await a.close()}}function ot(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!dn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function X(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Y(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function ln(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{PortableCmsSchemaEnvelopeSchema as hn,PortableCmsSchemaStatementSchema as fn}from"@vcp-dev/contracts";var gn=3e4;function ct(e){try{let t=hn.safeParse(e.proof);if(!t.success||!mn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),o=JSON.parse(s);if(JSON.stringify(o)!==s)return null;let i=fn.safeParse(o),r=e.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>r+gn||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function mn(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 An,SiteEditPortableExportRequestSchema as Pn,SiteEditPortableExportResultSchema as On,SiteEditPortableAssetRequestSchema as Nn,SiteEditPortableAssetResultSchema as Bn,computeSiteEditCompositionKey as K}from"@vcp-dev/contracts";var Hn="127.0.0.1",Mn=30218,Dn="/__vcp/site-edit/bridge",gt=6*1024*1024,Ln=gt*2,jn=3e3,dt=50,ke=".vcp/current-snapshot.json",ut="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function mt(e,t,n={}){let s=new ve(St(t),e,!1,n);return s.start({listen:!1}),s}var ve=class{constructor(t,n=yn.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 re,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{Z.mkdirSync(P.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=Ne({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 Tn({projectRoot:this.options.projectRoot,watch_dirs:Kn(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=Wn(),n=Vn(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??In)({...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=$n(t.composition),o=this.getRuntime(),i=T(s);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,s);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let o=n.getDocument(s);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return 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))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let o=ct({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;n.push(o)}return n}async exportPortableBlock(t,n,s){let o=(b,C,v)=>({complete:!1,unresolved:[{code:b,path:C,message:v}]}),i=Pn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=T(n);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let c=()=>{let b=this.getRuntime().getDocument(a).data;return{site_id:b.siteId,snapshot_id:b.snapshotId,document_version:b.version}},p=c();if(p.site_id!==r.site_id||p.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(p.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let g=this.dependencies.loadTrustedPortableSnapshot??(b=>at({...b,projectRoot:this.options.projectRoot})),h;try{h=await g({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(!h)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let d=new Map([...h.snapshot.files].map(([b,C])=>[b,typeof C=="string"?C:new Uint8Array(C)])),m={...h,snapshot:{...h.snapshot,files:d}};if(!await de(this.options.projectRoot,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:w,...I}=r,E=await En({...I,...m,trusted_cms_schemas:l,read_current_identity:c}),_=On.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!==a.routeId||_.data.target.composition.templateId!==a.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 de(this.options.projectRoot,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let b=c();if(this.options.snapshotId!==r.base_snapshot_id||b.site_id!==r.site_id||b.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(b.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?.(d)}return _.data}async exportPortableBlockAsset(t,n){let s=p=>({complete:!1,unresolved:[{code:p,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Nn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,n,p=>{r=p});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=wn({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),c=Bn.safeParse(u);if(!c.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!c.data.complete)return c.data;if(!await de(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let p=this.getRuntime().getDocument(T(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||p.siteId!==i.request.site_id||p.snapshotId!==i.request.base_snapshot_id||p.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?c.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 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 Oe("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??xn)(Fn({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=K(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?K(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let 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=>!Zn(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=Z.readFileSync(P.join(this.options.projectRoot,ke),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Te(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=Un(this.options.projectRoot),s=vn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(c=>({...c})),i=Cn({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(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[K(c.context),c])),u=new Map(i.map(c=>[K(c.context),c]));if(this.runtime){for(let[c,p]of a){let l=u.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.unregisterComposition(T(p.context))}for(let[c,p]of u){let l=a.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.registerComposition(p.context,p.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=kn(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=Rn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=K(o.context);if(!this.compositions.some(r=>K(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(K(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:P.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Hn,port:e.port??Mn,path:e.path??Dn,sessionKey:e.sessionKey??Yn(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Kn(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 Un(e){let t=[],n=["app","src/app",".vcp"],s=new Set([".git",".next",".turbo","coverage","dist","node_modules","output","snapshot-store"]),o=i=>{if(!Z.existsSync(i))return;let r;try{r=Z.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;o(P.join(i,a.name));continue}if(!a.isFile())continue;let u=P.join(i,a.name),c="";try{c=Z.readFileSync(u,"utf8")}catch{}t.push({path:P.relative(e,u).replaceAll(P.sep,"/"),content:c})}};for(let i of n)o(P.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function $n(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Fn(e){return P.join(P.resolve(e.root),Te(e.siteId),Te(e.snapshotId),Oe("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Te(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Oe("sha256").update(e).digest("hex").slice(0,32)}function Wn(){let e=globalThis;return e[ut]??=new Map,e[ut]}function Vn(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 Ne(e){let t=new bn({maxPayload:gt,noServer:!0}),n=new WeakSet,s=i=>{new oe({socket:new Ae(i),engine:e.engine,validateOperationRequest:r=>An.safeParse(r).success})},o=(i,r,a)=>{if(!qn(i,e))return;let u=zn(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
1
|
+
import Le from"node:http";import{existsSync as z,readFileSync as q}from"node:fs";import{randomUUID as ls}from"node:crypto";import{createRequire as Rt}from"node:module";import{Socket as Et}from"node:net";import Z from"node:path";import{basename as Ct,dirname as ee,join as te}from"node:path";import{fileURLToPath as kt}from"node:url";import{createRequire as es}from"node:module";import{pathToFileURL as ts}from"node:url";import{Worker as ns}from"node:worker_threads";var Ke=["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 yn from"node:http";import Y from"node:fs";import{createHash as Oe,randomBytes as Sn,timingSafeEqual as _n}from"node:crypto";import P from"node:path";import{WebSocket as ft,WebSocketServer as bn}from"ws";import{createPreviewSiteEditEngineRuntime as In,exportPortableBlockFromSnapshot as En,readPortableBlockLocalAssetChunk as wn,openFileHistoryStore as xn,resolveManagedPageTemplateComposition as Rn,scanSiteEditCompositionsFromFiles as Cn}from"@vcp-dev/site-edit-engine";import{resolveNextAppRouteId as kn,scanNextAppRouterRoutesFromFiles as vn}from"@vcp-dev/site-edit-engine/next-app-router";import{SiteEditSourceWatcher as Tn}from"@vcp-dev/site-edit-engine/source-watcher";function We(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((h,d)=>[h,d])),a=e.pageComposition.status==="supported"?{status:"supported",containerKey:e.pageComposition.containerKey,hasBusinessMembers:e.pageComposition.hasBusinessMembers,placementUnitKeys:e.pageComposition.placementUnitKeys,placements:e.pageComposition.placements.map(h=>({placementKey:h.placementKey,placementUnitKey:h.placementUnitKey,relation:h.relation}))}:{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics},u=e.entries.flatMap((h,d)=>h.dynamicDataSummary?[[d,h.dynamicDataSummary]]:[]),c=new Map(e.entries.map((h,d)=>[h.key,d])),p=[];for(let[h,d]of e.entries.entries()){let m=d.pageCompositionActionScope;if(!m)continue;if(m.kind!=="source-siblings"){p.push([h,{kind:m.kind}]);continue}let w=m.siblingKeys.map(I=>{let E=c.get(I);if(E===void 0)throw new Error("Render entry "+d.key+" references missing source sibling "+I);return E});p.push([h,{kind:"source-siblings",siblingEntryIndexes:w}])}let l=h=>{let d=t.get(h);if(typeof d=="number")return d;let m=n.length;return n.push(h),t.set(h,m),m},g=h=>{let d=null;for(let m of Wt(h)){let w=`${d??"root"}\0${m}`,I=s.get(w);if(typeof I=="number"){d=I;continue}let E=o.length;o.push([d,l(m)]),s.set(w,E),d=E}if(d===null)throw new Error("Document key must not be empty");return d};return{encoding:"segment-trie-v1",siteId:e.siteId,snapshotId:e.snapshotId,composition:{...e.composition},routeId:e.composition.routeId,version:e.version,pageComposition:a,tokens:n,nodes:o,entries:e.entries.map(h=>{let d=h.pageCompositionUnitKey?r.get(h.pageCompositionUnitKey)??-1:-1;if(h.pageCompositionUnitKey&&d<0)throw new Error(`Render entry ${h.key} references unknown page composition unit ${h.pageCompositionUnitKey}`);return[g(h.key),Bt(h.operationSummary),...d>=0?[d]:[]]}),...p.length>0?{pageCompositionActionScopes:p}:{},...e.entries.every(h=>h.parentKey!==void 0)?{entryParentNodeIds:e.entries.map(h=>h.parentKey===null?null:g(h.parentKey))}:{},...u.length>0?{dynamicDataSummaries:u}:{},...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 j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(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(!j(n)||!W(n,["blockKey","rootRef","definitionKey","source","owner","siblingBlockKeys","placementUnitKey","capabilities","unavailableReasons"])||!ne(n.blockKey,256)||!ne(n.definitionKey,512)||!Mt(n.rootRef)||!Dt(n.source)||!Lt(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!j(e)||!W(e,["key","instanceIndex","instanceCount"])||!F(e.key)||e.instanceIndex!==void 0&&!Ue(e.instanceIndex)||e.instanceCount!==void 0&&(!Ue(e.instanceCount)||e.instanceCount<1)?!1:!(e.instanceIndex!==void 0&&e.instanceCount!==void 0&&e.instanceIndex>=e.instanceCount)}function Dt(e){return j(e)&&W(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 Lt(e){return j(e)&&W(e,["kind","key"])&&(e.kind==="route-member"||e.kind==="component-definition")&&ne(e.key,512)}function jt(e){return j(e)&&W(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 j(e)&&Object.entries(e).every(([t,n])=>F(t)&&j(n)&&W(n,["code","reason"])&&F(n.code)&&F(n.reason))}function Ut(e){let t=$t(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 $t(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=>$e(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("]")?!$e(r):/[\[\]()%]/u.test(r)||r.startsWith("_")||r.startsWith("@")))return!1;try{let r=o.replace(/-/gu,"+").replace(/_/gu,"/"),a=atob(r),u=Uint8Array.from(a,p=>p.charCodeAt(0)),c=new TextDecoder("utf-8",{fatal:!0}).decode(u);return c.length>0&&c.length<=191&&!/[^\x20-\x7e\xa0-\xff]/u.test(c)&&!c.startsWith(" ")&&!c.endsWith(" ")&&new TextEncoder().encode(c).byteLength<=191&&btoa(String.fromCharCode(...new TextEncoder().encode(c))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=+$/u,"")===o}catch{return!1}}function $e(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 W(e,t){let n=new Set(t);return Object.keys(e).every(s=>n.has(s))}function Wt(e){if(!e)return[];let t=[],n=0,s=Fe(e,n);if(s<0)return t.push(e),t;for(t.push(e.slice(0,s)),n=s;n<e.length;){if(s=Fe(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 Fe(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 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(S(t)&&S(t.payload)){let n=typeof t.payload.id=="string"?t.payload.id:"unknown",s=this.isRequestKind(t.payload.kind)?t.payload.kind:"get-document";return{id:n,kind:s}}return{id:"unknown",kind:"get-document"}}static isRequestKind(t){return t==="initialize-session"||t==="get-document"||t==="get-history-status"||t==="get-style-context"||t==="get-object-edit-context"||t==="get-class-name-source"||t==="get-source-tree"||t==="get-source-file"||t==="export-portable-block"||t==="export-portable-block-asset"||t==="resolve-source-location"||t==="execute"||t==="get-operation-result"||t==="get-history-operation-result"||t==="undo"||t==="redo"}static isMessage(t,n={}){return!S(t)||typeof t.type!="string"?!1:t.type==="request"?zt(t.payload,n):t.type==="response"||t.type==="error"?S(t.payload)&&typeof t.payload.id=="string":t.type==="event"?S(t.payload)&&S(t.payload.event):t.type==="auth"?S(t.payload)&&typeof t.payload.key=="string":t.type==="ping"||t.type==="pong"?S(t.payload)&&typeof t.payload.id=="string":t.type==="auth-ok"&&S(t.payload)&&t.payload.ok===!0}},ie=class{constructor(t){this.options=t,this.session={subscribedCompositionKeys:new Set},this.messageQueue=new Ie,this.eventDispatcher=new be(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),a=await this.options.engine.initializeSession({composition:r.context,...s.mutationContext?{mutationContext:s.mutationContext}:{}});this.activateSession(r.context),this.sendJson({type:"response",payload:{id:o,kind:s.kind,result:D({...a,data:{...a.data,document:Je(a.data.document)}},r.context)}});return}case"get-document":{let i=await this.resolveWireContext(s),r=await this.options.engine.getDocument(i);this.sendResult(o,s.kind,Zt(r,i));return}case"get-history-status":{let i=await this.resolveWireContext(s),r=await this.options.engine.getHistoryStatus(i);this.sendResult(o,s.kind,D(r,i));return}case"get-style-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getStyleContext(i),i));return}case"get-object-edit-context":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getObjectEditContext(s.key,i,s.selectionRef),i));return}case"get-class-name-source":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getClassNameSource(s.key,i),i));return}case"get-source-tree":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceTree(i),i));return}case"get-source-file":{let i=await this.resolveWireContext(s);this.sendResult(o,s.kind,D(await this.options.engine.getSourceFile({path:s.path,composition:i}),i));return}case"export-portable-block":{if(!we(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(V,"The portable export target does not match the active composition.");let a=this.options.engine.exportPortableBlock?await this.options.engine.exportPortableBlock(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE",path:"<snapshot>",message:"No trusted Snapshot proof is available."}]};this.sendResult(o,s.kind,a);return}case"export-portable-block-asset":{if(!qe(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(V,"The portable asset target does not match the active composition.");let a=this.options.engine.exportPortableBlockAsset?await this.options.engine.exportPortableBlockAsset(s.request,i):{complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image is unavailable."}]};this.sendResult(o,s.kind,a);return}case"resolve-source-location":{let i=await this.resolveWireContext(s),r=D(await this.options.engine.resolveSourceLocation({key:s.key,composition:i}),i);this.sendResult(o,s.kind,r);return}case"execute":case"get-operation-result":{let i=await this.resolveOperationWireContext(s.request),r=await this.resolveWireContext(s);if(R(i)!==R(r))throw new k(V,"The execute request composition does not match its operation composition.");let a=await this.normalizeOperationRequest(s.request,i);if(s.kind==="get-operation-result"){this.sendResult(o,s.kind,await this.options.engine.getOperationResult?.(a)??null);return}await this.handleBufferedOperation(o,s.kind,()=>this.options.engine.execute(a));return}case"get-history-operation-result":{let i=await this.resolveWireContext(s),r=await this.resolveAndAssert(s.request.composition);if(R(i)!==R(r))throw new k(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 u=await this.resolveAndAssert(r.composition);if(r.kind!==s.kind||R(i)!==R(u))throw new k(V,"History request does not match its cursor operation.")}let a=r?{...r,composition:se(i)}:void 0;await this.handleBufferedOperation(o,s.kind,()=>s.kind==="undo"?this.options.engine.undo(i,a):this.options.engine.redo(i,a));return}}}catch(n){let s=A.extractRequestInfo(t);this.sendJson({type:"error",payload:{...s,message:_e(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 k(Ee,"Initialize a composition session before issuing this request.");if(R(s)!==R(n.context))throw new k(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=Xt(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=me(o),r=await this.resolveAndAssert(i);s.target={...o,composition:se(r)}}return s}handleEngineEvent(t){let n=t?.composition;if(!Qt(n))return;let s=R(n);this.session.subscribedCompositionKeys.has(s)&&(this.eventDispatcher.push(t),t.type==="site-edit.graph.invalidated"&&s===Yt(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=en(t);this.sendJson({type:"error",payload:{...s,message:_e(n),code:Se(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: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 S(t)&&t.type==="ping"&&S(t.payload)&&typeof t.payload.id=="string"?t.payload.id:null}catch{return null}}var k=class extends Error{constructor(t,n){super(n),this.code=t,this.name="BridgeProtocolError"}},be=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(!S(e)||typeof e.id!="string"||!A.isRequestKind(e.kind))return!1;let n=L(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&&ze(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 qe(e);case"execute":case"get-operation-result":return n&&Gt(e.request)&&(e.request.mutationContext===void 0||ye(e.request.mutationContext))&&(t.validateOperationRequest?.(e.request)??!0);case"get-history-operation-result":return n&&Ve(e.request);case"undo":case"redo":return n&&(e.request===void 0||Ve(e.request)&&e.request.kind===e.kind)&&(e.mutationContext===void 0||ye(e.mutationContext))}}function we(e){if(!L(e.composition)||!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["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||!S(t.target)||t.target.kind!=="page-block"||typeof t.target.blockKey!="string"||!t.target.blockKey.length||t.target.blockKey.length>256||!Object.keys(t.target).every(n=>["kind","composition","blockKey"].includes(n))||!L(t.target.composition)||t.target.composition.routeId!==e.composition.routeId||t.target.composition.templateId!==e.composition.templateId||t.selection_ref===void 0||!ze(t.selection_ref)||t.cms_schema_proofs!==void 0&&!Jt(t.cms_schema_proofs))}function Jt(e){if(!Array.isArray(e)||e.length>16||!Reflect.ownKeys(e).every(t=>t==="length"||typeof t=="string"&&/^(0|[1-9][0-9]*)$/u.test(t)&&Number(t)<e.length))return!1;for(let t=0;t<e.length;t++){let n=Object.getOwnPropertyDescriptor(e,String(t));if(!n||!("value"in n))return!1;let s=n.value;if(!S(s)||!Reflect.ownKeys(s).every(i=>typeof i=="string"&&i==="payload"))return!1;let o=Object.getOwnPropertyDescriptor(s,"payload");if(!o||!("value"in o)||typeof o.value!="string"||o.value.length<1||o.value.length>262144||!/^[A-Za-z0-9_-]+$/u.test(o.value))return!1}return!0}function qe(e){if(!Object.keys(e).every(n=>["id","kind","composition","request"].includes(n))||!S(e.request))return!1;let t=e.request;return!(!Object.keys(t).every(n=>["request","snapshot_digest","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 Ve(e){return S(e)&&typeof e.request_id=="string"&&e.request_id.length>0&&e.request_id.length<=128&&typeof e.site_id=="string"&&e.site_id.length>0&&typeof e.base_snapshot_id=="string"&&e.base_snapshot_id.length>0&&(e.kind==="undo"||e.kind==="redo")&&L(e.composition)&&Object.keys(e).every(t=>["request_id","site_id","base_snapshot_id","kind","composition"].includes(t))}function ze(e){if(e===void 0)return!0;if(!S(e)||typeof e.key!="string"||e.key.length===0)return!1;let t=e.instanceIndex,n=e.instanceCount;return t!==void 0&&(typeof t!="number"||!Number.isInteger(t)||t<0)||n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0)||typeof t=="number"&&typeof n=="number"&&t>=n?!1:Object.keys(e).every(s=>s==="key"||s==="instanceIndex"||s==="instanceCount")}function Gt(e){return S(e)&&typeof e.id=="string"&&typeof e.siteId=="string"&&typeof e.baseSnapshotId=="string"&&L(e.composition)&&typeof e.kind=="string"&&S(e.target)&&(e.target.kind!=="route"||L(e.target.composition))&&typeof e.documentVersion=="number"&&Number.isInteger(e.documentVersion)&&e.documentVersion>=0&&S(e.params)}function L(e){return S(e)&&typeof e.routeId=="string"&&e.routeId.length>0&&(e.templateId===void 0||typeof e.templateId=="string"&&e.templateId.length>0)&&Object.keys(e).every(t=>t==="routeId"||t==="templateId")}function Qt(e){return S(e)&&typeof e.routeId=="string"&&(e.effectiveTemplateId===void 0||typeof e.effectiveTemplateId=="string")}function me(e){if(L(e.composition))return e.composition;throw new k(Ee,"A composition selector is required for this request.")}function Xt(e){if(S(e)&&L(e.composition))return e.composition;throw new k(Ee,"A composition selector is required for execute.")}function se(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Yt(e){return e.activeComposition?R(e.activeComposition):null}function R(e){return JSON.stringify([e.routeId,e.effectiveTemplateId??null])}function D(e,t){return S(e)&&e.ok===!0?{...e,composition:t}:e}function Zt(e,t){return!S(e)||e.ok!==!0?e:{...e,...t?{composition:t}:{},data:Je(e.data)}}function Je(e){let t=e;return We(t.routeId?t:{...t,routeId:t.composition.routeId})}function S(e){return typeof e=="object"&&e!==null}function ye(e){return S(e)&&typeof e.editingSessionId=="string"&&e.editingSessionId.length>0&&typeof e.lockId=="string"&&e.lockId.length>0&&typeof e.ownerId=="string"&&e.ownerId.length>0&&typeof e.leaseAssertion=="string"&&e.leaseAssertion.length>0}function Se(e){if(!(!S(e)||typeof e.code!="string"||e.code.length===0))return e.code}function _e(e){return e instanceof Error||S(e)&&typeof e.message=="string"&&e.message.length>0?e.message:"Unknown websocket operation failure"}function en(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 Ye}from"node:crypto";import{constants as Ze,promises as xe}from"node:fs";import et from"node:path";import{createHash as tn}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
|
+
`)),Ge=Buffer.from(re.toString("utf8").replaceAll("./.next/types/","./.next/dev/types/")),Qe=e=>`sha256:${tn("sha256").update(e).digest("hex")}`,nn=Qe(re),sn=Qe(Ge);function Q(e,t,n){return e==="next-env.d.ts"&&t===re.byteLength&&n===nn?Ge.byteLength:null}function ae(e){return Q(e.file,e.expectedSize,e.expectedDigest)===e.actualSize&&e.actualDigest===sn}function Xe(){return Uint8Array.from(re)}var tt=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]),nt=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(a=>!a||a==="."||a==="..")||tt.has(i.split("/")[0])||typeof r!="string"&&!(r instanceof Uint8Array))return!1;let n=0,s=new Set,o=async(i,r)=>{if(r>nt||++n>t.size*nt+1)return!1;let a=await xe.readdir(et.join(e,i),{withFileTypes:!0});for(let u of a){let c=i?`${i}/${u.name}`:u.name;if(!i&&tt.has(u.name))continue;if(u.isDirectory()){if(!await o(c,r+1))return!1;continue}if(!u.isFile())return!1;let p=t.get(c);if(p===void 0||s.has(c))return!1;s.add(c);let l=et.join(e,c),g=await xe.lstat(l),h=typeof p=="string"?Buffer.byteLength(p,"utf8"):p.byteLength,d=`sha256:${Ye("sha256").update(p).digest("hex")}`;if(!g.isFile()||g.isSymbolicLink()||g.size!==h&&g.size!==Q(c,h,d))return!1;let m=Ye("sha256"),w=await xe.open(l,Ze.O_RDONLY|Ze.O_NOFOLLOW);try{let E=await w.stat();if(!E.isFile()||E.size!==g.size)return!1;let _=0,b=w.createReadStream({autoClose:!1});for await(let C of b){if(_+=C.byteLength,_>g.size)return b.destroy(),!1;m.update(C)}if(_!==g.size)return!1}finally{await w.close()}let I=`sha256:${m.digest("hex")}`;if((g.size!==h||I!==d)&&!ae({file:c,expectedSize:h,expectedDigest:d,actualSize:g.size,actualDigest:I}))return!1}return!0};return await o("",0)&&s.size===t.size}catch{return!1}}import{createHash as rt}from"node:crypto";import{constants as st,promises as ue}from"node:fs";import Re from"node:path";import{GeneratedSiteCapabilitiesSchema as on}from"@vcp-dev/contracts";var rn=".vcp/portable-snapshot-proof.json",it=4*1024*1024,an=256*1024*1024,cn=1e4,dn=new Set([".vcp",".git",".next",".open-next",".turbo",".wrangler","node_modules","dist","coverage"]);async function at(e){try{let t=Re.join(e.projectRoot,rn),n=await ue.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>it)return null;let s=JSON.parse(await ue.readFile(t,"utf8"));if(!X(s)||!de(s,["payload"])||!ln(s.payload,it))return null;let o=Buffer.from(s.payload,"base64url"),i=new TextDecoder("utf-8",{fatal:!0}).decode(o),r=JSON.parse(i);if(JSON.stringify(r)!==i||!X(r)||!de(r,["kind","manifest","host_capabilities","trusted_host_file_hashes"])||r.kind!=="vcp-portable-snapshot-v1"||!X(r.manifest))return null;let a=r.manifest;if(a.version!==1||a.site_id!==e.site_id||a.snapshot_id!==e.base_snapshot_id||typeof a.created_at!="string"||!Array.isArray(a.files)||!a.files.length||a.files.length>cn)return null;let u=on.safeParse(r.host_capabilities);if(!u.success||!Array.isArray(r.trusted_host_file_hashes)||r.trusted_host_file_hashes.length>512)return null;let c=new Map;for(let d of r.trusted_host_file_hashes){if(!X(d)||!de(d,["path","hash"])||typeof d.path!="string"||!un(d.path)||!ot(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||c.has(d.path))return null;c.set(d.path,d.hash)}let p=0,l=[],g=new Set;for(let d of a.files){if(!X(d)||!de(d,["path","hash","size_bytes"])||typeof d.path!="string"||!ot(d.path)||typeof d.hash!="string"||!/^sha256:[a-f0-9]{64}$/u.test(d.hash)||typeof d.size_bytes!="number"||!Number.isSafeInteger(d.size_bytes)||d.size_bytes<0||g.has(d.path)||(g.add(d.path),p+=d.size_bytes,p>an))return null;l.push({path:d.path,hash:d.hash,size_bytes:d.size_bytes})}let h=new Map;for(let d of l){let m=await pn(e.projectRoot,d.path,d.size_bytes,d.hash);if(!m||`sha256:${rt("sha256").update(m).digest("hex")}`!==d.hash)return null;h.set(d.path,m)}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:h},host_capabilities:u.data,trusted_host_file_hashes:c}}catch{return null}}function un(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 pn(e,t,n,s){let o=t.split("/"),i=e;for(let u of o.slice(0,-1)){i=Re.join(i,u);let c=await ue.lstat(i);if(!c.isDirectory()||c.isSymbolicLink())return null}let r=Re.join(i,o.at(-1)),a=await ue.open(r,st.O_RDONLY|st.O_NOFOLLOW);try{let u=await a.stat(),c=Q(t,n,s);if(!u.isFile()||u.size!==n&&u.size!==c)return null;let p=[],l=0,g=a.createReadStream({autoClose:!1});for await(let d of g){let m=d;if(l+=m.byteLength,l>u.size)return g.destroy(),null;p.push(m)}if(l!==u.size)return null;let h=Buffer.concat(p,l);return l===n?h:ae({file:t,expectedSize:n,expectedDigest:s,actualSize:l,actualDigest:`sha256:${rt("sha256").update(h).digest("hex")}`})?Xe():null}finally{await a.close()}}function ot(e){let t=e.split("/");return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/[\\\0]/u.test(e)&&!dn.has(t[0])&&t.every(n=>n&&n!=="."&&n!=="..")}function X(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 ln(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{PortableCmsSchemaEnvelopeSchema as hn,PortableCmsSchemaStatementSchema as fn}from"@vcp-dev/contracts";var gn=3e4;function ct(e){try{let t=hn.safeParse(e.proof);if(!t.success||!mn(t.data.payload,262144))return null;let n=Buffer.from(t.data.payload,"base64url"),s=new TextDecoder("utf-8",{fatal:!0}).decode(n),o=JSON.parse(s);if(JSON.stringify(o)!==s)return null;let i=fn.safeParse(o),r=e.now??Date.now();return!i.success||!Number.isSafeInteger(r)||i.data.site_id!==e.site_id||i.data.base_snapshot_id!==e.base_snapshot_id||i.data.issued_at>r+gn||i.data.expires_at<=r?null:{source_slug:i.data.slug,evidence_path:`trusted-cms-schema:${i.data.slug}`,fields:i.data.fields}}catch{return null}}function mn(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 An,SiteEditPortableExportRequestSchema as Pn,SiteEditPortableExportResultSchema as On,SiteEditPortableAssetRequestSchema as Nn,SiteEditPortableAssetResultSchema as Bn,computeSiteEditCompositionKey as K}from"@vcp-dev/contracts";var Hn="127.0.0.1",Mn=30218,Dn="/__vcp/site-edit/bridge",gt=6*1024*1024,Ln=gt*2,jn=3e3,dt=50,ke=".vcp/current-snapshot.json",ut="__VCP_SITE_EDIT_BRIDGE_SERVERS__";function mt(e,t,n={}){let s=new ve(St(t),e,!1,n);return s.start({listen:!1}),s}var ve=class{constructor(t,n=yn.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(P.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=Ne({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 Tn({projectRoot:this.options.projectRoot,watch_dirs:Kn(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=Wn(),n=Vn(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??In)({...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=$n(t.composition),o=this.getRuntime(),i=T(s);await o.initializeComposition(i);let a=o.getDocument(i).data;await this.recordRuntimeVersion(a.version,s);let u=(await o.getHistoryStatus()).data;return{ok:!0,composition:s,data:{document:a,historyStatus:u}}}),getDocument:async t=>{let n=this.getRuntime(),s=T(t);await n.initializeComposition(s);let o=n.getDocument(s);return await this.recordRuntimeVersion(o.data.version,t),{...o,composition:t}},getHistoryStatus:async t=>({...await this.getRuntime().getHistoryStatus(),composition:t}),getStyleContext:async t=>this.getRuntime().getStyleContext(T(t)),getObjectEditContext:async(t,n,s)=>this.getRuntime().getObjectEditContext(t,T(n),s),getClassNameSource:async(t,n)=>this.getRuntime().getClassNameSource(t,T(n)),getSourceTree:async t=>this.getRuntime().getSourceTree(T(t)),getSourceFile:async t=>this.getRuntime().getSourceFile({path:t.path,composition:T(t.composition)}),exportPortableBlock:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlock(t,n)),exportPortableBlockAsset:(t,n)=>this.mutationQueue.run(()=>this.exportPortableBlockAsset(t,n)),resolveSourceLocation:async t=>this.getRuntime().resolveSourceLocation({key:t.key,composition:T(t.composition)}),execute:(t,n)=>this.executeWithReceipt(t,()=>this.mutationQueue.run(async()=>{let s=await this.bindHistorySession(this.options.snapshotId);if(!s.ok)return 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))}}verifyCmsSchemaProofs(t){let n=[];for(let s of t.cms_schema_proofs??[]){let o=ct({proof:s,site_id:t.site_id,base_snapshot_id:t.base_snapshot_id});if(!o)return null;n.push(o)}return n}async exportPortableBlock(t,n,s){let o=(b,C,v)=>({complete:!1,unresolved:[{code:b,path:C,message:v}]}),i=Pn.safeParse(t);if(!i.success)return o("PORTABLE_EXPORT_REQUEST_INVALID","<selection>","The selected block export request is invalid.");let r=i.data,a=T(n);if(r.target.composition.routeId!==a.routeId||r.target.composition.templateId!==a.templateId)return o("PORTABLE_EXPORT_COMPOSITION_MISMATCH","<selection>","The target does not match the active composition.");if(r.site_id!==this.options.siteId||r.base_snapshot_id!==this.options.snapshotId)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");await this.getRuntime().initializeComposition(a);let c=()=>{let b=this.getRuntime().getDocument(a).data;return{site_id:b.siteId,snapshot_id:b.snapshotId,document_version:b.version}},p=c();if(p.site_id!==r.site_id||p.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot is no longer active.");if(p.document_version!==r.document_version)return o("DOCUMENT_VERSION_STALE","<document>","The selected document version is no longer current.");let l=this.verifyCmsSchemaProofs(r);if(!l)return o("PORTABLE_CMS_SCHEMA_PROOF_INVALID","<cms-schema>","The CMS schema proof is invalid, expired or bound to another authority.");let g=this.dependencies.loadTrustedPortableSnapshot??(b=>at({...b,projectRoot:this.options.projectRoot})),h;try{h=await g({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(!h)return o("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE","<snapshot>","No trusted Snapshot proof is available.");let d=new Map([...h.snapshot.files].map(([b,C])=>[b,typeof C=="string"?C:new Uint8Array(C)])),m={...h,snapshot:{...h.snapshot,files:d}};if(!await ce(this.options.projectRoot,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace does not match the trusted Snapshot.");let{cms_schema_proofs:w,...I}=r,E=await En({...I,...m,trusted_cms_schemas:l,read_current_identity:c}),_=On.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!==a.routeId||_.data.target.composition.templateId!==a.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,d))return o("SNAPSHOT_WORKSPACE_MISMATCH","<snapshot>","The live workspace changed during export.");try{let b=c();if(this.options.snapshotId!==r.base_snapshot_id||b.site_id!==r.site_id||b.snapshot_id!==r.base_snapshot_id)return o("SNAPSHOT_MISMATCH","<snapshot>","The selected Snapshot changed during export.");if(b.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?.(d)}return _.data}async exportPortableBlockAsset(t,n){let s=p=>({complete:!1,unresolved:[{code:p,path:"<asset>",message:"The selected local image could not be verified."}]}),o=Nn.safeParse(t);if(!o.success)return s("PORTABLE_LOCAL_ASSET_REQUEST_INVALID");let i=o.data,r,a=await this.exportPortableBlock(i.request,n,p=>{r=p});if(!a.complete)return{complete:!1,unresolved:a.unresolved};if(a.snapshot_digest!==i.snapshot_digest)return s("SNAPSHOT_MISMATCH");if(!r)return s("PORTABLE_SNAPSHOT_PROOF_UNAVAILABLE");let u=wn({exported:a,snapshot_files:r,snapshot_digest:i.snapshot_digest,file_path:i.file_path,occurrence:i.occurrence,offset:i.offset}),c=Bn.safeParse(u);if(!c.success)return s("PORTABLE_LOCAL_ASSET_RESULT_INVALID");if(!c.data.complete)return c.data;if(!await ce(this.options.projectRoot,r))return s("SNAPSHOT_WORKSPACE_MISMATCH");try{let p=this.getRuntime().getDocument(T(n)).data;if(this.options.snapshotId!==i.request.base_snapshot_id||p.siteId!==i.request.site_id||p.snapshotId!==i.request.base_snapshot_id||p.version!==i.request.document_version)return s("DOCUMENT_VERSION_STALE")}catch{return s("RUNTIME_IDENTITY_UNAVAILABLE")}return this.verifyCmsSchemaProofs(i.request)?c.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 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 Oe("sha256").update(JSON.stringify(t)).digest("hex")}readOperationReceipt(t){if(!this.isActiveReceiptIdentity(t))return null;let n=this.operationReceipts.get(this.operationReceiptKey(t));return n?.fingerprint===this.operationFingerprint(t)?n.result:null}executeWithReceipt(t,n){if(!this.isActiveReceiptIdentity(t))return n();let s=this.operationReceiptKey(t),o=this.operationFingerprint(t),i=this.operationReceipts.get(s);if(i)return i.fingerprint!==o?Promise.reject(new Error("Operation ID was reused with a different request.")):i.result;let r={fingerprint:o,result:n(),settled:!1};return this.operationReceipts.set(s,r),r.result.then(()=>{r.settled=!0;for(let[a,u]of this.operationReceipts){if(this.operationReceipts.size<=256)break;u.settled&&this.operationReceipts.delete(a)}},()=>{this.operationReceipts.delete(s)}),r.result}async bindHistorySession(t){if(!this.options.historyRoot)return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history is not configured."};if(this.activeHistorySessionId===t)return{ok:!0};let n=this.historySessionTransition.then(async()=>{if(this.activeHistorySessionId===t)return;let s=await(this.dependencies.openHistoryStore??xn)(Fn({root:this.options.historyRoot,siteId:this.options.siteId,snapshotId:this.options.snapshotId,editingSessionId:t}));if(!this.isStarted)return;let o=s.readDocumentVersion?await s.readDocumentVersion():0,i=this.versionCheckpoints.get(s);i?i.durableVersion=Math.max(i.durableVersion,o):this.versionCheckpoints.set(s,{durableVersion:o,requestedVersion:o,pending:null});let r=this.compositions[0]?.context;if(r){let a=K(r);this.runtimeVersionFloors.set(a,Math.max(this.runtimeVersionFloors.get(a)??0,o))}this.createRuntime(s,t)});this.historySessionTransition=n.catch(()=>{});try{return await n,{ok:!0}}catch{return{ok:!1,code:"RECOVERY_PERSIST_FAILED",message:"Durable edit history could not be opened."}}}recordRuntimeVersion(t,n){let s=n?K(n):null;s&&this.runtimeVersionFloors.set(s,Math.max(this.runtimeVersionFloors.get(s)??0,t));let o=this.activeHistoryStore;if(!o?.writeDocumentVersion)return Promise.resolve();let i=s?this.runtimeVersionFloors.get(s)??t:t,r=this.versionCheckpoints.get(o);if(r||(r={durableVersion:0,requestedVersion:0,pending:null},this.versionCheckpoints.set(o,r)),i<=r.durableVersion)return Promise.resolve();if(r.requestedVersion=Math.max(r.requestedVersion,i),r.pending)return r.pending;let a=r,u=this.versionPersistence.then(async()=>{try{for(;a.requestedVersion>a.durableVersion;){let c=a.requestedVersion;await o.writeDocumentVersion(c),a.durableVersion=Math.max(a.durableVersion,c)}}catch{console.warn("[vcp-site-edit] document version checkpoint persistence failed")}finally{a.pending=null}});return a.pending=u,this.versionPersistence=u,u}handleFileChanged(t){this.handleFilesChanged([t])}handleFilesChanged(t){for(let 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=>!Zn(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(P.join(this.options.projectRoot,ke),"utf8"),n=JSON.parse(t),s=typeof n.snapshot_id=="string"?n.snapshot_id:"";return!s||Te(s)!==s?(console.warn("[vcp-site-edit] current-snapshot marker has no valid snapshot_id"),null):s}catch(t){return console.warn(`[vcp-site-edit] current-snapshot marker unreadable: ${t instanceof Error?t.message:String(t)}`),null}}async advanceSnapshotId(t){if(this.stopping||!this.isStarted||t===this.options.snapshotId)return;let n=this.options.snapshotId;this.options.snapshotId=t;try{if(this.options.historyRoot){let o=await this.bindHistorySession(t);if(!o.ok)throw new Error(`${o.code}: ${o.message}`)}else this.createRuntime()}catch(o){this.options.snapshotId=n,console.warn(`[vcp-site-edit] snapshot identity advance rolled back to ${n}: ${o instanceof Error?o.message:String(o)}`);return}let s=new Date().toISOString();for(let o of this.compositions){let i={type:"site-edit.snapshot.changed",siteId:this.options.siteId,composition:o.context,snapshotId:t,previousSnapshotId:n,at:s};for(let r of this.eventListeners)try{r(i)}catch(a){console.warn(`[vcp-site-edit] snapshot.changed listener failed: ${a instanceof Error?a.message:String(a)}`)}}try{this.options.onSnapshotIdChanged?.(t,n)}catch(o){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${o instanceof Error?o.message:String(o)}`)}}refreshCompositions(t=!1){try{let n=Un(this.options.projectRoot),s=vn(n),o=s.length>0?s:(this.options.runtime.routes??[]).map(c=>({...c})),i=Cn({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(c=>c.context.effectiveTemplateId!==void 0).map(c=>c.entryFile).sort());if(t&&(this.launchCandidateEntries=r),this.launchCandidateEntries!==r)throw new Error("SITE_EDIT_RUNTIME_RELOAD_REQUIRED: Candidate route collection changed since preview launch");let a=new Map(this.compositions.map(c=>[K(c.context),c])),u=new Map(i.map(c=>[K(c.context),c]));if(this.runtime){for(let[c,p]of a){let l=u.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.unregisterComposition(T(p.context))}for(let[c,p]of u){let l=a.get(c);(!l||l.entryFile!==p.entryFile)&&this.runtime.registerComposition(p.context,p.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=kn(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=Rn({selector:{routeId:n,...t.templateId!==void 0?{templateId:t.templateId}:{}},files:this.compositionFiles,canonicalEntryFile:s.entryFile}),i=K(o.context);if(!this.compositions.some(r=>K(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(K(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:P.resolve(e.projectRoot??process.cwd()),basePath:e.basePath??"",host:e.host??Hn,port:e.port??Mn,path:e.path??Dn,sessionKey:e.sessionKey??Yn(),historyRoot:e.historyRoot,allowedOrigins:e.allowedOrigins??[],runtime:e.runtime??{},onSnapshotIdChanged:e.onSnapshotIdChanged,onHealthChanged:e.onHealthChanged}}function Kn(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 Un(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 a of r){if(a.name.startsWith(".")&&a.name!==".vcp")continue;if(a.isDirectory()){if(s.has(a.name))continue;o(P.join(i,a.name));continue}if(!a.isFile())continue;let u=P.join(i,a.name),c="";try{c=Y.readFileSync(u,"utf8")}catch{}t.push({path:P.relative(e,u).replaceAll(P.sep,"/"),content:c})}};for(let i of n)o(P.join(e,i));return t.sort((i,r)=>i.path.localeCompare(r.path))}function $n(e){if(!e||typeof e!="object"||typeof e.routeId!="string")throw new Error("Normalized composition context is required.");if("effectiveTemplateId"in e)return e;let t=e;return{routeId:t.routeId,...t.templateId?{effectiveTemplateId:t.templateId}:{}}}function T(e){return{routeId:e.routeId,...e.effectiveTemplateId?{templateId:e.effectiveTemplateId}:{}}}function Fn(e){return P.join(P.resolve(e.root),Te(e.siteId),Te(e.snapshotId),Oe("sha256").update(e.editingSessionId).digest("hex").slice(0,32))}function Te(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e)&&e!=="."&&e!==".."?e:Oe("sha256").update(e).digest("hex").slice(0,32)}function Wn(){let e=globalThis;return e[ut]??=new Map,e[ut]}function Vn(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 Ne(e){let t=new bn({maxPayload:gt,noServer:!0}),n=new WeakSet,s=i=>{new ie({socket:new Ae(i),engine:e.engine,validateOperationRequest:r=>An.safeParse(r).success})},o=(i,r,a)=>{if(!qn(i,e))return;let u=zn(i,e);if(!u){r.write(`HTTP/1.1 401 Unauthorized\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
\r
|
|
5
5
|
`),r.destroy();return}u.authenticatedByHeader&&n.add(i),t.handleUpgrade(i,r,a,c=>{t.emit("connection",c,i)})};return e.server.on("upgrade",o),t.on("connection",(i,r)=>{if(n.has(r)){s(i);return}Jn(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 Ae=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")>Ln){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 zn(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=_t(s,t.sessionKey),i=Ce(e.headers.host),r=Ce(e.headers.origin);return i&&!Gn(i,t.host,r)?null:r?Xn(r,i,t.allowedOrigins)?{authenticatedByHeader:o}:null:o?{authenticatedByHeader:!0}:null}function Jn(e,t,n){let s=setTimeout(()=>{e.close(1008,"bridge authentication timeout")},jn),o,i=()=>{clearTimeout(s),e.off("message",o),e.off("close",i)},r=()=>{i(),e.close(1008,"bridge authentication failed")};o=a=>{try{let u=A.parseMessage(a.toString());if(u.type!=="auth"||!_t(u.payload.key,t)){r();return}i(),e.readyState===ft.OPEN&&e.send(A.stringifyMessage({type:"auth-ok",payload:{ok:!0}})),n()}catch{r()}},e.on("message",o),e.on("close",i)}function _t(e,t){if(!e)return!1;let n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&_n(n,s)}function Gn(e,t,n){let s=ht(e),o=ht(t);return s===o||lt(o)&<(s)&&(!n||Pe(n,e))||Qn(o)&&(!n||Pe(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 Xn(e,t,n){return n.includes(e)||(t?Pe(e,t):!1)}function Pe(e,t){try{return new URL(e).host===bt(t)}catch{return!1}}function ht(e){let t=bt(e);return t.startsWith("[")?t.slice(1,t.indexOf("]")):t.split(":").length-1===1?t.split(":",1)[0]??"":t}function bt(e){return e.trim().toLowerCase()}function Ce(e){return Array.isArray(e)?e[0]:e}function Yn(){return Sn(32).toString("base64url")}function It(e){let t=e.replaceAll("\\","/");return t===ke||t.endsWith(`/${ke}`)}function Zn(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 ss="SITE_EDIT_ENGINE_UNAVAILABLE",is=5e3,os=1024,rs="VCP_SITE_EDIT_ENGINE_MAX_HEAP_MB",as=3,cs=10*6e4,ds=1012;function Be(e,t,n={}){let s=yt(t),{onSnapshotIdChanged:o,onHealthChanged:i,...r}=s,a={options:r},u=n.maxHeapMb??ps(process.env[rs])??os,c=n.maxRestarts??as,p=n.restartWindowMs??cs,l="starting",g,h=0,d=[],m=null,w=0,I=new Map,E=new Set,_,b,C=new Promise((f,y)=>{_=f,b=y});C.catch(()=>{});let v=f=>{let y=new Error(`VCP site edit preview bridge runtime is not ready: ${f}`);return y.code=ss,y},J=f=>{for(let y of I.values())y.reject(f);I.clear()},N=f=>{switch(f.type){case"ready":m=f.health,l==="starting"?(l="ready",_()):l==="restarting"&&(l="ready",console.warn("[vcp-site-edit] engine worker restarted"));return;case"start-failed":l==="starting"&&B(ge(f.error));return;case"result":{let y=I.get(f.id);if(!y)return;I.delete(f.id),f.ok?y.resolve(f.value):y.reject(ge(f.error));return}case"event":for(let y of E)try{y(f.event)}catch(x){console.warn(`[vcp-site-edit] engine event listener failed: ${x instanceof Error?x.message:String(x)}`)}return;case"health":m=f.health;return;case"snapshot-id-changed":a.options.snapshotId=f.next;try{o?.(f.next,f.previous)}catch(y){console.warn(`[vcp-site-edit] onSnapshotIdChanged callback failed: ${y instanceof Error?y.message:String(y)}`)}return}},U=()=>{let f=h+=1,y=n.workerUrl??new URL("./engine-worker.js",import.meta.url),x=new ns(us(y),{workerData:a,resourceLimits:{maxOldGenerationSizeMb:u},...n.execArgv?{execArgv:n.execArgv}:{}});x.unref();let M=()=>f===h;x.on("message",O=>{M()&&N(O)}),x.on("error",O=>{M()&&B(O instanceof Error?O:new Error(String(O)))}),x.on("exit",O=>{M()&&B(new Error(`engine worker exited with code ${O}`))}),g=x,n.onWorker?.(x)},B=f=>{if(l==="stopped"||l==="failed")return;if(J(v(f.message)),m=null,l==="starting"){l="failed",console.error(`[vcp-site-edit] engine worker failed to start: ${f.message}`),b(f);return}let y=Date.now();for(;d.length>0&&y-d[0]>p;)d.shift();if(d.length>=c){l="failed",console.error(`[vcp-site-edit] engine worker stopped unexpectedly and exhausted ${c} restarts: ${f.message}`);return}d.push(y),l="restarting";for(let x of H.clients)x.close(ds,"site edit engine restarting");console.error(`[vcp-site-edit] engine worker stopped unexpectedly, restarting (${d.length}/${c}): ${f.message}`),U()},G=(f,y)=>{if(l==="failed"||l==="stopped"||l==="restarting")return Promise.reject(v(l));let x=w+=1;return new Promise((M,O)=>{I.set(x,{resolve:M,reject:O});let Nt={type:"call",id:x,method:f,args:y};g.postMessage(Nt)})},$=Object.fromEntries(Ke.map(f=>[f,(...y)=>G(f,y)])),H=Ne({server:e,path:s.path,sessionKey:s.sessionKey,host:s.host,allowedOrigins:s.allowedOrigins,engine:{...$,subscribe(f){return E.add(f),()=>E.delete(f)}}});return U(),{getHealth(){return l==="ready"&&m?m:{ok:!1,bridgePath:s.path,runtimeReady:!1,routesIndexed:m?.routesIndexed??0,sessionRequired:!!s.sessionKey}},stop(){if(l==="stopped")return;let f=l==="starting";l="stopped",H.stop(),f&&b(v("bridge stopped")),J(v("bridge stopped")),E.clear();let y=g,x={type:"stop"};y.postMessage(x);let M=setTimeout(()=>{y.terminate()},is);M.unref(),y.once("exit",()=>clearTimeout(M))},whenReady(){return C},eventListeners:E}}function us(e){if(!e.pathname.endsWith(".ts"))return e;let t=ts(es(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 ps(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var hs="next",fs="VCP_SITE_EDIT_ENGINE_IN_PROCESS",vt="127.0.0.1",gs=3e3,he="/__vcp/site-edit/bridge",Tt="/__vcp/site-edit/health",ms="probe",ys="render",wt="/_error",fe="/__vcp/site-edit/client/",Ss=`${fe}auto-bootstrap.js`,At='data-vcp-site-edit-bootstrap="true"',_s=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],bs="@vcp-dev/site-edit-engine/webpack-loader",Is=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Es=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ws=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 ro(e={},t={}){let n=t.process??process,s=t.createServer??Le.createServer,o=t.attachBridgeServer??(n.env[fs]==="1"?mt:Be),i=t.loadNext??ei,r=ee.resolve(e.projectRoot??process.cwd()),a=e.host??vt,u=e.port??ii(n.env.PORT)??gs,c=e.bridgePath??he,p=As(c),l=Gs(),g=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",h=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,d=await i(r),m=xs(r),w=d({dev:!0,dir:r,hostname:a,port:u,...Rs(m)}),I=w.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",_=e.snapshotId??n.env.VCP_SNAPSHOT_ID??si(r),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=b?.trim()?ee.resolve(b):void 0,v=null,J={launchId:ls(),pid:process.pid,snapshotId:_},N=s((H,f)=>{Ds({basePath:g,bridgePath:c,bridgeHealthPath:p,bridgeSessionKey:l,getBridgeHealth:()=>v?.getHealth()??Fs(c),launch:J,runRenderProbe:()=>Ks(w),handle:I,request:H,response:f}).catch(y=>{console.error(y),f.headersSent||(f.statusCode=500),f.end("site edit preview request failed")})}),U=null,B=null,G=()=>B||(le(()=>n.off("SIGINT",$)),le(()=>n.off("SIGTERM",$)),le(()=>U?.()),U=null,le(()=>v?.stop()),v=null,B=Promise.allSettled([ri(N),ai(()=>w.close())]).then(()=>{}),B),$=()=>{G()};try{return await w.prepare(),v=o(N,{...h?{tenantId:h}:{},siteId:E,snapshotId:_,projectRoot:r,basePath:g,host:a,port:u,path:c,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:H=>{J.snapshotId=H}}),U=vs({server:N,bridgePath:c,handleUpgrade:w.getUpgradeHandler()}),n.on("SIGINT",$),n.on("SIGTERM",$),await v.whenReady?.(),await oi(N,u,a),{bundler:m,close:G,host:a,port:ci(N,u),server:N}}catch(H){throw await G(),H}}function xs(e){let t=Cs(e);return t&&ks(t)?"webpack":"turbopack"}function Rs(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Cs(e){for(let t of _s){let n=ne(e,t);if(z(n))return q(n,"utf8")}return null}function ks(e){return e.includes(bs)?!0:Is.test(e)&&Es.some(t=>t.test(e))}function vs(e){let t=(n,s,o)=>{Ts(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 Ts(e,t){return new URL(e??"/","http://localhost").pathname===t}function As(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 Ps(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??Os()});return`<script type="module" ${At}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ss)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Os(){return{bridge:He("@vcp-dev/site-edit-bridge"),contracts:He("@vcp-dev/contracts"),engine:He("@vcp-dev/site-edit-engine")}}function He(e){let t=Rt(import.meta.url);try{let n=t.resolve(e),s=Ns(n,e);if(!s)return;let o=JSON.parse(q(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Ns(e,t){let n=ee.parse(e).root,s=te(e);for(;s&&s!==n;){let o=ne(s,"package.json");if(z(o))try{if(JSON.parse(q(o,"utf8")).name===t)return o}catch{return}s=te(s)}}function Bs(e,t){if(e.includes(At))return e;let n=Ps(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function ao(e,t=te(kt(import.meta.url)),n=z){return Pt(e,t,n)?.path??null}function Pt(e,t=te(kt(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(!ws.has(o))return null;let i=je(ti(t),o);if(Ct(t)!=="src")return{path:i,requiresTranspile:!1};let r=je(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Hs(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 Ms(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 Ms(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Ds({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:a,request:u,response:c}){if(Ls(u.url,e)){c.statusCode=404,c.end();return}if(await $s(u,c,n,o,i,r)||await Hs(u,c))return;let p=Ws(u),l=Vs(u),g=p||l?Js(c,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...i}}):()=>{};try{await a(u,c)}catch(h){throw g(),h}}function Ls(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 js(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 Ks(e){let t=new Le.IncomingMessage(new Et);t.method="GET",t.url=wt,t.headers={host:vt};let n=new Le.ServerResponse(t);n.assignSocket(new Et);try{return await e.renderToHTML(t,n,wt,{}),{verdict:"ok"}}catch(s){return js(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Us(e){return new URL(e??"/","http://localhost").searchParams.get(ms)===ys}async function $s(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=s(),u=Us(e.url)?await i():void 0,c={...a,launch:o,...u?{render:u}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function Fs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ws(e){return qs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Vs(e){return zs(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(fe)||n===he||n===Tt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function zs(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 Js(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),a=!1;s.flushHeaders=()=>{};let u=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let p=xt(e,c,t);return p!==c&&!e.headersSent&&e.removeHeader("content-length"),i(p),n.length=0,a=!0,!0};return s.write=(c,p,l)=>a?(c!==void 0&&i(Me(c,De(p))),pe(p),pe(l),!0):(c!==void 0&&(n.push(Me(c,De(p))),u()),pe(p),pe(l),!0),s.end=(c,p,l)=>{let g=typeof c=="function"?void 0:c;if(a)return s.write=i,s.end=r,s.flushHeaders=o,g===void 0?typeof c=="function"?r(c):typeof p=="function"?r(p):typeof l=="function"?r(l):r():typeof p=="function"?r(g,p):typeof l=="function"?r(g,p,l):r(g,p);g!==void 0&&n.push(Me(g,De(p))),s.write=i,s.end=r,s.flushHeaders=o;let h=Buffer.concat(n),d=xt(e,h,t);d!==h&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof p=="function"?p:typeof l=="function"?l:void 0;return m?r(d,m):r(d)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function xt(e,t,n){if(Qs(e,t))return Buffer.from(Bs(t.toString("utf8"),n));if(n.patchNextDevChunk&&Xs(e)){let s=t.toString("utf8"),o=Ys(s);if(o!==s)return Buffer.from(o)}return t}function Gs(){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 Xs(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 Ys(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(`
|
|
6
|
+
`);return new URL(`data:text/javascript,${encodeURIComponent(n)}`)}function ps(e){if(!e||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}var hs="next",fs="VCP_SITE_EDIT_ENGINE_IN_PROCESS",vt="127.0.0.1",gs=3e3,he="/__vcp/site-edit/bridge",Tt="/__vcp/site-edit/health",ms="probe",ys="render",wt="/_error",fe="/__vcp/site-edit/client/",Ss=`${fe}auto-bootstrap.js`,At='data-vcp-site-edit-bootstrap="true"',_s=["next.config.ts","next.config.mts","next.config.cts","next.config.js","next.config.mjs","next.config.cjs"],bs="@vcp-dev/site-edit-engine/webpack-loader",Is=/@vcp\/site-edit-engine\/(?:webpack-loader|site-edit-instrumentation-loader)/,Es=[/\bconfig\.webpack\s*=/,/\bwebpack\s*\([^)]*\)\s*\{/,/\bwebpack\s*:\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)?\s*=>/,/\bwebpack\s*:\s*(?:async\s+)?function\b/],ws=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 ro(e={},t={}){let n=t.process??process,s=t.createServer??Le.createServer,o=t.attachBridgeServer??(n.env[fs]==="1"?mt:Be),i=t.loadNext??ei,r=Z.resolve(e.projectRoot??process.cwd()),a=e.host??vt,u=e.port??ii(n.env.PORT)??gs,c=e.bridgePath??he,p=As(c),l=Gs(),g=e.basePath??n.env.VCP_SITE_PREVIEW_BASE_PATH??"/",h=(e.tenantId??n.env.VCP_TENANT_ID)?.trim()||void 0,d=await i(r),m=xs(r),w=d({dev:!0,dir:r,hostname:a,port:u,...Rs(m)}),I=w.getRequestHandler(),E=e.siteId??n.env.VCP_SITE_ID??"018f6f4d-a9b8-7120-8000-000000000120",_=e.snapshotId??n.env.VCP_SNAPSHOT_ID??si(r),b=e.historyRoot??n.env.VCP_SITE_EDIT_HISTORY_ROOT,C=b?.trim()?Z.resolve(b):void 0,v=null,J={launchId:ls(),pid:process.pid,snapshotId:_},N=s((H,f)=>{Ds({basePath:g,bridgePath:c,bridgeHealthPath:p,bridgeSessionKey:l,getBridgeHealth:()=>v?.getHealth()??Fs(c),launch:J,runRenderProbe:()=>Ks(w),handle:I,request:H,response:f}).catch(y=>{console.error(y),f.headersSent||(f.statusCode=500),f.end("site edit preview request failed")})}),U=null,B=null,G=()=>B||(le(()=>n.off("SIGINT",$)),le(()=>n.off("SIGTERM",$)),le(()=>U?.()),U=null,le(()=>v?.stop()),v=null,B=Promise.allSettled([ri(N),ai(()=>w.close())]).then(()=>{}),B),$=()=>{G()};try{return await w.prepare(),v=o(N,{...h?{tenantId:h}:{},siteId:E,snapshotId:_,projectRoot:r,basePath:g,host:a,port:u,path:c,sessionKey:l,...C?{historyRoot:C}:{},onSnapshotIdChanged:H=>{J.snapshotId=H}}),U=vs({server:N,bridgePath:c,handleUpgrade:w.getUpgradeHandler()}),n.on("SIGINT",$),n.on("SIGTERM",$),await v.whenReady?.(),await oi(N,u,a),{bundler:m,close:G,host:a,port:ci(N,u),server:N}}catch(H){throw await G(),H}}function xs(e){let t=Cs(e);return t&&ks(t)?"webpack":"turbopack"}function Rs(e){return e==="webpack"?{webpack:!0}:{turbopack:!0}}function Cs(e){for(let t of _s){let n=te(e,t);if(z(n))return q(n,"utf8")}return null}function ks(e){return e.includes(bs)?!0:Is.test(e)&&Es.some(t=>t.test(e))}function vs(e){let t=(n,s,o)=>{Ts(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 Ts(e,t){return new URL(e??"/","http://localhost").pathname===t}function As(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 Ps(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??Os()});return`<script type="module" ${At}>import { startSiteEditAutoBootstrap } from ${JSON.stringify(Ss)};void startSiteEditAutoBootstrap(window, ${t}).catch(() => undefined);</script>`}function Os(){return{bridge:He("@vcp-dev/site-edit-bridge"),contracts:He("@vcp-dev/contracts"),engine:He("@vcp-dev/site-edit-engine")}}function He(e){let t=Rt(import.meta.url);try{let n=t.resolve(e),s=Ns(n,e);if(!s)return;let o=JSON.parse(q(s,"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}function Ns(e,t){let n=Z.parse(e).root,s=ee(e);for(;s&&s!==n;){let o=te(s,"package.json");if(z(o))try{if(JSON.parse(q(o,"utf8")).name===t)return o}catch{return}s=ee(s)}}function Bs(e,t){if(e.includes(At))return e;let n=Ps(t),s=/<\/body\s*>/i.exec(e);return s?`${e.slice(0,s.index)}${n}${e.slice(s.index)}`:`${e}${n}`}function ao(e,t=ee(kt(import.meta.url)),n=z){return Pt(e,t,n)?.path??null}function Pt(e,t=ee(kt(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(!ws.has(o))return null;let i=je(ti(t),o);if(Ct(t)!=="src")return{path:i,requiresTranspile:!1};let r=je(t,o.replace(/\.js$/,".ts"));return n(r)?{path:r,requiresTranspile:!0}:{path:i,requiresTranspile:!1}}async function Hs(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 Ms(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 Ms(e){let t=await import("typescript");return t.transpileModule(e,{compilerOptions:{module:t.ModuleKind.ES2022,target:t.ScriptTarget.ES2022}}).outputText}async function Ds({basePath:e,bridgePath:t,bridgeHealthPath:n,bridgeSessionKey:s,getBridgeHealth:o,launch:i,runRenderProbe:r,handle:a,request:u,response:c}){if(Ls(u.url,e)){c.statusCode=404,c.end();return}if(await $s(u,c,n,o,i,r)||await Hs(u,c))return;let p=Ws(u),l=Vs(u),g=p||l?Js(c,{basePath:e,bridgePath:t,bridgeSessionKey:s,patchNextDevChunk:l,launch:{...i}}):()=>{};try{await a(u,c)}catch(h){throw g(),h}}function Ls(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 js(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 Ks(e){let t=new Le.IncomingMessage(new Et);t.method="GET",t.url=wt,t.headers={host:vt};let n=new Le.ServerResponse(t);n.assignSocket(new Et);try{return await e.renderToHTML(t,n,wt,{}),{verdict:"ok"}}catch(s){return js(s)}finally{try{let s=n.socket;s&&(n.detachSocket(s),s.destroy())}catch{}}}function Us(e){return new URL(e??"/","http://localhost").searchParams.get(ms)===ys}async function $s(e,t,n,s,o,i){if(e.method!=="GET"||new URL(e.url??"/","http://localhost").pathname!==n)return!1;let a=s(),u=Us(e.url)?await i():void 0,c={...a,launch:o,...u?{render:u}:{}};return t.writeHead(a.ok?200:503,{"cache-control":"no-store","content-type":"application/json; charset=utf-8"}),t.end(JSON.stringify(c)),!0}function Fs(e){return{ok:!1,bridgePath:e,runtimeReady:!1,routesIndexed:0,sessionRequired:!0}}function Ws(e){return qs(e)?(e.headers["accept-encoding"]="identity",!0):!1}function Vs(e){return zs(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(fe)||n===he||n===Tt)return!1;let s=e.headers.accept??"";return s===""||s.includes("text/html")}function zs(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 Js(e,t){let n=[],s=e,o=s.flushHeaders.bind(e),i=s.write.bind(e),r=s.end.bind(e),a=!1;s.flushHeaders=()=>{};let u=()=>{if(t.patchNextDevChunk||a)return!1;let c=Buffer.concat(n);if(!/<body\b[^>]*>/iu.test(c.toString("utf8")))return!1;let p=xt(e,c,t);return p!==c&&!e.headersSent&&e.removeHeader("content-length"),i(p),n.length=0,a=!0,!0};return s.write=(c,p,l)=>a?(c!==void 0&&i(Me(c,De(p))),pe(p),pe(l),!0):(c!==void 0&&(n.push(Me(c,De(p))),u()),pe(p),pe(l),!0),s.end=(c,p,l)=>{let g=typeof c=="function"?void 0:c;if(a)return s.write=i,s.end=r,s.flushHeaders=o,g===void 0?typeof c=="function"?r(c):typeof p=="function"?r(p):typeof l=="function"?r(l):r():typeof p=="function"?r(g,p):typeof l=="function"?r(g,p,l):r(g,p);g!==void 0&&n.push(Me(g,De(p))),s.write=i,s.end=r,s.flushHeaders=o;let h=Buffer.concat(n),d=xt(e,h,t);d!==h&&!e.headersSent&&e.removeHeader("content-length");let m=typeof c=="function"?c:typeof p=="function"?p:typeof l=="function"?l:void 0;return m?r(d,m):r(d)},()=>{s.write=i,s.end=r,s.flushHeaders=o}}function xt(e,t,n){if(Qs(e,t))return Buffer.from(Bs(t.toString("utf8"),n));if(n.patchNextDevChunk&&Xs(e)){let s=t.toString("utf8"),o=Ys(s);if(o!==s)return Buffer.from(o)}return t}function Gs(){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 Xs(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 Ys(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])=>Zs(n,s,o),e)}function Zs(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 Me(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 ei(e){let n=Rt(
|
|
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])=>Zs(n,s,o),e)}function Zs(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 Me(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 ei(e){let n=Rt(te(e,"package.json"))(hs);return n.default??n}function ti(e){return Ct(e)!=="src"?e:je(ni(e),"dist")}function ni(e){return Ot(e)?Z.posix.dirname(e):ee(e)}function je(e,t){return Ot(e)?Z.posix.join(e,t):te(e,t)}function Ot(e){return e.includes("/")&&!e.includes("\\")}function si(e){let t=te(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 ii(e){if(!e)return null;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function oi(e,t,n){return new Promise((s,o)=>{e.once("error",o),e.listen(t,n,()=>{e.off("error",o),s()})})}function ri(e){return new Promise(t=>{e.close(()=>t())})}function le(e){try{e()}catch{}}function ai(e){try{return e()}catch(t){return Promise.reject(t)}}function ci(e,t){let n=e.address();return typeof n=="object"&&n?n.port:t}export{vs as attachNextDevUpgradeHandler,Be as attachSiteEditBridgeServerInWorker,js as classifySiteEditRenderProbeError,Ps as createSiteEditAutoBootstrapHtmlSnippet,Bs as injectSiteEditAutoBootstrap,Us as isSiteEditRenderProbeRequested,Ys as patchNextFirefoxDevChunk,Vs as prepareFirefoxNextDevChunkPatchRequest,Ws as prepareSiteEditHtmlInjectionRequest,As as resolveSiteEditBridgeHealthPath,Pt as resolveSiteEditClientAsset,ao as resolveSiteEditClientAssetPath,xs as resolveSiteEditNextDevBundler,Ks as runSiteEditRenderProbe,ro as startSiteEditNextDevServer,Ms as transpileSiteEditClientSource};
|
|
@@ -32,8 +32,7 @@ export async function readVerifiedPortableSnapshot(input) {
|
|
|
32
32
|
return null;
|
|
33
33
|
const envelope = JSON.parse(await fs.readFile(proofPath, "utf8"));
|
|
34
34
|
if (!isRecord(envelope) ||
|
|
35
|
-
!
|
|
36
|
-
exactKeys(envelope, ["payload", "signature"])) ||
|
|
35
|
+
!exactKeys(envelope, ["payload"]) ||
|
|
37
36
|
!isBase64Url(envelope.payload, MAX_PROOF_BYTES))
|
|
38
37
|
return null;
|
|
39
38
|
const payloadBytes = Buffer.from(envelope.payload, "base64url");
|
package/dist/protocol.js
CHANGED
|
@@ -580,23 +580,16 @@ function isPortableCmsSchemaEnvelopes(value) {
|
|
|
580
580
|
return false;
|
|
581
581
|
const proof = descriptor.value;
|
|
582
582
|
if (!isRecord(proof) ||
|
|
583
|
-
!Reflect.ownKeys(proof).every((key) => typeof key === "string" &&
|
|
583
|
+
!Reflect.ownKeys(proof).every((key) => typeof key === "string" && key === "payload"))
|
|
584
584
|
return false;
|
|
585
585
|
const payload = Object.getOwnPropertyDescriptor(proof, "payload");
|
|
586
|
-
|
|
587
|
-
if (!payload ||
|
|
588
|
-
!("value" in payload) ||
|
|
589
|
-
!signature ||
|
|
590
|
-
!("value" in signature))
|
|
586
|
+
if (!payload || !("value" in payload))
|
|
591
587
|
return false;
|
|
592
588
|
if (typeof payload.value !== "string" ||
|
|
593
589
|
payload.value.length < 1 ||
|
|
594
590
|
payload.value.length > 262_144 ||
|
|
595
591
|
!/^[A-Za-z0-9_-]+$/u.test(payload.value))
|
|
596
592
|
return false;
|
|
597
|
-
if (typeof signature.value !== "string" ||
|
|
598
|
-
!/^[A-Za-z0-9_-]{86}$/u.test(signature.value))
|
|
599
|
-
return false;
|
|
600
593
|
}
|
|
601
594
|
return true;
|
|
602
595
|
}
|