@vcp-dev/site-edit-engine 0.10.34 → 0.10.36

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -11,4 +11,4 @@ import*as ey from"@babel/parser";import*as Xn from"@babel/types";import*as Zt fr
11
11
  `||m==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(m==="\\")i=!0;else if(m===o)o=null;else if(n==="css"&&(m===`
12
12
  `||m==="\r"))return Sr(t,`Unterminated string literal in ${t}.`);l=m===`
13
13
  `||m==="\r";continue}if(m==="/"&&u==="*"){s=!0,f+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&u==="/"){a=!0,f+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:f}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let g=m==="}"?"{":m===")"?"(":"[",h=r.pop();if(!h||h.char!==g)return Sr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
14
- `||m==="\r"}if(s)return Sr(t,`Unterminated block comment in ${t}.`);if(o)return Sr(t,`Unterminated string literal in ${t}.`);if(c)return Sr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?Sr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function Sr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function ks(e){let t="idle",n=e.fileSystem??$w(),r=hd(),o=ih({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?of(e.historyStore):Kw()),d=rh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=C();function E(p){return(Es.isAbsolute(p)?Es.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,b){let x=Es.posix.dirname(p),I=b.replace(/\.(?:tsx?|jsx?)$/i,""),P=Es.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function v(p,b){return p.startLine===b.startLine&&p.startColumn===b.startColumn&&p.endLine===b.endLine&&p.endColumn===b.endColumn}async function C(){let p=e.historyStore;if(p)try{let b=await p.readTransactionJournal();if(!b)return;let x=await p.readIndex(),I=await Promise.all(b.files.map(async F=>await n.exists(F.path)?Se(await n.readFile(F.path)):null));if(hh({journal:b,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(b.transactionId);let F=await p.readStatus();F.recoveryRequired||(await p.cleanupTmp(),F=await p.readStatus()),g=F.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${b.transactionId} at phase ${b.phase}`),g=!0}catch(b){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(b)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let b=Eh(p.context,p.entryFile);i.set(p.key,b),A(b,b.dependencyFiles)}function A(p,b){let x=new Set(b);R(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function R(p){for(let b of p.dependencyFiles){let x=s.get(b);x&&(x.delete(p.key),x.size===0&&s.delete(b))}p.dependencyFiles.clear()}function T(p){let b=new Set;for(let x of p)for(let I of s.get(x)??[])b.add(I);return b}function O(p){for(let b of p)if(!s.has(b))return!1;return!0}async function M(p,b,x,I,P){let F=new Map,L=vg(P.values()),G=new Map,X=typeof n.exists=="function"?B=>n.exists(B):async()=>!1;for(let[B,j]of p.elements){let ie=b.nodes.get(B);if(!ie)continue;let te=x.get(j.sourceFile)??I.get(j.sourceFile),Fe=new Map,ye=new Map,we=new Map,Ne=[];for(let Ce of j.textSegments){if(!te){Fe.set(Ce.index,null);continue}let Er=await kg({file:j.sourceFile,source:te,segment:Ce,readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Cl({file:j.sourceFile,source:te,target:{kind:"text-segment",segment:Ce},readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),dt=Qw(Er);Fe.set(Ce.index,dt),ye.set(Ce.index,Er),we.set(Ce.index,Ze),Ne.push({editable:Ce.editable,source:dt})}let _=new Map,D=new Map;if(te)for(let Ce of j.attributes??[]){let Er=await xr({file:j.sourceFile,source:te,sourceRange:Ce.sourceRange,expression:Ce.source?.expression??Ce.value,sourceInfo:Ce.source,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Fg({element:j,file:j.sourceFile,source:te,propertyName:Ce.name,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L});D.set(Ce.name,Ze),_.set(Ce.name,Er)}let pe=Ug(qw(ie.writeTarget),Ne),fe=_g({key:B,element:j,graph:p,provenances:we}),Ie=Wg(j),De=te?await Rm({element:j,graph:p,file:j.sourceFile,source:te,readFile:Ce=>n.readFile(Ce),exists:X,fileCache:G}):void 0,Xe=p.regions.find(Ce=>Ce.kind==="conditional-region"&&Ce.childKeys.includes(B)),mn,_s=Xe?.sourceCandidates?.[0];if(te&&Xe&&_s?.kind==="conditional-branch"){let Ce=await Cl({file:j.sourceFile,source:te,target:{kind:"conditional-branch",candidate:_s},readFile:Ze=>n.readFile(Ze),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:dt,capabilities:it})=>({sourceType:Ze,adapterId:dt,capabilities:it})),functionCallContracts:e.functionCallContracts,fileCache:L});mn={currentBranch:Xe.childKeys.indexOf(B)<=0?"then":"else",availableBranches:Xe.childKeys.length>1?["then","else"]:["then"],conditionExpression:_s.conditionExpression,provenance:{finalSource:Ce.finalSource?{kind:Ce.finalSource.kind,file:Ce.finalSource.file,displayPath:Ce.finalSource.displayPath}:null,chain:Ce.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Ce.confidence,editMode:Ce.editMode,diagnostics:Ce.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}F.set(B,{textSources:Fe,textTargets:ye,elementPropertyTargets:_,propertyProvenances:D,isRepeat:xN(B,p),provenances:we,writeTarget:pe,componentSemantic:fe,styleSource:Ie,conditional:mn,dynamicData:De})}return F}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(p,b){let x=o.initialVersions.get(p.key)??0;for(let I of b.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function Re(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Q(p){try{return Re(o.resolveSelector(p.composition).key)}catch{return 0}}async function de(p,b,x=n,I=1){let P=await Cd(p,b,F=>x.readFile(F),F=>x.exists(F),{additionalEntries:await Gt(p,x),version:I});if(P.diagnostics.length>0)throw new Ro(P.diagnostics);return P}async function Te(p,b,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??Ll(f,[]),{graph:F,allSources:L,parsedModules:G,entryModule:X}=await de(I.entryFile,b,n,I.graph?.version??1),B=new Map;for(let Xe of L.keys())B.set(Xe,U(Xe));let j=Math.max(ee(I,B),x.minimumVersion??0);x.changed&&j<=(I.graph?.version??0)&&(j=(I.graph?.version??0)+1),F.version=j;for(let[Xe,mn]of L)Bl(P,Xe,mn,xh);let ie=await Yt(I.composition,I.entryFile,L,P);F.routeId=I.routeId,F.composition=I.composition;let te=Gg(F),Fe=dd(te,F),ye=await M(F,te,L,P,G),we=_h(F,Fe,ye),Ne=Fh(ye),_=ch(Bg(F,te,Fe,{canUpdateTextByKey:we,dynamicDataSummaryByKey:Ne}),F,ye),D=Kf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:j,source:b,ast:X?.ast}),pe=Uf(D);D.ok&&oN(_,F,D.projection,G);let fe={..._,composition:I.composition,...ie?{styleContext:ie}:{},pageComposition:pe},Ie=new Set([I.entryFile,...L.keys()]);if(ie){Ie.add(ie.entryCss.path);for(let Xe of ie.stylesheets)Ie.add(Xe.path)}let De={...I,dependencyFiles:Ie,graph:F,topology:te,capabilities:Fe,document:fe,pageComposition:pe,pageCompositionProjection:D.projection,pagePlacementByKey:D.ok?D.projection.placementByKey:null,pagePlacementUnitByKey:D.ok?D.projection.placementUnitByKey:null,pageUnitByKey:D.ok?D.projection.unitByKey:null,pagePlacementsByUnitKey:D.ok?D.projection.placementsByUnitKey:null,documentIndex:ah(fe),detailProjections:ye,fileVersions:B,styleContext:ie};if(x.publish===!1)return De;br(f,P);for(let Xe of P.keys())m.delete(Xe);return A(I,Ie),Object.assign(I,De),I}async function Gt(p,b=n){let x=[];for(let I of fN(p))typeof b.exists=="function"&&await b.exists(I)&&x.push({file:I,source:await b.readFile(I)});return x}async function Yt(p,b,x,I){let P=[];for(let[B,j]of x){if(jl(B)){P.push(B);continue}for(let ie of mN(j)){let te=wh(B,ie);te&&P.push(te)}}if(!P.length){for(let B of pN(b))if(await Vl(B)){P.push(B);break}}let F=new Map,L=yN(P).slice(0,yh);for(;L.length>0&&F.size<yh;){let B=L.shift();if(F.has(B)||!jl(B))continue;let j=await Th(B,I);if(j!==null){F.set(B,{path:B,content:j});for(let ie of gN(j)){let te=wh(B,ie);te&&!F.has(te)&&!L.includes(te)&&L.push(te)}}}let G=[...F.values()].map(B=>({...B,hash:Se(B.content)})),X=G[0];return X?{composition:p,revision:Se(JSON.stringify(G.map(({path:B,hash:j})=>({path:B,hash:j})))),entryCss:X,stylesheets:G.slice(1)}:null}async function Th(p,b){let x=b.get(p);if(x!==void 0)return x;if(!await Vl(p))return null;let I=await n.readFile(p);return Bl(b,p,I,xh),I}async function Vl(p){return typeof n.exists=="function"?n.exists(p):!1}function Fh(p){let b=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&b.set(x,Lm(I.dynamicData.bindings));return b}function _h(p,b,x){let I=new Map;for(let[P,F]of p.elements){if(!b.get(P)?.canUpdateText){I.set(P,!1);continue}let G=x.get(P),X=F.textSegments.some(B=>{if(!B.editable)return!1;let j=G?.provenances.get(B.index)??null;return!j||Oh(j)});I.set(P,X)}return I}function Oh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Po(p,b={}){let x=[...new Set(p)],I=b.affectedCompositionKeys!==void 0,P=I?new Set(b.affectedCompositionKeys):T(x);if(!I&&(P.size===0||!O(x)))for(let X of i.values())Kl(X,x)&&P.add(X.key);let F=!I&&P.size===0&&x.some(Rh),L=b.publish===!1?Ll(f,x):void 0,G={rebuiltRoutes:[],failedRoutes:[],...b.publish===!1?{candidateRouteStates:[],candidateSourceCache:L}:{}};for(let X of i.values())if(!(b.excludedCompositionKeys?.has(X.key)||!(P.has(X.key)||F)))try{let j=!!X.graph,ie=await n.readFile(X.entryFile),te=await Te(X.key,ie,{...b,...L?{sourceCache:L}:{}});te?.graph&&(G.rebuiltRoutes.push({documentChanged:j,composition:X.composition,routeId:X.routeId,version:te.graph.version}),G.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:te}))}catch(j){G.failedRoutes.push({...mh(X.routeId,j),composition:X.composition})}return G}function Vn(p){let b=[...new Set(p)],x=T(b);if(x.size>0&&O(b))return[...x];for(let I of i.values())Kl(I,b)&&x.add(I.key);return[...x]}function Mh(p){let b=new Set(Vn(p));return o.entries.filter(x=>b.has(x.key)).map(x=>x.context)}function Dh(p){return[...new Set(Vn(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Lh(p,b){let x=new Set(Vn(b)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(F=>o.resolveContext(F).key))].some(F=>!x.has(F)))throw new Error("History provenance does not match the affected composition index.");return x}function Bh(p,b){let x=p.composition??p.provenance?.initiatingComposition;if(x){let F=o.resolveContext(x);return{context:F.context,key:F.key}}let I=[...new Set(Vn(b))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function ws(p,b){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of b.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of b.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Kl(p,b){return b.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Ul(p){for(let b of p)a.add(b);c||N()||(c=(async()=>{t="building";let b=!1;try{for(;a.size>0;){if(N())return;await jh();let x=[...a];a.clear();let I=await Jl(x);if(I.length===0)continue;let P=Vn(I);for(let G of P){let X=i.get(G)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:F,failedRoutes:L}=await Po(I,{changed:!0});for(let{documentChanged:G,composition:X,version:B}of F)r.emit({type:"graph-ready",composition:X,version:B}),G&&r.emit({type:"document-changed",composition:X,version:B});for(let{composition:G,message:X}of L)b=!0,r.emit({type:"graph-error",composition:G,message:X})}}finally{c=null,t!=="disposed"&&(t=!b&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Ul([])}})())}async function jh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Jl(p){let b=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),b.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),b.push(x))}catch(P){if(!rN(P))try{if(await n.exists(x))continue}catch{continue}m.add(x),b.push(x)}}return b}function Xl(p){gh(f,p);for(let b of p)b.exists===!1?m.add(b.file):m.delete(b.file)}function zl(p){m.clear();for(let b of p)m.add(b)}async function Hl(p){let b=await Jl(p);if(b.length===0)return;let x=Vn(b);for(let F of x){let L=i.get(F)?.composition;L&&r.emit({type:"graph-invalidated",composition:L})}let{rebuiltRoutes:I,failedRoutes:P}=await Po(b,{changed:!0});for(let{documentChanged:F,composition:L,version:G}of I)r.emit({type:"graph-ready",composition:L,version:G}),F&&r.emit({type:"document-changed",composition:L,version:G});for(let{composition:F,message:L}of P)r.emit({type:"graph-error",composition:F,message:L})}async function $h(p,b){let x=Jn(p,b);if(!x?.graph)return;let I=ot(p)??p,P=x.graph.elements.get(I);P&&await Hl([P.sourceFile])}async function Wl(p){let b=new Set;if(p.target.kind==="node"){let x=Jn(p.target.key,p.composition),I=ot(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&b.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="source-file")b.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)b.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=Jn(I,p.composition),F=ot(I)??I,L=P?.graph?.elements.get(F);L&&b.add(L.sourceFile)}}await Hl(b)}async function Vh(p){if(p.params.kind!=="source-edit")return Ns(p,"invalid-params","source-edit requires source-edit params");for(let b of p.params.edits){let x=nN(b);if(!x.ok)return Ns(p,x.errorCode,x.message,x.details)}u+=1;try{let b=await zh(p.params.edits);if(!b.ok)return Ns(p,b.errorCode,b.message,b.details);await Wl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Un({request:p,filePlan:x})}catch(b){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(b)}}}finally{u-=1}}async function Kh(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ce(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let b=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!b.ok)return ce(p,V.MATERIALIZATION_REJECTED,b.message);let x=await Wa({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):ce(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(b){return ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Uh(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ce(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ce(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let b=Nh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(b.truncated)return ce(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:b.truncated.reasons});let x=b.files.filter(({path:L})=>/\.(?:tsx?|jsx?)$/.test(L)),I=Object.fromEntries(await Promise.all(x.map(async({path:L})=>[L,await n.readFile(L)]))),P=fp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return ce(p,P.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,P.message);let F=await Promise.all(P.edits.map(async L=>({...L,baseContentHash:Se(await n.readFile(L.file))})));return Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:F},output:{kind:"delete-page-source",deleted_files:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(b){return ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Jh(p,b){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ce(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ce(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return ce(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=p.params.kind==="insert-child"?p.params.position:null,L=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map(B=>({path:B.pathTemplate,content:B.content})),exists:B=>n.exists(B),readFile:B=>n.readFile(B)});if(!L.ok)return ce(p,V.MATERIALIZATION_REJECTED,L.message);let G=await Vw(n,Object.keys(P.projectDependencies??{})),X=await Rf({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(B=>({pathTemplate:B.pathTemplate})),exists:B=>n.exists(B),availableHostDependencies:G,commit:async B=>{let j=await n.readFile(b.entryFile),ie=b.document,te=b.pageCompositionProjection;if(!ie||ie.pageComposition?.status!=="supported"||ie.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==ie.version)return{ok:!0,data:ce(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Fe=B.entry.path,ye=qh(B.instanceName),we,Ne=[];if(p.params.kind==="insert-child"){if(!F||!("kind"in F)||F.kind!=="page-composition")return{ok:!0,data:ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let fe=tc({routeId:b.routeId,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementKey:F.placementKey,component:{source:Fe,exportName:B.entry.export.kind==="default"?"default":B.entry.export.name,localName:ye}});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"insert-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"insert",jsx:Ie.node.jsx,placement:Ie.placement,replaceOriginal:Ie.replaceOriginal}});break;case"insert-child":De=Wn({source:j,locator:Ie.parentLocator,node:Ie.node,placement:Ie.placement,...Ie.anchorLocator?{anchorLocator:Ie.anchorLocator}:{}});break;default:De={ok:!1,source:j,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ie)}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};we=De.source}else{let fe=nc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"replace-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":De=Qo({source:j,locator:Ie.locator,node:{jsx:`<${ye} />`}});break;default:De={ok:!1,source:j,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ie.kind}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};let Xe=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:j,mutatedSource:De.source});we=Xe.source,Ne=await Promise.all(Xe.files.map(async mn=>({operation:"delete",file:mn,baseContentHash:Se(await n.readFile(mn))})))}let _=Zn({source:we,moduleSpecifier:y(b.entryFile,Fe),imports:B.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:B.entry.export.name,local:ye}]});if(!_.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,_.diagnostic.message)};let D=B.files.map(fe=>({operation:"create-only",file:fe.path,content:fe.content})),pe=[{operation:"upsert",file:b.entryFile,content:_.source,baseContentHash:Se(j)},...D,...Ne];u+=1;try{let fe=await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!fe.ok&&fe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:fe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:fe}}finally{u-=1}}});return X.ok?X.data:ce(p,X.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,X.error.message,{materializationCode:X.error.code})}async function Xh(p,b){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(b.entryFile),F=nc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!F.ok)return ce(p,Fs(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let L=F.plan.rewriteStep,G;switch(L.kind){case"move-node":G=Gn({source:P,locator:L.locator,targetParentLocator:L.targetParentLocator,placement:L.placement,...L.anchorLocator?{anchorLocator:L.anchorLocator}:{}});break;case"remove-node":G=Hn({source:P,locator:L.locator});break;case"remove-root-expression":G=Oi({source:P,locator:L.locator,expectedSourceHash:L.sourceHash,action:{kind:"remove"}});break;default:G={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${L.kind}`}}}if(!G.ok)return ce(p,V.AST_PARSE_ERROR,G.diagnostic.message);let X=G.source,B=[];if(p.kind==="remove-node"){let ie=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:X});X=ie.source,B=await Promise.all(ie.files.map(async te=>({operation:"delete",file:te,baseContentHash:Se(await n.readFile(te))})))}let j=[{operation:"upsert",file:b.entryFile,content:X,baseContentHash:Se(P)},...B];u+=1;try{return await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:j}})}finally{u-=1}}async function Gl(p){let b={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return b;let F=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!F)return b;let L=[...x.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&v(_.sourceRange,F));if(!L?.importedFrom||!L.exportName)return b;let G=E(L.importedFrom),X="components/site/generated/";if(!G.startsWith(X))return b;let B=G.slice(X.length).split("/")[0];if(!B||!/-[0-9a-f]{8}$/i.test(B))return b;let j=`${X}${B}`;if([...x.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===G).length!==1)return b;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),Fe=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return b;let ye=Fe.map(({path:_})=>_).filter(_=>_===j||_.startsWith(`${j}/`));if(ye.length===0||!ye.includes(G))return b;for(let{path:_}of Fe)if(!(_===p.routeState.entryFile||_===j||_.startsWith(`${j}/`)))try{if((await n.readFile(_)).includes(B))return b}catch{return b}let we=y(p.routeState.entryFile,G),Ne=Qn({source:p.mutatedSource,moduleSpecifier:we,imports:L.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:L.exportName}]});return Ne.ok?Ne.source.includes(B)?{source:Ne.source,files:[]}:{source:Ne.source,files:ye.sort((_,D)=>_.localeCompare(D))}:b}async function zh(p){if(n.getFileInfo){for(let I of p)if(await n.exists(I.path)&&await n.getFileInfo(I.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${I.path}`,details:{path:I.path}}}for(let I of p){if(I.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(I.path))continue;let P=await n.exists(I.path)?await Ys(n,I.path):null;if(P?.ok){let F=Aw(P.content,I.content);if(!F.ok)return{ok:!1,errorCode:"invalid-params",message:F.message,details:{path:I.path,code:F.code}}}}let b=Hh(p);if(b.length===0)return{ok:!0};let x=eN(n,p);try{for(let I of b){let P=i.get(I);P&&await de(P.entryFile,await x.readFile(P.entryFile),x)}}catch(I){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(I)}`,details:{compositionKeys:b}}}return{ok:!0}}function Hh(p){return p.map(x=>x.path).some(Rh)?[...i.keys()]:[]}function Ns(p,b,x,I){let P=wo(b);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function Ps(p){let b=[];for(let x of new Set(p))b.push(await Wh(x));return b}async function Wh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,U(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,U(p)),exists:!0,sha256:Se(x)}}async function Yl(p,b,x,I){if(!e.historyStore)return null;let P=new Map(b.map(G=>[G.file,G])),F=new Map(x.map(G=>[G.file,G])),L=[...new Set([...P.keys(),...F.keys()])].sort().map(G=>{let X=P.get(G),B=F.get(G);return{path:G,preDigest:X?.exists===!1||!X?null:Se(X.content),postDigest:B?.exists===!1||!B?null:Se(B.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:L}}async function Zl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Kn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function As(p,b){let x=[];try{for(let I of p)await Ql(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await Gh(b.filter(F=>x.includes(F.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${qe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Yh)}}async function Ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Gh(p){let b=[];for(let x of p)try{await Ql(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{b.push(x.file)}return b.length===0?{ok:!0}:{ok:!1,failedFiles:b}}function Yh(p){let b=p.exists!==!1;return{file:p.file,content:b?p.content:"",version:p.version,exists:b,...b?{sha256:Se(p.content)}:{}}}async function Un(p){return h.runExclusive(()=>Zh(p))}async function Zh(p){let b=p.filePlan.edits.map(_=>_.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Dh(b)},F=await Ps(b),L=new Map(F.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),G=eu(),X=new Map(f),B=new Set(m),j=new Set([...i.values()].filter(_=>p.filePlan.edits.some(D=>D.operation==="delete"&&D.file===_.entryFile)).map(_=>_.key)),ie=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:Se(_.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Fe=null,ye=!1,we=await ys({overlay:L,exists:_=>n.exists(_),plan:te,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:F,postSnapshots:ie,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),D=_?.historyTransition?_.historyTransition:e.historyStore?jw(await e.historyStore.readIndex()):null;if(e.historyStore&&!D)throw new Error("Durable history did not provide an exact index transition.");return Fe=await Yl(p.request.id,F,ie,D),Fe=await Zl(Fe),{history:_,historyTransition:D}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new vs(_);return{postSnapshots:await Ps(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:D})=>{let pe=await Po(D.affectedFiles,{changed:!0,minimumVersion:D.internalResultVersion,publish:!1,excludedCompositionKeys:j});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(G,pe.candidateRouteStates??[]),Ie=tu(fe,x.key);return{..._,rebuild:pe,routeSnapshots:fe,resultVersion:Ie,...vh(p.selectionRef,fe.map(De=>De.state.document))?{selectionRef:vh(p.selectionRef,fe.map(De=>De.state.document))}:{}}},publishCandidate:async({candidate:_,history:D,receipt:pe})=>{D?.history&&(await l.publishPrepared(D.history),ye=!0);let fe=_.resultVersion??pe.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:fe,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:D})=>{_.routeSnapshots&&Ao(_.routeSnapshots),_.rebuild?.candidateSourceCache&&br(f,_.rebuild.candidateSourceCache),Xl(D.postSnapshots)},finalizeCandidate:async()=>{await Kn(Fe);for(let _ of j)i.delete(_)},emitCommitted:({candidate:_,published:D})=>{ws(D,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:D})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(D){let pe=await As(F,D.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Ao(G),br(f,X),zl(B),_?.history&&await l.discardPrepared?.(_.history),await Kn(Fe)}});if(we.ok)return we.published;if(we.stage==="precheck"||we.stage==="build")try{await Kn(Fe)}catch(_){let D=await To(qe(_));return ce(p.request,D,"Unable to clear an uncommitted transaction journal.")}if(we.recoveryRequired){let _=await To(we.reason);return ce(p.request,_===V.RECOVERY_PERSIST_FAILED?_:V.ROLLBACK_FAILED,we.reason)}let Ne=we.error;return Ne instanceof vs?{...ce(p.request,wo(Ne.result.errorCode),Ne.result.reason),...Ne.result.affectedFiles?{affectedFiles:Ne.result.affectedFiles}:{}}:Ne instanceof jn?ce(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Dl(Ne.failedRoutes)}`,{failedRoutes:Ne.failedRoutes}):ce(p.request,ou(we.stage),qe(Ne))}async function ql(p){return h.runExclusive(async()=>{let b=p==="undo"?await l.prepareUndo():await l.prepareRedo();return b?Qh(p,b):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Qh(p,b){let x=b.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,F=I.map(D=>D.file),{context:L,key:G}=Bh(x,F),X=await Ps(F),B=new Map(X.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),j=Re(G),ie=eu(),te=new Map(f),Fe=new Set(m),ye=null,we=!1,Ne,_=await ys({overlay:B,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(D=>D.exists===!1?{kind:"delete",path:D.file}:{kind:"upsert",path:D.file,content:D.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Yl(`${p}:${x.operationId}`,X,I,b.historyTransition),ye=await Zl(ye),b),reverify:async()=>{},writeCandidate:async()=>{let D=await As(I,P);if(!D.ok)throw new Error(D.reason);return{snapshots:D.snapshots}},validateCandidate:async({candidate:D})=>{Ne=Lh(x,F);let pe=await Po(F,{changed:!0,minimumVersion:j+1,publish:!1,affectedCompositionKeys:Ne});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(ie,pe.candidateRouteStates??[]),Ie=tu(fe,G);return{...D,rebuild:pe,routeSnapshots:fe,resultVersion:Ie}},publishCandidate:async({candidate:D,history:pe})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),we=!0;let fe=D.resultVersion??j+1;return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:fe,affectedFiles:F,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:D,receipt:pe})=>{D.routeSnapshots&&Ao(D.routeSnapshots),D.rebuild?.candidateSourceCache&&br(f,D.rebuild.candidateSourceCache),Xl(pe.snapshots)},finalizeCandidate:async()=>{await Kn(ye)},emitCommitted:({candidate:D,published:pe})=>ws(pe,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:D,receipt:pe})=>{if(we)throw new Error("history cursor was published before transaction finalization failed");if(pe){let fe=await As(P,pe.snapshots);if(!fe.ok)throw new Error(fe.reason)}Ao(ie),br(f,te),zl(Fe),D&&await l.discardPrepared?.(D),await Kn(ye)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Kn(ye)}catch(D){let pe=await To(qe(D));return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let D=await To(_.reason);return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:D===V.RECOVERY_PERSIST_FAILED?D:V.ROLLBACK_FAILED,message:_.reason}}}return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:_.error instanceof jn?V.ROUTE_REBUILD_FAILED:ou(_.stage),message:qe(_.error),..._.error instanceof jn?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function eu(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function tu(p,b){return p.find(I=>I.key===b)?.state.graph?.version??o.initialVersions.get(b)??0}function nu(p,b){let x=new Map(p.map(I=>[I.key,I]));for(let I of b)x.set(I.key,I);return[...x.values()]}function Ao(p){for(let b of i.values())R(b);for(let b of p){let x={...b.state,dependencyFiles:new Set(b.state.dependencyFiles),fileVersions:new Map(b.state.fileVersions)};i.set(b.key,x),A(x,x.dependencyFiles)}}async function Ts(p){let b=i.get(p);if(!b)throw new Error(`Composition not found: ${p}`);if(b.graph)return;let x=await n.readFile(b.entryFile);await Te(p,x)}function Jn(p,b){let x=i.get(o.resolveSelector(b).key)??null;return!x||!ru(x,p)?null:x}function ru(p,b){if(p.documentIndex?.entriesByKey.has(b)||p.graph?.elements.has(b))return!0;let x=ot(b);return x&&x!==b?p.graph?.elements.has(x)===!0:!1}function ce(p,b,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:b,message:x,...I?{details:I}:{}}}}function ou(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function To(p){if(g=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function qh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Fs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function iu(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ts(x.key),x):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ts(x.key),x):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ce(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let b=i.get(o.resolveSelector(p.composition).key)??null;return b?(b.graph||await Ts(b.key),ru(b,p.target.key)?b:ce(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,b){let x=o.register({context:p,entryFile:b}),I=i.get(x.key);if(I?.entryFile===b)return;I&&R(I);let P=Eh(x.context,b);i.set(x.key,P),A(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);x&&(R(x),i.delete(b.key),o.unregister(b.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:b.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await Te(b.key,I),t="ready",r.emit({type:"graph-ready",composition:b.context,version:i.get(b.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:b.context,message:qe(I)}),I}}},getDocument(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(!x.document)throw new Error(`Composition not built: ${b.key}`);return x.document},async getHistoryStatus(){await S;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,b,x){let I=Jn(p,b),P=ot(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let F=I.detailProjections.get(P);if(F){let L=I.graph.elements.get(P);if(!L)throw new Error(`Key not found: ${p}`);let G=zw(p,P,x),X=new Map;if(F.isRepeat&&G?.instanceIndex!==void 0)for(let ie of L.attributes??[])X.set(ie.name,dl({file:L.sourceFile,source:f.get(L.sourceFile)??"",element:L,propertyName:ie.name,selectionRef:G,graph:I.graph,sources:f}));let B=Lg({element:L,graph:I.graph,source:f.get(L.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:F.isRepeat,propertyProvenance:F.propertyProvenances,repeatTargets:X}),j=$g(P,I.graph,I.topology,I.capabilities,F.textSources,F.provenances,F.dynamicData,B);return p===P?j:fh(j,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,b){let x=Jn(p,b),I=ot(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let F=jg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?F:dh(F,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,b){let x=Jn(p,b),I=ot(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let F=f.get(P.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return ga({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:F}})},refreshSourceForKey:$h,async execute(p){if(await S,g)return ce(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Vh(p);if(p.kind==="insert-page-resource")return Kh(p);if(p.kind==="delete-page-source")return Uh(p);let b=await iu(p);if("ok"in b)return b;await Wl(p);let x=await iu(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let j=p;return p.kind==="insert-child"||p.kind==="replace-node"?Jh(j,I):p.kind==="move-node"||p.kind==="remove-node"?Xh(j,I):ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let F=p.params,L=p.target.kind==="node"?p.target.key:null;if(F.kind==="move-node"&&"kind"in F.target&&F.target.kind==="source-sibling"){let j=F.target,ie=L?I.document?.entries.find(D=>D.key===L):null,te=I.document?.entries.find(D=>D.key===j.anchorKey),Fe=ie?.pageCompositionActionScope,ye=Fe?.kind==="source-siblings"?Fe.siblingKeys:null,we=ye?.indexOf(ie?.key??"")??-1,Ne=ye?.indexOf(j.anchorKey)??-1,_=j.relation==="before"?we-1:we+1;if(!ie||!te||!ye||we<0||Ne!==_||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==ye.length||te.pageCompositionActionScope.siblingKeys.some((D,pe)=>D!==ye[pe])||!ie.operationSummary.canMove)return ce(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let G=uN(I,I.graph,I.capabilities,f,i),X=await new ts(G).plan(p);if(!X.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:wo(X.errorCode),message:X.reason}};let B=X.plan;if(B.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Q(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(B.steps.some(ie=>ie.type==="invoke-external-adapter")){let ie=await d.execute(B);if(!ie.ok)return ce(p,wo(ie.errorCode),ie.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Q(p),ie.resultVersion),affectedFiles:ie.affectedFiles,...ie.selectionRef?{selectionRef:ie.selectionRef}:{}};return ws(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let j=await d.prepareRewritePlan(B);return j.ok?await Un({request:p,filePlan:j.filePlan,...j.selectionRef?{selectionRef:j.selectionRef}:{}}):ce(p,wo(j.errorCode),j.reason)}catch(j){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(j)}}}finally{u-=1}},async undo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await ql("undo")}finally{u-=1}},async redo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await ql("redo")}finally{u-=1}},notifyFileChanged(p){Ul([p])},getAffectedCompositions(p){return Mh(p)},subscribe(p){return r.subscribe(p)}}}function rN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function oN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,u)=>{let g=f.get(m)??new Set,h=g.size;return g.add(u),f.set(m,g),g.size!==h},a=(f,m)=>{if(!f.importedFrom)return!1;if(f.exportName==="default")return s(i,f.importedFrom,m);let u=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(u=s(o,`${f.importedFrom}#${f.exportName}`,m)||u),u},c=f=>o.get(`${f.sourceFile}#${f.componentName}`)??i.get(f.sourceFile);for(let f of t.elements.values()){if(f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=n.placements.find(g=>g.members.some(h=>h.sourceRange!==null&&No(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&No(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(No(u.sourceRange,y.sourceRange)||lN(y.sourceRange,u.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${u.sourceFile}#${u.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(u.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}iN(e,t,n,r)}function iN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let u=m.pageCompositionUnitKey;return u?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==u:!0:!1}),s=new Map,a=(m,u)=>{s.set(m,Math.min(2,(s.get(m)??0)+u))},c=m=>n.placements.some(u=>u.members.some(g=>g.sourceRange!==null&&No(m.sourceRange,g.sourceRange)));for(let m of t.elements.values())m.sourceFile!==n.entryFile||!m.importedFrom||!/^[A-Z]/.test(m.tag)||!c(m)||a(`${m.importedFrom}#${m.exportName??m.tag}`,1);let l=[...t.elements.values()].flatMap(m=>m.sourceFile!==n.entryFile&&m.importedFrom&&/^[A-Z]/.test(m.tag)?[{owner:`${m.sourceFile}#${m.componentName}`,ownerDefault:`${m.sourceFile}#default`,target:`${m.importedFrom}#${m.exportName??m.tag}`}]:[]);for(let m=0;m<=l.length;m+=1){let u=!1;for(let g of l){let h=s.get(g.owner)??s.get(g.ownerDefault)??0;if(!h)continue;let S=s.get(g.target)??0,E=Math.min(2,S+h);E!==S&&(s.set(g.target,E),u=!0)}if(!u)break}let d=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let u=t.elements.get(m.key);m.pageCompositionUnitKey&&u?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let u=t.elements.get(m.key);if(!u||u.sourceFile===n.entryFile||m.key!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=se(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:u.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&_e(E))){d(u)===1&&Ih(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Ih(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],S=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(sN(y))continue;if(!aN(y)){S=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===u.element.sourceFile&&N.componentName===u.element.componentName&&No(N.sourceRange,cN(y))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==g||d(v)!==1){S=!1;break}h.push(C)}if(!S||h.length!==m.length||m.some(({entry:y})=>!h.some(v=>v.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Ih(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function sN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function aN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function cN(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function No(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lN(e,t){return Ch(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ch(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ch(e,t,n,r){return e!==n?e-n:t-r}function uN(e,t,n,r,o){let i=new Map,s=new Map,a=(d,f)=>{if(s.has(d))return;s.set(d,f);let m=t.elements.get(d);for(let u of m?.childKeys??[])a(u,f)};for(let d of t.regions)if(d.kind==="repeat-region")for(let f of d.childKeys)i.set(f,d.ownerKey),a(f,d.ownerKey);return{getNode(d){let f=c(d),m=t.elements.get(f.baseKey);return m?l(d,m):null},getChildNodes(d){let f=c(d),u=e.documentIndex?.entriesByKey.get(d)?.childKeys;if(u)return u.map(h=>{let S=ot(h)??h,E=t.elements.get(S);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let S=t.elements.get(h);return S?l(h,S):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([d,f])=>({file:d,content:f}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},getCapability(d){let f=c(d),m=n.get(f.baseKey);return m?{...m,key:d,constraints:m.constraints.map(u=>({...u})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:d,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(d){return r.get(d)??""},getFileVersion(d){return Math.max(e.fileVersions.get(d)??0,t.version)},getRouteEntryFile(d){return e.routeId===d?e.entryFile:null},getComponentSemantic(d){let f=c(d);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(d){let f=c(d),m=t.elements.get(f.baseKey),u=m?r.get(m.sourceFile):void 0;return!m||u===void 0?null:ga({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:u}})},getEditableTextSegmentIndex(d){let f=c(d),u=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return u&&!u.done?u.value:null},async getTextWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return null;let S=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(S)return S;let E=g.attributes?.find(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return dl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(d,f){let m=c(d);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(d){let f=Ow(d);return f?{baseKey:f.baseKey,repeatIndex:uh(e.document??null,d,f.baseKey,e.documentIndex)??lh(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var dN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function wo(e){return dN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Rh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function fN(e){let t=$n(e);if(!Lw.test(t))return[];let n=t.startsWith("src/app/")?"src/app":"app",r=t.slice(0,t.lastIndexOf("/")),o=[],i=r;for(;(i===n||i.startsWith(`${n}/`))&&(o.unshift(i),i!==n);)i=i.slice(0,i.lastIndexOf("/"));return o.flatMap(s=>Bw.map(a=>`${s}/${a}`))}function pN(e){let n=$n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function mN(e){return Ph(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function gN(e){return Ph(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ph(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ah(r[1]??"");o&&n.push(o)}return n}function wh(e,t){let n=Ah(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?$n(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?$n(`${hN(e)}/${n}`):n.startsWith("/")?$n(n.slice(1)):jl(n)?$n(n):null}function Ah(e){return e.split(/[?#]/,1)[0]?.trim()??""}function jl(e){return/\.css$/i.test(e)}function hN(e){let t=$n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function yN(e){return Array.from(new Set(e))}function $n(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function xN(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}var Is=class{constructor(t){this.options=t,this.fileSystem=new kr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return $o(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Xo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=SN.safeParse(t);if(!n.success)return{result:Bo(t,n.error.issues.map(i=>i.message))};let r=new kr(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:kn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=EN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>vN(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return ks({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Vo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function vN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Se(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Se(e.before)},fullContent:e.after}}function kN(e){return new Is(e)}import{SiteEditOperationRequestSchema as RN}from"@vcp-dev/contracts";import Rt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as IN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as CN}from"@vcp-dev/contracts";var Cs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=ks({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Xo(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return Rt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return Rt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await Rt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ui(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await Rt.mkdir(et.dirname(i),{recursive:!0});let s=await Rt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Rt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Rt.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await Rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await Rt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...CN,...IN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await d(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function d(f,m,u){if(r.maxDepth!==void 0&&u>r.maxDepth){a.add("max-depth");return}let g=et.join(n,...f.split("/")),h;try{h=await Rt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let S=await Rt.readdir(g,{withFileTypes:!0});for(let E of S)E.isSymbolicLink()||await d(`${f}/${E.name}`,m,u+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function $l(e){return new Cs(e)}var Rs=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=$l({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Vo(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:$o(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=RN.safeParse(r);if(!o.success)return Bo(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message,...s.details?{details:s.details}:{}},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:kn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:kn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:kn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function wN(e){return new Rs(e)}export{oe as FileHistoryStoreError,Zr as PageTemplateManagedSourceError,Rs as PreviewFileSystemSiteEditEngineRuntime,lf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Is as SnapshotSiteEditEngineRuntime,_o as checkComponentI18nHostCompatibility,ep as computeManagedPageTemplatePaths,wN as createPreviewSiteEditEngineRuntime,kN as createSiteEditEngineRuntime,Zf as decodePageTemplateKey,gc as encodePageTemplateId,ky as instrumentSiteEditRuntimeAttributes,tp as isManagedPageTemplateSourcePath,Bd as openFileHistoryStore,ay as parseSourceModule,cy as resolveImportBase,Sk as resolveManagedPageTemplateComposition,Li as scanManagedPageTemplateCandidates,rp as scanSiteEditCompositionsFromFiles,Jr as scanSiteEditThemeStyleViolations};
14
+ `||m==="\r"}if(s)return Sr(t,`Unterminated block comment in ${t}.`);if(o)return Sr(t,`Unterminated string literal in ${t}.`);if(c)return Sr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?Sr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function Sr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function ks(e){let t="idle",n=e.fileSystem??$w(),r=hd(),o=ih({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?of(e.historyStore):Kw()),d=rh(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=Ol(),S=C();function E(p){return(Es.isAbsolute(p)?Es.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function y(p,b){let x=Es.posix.dirname(p),I=b.replace(/\.(?:tsx?|jsx?)$/i,""),P=Es.posix.relative(x,I);return P.startsWith(".")?P:`./${P}`}function v(p,b){return p.startLine===b.startLine&&p.startColumn===b.startColumn&&p.endLine===b.endLine&&p.endColumn===b.endColumn}async function C(){let p=e.historyStore;if(p)try{let b=await p.readTransactionJournal();if(!b)return;let x=await p.readIndex(),I=await Promise.all(b.files.map(async F=>await n.exists(F.path)?Se(await n.readFile(F.path)):null));if(hh({journal:b,index:x,observedFileDigests:I})!=="ambiguous"){await p.clearTransactionJournal(b.transactionId);let F=await p.readStatus();F.recoveryRequired||(await p.cleanupTmp(),F=await p.readStatus()),g=F.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${b.transactionId} at phase ${b.phase}`),g=!0}catch(b){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(b)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let b=Eh(p.context,p.entryFile);i.set(p.key,b),A(b,b.dependencyFiles)}function A(p,b){let x=new Set(b);R(p),p.dependencyFiles=x;for(let I of p.dependencyFiles){let P=s.get(I);P||(P=new Set,s.set(I,P)),P.add(p.key)}}function R(p){for(let b of p.dependencyFiles){let x=s.get(b);x&&(x.delete(p.key),x.size===0&&s.delete(b))}p.dependencyFiles.clear()}function T(p){let b=new Set;for(let x of p)for(let I of s.get(x)??[])b.add(I);return b}function O(p){for(let b of p)if(!s.has(b))return!1;return!0}async function M(p,b,x,I,P){let F=new Map,L=vg(P.values()),G=new Map,X=typeof n.exists=="function"?B=>n.exists(B):async()=>!1;for(let[B,j]of p.elements){let ie=b.nodes.get(B);if(!ie)continue;let te=x.get(j.sourceFile)??I.get(j.sourceFile),Fe=new Map,ye=new Map,we=new Map,Ne=[];for(let Ce of j.textSegments){if(!te){Fe.set(Ce.index,null);continue}let Er=await kg({file:j.sourceFile,source:te,segment:Ce,readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Cl({file:j.sourceFile,source:te,target:{kind:"text-segment",segment:Ce},readFile:it=>n.readFile(it),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:it,adapterId:gn,capabilities:Os})=>({sourceType:it,adapterId:gn,capabilities:Os})),functionCallContracts:e.functionCallContracts,fileCache:L}),dt=Qw(Er);Fe.set(Ce.index,dt),ye.set(Ce.index,Er),we.set(Ce.index,Ze),Ne.push({editable:Ce.editable,source:dt})}let _=new Map,D=new Map;if(te)for(let Ce of j.attributes??[]){let Er=await xr({file:j.sourceFile,source:te,sourceRange:Ce.sourceRange,expression:Ce.source?.expression??Ce.value,sourceInfo:Ce.source,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L}),Ze=await Fg({element:j,file:j.sourceFile,source:te,propertyName:Ce.name,readFile:dt=>n.readFile(dt),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:it,capabilities:gn})=>({sourceType:dt,adapterId:it,capabilities:gn})),functionCallContracts:e.functionCallContracts,fileCache:L});D.set(Ce.name,Ze),_.set(Ce.name,Er)}let pe=Ug(qw(ie.writeTarget),Ne),fe=_g({key:B,element:j,graph:p,provenances:we}),Ie=Wg(j),De=te?await Rm({element:j,graph:p,file:j.sourceFile,source:te,readFile:Ce=>n.readFile(Ce),exists:X,fileCache:G}):void 0,Xe=p.regions.find(Ce=>Ce.kind==="conditional-region"&&Ce.childKeys.includes(B)),mn,_s=Xe?.sourceCandidates?.[0];if(te&&Xe&&_s?.kind==="conditional-branch"){let Ce=await Cl({file:j.sourceFile,source:te,target:{kind:"conditional-branch",candidate:_s},readFile:Ze=>n.readFile(Ze),exists:X,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ze,adapterId:dt,capabilities:it})=>({sourceType:Ze,adapterId:dt,capabilities:it})),functionCallContracts:e.functionCallContracts,fileCache:L});mn={currentBranch:Xe.childKeys.indexOf(B)<=0?"then":"else",availableBranches:Xe.childKeys.length>1?["then","else"]:["then"],conditionExpression:_s.conditionExpression,provenance:{finalSource:Ce.finalSource?{kind:Ce.finalSource.kind,file:Ce.finalSource.file,displayPath:Ce.finalSource.displayPath}:null,chain:Ce.chain.map(Ze=>({kind:Ze.kind,file:Ze.file,displayName:Ze.displayName,canEditHere:Ze.canEditHere})),confidence:Ce.confidence,editMode:Ce.editMode,diagnostics:Ce.diagnostics.map(Ze=>({code:Ze.code,message:Ze.message}))}}}F.set(B,{textSources:Fe,textTargets:ye,elementPropertyTargets:_,propertyProvenances:D,isRepeat:xN(B,p),provenances:we,writeTarget:pe,componentSemantic:fe,styleSource:Ie,conditional:mn,dynamicData:De})}return F}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function ee(p,b){let x=o.initialVersions.get(p.key)??0;for(let I of b.values())x=Math.max(x,I);return Math.max(x,p.graph?.version??0)}function Re(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Q(p){try{return Re(o.resolveSelector(p.composition).key)}catch{return 0}}async function de(p,b,x=n,I=1){let P=await Cd(p,b,F=>x.readFile(F),F=>x.exists(F),{additionalEntries:await Gt(p,x),version:I});if(P.diagnostics.length>0)throw new Ro(P.diagnostics);return P}async function Te(p,b,x={}){let I=i.get(p);if(!I)return null;let P=x.sourceCache??Ll(f,[]),{graph:F,allSources:L,parsedModules:G,entryModule:X}=await de(I.entryFile,b,n,I.graph?.version??1),B=new Map;for(let Xe of L.keys())B.set(Xe,U(Xe));let j=Math.max(ee(I,B),x.minimumVersion??0);x.changed&&j<=(I.graph?.version??0)&&(j=(I.graph?.version??0)+1),F.version=j;for(let[Xe,mn]of L)Bl(P,Xe,mn,xh);let ie=await Yt(I.composition,I.entryFile,L,P);F.routeId=I.routeId,F.composition=I.composition;let te=Gg(F),Fe=dd(te,F),ye=await M(F,te,L,P,G),we=_h(F,Fe,ye),Ne=Fh(ye),_=ch(Bg(F,te,Fe,{canUpdateTextByKey:we,dynamicDataSummaryByKey:Ne}),F,ye),D=Kf({route:I.routeId,composition:I.composition,entryFile:I.entryFile,version:j,source:b,ast:X?.ast}),pe=Uf(D);D.ok&&oN(_,F,D.projection,G);let fe={..._,composition:I.composition,...ie?{styleContext:ie}:{},pageComposition:pe},Ie=new Set([I.entryFile,...L.keys()]);if(ie){Ie.add(ie.entryCss.path);for(let Xe of ie.stylesheets)Ie.add(Xe.path)}let De={...I,dependencyFiles:Ie,graph:F,topology:te,capabilities:Fe,document:fe,pageComposition:pe,pageCompositionProjection:D.projection,pagePlacementByKey:D.ok?D.projection.placementByKey:null,pagePlacementUnitByKey:D.ok?D.projection.placementUnitByKey:null,pageUnitByKey:D.ok?D.projection.unitByKey:null,pagePlacementsByUnitKey:D.ok?D.projection.placementsByUnitKey:null,documentIndex:ah(fe),detailProjections:ye,fileVersions:B,styleContext:ie};if(x.publish===!1)return De;br(f,P);for(let Xe of P.keys())m.delete(Xe);return A(I,Ie),Object.assign(I,De),I}async function Gt(p,b=n){let x=[];for(let I of fN(p))typeof b.exists=="function"&&await b.exists(I)&&x.push({file:I,source:await b.readFile(I)});return x}async function Yt(p,b,x,I){let P=[];for(let[B,j]of x){if(jl(B)){P.push(B);continue}for(let ie of mN(j)){let te=wh(B,ie);te&&P.push(te)}}if(!P.length){for(let B of pN(b))if(await Vl(B)){P.push(B);break}}let F=new Map,L=yN(P).slice(0,yh);for(;L.length>0&&F.size<yh;){let B=L.shift();if(F.has(B)||!jl(B))continue;let j=await Th(B,I);if(j!==null){F.set(B,{path:B,content:j});for(let ie of gN(j)){let te=wh(B,ie);te&&!F.has(te)&&!L.includes(te)&&L.push(te)}}}let G=[...F.values()].map(B=>({...B,hash:Se(B.content)})),X=G[0];return X?{composition:p,revision:Se(JSON.stringify(G.map(({path:B,hash:j})=>({path:B,hash:j})))),entryCss:X,stylesheets:G.slice(1)}:null}async function Th(p,b){let x=b.get(p);if(x!==void 0)return x;if(!await Vl(p))return null;let I=await n.readFile(p);return Bl(b,p,I,xh),I}async function Vl(p){return typeof n.exists=="function"?n.exists(p):!1}function Fh(p){let b=new Map;for(let[x,I]of p)I.dynamicData?.bindings.length&&b.set(x,Lm(I.dynamicData.bindings));return b}function _h(p,b,x){let I=new Map;for(let[P,F]of p.elements){if(!b.get(P)?.canUpdateText){I.set(P,!1);continue}let G=x.get(P),X=F.textSegments.some(B=>{if(!B.editable)return!1;let j=G?.provenances.get(B.index)??null;return!j||Oh(j)});I.set(P,X)}return I}function Oh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Po(p,b={}){let x=[...new Set(p)],I=b.affectedCompositionKeys!==void 0,P=I?new Set(b.affectedCompositionKeys):T(x);if(!I&&(P.size===0||!O(x)))for(let X of i.values())Kl(X,x)&&P.add(X.key);let F=!I&&P.size===0&&x.some(Rh),L=b.publish===!1?Ll(f,x):void 0,G={rebuiltRoutes:[],failedRoutes:[],...b.publish===!1?{candidateRouteStates:[],candidateSourceCache:L}:{}};for(let X of i.values())if(!(b.excludedCompositionKeys?.has(X.key)||!(P.has(X.key)||F)))try{let j=!!X.graph,ie=await n.readFile(X.entryFile),te=await Te(X.key,ie,{...b,...L?{sourceCache:L}:{}});te?.graph&&(G.rebuiltRoutes.push({documentChanged:j,composition:X.composition,routeId:X.routeId,version:te.graph.version}),G.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:te}))}catch(j){G.failedRoutes.push({...mh(X.routeId,j),composition:X.composition})}return G}function Vn(p){let b=[...new Set(p)],x=T(b);if(x.size>0&&O(b))return[...x];for(let I of i.values())Kl(I,b)&&x.add(I.key);return[...x]}function Mh(p){let b=new Set(Vn(p));return o.entries.filter(x=>b.has(x.key)).map(x=>x.context)}function Dh(p){return[...new Set(Vn(p))].sort((x,I)=>x<I?-1:x>I?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function Lh(p,b){let x=new Set(Vn(b)),I=p.provenance?.affectedCompositions??[];if(I.length===0)return x;if([...new Set(I.map(F=>o.resolveContext(F).key))].some(F=>!x.has(F)))throw new Error("History provenance does not match the affected composition index.");return x}function Bh(p,b){let x=p.composition??p.provenance?.initiatingComposition;if(x){let F=o.resolveContext(x);return{context:F.context,key:F.key}}let I=[...new Set(Vn(b))];if(I.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${I.length}).`);let P=o.getByKey(I[0]);if(!P)throw new Error("Legacy history entry references an unknown affected composition.");return{context:P.context,key:P.key}}function ws(p,b){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:I}of b.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:I});for(let{composition:x,message:I}of b.failedRoutes)r.emit({type:"graph-error",composition:x,message:I})}function Kl(p,b){return b.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Ul(p){for(let b of p)a.add(b);c||N()||(c=(async()=>{t="building";let b=!1;try{for(;a.size>0;){if(N())return;await jh(),await h.runExclusive(async()=>{if(u>0||N())return;let x=[...a];a.clear();let I=await Jl(x);if(I.length===0)return;let P=Vn(I);for(let G of P){let X=i.get(G)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:F,failedRoutes:L}=await Po(I,{changed:!0});for(let{documentChanged:G,composition:X,version:B}of F)r.emit({type:"graph-ready",composition:X,version:B}),G&&r.emit({type:"document-changed",composition:X,version:B});for(let{composition:G,message:X}of L)b=!0,r.emit({type:"graph-error",composition:G,message:X})})}}finally{c=null,t!=="disposed"&&(t=!b&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Ul([])}})())}async function jh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Jl(p){let b=[];for(let x of new Set(p)){let I=f.get(x);if(I===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),b.push(x);continue}try{await n.readFile(x)!==I&&(m.delete(x),b.push(x))}catch(P){if(!rN(P))try{if(await n.exists(x))continue}catch{continue}m.add(x),b.push(x)}}return b}function Xl(p){gh(f,p);for(let b of p)b.exists===!1?m.add(b.file):m.delete(b.file)}function zl(p){m.clear();for(let b of p)m.add(b)}async function Hl(p){let b=await Jl(p);if(b.length===0)return;let x=Vn(b);for(let F of x){let L=i.get(F)?.composition;L&&r.emit({type:"graph-invalidated",composition:L})}let{rebuiltRoutes:I,failedRoutes:P}=await Po(b,{changed:!0});for(let{documentChanged:F,composition:L,version:G}of I)r.emit({type:"graph-ready",composition:L,version:G}),F&&r.emit({type:"document-changed",composition:L,version:G});for(let{composition:F,message:L}of P)r.emit({type:"graph-error",composition:F,message:L})}async function $h(p,b){let x=Jn(p,b);if(!x?.graph)return;let I=ot(p)??p,P=x.graph.elements.get(I);P&&await Hl([P.sourceFile])}async function Wl(p){let b=new Set;if(p.target.kind==="node"){let x=Jn(p.target.key,p.composition),I=ot(p.target.key)??p.target.key,P=x?.graph?.elements.get(I);P&&b.add(P.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&b.add(x.entryFile)}else if(p.target.kind==="source-file")b.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)b.add(x);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let x=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let I of x){let P=Jn(I,p.composition),F=ot(I)??I,L=P?.graph?.elements.get(F);L&&b.add(L.sourceFile)}}await Hl(b)}async function Vh(p){if(p.params.kind!=="source-edit")return Ns(p,"invalid-params","source-edit requires source-edit params");for(let b of p.params.edits){let x=nN(b);if(!x.ok)return Ns(p,x.errorCode,x.message,x.details)}u+=1;try{let b=await zh(p.params.edits);if(!b.ok)return Ns(p,b.errorCode,b.message,b.details);await Wl(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(I=>I.operation==="delete"?{operation:"delete",file:I.path,baseContentHash:I.baseContentHash??null}:{operation:"upsert",file:I.path,baseContentHash:I.baseContentHash??null,content:I.content})};return await Un({request:p,filePlan:x})}catch(b){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(b)}}}finally{u-=1}}async function Kh(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ce(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let b=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content}))),...p.params.artifact.pages.flatMap(I=>I.materialization.files.map(P=>({path:P.pathTemplate,content:P.content})))],exists:I=>n.exists(I),readFile:I=>n.readFile(I)});if(!b.ok)return ce(p,V.MATERIALIZATION_REJECTED,b.message);let x=await Wa({artifact:p.params.artifact,exists:I=>n.exists(I)});return x.ok?await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:x.files},output:{kind:"insert-page-resource",package_instance_id:x.packageInstanceId,pages:x.pages},historyPolicy:"none"}):ce(p,x.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(b){return ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Uh(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ce(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ce(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let b=Nh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(b.truncated)return ce(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:b.truncated.reasons});let x=b.files.filter(({path:L})=>/\.(?:tsx?|jsx?)$/.test(L)),I=Object.fromEntries(await Promise.all(x.map(async({path:L})=>[L,await n.readFile(L)]))),P=fp({expectedUrlPath:p.params.expectedUrlPath,files:I});if(!P.ok)return ce(p,P.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:P.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,P.message);let F=await Promise.all(P.edits.map(async L=>({...L,baseContentHash:Se(await n.readFile(L.file))})));return Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:F},output:{kind:"delete-page-source",deleted_files:P.deletedFiles,updated_files:P.updatedFiles,preserved_shared_files:P.preservedSharedFiles,warnings:P.warnings},historyPolicy:"none"})}catch(b){return ce(p,V.INTERNAL_ERROR,qe(b))}finally{u-=1}}async function Jh(p,b){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ce(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ce(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!P)return ce(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let F=p.params.kind==="insert-child"?p.params.position:null,L=await _o({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:P.files.map(B=>({path:B.pathTemplate,content:B.content})),exists:B=>n.exists(B),readFile:B=>n.readFile(B)});if(!L.ok)return ce(p,V.MATERIALIZATION_REJECTED,L.message);let G=await Vw(n,Object.keys(P.projectDependencies??{})),X=await Rf({manifest:P,generatedRoot:"components/site/generated",controlledFiles:P.files.map(B=>({pathTemplate:B.pathTemplate})),exists:B=>n.exists(B),availableHostDependencies:G,commit:async B=>{let j=await n.readFile(b.entryFile),ie=b.document,te=b.pageCompositionProjection;if(!ie||ie.pageComposition?.status!=="supported"||ie.version!==p.documentVersion||!te||te.status!=="supported"||te.documentVersion!==ie.version)return{ok:!0,data:ce(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Fe=B.entry.path,ye=qh(B.instanceName),we,Ne=[];if(p.params.kind==="insert-child"){if(!F||!("kind"in F)||F.kind!=="page-composition")return{ok:!0,data:ce(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let fe=tc({routeId:b.routeId,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementKey:F.placementKey,component:{source:Fe,exportName:B.entry.export.kind==="default"?"default":B.entry.export.name,localName:ye}});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"insert-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"insert",jsx:Ie.node.jsx,placement:Ie.placement,replaceOriginal:Ie.replaceOriginal}});break;case"insert-child":De=Wn({source:j,locator:Ie.parentLocator,node:Ie.node,placement:Ie.placement,...Ie.anchorLocator?{anchorLocator:Ie.anchorLocator}:{}});break;default:De={ok:!1,source:j,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ie)}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};we=De.source}else{let fe=nc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:p.documentVersion,source:j,projection:te,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!fe.ok)return{ok:!0,data:ce(p,Fs(fe.error.code),fe.error.message,{diagnostics:fe.error.diagnostics})};let Ie=fe.plan.rewriteStep,De;switch(Ie.kind){case"replace-root-expression":De=Oi({source:j,locator:Ie.locator,expectedSourceHash:Ie.sourceHash,action:{kind:"replace",jsx:`<${ye} />`}});break;case"replace-node":De=Qo({source:j,locator:Ie.locator,node:{jsx:`<${ye} />`}});break;default:De={ok:!1,source:j,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ie.kind}`}}}if(!De.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,De.diagnostic.message)};let Xe=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:j,mutatedSource:De.source});we=Xe.source,Ne=await Promise.all(Xe.files.map(async mn=>({operation:"delete",file:mn,baseContentHash:Se(await n.readFile(mn))})))}let _=Zn({source:we,moduleSpecifier:y(b.entryFile,Fe),imports:B.entry.export.kind==="default"?[{kind:"default",local:ye}]:[{kind:"named",imported:B.entry.export.name,local:ye}]});if(!_.ok)return{ok:!0,data:ce(p,V.AST_PARSE_ERROR,_.diagnostic.message)};let D=B.files.map(fe=>({operation:"create-only",file:fe.path,content:fe.content})),pe=[{operation:"upsert",file:b.entryFile,content:_.source,baseContentHash:Se(j)},...D,...Ne];u+=1;try{let fe=await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!fe.ok&&fe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:fe.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:fe}}finally{u-=1}}});return X.ok?X.data:ce(p,X.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,X.error.message,{materializationCode:X.error.code})}async function Xh(p,b){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=b.document,I=b.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!I||I.status!=="supported")return ce(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||I.documentVersion!==x.version)return ce(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let P=await n.readFile(b.entryFile),F=nc({routeId:b.routeId,composition:b.composition,entryFile:b.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:P,projection:I,placementUnitKey:p.target.placementUnitKey,operation:p.kind,targetPlacement:p.kind==="move-node"&&p.params.kind==="move-node"&&"kind"in p.params.target&&p.params.target.kind==="page-composition"?p.params.target:void 0});if(!F.ok)return ce(p,Fs(F.error.code),F.error.message,{diagnostics:F.error.diagnostics});let L=F.plan.rewriteStep,G;switch(L.kind){case"move-node":G=Gn({source:P,locator:L.locator,targetParentLocator:L.targetParentLocator,placement:L.placement,...L.anchorLocator?{anchorLocator:L.anchorLocator}:{}});break;case"remove-node":G=Hn({source:P,locator:L.locator});break;case"remove-root-expression":G=Oi({source:P,locator:L.locator,expectedSourceHash:L.sourceHash,action:{kind:"remove"}});break;default:G={ok:!1,source:P,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${L.kind}`}}}if(!G.ok)return ce(p,V.AST_PARSE_ERROR,G.diagnostic.message);let X=G.source,B=[];if(p.kind==="remove-node"){let ie=await Gl({routeState:b,placementUnitKey:p.target.placementUnitKey,source:P,mutatedSource:X});X=ie.source,B=await Promise.all(ie.files.map(async te=>({operation:"delete",file:te,baseContentHash:Se(await n.readFile(te))})))}let j=[{operation:"upsert",file:b.entryFile,content:X,baseContentHash:Se(P)},...B];u+=1;try{return await Un({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:b.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:j}})}finally{u-=1}}async function Gl(p){let b={source:p.mutatedSource,files:[]},x=p.routeState.graph,I=p.routeState.pageCompositionProjection;if(!x||!I||I.status!=="supported"||!n.listFiles)return b;let F=I.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!F)return b;let L=[...x.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&v(_.sourceRange,F));if(!L?.importedFrom||!L.exportName)return b;let G=E(L.importedFrom),X="components/site/generated/";if(!G.startsWith(X))return b;let B=G.slice(X.length).split("/")[0];if(!B||!/-[0-9a-f]{8}$/i.test(B))return b;let j=`${X}${B}`;if([...x.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===G).length!==1)return b;let te=await n.listFiles({maxFiles:5e3,maxDepth:32}),Fe=Array.isArray(te)?te:te.files;if(!Array.isArray(te)&&te.truncated)return b;let ye=Fe.map(({path:_})=>_).filter(_=>_===j||_.startsWith(`${j}/`));if(ye.length===0||!ye.includes(G))return b;for(let{path:_}of Fe)if(!(_===p.routeState.entryFile||_===j||_.startsWith(`${j}/`)))try{if((await n.readFile(_)).includes(B))return b}catch{return b}let we=y(p.routeState.entryFile,G),Ne=Qn({source:p.mutatedSource,moduleSpecifier:we,imports:L.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:L.exportName}]});return Ne.ok?Ne.source.includes(B)?{source:Ne.source,files:[]}:{source:Ne.source,files:ye.sort((_,D)=>_.localeCompare(D))}:b}async function zh(p){if(n.getFileInfo){for(let I of p)if(await n.exists(I.path)&&await n.getFileInfo(I.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${I.path}`,details:{path:I.path}}}for(let I of p){if(I.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(I.path))continue;let P=await n.exists(I.path)?await Ys(n,I.path):null;if(P?.ok){let F=Aw(P.content,I.content);if(!F.ok)return{ok:!1,errorCode:"invalid-params",message:F.message,details:{path:I.path,code:F.code}}}}let b=Hh(p);if(b.length===0)return{ok:!0};let x=eN(n,p);try{for(let I of b){let P=i.get(I);P&&await de(P.entryFile,await x.readFile(P.entryFile),x)}}catch(I){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(I)}`,details:{compositionKeys:b}}}return{ok:!0}}function Hh(p){return p.map(x=>x.path).some(Rh)?[...i.keys()]:[]}function Ns(p,b,x,I){let P=wo(b);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:P,message:x,...I?{details:I}:{}}}}async function Ps(p){let b=[];for(let x of new Set(p))b.push(await Wh(x));return b}async function Wh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,U(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,U(p)),exists:!0,sha256:Se(x)}}async function Yl(p,b,x,I){if(!e.historyStore)return null;let P=new Map(b.map(G=>[G.file,G])),F=new Map(x.map(G=>[G.file,G])),L=[...new Set([...P.keys(),...F.keys()])].sort().map(G=>{let X=P.get(G),B=F.get(G);return{path:G,preDigest:X?.exists===!1||!X?null:Se(X.content),postDigest:B?.exists===!1||!B?null:Se(B.content)}});return{schemaVersion:2,transactionId:`${p}:${I.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:I,files:L}}async function Zl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Kn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function As(p,b){let x=[];try{for(let I of p)await Ql(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file),x.push(I.file)}catch(I){let P=await Gh(b.filter(F=>x.includes(F.file)));return P.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(I)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${P.failedFiles.join(", ")}: ${qe(I)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Yh)}}async function Ql(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Gh(p){let b=[];for(let x of p)try{await Ql(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{b.push(x.file)}return b.length===0?{ok:!0}:{ok:!1,failedFiles:b}}function Yh(p){let b=p.exists!==!1;return{file:p.file,content:b?p.content:"",version:p.version,exists:b,...b?{sha256:Se(p.content)}:{}}}async function Un(p){return h.runExclusive(()=>Zh(p))}async function Zh(p){let b=p.filePlan.edits.map(_=>_.file),x=o.resolveSelector(p.request.composition),I=x.context,P=p.historyPolicy==="none"?void 0:{initiatingComposition:I,affectedCompositions:Dh(b)},F=await Ps(b),L=new Map(F.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),G=eu(),X=new Map(f),B=new Set(m),j=new Set([...i.values()].filter(_=>p.filePlan.edits.some(D=>D.operation==="delete"&&D.file===_.entryFile)).map(_=>_.key)),ie=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:Se(_.content)}),te={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(_=>_.operation==="delete"?{kind:"delete",path:_.file}:{kind:_.operation==="create-only"?"create-only":"upsert",path:_.file,content:_.content})},Fe=null,ye=!1,we=await ys({overlay:L,exists:_=>n.exists(_),plan:te,buildCandidate:async({plan:_})=>({plan:_}),prepareHistory:async()=>{let _=p.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(p.request.composition).context,operationId:p.request.id,kind:p.request.kind,target:p.request.target,preSnapshots:F,postSnapshots:ie,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...P?{provenance:P}:{}}),D=_?.historyTransition?_.historyTransition:e.historyStore?jw(await e.historyStore.readIndex()):null;if(e.historyStore&&!D)throw new Error("Durable history did not provide an exact index transition.");return Fe=await Yl(p.request.id,F,ie,D),Fe=await Zl(Fe),{history:_,historyTransition:D}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new vs(_);return{postSnapshots:await Ps(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:D})=>{let pe=await Po(D.affectedFiles,{changed:!0,minimumVersion:D.internalResultVersion,publish:!1,excludedCompositionKeys:j});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(G,pe.candidateRouteStates??[]),Ie=tu(fe,x.key);return{..._,rebuild:pe,routeSnapshots:fe,resultVersion:Ie,...vh(p.selectionRef,fe.map(De=>De.state.document))?{selectionRef:vh(p.selectionRef,fe.map(De=>De.state.document))}:{}}},publishCandidate:async({candidate:_,history:D,receipt:pe})=>{D?.history&&(await l.publishPrepared(D.history),ye=!0);let fe=_.resultVersion??pe.internalResultVersion;return{composition:I,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:fe,affectedFiles:pe.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:D})=>{_.routeSnapshots&&Ao(_.routeSnapshots),_.rebuild?.candidateSourceCache&&br(f,_.rebuild.candidateSourceCache),Xl(D.postSnapshots)},finalizeCandidate:async()=>{await Kn(Fe);for(let _ of j)i.delete(_)},emitCommitted:({candidate:_,published:D})=>{ws(D,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:D})=>{if(ye)throw new Error("history was published before transaction finalization failed");if(D){let pe=await As(F,D.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Ao(G),br(f,X),zl(B),_?.history&&await l.discardPrepared?.(_.history),await Kn(Fe)}});if(we.ok)return we.published;if(we.stage==="precheck"||we.stage==="build")try{await Kn(Fe)}catch(_){let D=await To(qe(_));return ce(p.request,D,"Unable to clear an uncommitted transaction journal.")}if(we.recoveryRequired){let _=await To(we.reason);return ce(p.request,_===V.RECOVERY_PERSIST_FAILED?_:V.ROLLBACK_FAILED,we.reason)}let Ne=we.error;return Ne instanceof vs?{...ce(p.request,wo(Ne.result.errorCode),Ne.result.reason),...Ne.result.affectedFiles?{affectedFiles:Ne.result.affectedFiles}:{}}:Ne instanceof jn?ce(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Dl(Ne.failedRoutes)}`,{failedRoutes:Ne.failedRoutes}):ce(p.request,ou(we.stage),qe(Ne))}async function ql(p){return h.runExclusive(async()=>{let b=p==="undo"?await l.prepareUndo():await l.prepareRedo();return b?Qh(p,b):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Qh(p,b){let x=b.entry,I=p==="undo"?x.preSnapshots:x.postSnapshots,P=p==="undo"?x.postSnapshots:x.preSnapshots,F=I.map(D=>D.file),{context:L,key:G}=Bh(x,F),X=await Ps(F),B=new Map(X.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),j=Re(G),ie=eu(),te=new Map(f),Fe=new Set(m),ye=null,we=!1,Ne,_=await ys({overlay:B,plan:{operationId:`${p}:${x.operationId}`,intents:I.map(D=>D.exists===!1?{kind:"delete",path:D.file}:{kind:"upsert",path:D.file,content:D.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ye=await Yl(`${p}:${x.operationId}`,X,I,b.historyTransition),ye=await Zl(ye),b),reverify:async()=>{},writeCandidate:async()=>{let D=await As(I,P);if(!D.ok)throw new Error(D.reason);return{snapshots:D.snapshots}},validateCandidate:async({candidate:D})=>{Ne=Lh(x,F);let pe=await Po(F,{changed:!0,minimumVersion:j+1,publish:!1,affectedCompositionKeys:Ne});if(pe.failedRoutes.length>0)throw new jn(pe.failedRoutes);let fe=nu(ie,pe.candidateRouteStates??[]),Ie=tu(fe,G);return{...D,rebuild:pe,routeSnapshots:fe,resultVersion:Ie}},publishCandidate:async({candidate:D,history:pe})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),we=!0;let fe=D.resultVersion??j+1;return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:fe,affectedFiles:F,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:D,receipt:pe})=>{D.routeSnapshots&&Ao(D.routeSnapshots),D.rebuild?.candidateSourceCache&&br(f,D.rebuild.candidateSourceCache),Xl(pe.snapshots)},finalizeCandidate:async()=>{await Kn(ye)},emitCommitted:({candidate:D,published:pe})=>ws(pe,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:D,receipt:pe})=>{if(we)throw new Error("history cursor was published before transaction finalization failed");if(pe){let fe=await As(P,pe.snapshots);if(!fe.ok)throw new Error(fe.reason)}Ao(ie),br(f,te),zl(Fe),D&&await l.discardPrepared?.(D),await Kn(ye)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Kn(ye)}catch(D){let pe=await To(qe(D));return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let D=await To(_.reason);return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:D===V.RECOVERY_PERSIST_FAILED?D:V.ROLLBACK_FAILED,message:_.reason}}}return{composition:L,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:F,error:{code:_.error instanceof jn?V.ROUTE_REBUILD_FAILED:ou(_.stage),message:qe(_.error),..._.error instanceof jn?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function eu(){return[...i.values()].map(p=>({composition:p.composition,key:p.key,routeId:p.routeId,state:{...p,dependencyFiles:new Set(p.dependencyFiles),fileVersions:new Map(p.fileVersions)}}))}function tu(p,b){return p.find(I=>I.key===b)?.state.graph?.version??o.initialVersions.get(b)??0}function nu(p,b){let x=new Map(p.map(I=>[I.key,I]));for(let I of b)x.set(I.key,I);return[...x.values()]}function Ao(p){for(let b of i.values())R(b);for(let b of p){let x={...b.state,dependencyFiles:new Set(b.state.dependencyFiles),fileVersions:new Map(b.state.fileVersions)};i.set(b.key,x),A(x,x.dependencyFiles)}}async function Ts(p){let b=i.get(p);if(!b)throw new Error(`Composition not found: ${p}`);if(b.graph)return;let x=await n.readFile(b.entryFile);await Te(p,x)}function Jn(p,b){let x=i.get(o.resolveSelector(b).key)??null;return!x||!ru(x,p)?null:x}function ru(p,b){if(p.documentIndex?.entriesByKey.has(b)||p.graph?.elements.has(b))return!0;let x=ot(b);return x&&x!==b?p.graph?.elements.has(x)===!0:!1}function ce(p,b,x,I){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:b,message:x,...I?{details:I}:{}}}}function ou(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function To(p){if(g=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function qh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(I=>I.charAt(0).toUpperCase()+I.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function Fs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function iu(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ts(x.key),x):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await Ts(x.key),x):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ce(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let b=i.get(o.resolveSelector(p.composition).key)??null;return b?(b.graph||await Ts(b.key),ru(b,p.target.key)?b:ce(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ce(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),f.clear(),m.clear()},registerComposition(p,b){let x=o.register({context:p,entryFile:b}),I=i.get(x.key);if(I?.entryFile===b)return;I&&R(I);let P=Eh(x.context,b);i.set(x.key,P),A(P,P.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);x&&(R(x),i.delete(b.key),o.unregister(b.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:b.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(x.graph)t="ready";else{t="building";try{let I=await n.readFile(x.entryFile);await Te(b.key,I),t="ready",r.emit({type:"graph-ready",composition:b.context,version:i.get(b.key)?.graph?.version??0})}catch(I){throw t="idle",r.emit({type:"graph-error",composition:b.context,message:qe(I)}),I}}},getDocument(p){let b=o.resolveSelector(p),x=i.get(b.key);if(!x)throw new Error(`Composition not registered: ${b.key}`);if(!x.document)throw new Error(`Composition not built: ${b.key}`);return x.document},async getHistoryStatus(){await S;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,b,x){let I=Jn(p,b),P=ot(p)??p;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let F=I.detailProjections.get(P);if(F){let L=I.graph.elements.get(P);if(!L)throw new Error(`Key not found: ${p}`);let G=zw(p,P,x),X=new Map;if(F.isRepeat&&G?.instanceIndex!==void 0)for(let ie of L.attributes??[])X.set(ie.name,dl({file:L.sourceFile,source:f.get(L.sourceFile)??"",element:L,propertyName:ie.name,selectionRef:G,graph:I.graph,sources:f}));let B=Lg({element:L,graph:I.graph,source:f.get(L.sourceFile),documentVersion:I.graph.version,selectionRef:x,isRepeat:F.isRepeat,propertyProvenance:F.propertyProvenances,repeatTargets:X}),j=$g(P,I.graph,I.topology,I.capabilities,F.textSources,F.provenances,F.dynamicData,B);return p===P?j:fh(j,p,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,b){let x=Jn(p,b),I=ot(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let P=x.detailProjections.get(I);if(P){let F=jg(I,x.graph,x.topology,x.capabilities,P.textSources,P.writeTarget,P.provenances,P.conditional,P.componentSemantic,P.styleSource,P.dynamicData);return p===I?F:dh(F,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,b){let x=Jn(p,b),I=ot(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let P=x.graph.elements.get(I);if(!P)throw new Error(`Key not found: ${p}`);let F=f.get(P.sourceFile);if(F===void 0)throw new Error(`Source not loaded: ${P.sourceFile}`);return ga({key:I,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:F}})},refreshSourceForKey:$h,async execute(p){if(await S,g)return ce(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return Vh(p);if(p.kind==="insert-page-resource")return Kh(p);if(p.kind==="delete-page-source")return Uh(p);let b=await iu(p);if("ok"in b)return b;await Wl(p);let x=await iu(p);if("ok"in x)return x;let I=x;if(p.target.kind==="page-unit"){let j=p;return p.kind==="insert-child"||p.kind==="replace-node"?Jh(j,I):p.kind==="move-node"||p.kind==="remove-node"?Xh(j,I):ce(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let F=p.params,L=p.target.kind==="node"?p.target.key:null;if(F.kind==="move-node"&&"kind"in F.target&&F.target.kind==="source-sibling"){let j=F.target,ie=L?I.document?.entries.find(D=>D.key===L):null,te=I.document?.entries.find(D=>D.key===j.anchorKey),Fe=ie?.pageCompositionActionScope,ye=Fe?.kind==="source-siblings"?Fe.siblingKeys:null,we=ye?.indexOf(ie?.key??"")??-1,Ne=ye?.indexOf(j.anchorKey)??-1,_=j.relation==="before"?we-1:we+1;if(!ie||!te||!ye||we<0||Ne!==_||te.pageCompositionActionScope?.kind!=="source-siblings"||te.pageCompositionActionScope.siblingKeys.length!==ye.length||te.pageCompositionActionScope.siblingKeys.some((D,pe)=>D!==ye[pe])||!ie.operationSummary.canMove)return ce(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!I.graph||!I.topology||!I.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let G=uN(I,I.graph,I.capabilities,f,i),X=await new ts(G).plan(p);if(!X.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:wo(X.errorCode),message:X.reason}};let B=X.plan;if(B.steps.length===0)return p.kind==="set-props"?{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Q(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(B.steps.some(ie=>ie.type==="invoke-external-adapter")){let ie=await d.execute(B);if(!ie.ok)return ce(p,wo(ie.errorCode),ie.reason);let te={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Q(p),ie.resultVersion),affectedFiles:ie.affectedFiles,...ie.selectionRef?{selectionRef:ie.selectionRef}:{}};return ws(te,{rebuiltRoutes:[],failedRoutes:[]}),te}let j=await d.prepareRewritePlan(B);return j.ok?await Un({request:p,filePlan:j.filePlan,...j.selectionRef?{selectionRef:j.selectionRef}:{}}):ce(p,wo(j.errorCode),j.reason)}catch(j){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Q(p),error:{code:V.INTERNAL_ERROR,message:qe(j)}}}finally{u-=1}},async undo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await ql("undo")}finally{u-=1}},async redo(p){if(await S,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Re(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await ql("redo")}finally{u-=1}},notifyFileChanged(p){Ul([p])},getAffectedCompositions(p){return Mh(p)},subscribe(p){return r.subscribe(p)}}}function rN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function oN(e,t,n,r){let o=new Map,i=new Map,s=(f,m,u)=>{let g=f.get(m)??new Set,h=g.size;return g.add(u),f.set(m,g),g.size!==h},a=(f,m)=>{if(!f.importedFrom)return!1;if(f.exportName==="default")return s(i,f.importedFrom,m);let u=s(o,`${f.importedFrom}#${f.tag}`,m);return f.exportName&&f.exportName!==f.tag&&(u=s(o,`${f.importedFrom}#${f.exportName}`,m)||u),u},c=f=>o.get(`${f.sourceFile}#${f.componentName}`)??i.get(f.sourceFile);for(let f of t.elements.values()){if(f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=n.placements.find(g=>g.members.some(h=>h.sourceRange!==null&&No(f.sourceRange,h.sourceRange)));if(!m)continue;let u=m.placementUnitKey;a(f,u)}let l=!0;for(;l;){l=!1;for(let f of t.elements.values()){if(f.sourceFile===n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag))continue;let m=c(f);if(m)for(let u of m)l=a(f,u)||l}}let d=n.placements.find(f=>f.placementKey===n.container.placementKey&&f.relation==="append");for(let f of e.entries){let m=ot(f.key)??f.key,u=t.elements.get(f.key)??t.elements.get(m);if(!u)continue;if(u.sourceFile===n.entryFile){if(n.container.sourceRange&&No(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let S=n.placements.find(E=>E.members.some(y=>y.sourceRange!==null&&(No(u.sourceRange,y.sourceRange)||lN(y.sourceRange,u.sourceRange))));if(S){f.pageCompositionUnitKey=S.placementUnitKey;continue}}let g=o.get(`${u.sourceFile}#${u.componentName}`);if(g){g.size===1&&(f.pageCompositionUnitKey=g.values().next().value);continue}let h=i.get(u.sourceFile);h?.size===1&&(f.pageCompositionUnitKey=h.values().next().value)}iN(e,t,n,r)}function iN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let u=m.pageCompositionUnitKey;return u?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==u:!0:!1}),s=new Map,a=(m,u)=>{s.set(m,Math.min(2,(s.get(m)??0)+u))},c=m=>n.placements.some(u=>u.members.some(g=>g.sourceRange!==null&&No(m.sourceRange,g.sourceRange)));for(let m of t.elements.values())m.sourceFile!==n.entryFile||!m.importedFrom||!/^[A-Z]/.test(m.tag)||!c(m)||a(`${m.importedFrom}#${m.exportName??m.tag}`,1);let l=[...t.elements.values()].flatMap(m=>m.sourceFile!==n.entryFile&&m.importedFrom&&/^[A-Z]/.test(m.tag)?[{owner:`${m.sourceFile}#${m.componentName}`,ownerDefault:`${m.sourceFile}#default`,target:`${m.importedFrom}#${m.exportName??m.tag}`}]:[]);for(let m=0;m<=l.length;m+=1){let u=!1;for(let g of l){let h=s.get(g.owner)??s.get(g.ownerDefault)??0;if(!h)continue;let S=s.get(g.target)??0,E=Math.min(2,S+h);E!==S&&(s.set(g.target,E),u=!0)}if(!u)break}let d=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let u=t.elements.get(m.key);m.pageCompositionUnitKey&&u?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let f=new Map;for(let m of i){let u=t.elements.get(m.key);if(!u||u.sourceFile===n.entryFile||m.key!==(ot(m.key)??m.key))continue;let g=r.get(u.sourceFile);if(!g)continue;let h=se(g.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:u.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let S=h.match.path,E=S.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&_e(E))){d(u)===1&&Ih(S)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Ih(E))continue;let y=f.get(E.node)??[];y.push({entry:m,element:u,parentPath:E}),f.set(E.node,y)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],S=!!(g&&d(u.element)===1);for(let y of u.parentPath.node.children){if(sN(y))continue;if(!aN(y)){S=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===u.element.sourceFile&&N.componentName===u.element.componentName&&No(N.sourceRange,cN(y))),C=v?o.get(v.identity.key):null;if(!v||!C||C.parentKey||C.pageCompositionUnitKey!==g||d(v)!==1){S=!1;break}h.push(C)}if(!S||h.length!==m.length||m.some(({entry:y})=>!h.some(v=>v.key===y.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(y=>y.key);for(let y of h)y.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Ih(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function sN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function aN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function cN(e){return{startLine:e.loc?.start.line??-1,startColumn:e.loc?.start.column??-1,endLine:e.loc?.end.line??-1,endColumn:e.loc?.end.column??-1}}function No(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lN(e,t){return Ch(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ch(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ch(e,t,n,r){return e!==n?e-n:t-r}function uN(e,t,n,r,o){let i=new Map,s=new Map,a=(d,f)=>{if(s.has(d))return;s.set(d,f);let m=t.elements.get(d);for(let u of m?.childKeys??[])a(u,f)};for(let d of t.regions)if(d.kind==="repeat-region")for(let f of d.childKeys)i.set(f,d.ownerKey),a(f,d.ownerKey);return{getNode(d){let f=c(d),m=t.elements.get(f.baseKey);return m?l(d,m):null},getChildNodes(d){let f=c(d),u=e.documentIndex?.entriesByKey.get(d)?.childKeys;if(u)return u.map(h=>{let S=ot(h)??h,E=t.elements.get(S);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let S=t.elements.get(h);return S?l(h,S):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([d,f])=>({file:d,content:f}))},getRouteEntryFiles(){return[...o.values()].map(d=>d.entryFile)},getCapability(d){let f=c(d),m=n.get(f.baseKey);return m?{...m,key:d,constraints:m.constraints.map(u=>({...u})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:d,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(d){return r.get(d)??""},getFileVersion(d){return Math.max(e.fileVersions.get(d)??0,t.version)},getRouteEntryFile(d){return e.routeId===d?e.entryFile:null},getComponentSemantic(d){let f=c(d);return e.detailProjections?.get(f.baseKey)?.componentSemantic??null},getClassNameSource(d){let f=c(d),m=t.elements.get(f.baseKey),u=m?r.get(m.sourceFile):void 0;return!m||u===void 0?null:ga({key:f.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:u}})},getEditableTextSegmentIndex(d){let f=c(d),u=e.detailProjections?.get(f.baseKey)?.textTargets.keys()?.next();return u&&!u.done?u.value:null},async getTextWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return Ml(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(f)??null,m.repeatIndex)},getPropertyState(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return null;let S=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(S)return S;let E=g.attributes?.find(y=>y.name===f);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${f}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:g.sourceFile,sourceRange:E.sourceRange}}:(g.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${f}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(d,f,m){let u=c(d),g=t.elements.get(u.baseKey);if(!g)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${d}`};let h=m?{...m,key:u.baseKey}:u.repeatIndex!==null?{key:u.baseKey,instanceIndex:u.repeatIndex}:void 0;return dl({file:g.sourceFile,source:r.get(g.sourceFile)??"",element:g,propertyName:f,selectionRef:h,graph:t,sources:r})},getTextProvenance(d,f){let m=c(d);return e.detailProjections?.get(m.baseKey)?.provenances.get(f)??null}};function c(d){let f=Ow(d);return f?{baseKey:f.baseKey,repeatIndex:uh(e.document??null,d,f.baseKey,e.documentIndex)??lh(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=ot(d)??d,u=e.documentIndex?.entriesByKey.get(d);return{key:d,file:f.sourceFile,component:f.componentName,tag:f.tag,structuralPath:f.identity.structuralPath,sourceRange:f.sourceRange,parentKey:u?.parentKey??f.parentKey??void 0,isRepeatRegion:f.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:f.importedFrom,exportName:f.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:f.attributes?.map(g=>({name:g.name,value:g.value,source:g.source?{expression:g.source.expression,base:g.source.base,path:g.source.path.map(h=>({...h}))}:null,resolvedValue:g.resolvedValue}))}}}var dN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function wo(e){return dN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Rh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function fN(e){let t=$n(e);if(!Lw.test(t))return[];let n=t.startsWith("src/app/")?"src/app":"app",r=t.slice(0,t.lastIndexOf("/")),o=[],i=r;for(;(i===n||i.startsWith(`${n}/`))&&(o.unshift(i),i!==n);)i=i.slice(0,i.lastIndexOf("/"));return o.flatMap(s=>Bw.map(a=>`${s}/${a}`))}function pN(e){let n=$n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function mN(e){return Ph(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function gN(e){return Ph(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Ph(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ah(r[1]??"");o&&n.push(o)}return n}function wh(e,t){let n=Ah(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?$n(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?$n(`${hN(e)}/${n}`):n.startsWith("/")?$n(n.slice(1)):jl(n)?$n(n):null}function Ah(e){return e.split(/[?#]/,1)[0]?.trim()??""}function jl(e){return/\.css$/i.test(e)}function hN(e){let t=$n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function yN(e){return Array.from(new Set(e))}function $n(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,""),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.pop();continue}n.push(r)}return n.join("/")}function xN(e,t){let n=t.elements.get(e);if(!n)return!1;for(let r of t.regions){if(r.kind!=="repeat-region")continue;let o=n;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}var Is=class{constructor(t){this.options=t,this.fileSystem=new kr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return $o(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Xo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=SN.safeParse(t);if(!n.success)return{result:Bo(t,n.error.issues.map(i=>i.message))};let r=new kr(this.options.files),o=this.createEngine(r,{emitEvents:!1});try{let i=await o.execute(n.data);if(!i.ok)return{result:{ok:!1,composition:i.composition,error:{code:i.error?.code??"INTERNAL_ERROR",message:i.error?.message??"Operation failed"},data:{requestId:i.requestId,kind:i.kind,target:i.target,resultVersion:i.resultVersion}}};let s={ok:!0,composition:i.composition,data:kn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=EN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>vN(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return ks({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Vo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function vN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Se(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Se(e.before)},fullContent:e.after}}function kN(e){return new Is(e)}import{SiteEditOperationRequestSchema as RN}from"@vcp-dev/contracts";import Rt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as IN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as CN}from"@vcp-dev/contracts";var Cs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=ks({...t,fileSystem:this.fileSystem})}get status(){return this.engine.status}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return this.engine.getDocument(t)}getAffectedCompositions(t){return this.engine.getAffectedCompositions(t)}getCompositionContext(t){return this.engine.getCompositionContext(t)}initializeComposition(t){return this.engine.initializeComposition(t)}getHistoryStatus(){return this.engine.getHistoryStatus()}getObjectEditContext(t,n,r){return r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n)}getRenderDetail(t,n){return this.engine.getRenderDetail(t,n)}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Uo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Jo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Xo(t,this.engine.getRenderDetail(t.key,t.composition))}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}execute(t){return this.engine.execute(t)}undo(t){return this.engine.undo(t)}redo(t){return this.engine.redo(t)}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.engine.subscribe(t)}dispose(){this.engine.dispose()}createFileSystem(){if(this.options.fileSystem)return this.options.fileSystem;let t=new Map,{projectRoot:n}=this.options;return{async readFile(r){return Rt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return Rt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await Rt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ui(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await Rt.mkdir(et.dirname(i),{recursive:!0});let s=await Rt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Rt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Rt.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await Rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await Rt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...CN,...IN],i=[],s=new Set,a=new Set,c=0;for(let f of o)await d(f,i,1);let l=i.sort((f,m)=>f.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function d(f,m,u){if(r.maxDepth!==void 0&&u>r.maxDepth){a.add("max-depth");return}let g=et.join(n,...f.split("/")),h;try{h=await Rt.lstat(g)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let E=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(E&&s.has(E))return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}E&&s.add(E),m.push({path:f,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&m.length>=r.maxFiles){a.add("max-files");return}let S=await Rt.readdir(g,{withFileTypes:!0});for(let E of S)E.isSymbolicLink()||await d(`${f}/${E.name}`,m,u+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function $l(e){return new Cs(e)}var Rs=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=$l({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Vo(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:$o(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}}getClassNameSource(t,n){return{ok:!0,composition:this.engine.getCompositionContext(n),data:this.engine.getClassNameSource(t,n)}}async getSourceTree(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:await this.engine.getSourceTree(t)}}async getSourceFile(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:await this.engine.getSourceFile(t)}}resolveSourceLocation(t){return{ok:!0,composition:this.engine.getCompositionContext(t.composition),data:this.engine.resolveSourceLocation(t)}}refreshSourceForKey(t,n){return this.engine.refreshSourceForKey(t,n)}async executeOperation(t,n){let r=n===void 0||t.mutationContext!==void 0?t:{...t,mutationContext:n},o=RN.safeParse(r);if(!o.success)return Bo(t,o.error.issues.map(s=>s.message));let i=await this.engine.execute(o.data);if(!i.ok){let s=i.error;if(!s)throw new Error("executeOperation failed without an error payload");return{ok:!1,composition:i.composition,error:{code:s.code,message:s.message,...s.details?{details:s.details}:{}},data:{requestId:i.requestId,kind:i.kind,composition:i.composition,target:i.target,resultVersion:i.resultVersion,...i.affectedFiles?.length?{affectedFiles:i.affectedFiles}:{}}}}return{ok:!0,composition:i.composition,data:kn(i)}}async undo(t){let n=await this.engine.undo();if(!n.ok){let r=n.error;if(!r)throw new Error("undo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:kn(n)}}async redo(t){let n=await this.engine.redo();if(!n.ok){let r=n.error;if(!r)throw new Error("redo failed without an error payload");return{ok:!1,composition:n.composition,error:{code:r.code,message:r.message},data:{requestId:n.requestId,kind:n.kind,composition:n.composition,target:n.target,resultVersion:n.resultVersion}}}return{ok:!0,composition:n.composition,data:kn(n)}}notifyFileChanged(t){this.engine.notifyFileChanged(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}dispose(){this.listeners.clear(),this.engine.dispose()}};function wN(e){return new Rs(e)}export{oe as FileHistoryStoreError,Zr as PageTemplateManagedSourceError,Rs as PreviewFileSystemSiteEditEngineRuntime,lf as SITE_EDIT_RAW_COLOR_LITERAL_RE,Is as SnapshotSiteEditEngineRuntime,_o as checkComponentI18nHostCompatibility,ep as computeManagedPageTemplatePaths,wN as createPreviewSiteEditEngineRuntime,kN as createSiteEditEngineRuntime,Zf as decodePageTemplateKey,gc as encodePageTemplateId,ky as instrumentSiteEditRuntimeAttributes,tp as isManagedPageTemplateSourcePath,Bd as openFileHistoryStore,ay as parseSourceModule,cy as resolveImportBase,Sk as resolveManagedPageTemplateComposition,Li as scanManagedPageTemplateCandidates,rp as scanSiteEditCompositionsFromFiles,Jr as scanSiteEditThemeStyleViolations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vcp-dev/site-edit-engine",
3
- "version": "0.10.34",
3
+ "version": "0.10.36",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -60,7 +60,7 @@
60
60
  "@babel/parser": "^7.29.3",
61
61
  "@babel/traverse": "^7.29.0",
62
62
  "@babel/types": "^7.29.0",
63
- "@vcp-dev/contracts": "0.10.34",
63
+ "@vcp-dev/contracts": "0.10.36",
64
64
  "yaml": "^2.9.0"
65
65
  },
66
66
  "devDependencies": {