@vcp-dev/site-edit-engine 0.10.24 → 0.10.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import*as xh from"@babel/parser";import*as Vn from"@babel/types";import*as Wt from"node:path";var Ss=[".tsx",".ts",".jsx",".js"],bh=Ss.map(e=>`/index${e}`),Sh=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function Hl(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Sh.has(n[1].toLowerCase())}function Wl(e){let t=[];for(let n of e.program.body)Vn.isImportDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Vn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Vn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value);return Es(e.program,t),t}function Es(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&wt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Es(o,t);else r&&typeof r=="object"&&Es(r,t)}function wt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function dn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Wt.dirname(e);return Wt.join(n,t).replace(/\\/g,"/")}async function Eh(e,t){if(Ss.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Ss){let r=`${e}${n}`;if(await t(r))return r}for(let n of bh){let r=`${e}${n}`;if(await t(r))return r}return null}async function fn(e,t,n){let r=await wo(e,t,n);return r.ok?r.path:null}async function wo(e,t,n){let r=dn(e,t);try{if(!vh(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await Eh(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function vh(e,t,n){if(!wt(t)||t.includes("\0")||t.includes("\\")||Wt.posix.isAbsolute(n))return!1;let r=Wt.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!Wt.posix.isAbsolute(e)}import{createHash as Ih}from"node:crypto";import*as Gl from"@babel/parser";function pn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:pn(t,n,r,o)}}function vs(e,t,n,r,o){return{ok:!1,source:e,diagnostic:pn(t,n,r,o)}}var kh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Nt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Gl.parse(t,{sourceType:"module",plugins:kh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:pn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ks(e,t){return Nt({source:e,profile:Yl(t.kind)})}function gr(e,t){return Nt({source:e,profile:Yl(t)})}function Yl(e){return"next-app-entry"}function mn(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var gn=(e,t)=>{let n=Nt({source:t,profile:mn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Ih("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Wl(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Ch(e,t){return gn(e,t)}function Rh(e,t){return dn(e,t)}import{SiteEditOperationRequestSchema as FR,SiteEditPatchPlanSchema as _R}from"@vcp-dev/contracts";function hn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function No(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Po(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Ao(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:wh(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function To(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:hn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function wh(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{checkGlobalsCssEdit as KC,computeSiteEditCompositionKey as JC,getSiteEditSourceDeleteProtectionReason as XC,isSiteEditTextSourcePath as zC,parseSiteEditRepeatInstanceKey as HC,SITE_EDIT_SOURCE_DELETE_CAPABILITY as WC,stripSiteEditRepeatInstanceKeys as qe}from"@vcp-dev/contracts";import es from"node:path";import{parse as GC}from"yaml";import Ns from"node:path";import{TextDecoder as Ph}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Ql,SITE_EDIT_SOURCE_ALLOWED_DIRS as ql,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as eu,SiteEditCompositionContextSchema as Ah,SiteEditSourceFileResponseSchema as Is,SiteEditSourceLocationSchema as Th,SiteEditSourcePathSchema as Fo,SiteEditSourceTreeResponseSchema as Fh,isSiteEditTextSourcePath as _h}from"@vcp-dev/contracts";import{createHash as Nh}from"node:crypto";var hr=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ve(e){return`sha256:${Nh("sha256").update(e).digest("hex")}`}var Oh=[...eu,...Ql,...ql];function Ps(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return Ah.parse(e.composition)}var Cs=2e3,Rs=12,ws=24*1024*1024,Zl=512*1024,Mh=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),Dh={".avif":"image/avif",".bin":"application/octet-stream",".eot":"application/vnd.ms-fontobject",".gif":"image/gif",".glb":"model/gltf-binary",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wasm":"application/wasm",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".zip":"application/zip"},Lh={".cjs":"javascript",".css":"css",".cts":"typescript",".html":"html",".js":"javascript",".jsx":"javascript",".json":"json",".md":"markdown",".mdx":"markdown",".mjs":"javascript",".mts":"typescript",".ts":"typescript",".tsx":"typescript",".txt":"plaintext",".yaml":"yaml",".yml":"yaml"},Bh=new Ph("utf-8",{fatal:!0});async function _o(e,t={}){let n=Ps(t),{files:r,truncated:o}=await Xh(e,t),i=Wh(r.map(s=>s.metadata));return Fh.parse({composition:n,nodes:i,defaultPath:Gh(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Oo(e,t,n={}){let r=Ps(n),o=Fo.parse(t.path),i=await jh(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Ts(o)){let a=ru(o),c=await Uh(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Is.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await As(e,o);return s.ok?Is.parse({composition:r,path:o,kind:"text",language:ou(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):Is.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function As(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=$h(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function $h(e){if(e.includes(0))return null;try{return Bh.decode(e)}catch{return null}}async function jh(e,t,n){if(!Kh(t,n))return null;let r=await Vh(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Vh(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=tu(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(Ts(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Uh(e,t){if(!Mh.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Zl)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Zl?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Kh(e,t){return eu.some(n=>n===e)||Ql.some(n=>n===e)||ql.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Fo.safeParse(n);return r.success&&r.data===e})}function Mo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Th.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function tu(e){return Array.isArray(e)?{files:e}:e}function Jh(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Xh(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=tu(await e.listFiles({roots:zh(t),maxFiles:Cs+1,maxDepth:Rs,maxTotalBytes:ws+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Fo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Rs){o.add("max-depth");continue}if(r.size>=Cs){o.add("max-files");break}if(i+a.sizeBytes>ws){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Hh(l,a.sizeBytes,Ps(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Jh([...o]),maxFiles:Cs,maxDepth:Rs,maxTotalBytes:ws}}:{}}}function zh(e){let t=new Set(Oh);for(let n of e.routeEntryFiles??[]){let r=Fo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Hh(e,t,n){return Ts(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:ru(e),readonly:!0}:{composition:n,path:e,kind:"text",language:ou(e),sizeBytes:t,readonly:!1}}function Wh(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(d=>d.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return nu(t)}function nu(e){return e.map(t=>t.kind==="directory"?{...t,children:nu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Gh(e){let t=e.find(r=>r.path.toLowerCase()==="design.md");if(t)return t.path;let n=e.find(r=>r.path==="app/page.tsx");return n?n.path:e.find(r=>r.kind==="text")?.path??e.at(0)?.path}function Ts(e){return!_h(e)}function ru(e){let t=Ns.posix.extname(e).toLowerCase();return!t&&Ns.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":Dh[t]??"application/octet-stream"}function ou(e){let t=Ns.posix.extname(e).toLowerCase();return Lh[t]??"plaintext"}import Fs from"@babel/traverse";import*as Pt from"@babel/types";function Pe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Pt.isJSXIdentifier(t)){let o=e.scope.getBinding(t.name);if(!o)return!1;let i=o.path;if(!i.isImportSpecifier())return!1;let s=i.node.imported;return(Pt.isIdentifier(s)&&s.name==="Fragment"||Pt.isStringLiteral(s)&&s.value==="Fragment")&&iu(i.parentPath)}if(!Pt.isJSXMemberExpression(t)||!Pt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Pt.isJSXIdentifier(t.object))return!1;let n=e.scope.getBinding(t.object.name);if(!n)return!1;let r=n.path;return(r.isImportDefaultSpecifier()||r.isImportNamespaceSpecifier())&&iu(r.parentPath)}function iu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Gt=typeof Fs=="function"?Fs:Fs.default,Do=new WeakMap,Lo=new WeakMap;function At(e,t){let n=ks(e,t);if(!n.ok)return vs(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=se(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:vs(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function se(e,t){return t.kind==="jsx-node"?lu(e,t):t.kind==="jsx-attribute"?ty(e,t):t.kind==="value"?ny(e,t):t.kind==="expression"?ry(e,t):t.kind==="directive"?oy(e,t):t.kind==="export"?iy(e,t):{ok:!1,diagnostic:pn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function lu(e,t){return t.strategy==="source-range"?Yh(e,t):Zh(e,t)}function Yh(e,t){let n=null;if(Gt(e,{JSXElement(o){if(!yn(o.node,t.sourceRange))return;let i=Oe("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!yn(o.node,t.sourceRange))return;let i=Oe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!yn(o.node,t.sourceRange))return;let i=Oe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!yn(o.node,t.sourceRange))return;let i=Oe("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Me("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!yy(r.path,t.expectedIdentity)?Me("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Zh(e,t){if(t.structuralPath===""){let r=qh(e,t.component);if(r){let o=ey(r);if(o)return o}}let n=null;return Gt(e,{JSXElement(r){if(xr(r)!==t.component||Os(r)!==t.structuralPath)return;let i=Oe("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(xr(r)!==t.component||Os(r)!==t.structuralPath)return;let i=Oe("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Qh(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Me("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Qh(e,t,n){let r=null;return Gt(e,{JSXElement(o){if(xr(o)!==t||!yn(o.node,n))return;let i=Oe("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(xr(o)!==t||!yn(o.node,n))return;let i=Oe("jsx-node",o);i&&(r=i,o.stop())}}),r}function qh(e,t){let n=null;return Gt(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function ey(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return Me("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function ty(e,t){let n=lu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>xy(c,t.name));if(!s||!s.isJSXAttribute())return Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Oe("jsx-attribute",s);return a?{ok:!0,match:a}:Me("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function ny(e,t){let n=sy(e,t);if(!n.ok)return n;let r=ay(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ut(r.match.path.node.loc,t.expectedRange)?Me("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function ry(e,t){let n=null;return Gt(e,{Identifier(r){if(!py(r))return;let o=au(r);if(!o||!cu(o,t))return;let i=Oe("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=au(r);if(!o||!cu(o,t))return;let i=Oe("expression",r);i&&(t.expectedRange&&!Ut(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("expression","locator-miss","Expression not found")}function oy(e,t){let n=null;return Gt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ut(i.node.loc,t.expectedRange))return;let s=Oe("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Me("directive","locator-miss",`Directive '${t.value}' not found`)}function iy(e,t){let n=null;return Gt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Oe("export",c);if(!m||t.expectedRange&&!Ut(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=Ms(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let d=l.get("init");if(!d.node)return;let f=Oe("export",d);if(!f||t.expectedRange&&!Ut(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ms(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ut(s.node.loc,t.expectedRange))return;let a=Oe("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Oe("export",o);i&&(t.expectedRange&&!Ut(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Me("export","export-not-found",`Export '${hy(t)}' not found`)}function sy(e,t){let n=null;return Gt(e,{Expression(r){if(n||t.root.kind!=="expression"||!yn(r.node,t.root.sourceRange))return;let o=Oe("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let u=r.get("init");if(!u.node)return;let g=Oe("value",u);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(u=>u?.type==="Identifier"&&u.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let d=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${d}`);if(!f||Array.isArray(f)||!f.node)return;let m=Oe("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Ms(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Oe("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Oe("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Me("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function ay(e,t){let n=_s(e);for(let o of t){if(n=_s(n),o.kind==="property"){if(!n.isObjectExpression())return Me("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Me("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>by(l,o.name));if(!c||!c.isObjectProperty())return Me("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Me("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Me("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Me("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=_s(n);let r=Oe("value",n);return r?{ok:!0,match:r}:Me("value","locator-miss","Resolved value has no source range")}function _s(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Oe(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function yn(e,t){return Ut(e.loc,t)}function Ut(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function Os(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Pe(n)){let o=du(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${su(n,o)}`):t.unshift(`${o}#${su(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||dy(n.parentPath)&&!fy(n.parentPath))break;n=n.parentPath}return t.join("/")}function su(e,t){let n=uu(e)??e.getFunctionParent();if(!n)return 0;let r=Do.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Do.get(n.node)?.get(t);if(!i){let a=Do.get(n.node);a||(a=new Map,Do.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?yr(n):cy(n);for(let a of s)if(du(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function cy(e){let t=Lo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!uu(r)&&n.push(r)}}),Lo.set(e.node,n),n}function uu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Pe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function yr(e){let t=Lo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Pe(o)){n.push(...yr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...yr(o));continue}o.isJSXExpressionContainer()&&n.push(...Vt(o.get("expression")))}return Lo.set(e.node,n),n}function Vt(e){if(e.isJSXElement())return Pe(e)?yr(e):[e];if(e.isJSXFragment())return yr(e);if(e.isParenthesizedExpression())return Vt(e.get("expression"));if(e.isLogicalExpression()&&ly(e.node.operator))return Vt(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Vt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Vt(a));break}}return i}else if(o.node&&o.isExpression())return Vt(o)}}}}return e.isConditionalExpression()?[...Vt(e.get("consequent")),...Vt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Vt(t)):[]}function ly(e){return e==="&&"||e==="||"||e==="??"}function du(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?uy(e.name):null}function uy(e){let t=[],n=e;for(;n.type==="JSXMemberExpression";)t.unshift(n.property.name),n=n.object;return t.unshift(n.name),t.join(".")}function xr(e){let t=e;for(;t;){if(t.isFunctionDeclaration())return t.node.id?.name??null;if((t.isArrowFunctionExpression()||t.isFunctionExpression())&&t.parentPath?.isVariableDeclarator()){let n=t.parentPath.node.id;return n.type==="Identifier"?n.name:null}t=t.parentPath}return null}function dy(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function fy(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function py(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function au(e){if(e.isIdentifier())return{base:e.node.name,path:[]};if(!e.isMemberExpression())return null;let t=[],n=e.node;for(;n.type==="MemberExpression";){if(n.computed)if(n.property.type==="NumericLiteral")t.unshift({kind:"index",index:n.property.value});else if(n.property.type==="StringLiteral")t.unshift({kind:"property",name:n.property.value});else return null;else if(n.property.type==="Identifier")t.unshift({kind:"property",name:n.property.name});else return null;if(n.object.type==="Identifier")return{base:n.object.name,path:t};if(n.object.type!=="MemberExpression")return null;n=n.object}return null}function cu(e,t){return e.base===t.base&&my(e.path,t.path??[])}function my(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}function gy(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function hy(e){return e.exportKind==="named"?e.name:e.exportKind}function Me(e,t,n,r){return{ok:!1,diagnostic:pn(t,n,e,r)}}function yy(e,t){return xr(e)!==t.component?!1:Os(e)===t.structuralPath}function xy(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Ms(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function by(e,t){return e.isObjectProperty()?gy(e.node)===t:!1}import*as pu from"@babel/parser";import{arrayExpression as Iy,booleanLiteral as Cy,identifier as Ry,jsxAttribute as wy,jsxExpressionContainer as Ny,jsxIdentifier as Py,nullLiteral as Ay,numericLiteral as Ty,objectExpression as Fy,objectProperty as _y,stringLiteral as Ls}from"@babel/types";import Ds from"@babel/generator";var Sy=typeof Ds=="function"?Ds:Ds.default;function Ey(e){let t=e.split(`
2
- `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function vy(e,t){let n=e.match(/^(\s+)(.*)/s);if(!n)return e;let r=n[1],o=n[2];if(r.length===0)return e;let i=r.includes(" ")?r.split(" ").length-1:Math.max(1,Math.round(r.length/2)),s=Math.min(Math.max(i,0),20);return t==="tab"?" ".repeat(s)+o:t==="4"?" ".repeat(s)+o:" ".repeat(s)+o}function ky(e,t){return e.split(`
3
- `).map(r=>vy(r,t)).join(`
4
- `)}function Bo(e){let{ast:t,source:n}=e;try{let r=Ey(n),i=Sy(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=ky(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function fu(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t|=0}return`0x${Math.abs(t).toString(16)}`}function br(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:fu(e),afterSourceHash:fu(t),inverse:n.inverse}}}function me(e,t,n){let r=Bo({ast:e,source:t});return r.ok?br(t,r.source,n):r}function we(e,t){let n=gr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function $o(e,t){return Bo({ast:e,source:t})}function Oy(e,t,n){let r=se(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function jo(e,t,n){let r=Oy(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Yt(e){return typeof e=="string"?Ls(e):typeof e=="number"?Ty(e):typeof e=="boolean"?Cy(e):e===null?Ay():Array.isArray(e)?Iy(e.map(t=>Yt(t))):Fy(Object.entries(e).map(([t,n])=>{let r=_y(Bs(t),Yt(n));return t==="__proto__"&&(r.computed=!0),r}))}function My(e){return typeof e=="string"?Ls(e):Ny(Yt(e))}function Sr(e,t){return wy(Py(e),My(t))}function Vo(e,t){try{let r=pu.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:J(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Bs(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?Ry(e):Ls(e)}function Uo(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=se(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=Dy(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Ly(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return me(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function Dy(e){let t=[],n=e.isJSXElement()||e.isJSXFragment()?e.get("children"):[];for(let r of n){if(r.isJSXText()){r.node.value.trim().length>0&&t.push({kind:"jsx-text",path:r});continue}if(r.isJSXExpressionContainer()){let o=By(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Ly(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function By(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)n[r].value.raw.trim().length>0&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as $s}from"@babel/types";function Un(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=se(r.ast,n);return o.ok?($y(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function $y(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith($s());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith($s());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith($s());return}e.remove()}import{cloneNode as jy}from"@babel/types";function Ko(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=se(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Vo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(jy(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Zy}from"@babel/types";import js from"@babel/traverse";import*as Q from"@babel/types";function Er(e,t,n){return`${e}::${t}::${n}`}var $={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var Vy=typeof js=="function"?js:js.default;function pt(e,t,n,r){if(!e.ok)return e;let o=ft(n,t);if(!o)return e;let i=Uy(t,o,r);return i?{...e,selectionRef:i}:e}function Uy(e,t,n){let r=Ky(e,t);if(!r)return;let o=n.sourceLocator?mu(n.sourceLocator):void 0,i=n.targetParentLocator?mu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Xy(r)??i?.component??o?.component;if(!(!s||!a))return{key:Er(s,a,zy(r))}}function mu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Ky(e,t){let n=Su(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Su(e,t){let n=null;return Vy(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function ft(e,t){if(!e)return null;if(Q.isJSXElement(e))return Yy(t,e)?gu(e.children,t):e;if(Q.isJSXFragment(e))return gu(e.children,t);if(Q.isJSXExpressionContainer(e)||Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSTypeAssertion(e)||Q.isTSNonNullExpression(e))return ft(e.expression,t);if(Q.isLogicalExpression(e))return ft(e.right,t);if(Q.isConditionalExpression(e))return ft(e.consequent,t)??ft(e.alternate,t);if(Q.isCallExpression(e)||Q.isOptionalCallExpression(e))return Eu(e)?Jy(e.arguments[0],t):null;if(Q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=ft(n,t);if(r)return r}return null}function gu(e,t){for(let n of e){let r=ft(n,t);if(r)return r}return null}function Jy(e,t){return!e||!Q.isArrowFunctionExpression(e)&&!Q.isFunctionExpression(e)?null:Q.isBlockStatement(e.body)?vr(e.body.body,t):ft(e.body,t)}function vr(e,t){for(let n of e){if(Q.isReturnStatement(n)){let r=ft(n.argument,t);if(r)return r;continue}if(Q.isBlockStatement(n)){let r=vr(n.body,t);if(r)return r;continue}if(Q.isIfStatement(n)){let r=hu(n.consequent,t);if(r)return r;let o=n.alternate?hu(n.alternate,t):null;if(o)return o;continue}if(Q.isSwitchStatement(n))for(let r of n.cases){let o=vr(r.consequent,t);if(o)return o}}return null}function hu(e,t){return Q.isBlockStatement(e)?vr(e.body,t):vr([e],t)}function Xy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isExportDefaultDeclaration()){let n=t.node.declaration;if(Q.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Q.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}var yu=new WeakMap,xu=new WeakMap,Vs=new WeakMap;function zy(e){let t=yu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Hy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return yu.set(e.node,o),o}function Hy(e){let t=vu(e.node.openingElement.name);return!t||Pe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${bu(e,t)}`:`${t}#${bu(e,t)}`}function bu(e,t){let n=Wy(e);if(!n)return 0;let r=Vs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Vs.get(n.node);o||(o=new Map,Vs.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of xn(n))if(vu(a.node.openingElement.name)===t){if(i.set(a.node,s),a.node===e.node)return s;s+=1}return i.get(e.node)??0}function Wy(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Pe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function xn(e){let t=xu.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Pe(o)){n.push(...xn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...xn(o));continue}o.isJSXExpressionContainer()&&n.push(...Tt(o.get("expression")))}return xu.set(e.node,n),n}function Tt(e){if(e.isJSXElement())return Pe(e)?xn(e):[e];if(e.isJSXFragment())return xn(e);if(e.isParenthesizedExpression())return Tt(e.get("expression"));if(e.isLogicalExpression())return Tt(e.get("right"));if(e.isConditionalExpression())return[...Tt(e.get("consequent")),...Tt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Tt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Eu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Gy(n):[]}return[]}function Gy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Pe(t)?xn(t):[t];if(t.isJSXFragment())return xn(t);if(t.isParenthesizedExpression())return Tt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Tt(t);if(!t.isBlockStatement())return[];let n=[];for(let r of t.get("body")){if(r.isVariableDeclaration())for(let i of r.get("declarations")){let s=i.get("init");(s.isJSXElement()||s.isJSXFragment())&&n.push(...Tt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Tt(o)),n}return n}function Eu(e){let t=e.callee;return(Q.isMemberExpression(t)||Q.isOptionalMemberExpression(t))&&Q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Yy(e,t){let n=Su(e,t);return n?Pe(n):!1}function vu(e){return Q.isJSXIdentifier(e)?e.name:Q.isJSXMemberExpression(e)?ku(e):Q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function ku(e){return`${Q.isJSXIdentifier(e.object)?e.object.name:ku(e.object)}.${e.property.name}`}function Zt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Us(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Us(n))return null;let r=n;for(;r&&r!==e;){if(!Us(r)||!Pe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Us(e){return e.isJSXElement()||e.isJSXFragment()}function Kn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let I=c.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=Vo(t,r.jsx);if(!d.ok)return d.result;let f=Zy(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=I=>s?pt(I,a.ast,f,u):I;if(o==="append")return m.push(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=se(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let b=Zt(c.match.path,h.match.path);if(!b)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=b;let E=l.node.children,v=E.findIndex(I=>I===h.match.path.node);return v===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Iu from"@babel/parser";import{cloneNode as Qy}from"@babel/types";function Jo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=qy(t,r);if(!c.ok)return c.result;let l=se(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=l.match.path,f=null;if(i){let E=se(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let v=Zt(l.match.path,E.match.path);if(!v)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=v,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Qy(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?pt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let b=u.findIndex(E=>E===f);return b===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function qy(e,t){try{let r=Iu.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as ex,nullLiteral as Ks}from"@babel/types";import*as Qt from"@babel/types";import*as Cu from"@babel/types";function kr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Cu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Jn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=se(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let I=se(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=I.match.path.isJSXElement()?kr(I.match.path,l.match.path):I.match.path,P=Zt(l.match.path,R);if(!P)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=P,f=R}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?kr(c.match.path,l.match.path):c.match.path,g=ex(u.node,!0);if(!Qt.isJSXElement(g)&&!Qt.isJSXExpressionContainer(g)&&!Qt.isJSXFragment(g)&&!Qt.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=u.parentPath?.node===d.node&&typeof u.key=="number"?u.key:-1;if(f&&u.parentPath?.node===f.parentPath?.node&&u.key===f.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");tx(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),pt($o(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),pt($o(a.ast,t),a.ast,g,E);let v=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?v:v+1,0,g),pt($o(a.ast,t),a.ast,g,E)}function tx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ks());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ks());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ks());return}e.remove()}import*as Ru from"@babel/parser";import{cloneNode as nx,nullLiteral as Js}from"@babel/types";function Xo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=rx(t,s);if(!l.ok)return l.result;let d=se(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};let f=se(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let I=f.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let I=se(c.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=Zt(f.match.path,I.match.path);if(!R)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=R,u=I.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=nx(l.node,!0);ox(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),pt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);if(o==="prepend")return E.unshift(h),pt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let v=E.findIndex(I=>I===u);return v===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,h),pt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function rx(e,t){try{let r=Ru.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ox(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Js());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Js());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Js());return}e.remove()}import{SiteEditSetPropsParamsSchema as ix,classifySiteEditPropertyName as sx}from"@vcp-dev/contracts";import*as Xn from"@babel/types";function zo(e){let t=ix.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=jo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=sx(a.name);if(c.owner!=="generic")return J(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Xn.isJSXAttribute),s=new Map;for(let a of i){let c=ax(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(d=>d!==c));continue}let l=Sr(a.name,a.value).value;c?c.value=l:o.attributes.push(Sr(a.name,a.value))}return me(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function ax(e){return Xn.isJSXIdentifier(e.name)?e.name.name:Xn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as $e from"@babel/types";import{classifySiteEditPropertyName as wu}from"@vcp-dev/contracts";function Ho(e){let t=wu(e.name),n=wu(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Nu(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=jo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>$e.isJSXAttribute(l)&&lx(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=cx(e.object,e.property),c=s[0];if(c)c.value=$e.jsxExpressionContainer(a);else{let l=Sr(e.name,"");l.value=$e.jsxExpressionContainer(a),i.attributes.push(l)}return me(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function cx(e,t){return Nu(t)?$e.memberExpression($e.identifier(e),$e.identifier(t)):$e.memberExpression($e.identifier(e),$e.stringLiteral(t),!0)}function Nu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function lx(e){return $e.isJSXIdentifier(e.name)?e.name.name:$e.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as dx,identifier as Ir,importDeclaration as fx,importDefaultSpecifier as px,importNamespaceSpecifier as mx,importSpecifier as gx,isImportDefaultSpecifier as Pu,isImportNamespaceSpecifier as Au,isImportSpecifier as Tu,stringLiteral as hx}from"@babel/types";function zn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!Cx(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=vx(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let v=Rx(b,E);return v?[v]:[]}))),f=i.imports.filter(b=>!d.has(Lu(b)));if(f.length===0)return br(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=kx(c.body),u=f.find(b=>m.has(Xs(b)));if(u)return J(t,"unsupported-syntax",`Import local binding already exists: ${Xs(u)}`);let g=Ex(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!Mu(_u(b)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(v=>yx(v,b));if(E)xx(E,b);else{let v=fx(Fu(b),hx(n));Ix(c.body,v),l.push(v)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function yx(e,t){return e.importKind==="type"?!1:Mu(Sx(bx(e),_u(t)))}function xx(e,t){let n=!1,r=new Set(e.specifiers.map(o=>zs(o)));for(let o of Fu(t)){let i=zs(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Du(e.specifiers),{changed:n}}function Fu(e){let t=e.map(n=>{switch(n.kind){case"named":return gx(n.local?Ir(n.local):Ir(n.imported),Ir(n.imported));case"default":return px(Ir(n.local));case"namespace":return mx(Ir(n.local));default:return n}});return Du(t),t}function _u(e){let t=Ou();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function bx(e){let t=Ou();for(let n of e.specifiers)Pu(n)?t.defaultLocals.add(n.local.name):Au(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Ou(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function Sx(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Mu(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Du(e){let t=[...e.filter(n=>Pu(n)),...e.filter(n=>Au(n)),...e.filter(n=>Tu(n))];e.splice(0,e.length,...t)}function Ex(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function vx(e){let t=new Map,n=new Map;for(let r of e){let o=Lu(r);if(t.has(o))continue;let i=Xs(r),s=n.get(i);if(s&&s!==o)return{ok:!1,message:`Import local binding is requested more than once: ${i}`};t.set(o,r),n.set(i,o)}return{ok:!0,imports:[...t.values()]}}function kx(e){let t=new Set;for(let n of e){if(n.type==="ImportDeclaration"){for(let o of n.specifiers)t.add(o.local.name);continue}let r=(n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration")&&n.declaration?n.declaration:n;if(r.type==="VariableDeclaration")for(let o of r.declarations)for(let i of Object.keys(dx(o.id)))t.add(i);else(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration"||r.type==="TSEnumDeclaration")&&r.id&&t.add(r.id.name)}return t}function Ix(e,t){let n=[...e].reverse().findIndex(r=>r.type==="ImportDeclaration");if(n===-1)e.unshift(t);else{let r=e.length-n;e.splice(r,0,t)}}function Cx(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string"&&(e.local===void 0||typeof e.local=="string"):t==="default"||t==="namespace"?typeof e.local=="string":!1}function Lu(e){switch(e.kind){case"default":return`default:${e.local}`;case"namespace":return`namespace:${e.local}`;case"named":return`named:${e.imported}:${e.local??e.imported}`;default:return e}}function Xs(e){return e.kind==="named"?e.local??e.imported:e.local}function Rx(e,t){return e.importKind==="type"||Tu(t)&&t.importKind==="type"?null:zs(t)}function zs(e){if(e.type==="ImportDefaultSpecifier")return`default:${e.local.name}`;if(e.type==="ImportNamespaceSpecifier")return`namespace:${e.local.name}`;let t=e.imported.type==="Identifier"?e.imported.name:e.imported.value,n=e.local.name;return`named:${t}:${n}`}function Hn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(d=>!Nx(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.source.value===n);if(c===-1)return br(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>wx(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function wx(e,t){return t.kind==="default"?e.type==="ImportDefaultSpecifier":t.kind==="namespace"?e.type==="ImportNamespaceSpecifier":e.type!=="ImportSpecifier"?!1:(e.imported.type==="Identifier"?e.imported.name:e.imported.value)===t.imported}function Nx(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string":t==="default"||t==="namespace"}function Cr(e){let{source:t,locator:n,next:r}=e,o=Zo(t,n);return o.ok?(o.path.replaceWith(Yt(r)),me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Wo(e){let{source:t,locator:n,index:r,value:o}=e,i=Zo(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Yt(o)),me(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Go(e){let{source:t,locator:n,index:r}=e,o=Zo(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),me(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Yo(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Zo(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return J(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),me(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Zo(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=se(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Ue from"@babel/types";function Qo(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=se(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Ue.isSpreadElement(a)||Ue.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ue.isObjectProperty(a)&&Px(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ue.unaryExpression("void",Ue.numericLiteral(0)):Yt(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ue.objectProperty(Bs(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return me(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Px(e){return Ue.isIdentifier(e)?e.name:Ue.isStringLiteral(e)?e.value:Ue.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Ax,isSiteEditRuntimeVoidElementTag as Tx}from"@vcp-dev/contracts/site-edit-runtime-capability";function Wn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function Fx(e,t,n){let r=Wn(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(R=>({kind:R.kind,message:R.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&Tx(d),u=f||Ax(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(R=>R.editable);m&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let b=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&u&&(!a||g);return{composition:r,key:e,canUpdateText:b,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function Bu(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Fx(r,e,t));return n}function Hs(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=_x(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:ju(r),version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:$u(e.route.source,o),valueRaw:s?$u(e.route.source,s):null,attrRange:ju(o),diagnostics:[]}}function Vu(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function _x(e,t){let n=Nt({source:e,profile:mn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=se(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Ox(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Uu(e){let t=Nt({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function $u(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function ju(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function Ox(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Ku(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as Mx}from"node:crypto";import qo from"node:fs/promises";import Ws from"node:path";import{setTimeout as Dx}from"node:timers/promises";var Lx={async mkdir(e,t){await qo.mkdir(e,t)},async writeFile(e,t,n){await qo.writeFile(e,t,n)},async rename(e,t){await qo.rename(e,t)},async rm(e,t){await qo.rm(e,t)}},Bx=new Set(["EACCES","EBUSY","EPERM"]),$x=[10,20,40,80,160];async function jx(e,t,n){for(let r of $x)try{await e.rename(t,n);return}catch(o){if(!Vx(o))throw o;await Dx(r)}await e.rename(t,n)}function Vx(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Bx.has(e.code)}async function ei(e,t,n=Lx){let r=Ws.dirname(e),o=Ws.basename(e),i=Ws.join(r,`.${o}.${process.pid}.${Mx()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await jx(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Ys from"@babel/traverse";import*as S from"@babel/types";import*as ue from"@babel/types";function Ft(e,t={}){if(ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTypeCastExpression(e)||ue.isParenthesizedExpression(e))return Ft(e.expression,t);if(ue.isStringLiteral(e))return{status:"resolved",value:e.value};if(ue.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(ue.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(ue.isNullLiteral(e))return{status:"resolved",value:null};if(ue.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(ue.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(ue.isUnaryExpression(e)&&e.operator==="void"&&ue.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(ue.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||ue.isSpreadElement(r))return{status:"unresolved"};let o=Ft(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(ue.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!ue.isObjectProperty(r)||r.computed||!ue.isExpression(r.value))return{status:"unresolved"};let o=Ux(r.key);if(o===null)return{status:"unresolved"};let i=Ft(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return ue.isMemberExpression(e)||ue.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Ux(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:ue.isNumericLiteral(e)?String(e.value):null}var ti="components/ui";function bn(e){if(!e)return!1;let t=Gs(e);return t===ti||t.startsWith(`${ti}/`)||t.includes(`/${ti}/`)||t.endsWith(`/${ti}`)}function Rr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?bn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?bn(Gs(`${Kx(t)}/${e}`)):bn(e):!1}function Gs(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function Kx(e){let t=Gs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}var Jx=typeof Ys=="function"?Ys:Ys.default;function Xe(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function Xx(e){return/^[A-Z]/.test(e)}function ta(e){let t=e.openingElement;return S.isJSXIdentifier(t.name)?t.name.name==="Fragment":S.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Yn(e){return S.isJSXFragment(e)}function Xu(e){return S.isJSXIdentifier(e.name)?e.name.name:S.isJSXMemberExpression(e.name)?zu(e.name):S.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function zu(e){return S.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:S.isJSXMemberExpression(e.object)?`${zu(e.object)}.${e.property.name}`:e.property.name}function zx(e){return e.split(".")[0]??e}function Hx(e){let t=e;for(;t;){let n=t.node;if(S.isFunctionDeclaration(n)&&n.id||S.isVariableDeclarator(n)&&S.isIdentifier(n.id))return n.id.name;if(S.isExportDefaultDeclaration(n)){let r=n.declaration;if(S.isFunctionDeclaration(r)&&r.id)return r.id.name;if(S.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Wx(){let e=new Map;return{getOrdinal(t,n){let r=t??"__root__";e.has(r)||e.set(r,new Map);let o=e.get(r),i=o.get(n)??0;return o.set(n,i+1),i}}}function Gx(e){let t=new Map;for(let n of e.program.body){if(!S.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(S.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(S.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(S.isImportSpecifier(o)){let i=S.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Kt(e,t=[]){if(S.isIdentifier(e))return t.push(e.name),t;if(S.isObjectPattern(e)){for(let n of e.properties)S.isObjectProperty(n)?Kt(n.value,t):S.isRestElement(n)&&Kt(n.argument,t);return t}if(S.isArrayPattern(e)){for(let n of e.elements)n&&(S.isRestElement(n)?Kt(n.argument,t):Kt(n,t));return t}return S.isAssignmentPattern(e)?(Kt(e.left,t),t):(S.isRestElement(e)&&Kt(e.argument,t),t)}function St(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function wr(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function Yx(e,t,n){e.set(t,{resolved:!0,value:n})}function na(e,t){e.set(t,{resolved:!1})}function Hu(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function Le(e,t,n){if(S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTypeCastExpression(e)||S.isParenthesizedExpression(e))return Le(e.expression,t,n);if(S.isLogicalExpression(e))return ni([Le(e.left,t,n),Le(e.right,t,n)]);if(S.isBinaryExpression(e))return ni([S.isExpression(e.left)?Le(e.left,t,n):null,S.isExpression(e.right)?Le(e.right,t,n):null]);if(S.isConditionalExpression(e))return ni([Le(e.consequent,t,n),Le(e.alternate,t,n)]);if(S.isTemplateLiteral(e))return ni(e.expressions.filter(S.isExpression).map(i=>Le(i,t,n)));if(S.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!S.isMemberExpression(e)&&!S.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;S.isMemberExpression(o)||S.isOptionalMemberExpression(o);){if(o.computed)if(S.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(S.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&S.isExpression(o.property)){let i=qt(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!S.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return S.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:St(e,t),base:o.name,path:r}:null}function ni(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function qt(e,t){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(S.isIdentifier(e)){let n=wr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return;let o=qt(r,t);if(o===void 0)return;n.push(o)}return n}if(S.isObjectExpression(e)){let n={};for(let r of e.properties){if(!S.isObjectProperty(r)||r.computed||!S.isExpression(r.value))return;let o=null;if(S.isIdentifier(r.key)?o=r.key.name:S.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!S.isIdentifier(r.value))return;let s=wr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=qt(r.value,t);if(i===void 0)return;n[o]=i}return n}if(S.isMemberExpression(e)){let n=Le(e,"",t);if(!n)return;let r=wr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Hu(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(S.isCallExpression(e))return Gu(e,t)??void 0}function Wu(e,t,n){let r=Le(e,n,t);if(!r)return S.isMemberExpression(e)||S.isBinaryExpression(e)||S.isLogicalExpression(e)||S.isConditionalExpression(e)||S.isCallExpression(e)?{value:St(e,n),source:null}:null;let o=wr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Hu(o.value,r.path):o;return i.kind==="resolved"&&(typeof i.value=="string"||typeof i.value=="number")?{value:String(i.value),source:r}:i.kind==="resolved"&&(typeof i.value=="boolean"||i.value===null)||i.kind==="known-empty"?null:{value:r.expression,source:r}}function Zs(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Wx(),parentStack:[],valueScopes:i,importMap:o}}function qs(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Kt(o.id))na(n,s);if(!S.isIdentifier(o.id)||!o.init||!S.isExpression(o.init))continue;let i=qt(o.init,t);i!==void 0&&Yx(n,o.id.name,i)}}function Zx(e){let t=[];for(let n of e){if(S.isVariableDeclaration(n)){t.push(n);continue}S.isExportNamedDeclaration(n)&&n.declaration&&S.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Qx(e,t,n){let r=[],o=0;for(let i of e)if(S.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Xe(i),editable:!0,source:null})}else if(S.isJSXExpressionContainer(i)&&S.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Xe(i),editable:!0,source:null});else if(S.isJSXExpressionContainer(i)&&S.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:Xe(i),editable:!0,source:null}):r.push({index:o++,value:St(s,n),sourceRange:Xe(i),editable:!0,source:Le(s,n,t)})}else if(S.isJSXExpressionContainer(i)&&S.isExpression(i.expression)){let s=Wu(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Xe(i),editable:!0,source:s.source})}return r}function qx(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!S.isJSXAttribute(i))continue;let s=tb(i.name);if(!s)continue;let a=St(i,n);if(S.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Xe(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:Xe(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(S.isJSXExpressionContainer(i.value)&&S.isExpression(i.value.expression)){let c=qt(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?Gu(i.value.expression,t):null;if(u){r.push({name:s,value:u,sourceRange:Xe(i),source:null,resolvedValue:u,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:u}});continue}}let l=Wu(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:cb(c),sourceRange:Xe(i),source:Le(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let d=nb(i.value.expression,t),f=Le(i.value.expression,n,t),m=l?.value??St(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:Xe(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function eb(e,t,n){return e.attributes.flatMap((r,o)=>!S.isJSXSpreadAttribute(r)||!S.isExpression(r.argument)?[]:[{raw:St(r.argument,n),sourceRange:Xe(r),order:o,source:Le(r.argument,n,t)}])}function tb(e){return S.isJSXIdentifier(e)?e.name:S.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function nb(e,t){return Ft(e,{resolveIdentifier(n){let r=wr(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=qt(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Gu(e,t){let n=Gn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Gn(e,t){if(S.isStringLiteral(e))return[e.value];if(S.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(S.isNullLiteral(e))return[];if(S.isBooleanLiteral(e))return e.value?null:[];if(S.isIdentifier(e)||S.isMemberExpression(e)){if(S.isIdentifier(e)&&e.name==="undefined")return[];let n=qt(e,t);return typeof n=="string"?[n]:null}if(S.isConditionalExpression(e)){let n=Gn(e.consequent,t),r=Gn(e.alternate,t);return!n||!r?null:[...n,...r]}if(S.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=qt(e.left,t);return n===!1||n===null?[]:Gn(e.right,t)}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return null;let o=Gn(r,t);if(!o)return null;n.push(...o)}return n}if(S.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!S.isObjectProperty(r))return null;let o=ob(r.key);if(!o)return null;n.push(o)}return n}if(S.isCallExpression(e)){let n=rb(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!S.isExpression(o))return null;let i=Gn(o,t);if(!i)return null;r.push(...i)}return r}return null}function rb(e){return S.isIdentifier(e)?e.name:S.isMemberExpression(e)&&S.isIdentifier(e.property)?e.property.name:null}function ob(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)?e.value:null}function ib(e,t){let n=e.attributes.find(r=>S.isJSXAttribute(r)&&S.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!S.isJSXAttribute(n)||!S.isJSXExpressionContainer(n.value)?null:n.value.expression}function sb(e,t){for(let n of t){let r=ib(e,n);if(r)return r}return null}function ab(e){return S.isJSXIdentifier(e.name)?e.name.name:null}function cb(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function lb(e){if(!S.isCallExpression(e)&&!S.isOptionalCallExpression(e))return null;let t=e.callee;return!S.isMemberExpression(t)&&!S.isOptionalMemberExpression(t)||!S.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!S.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Qs(e){return S.isArrowFunctionExpression(e)||S.isFunctionExpression(e)}function ub(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function db(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Ju(e,t,n,r){if(!e||!S.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:St(e,n),collectionSource:Le(e,n,r)};if(t){let i=t.params[0],s=t.params[1];S.isIdentifier(i)&&(o.itemParamName=i.name),S.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Jt(e,t,n){if(!e)return[];if(S.isJSXElement(e)){if(ta(e))return ai(e.children,t,n);let r=ii(e,t,n);return r?[r]:[]}return Yn(e)?si(e,t,n):S.isParenthesizedExpression(e)?Jt(e.expression,t,n):S.isExpression(e)?ci(e,t,n):[]}function ri(e,t,n){let r=new Map;for(let o of e.params)for(let i of Kt(o))na(r,i);t.valueScopes.push(r);try{if(!S.isBlockStatement(e.body))return Jt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return Yu(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function Yu(e,t,n){let r=[];for(let o of e){if(S.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){qs([o],t,i);for(let s of o.declarations)S.isIdentifier(s.id)&&(S.isJSXElement(s.init)||S.isJSXFragment(s.init))&&r.push(...Jt(s.init,t,n))}continue}r.push(...ea(o,t,n))}return r}function ea(e,t,n){if(S.isReturnStatement(e))return e.argument?Jt(e.argument,t,n):[];if(S.isBlockStatement(e))return Sn(e.body,t,n);if(S.isIfStatement(e)){let r=S.isBlockStatement(e.consequent)?Sn(e.consequent.body,t,n):ea(e.consequent,t,n),o=e.alternate?S.isBlockStatement(e.alternate)?Sn(e.alternate.body,t,n):ea(e.alternate,t,n):[];return[...r,...o]}if(S.isSwitchStatement(e))return Sn(e.cases.flatMap(r=>r.consequent),t,n);if(S.isTryStatement(e)){let r=Sn(e.block.body,t,n);return e.handler&&r.push(...Sn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Sn(e.finalizer.body,t,n)),r}return[]}function Sn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Yu(e,t,n)}finally{t.valueScopes.pop()}}function oi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Xe(r),sourceCandidates:i&&i.length>0?i:void 0})}function fb(e,t,n,r){let o=sb(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Xu(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!S.isJSXAttribute(s))continue;let a=ab(s);if(!a||!S.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!S.isJSXEmptyExpression(c)){if(ub(a)&&Qs(c)){let l=ri(c,n,r),d=Ju(o,c,r,n);oi(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(db(a)){let l=Qs(c)?ri(c,n,r):Jt(c,n,r);oi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!S.isJSXExpressionContainer(s)||!Qs(s.expression))continue;let a=ri(s.expression,n,r),c=Ju(o,s.expression,r,n);oi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ii(e,t,n){let r=Xu(e.openingElement);if(r==="Fragment"||ta(e))return ai(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Xx(r),a;if(s){let R=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${R}`}else{let R=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${R}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=Er(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=Qx(e.children,t,n),g=qx(e.openingElement,t,n),h=eb(e.openingElement,t,n),b,E,v=!1;if(s){let R=t.importMap.get(r)??t.importMap.get(zx(r));R&&(b=R.specifier,E=R.exportName,v=Rr(R.specifier,t.file))}let I={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Xe(e),parentKey:i,childKeys:[],textSegments:u,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,I),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),fb(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),pb(e.children,t,n),t.parentStack.pop()),d}function si(e,t,n){return ai(e.children,t,n)}function ai(e,t,n){let r=[];for(let o of e)if(S.isJSXElement(o))if(ta(o))r.push(...ai(o.children,t,n));else{let i=ii(o,t,n);i&&r.push(i)}else Yn(o)?r.push(...si(o,t,n)):S.isJSXExpressionContainer(o)&&r.push(...ci(o.expression,t,n));return r}function pb(e,t,n){for(let r of e)S.isJSXElement(r)?ii(r,t,n):Yn(r)?si(r,t,n):S.isJSXExpressionContainer(r)&&ci(r.expression,t,n)}function mb(e){return e==="&&"||e==="||"||e==="??"}function ci(e,t,n){if(S.isJSXEmptyExpression(e))return[];let r=lb(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:St(r.collection,n),collectionSource:Le(r.collection,n,t)};if(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];S.isIdentifier(d)&&(c.itemParamName=d.name),S.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Xe(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a))&&l.childKeys.push(...ri(a,t,n)),l.childKeys}if(S.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.test,n),conditionSource:Le(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.consequent,t,n)),s.childKeys.push(...Jt(e.alternate,t,n)),s.childKeys}if(S.isLogicalExpression(e)&&mb(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:St(e.left,n),conditionSource:Le(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Xe(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Jt(e.right,t,n)),s.childKeys}if(S.isParenthesizedExpression(e))return ci(e.expression,t,n);if(S.isJSXElement(e)){let o=ii(e,t,n);return o?[o]:[]}return Yn(e)?si(e,t,n):[]}function gb(e){let t=e.argument;return t&&(S.isExpression(t)||Yn(t))?t:null}function Nr(e,t){let n=[];for(let r of e){if(S.isReturnStatement(r)){let o=gb(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(S.isIfStatement(r)){let o=S.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Nr(o,r.test)),r.alternate){let i=S.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Nr(i,r.test))}continue}if(S.isSwitchStatement(r))for(let o of r.cases){let i=o.test?S.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Nr(o.consequent,i))}}return n}function Zu(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=Gx(r);Jx(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=Hx(f);if(!m)return;let u=f.node,g=[];if(S.isArrowFunctionExpression(u))S.isExpression(u.body)||Yn(u.body)?g=[{argument:u.body,statement:S.returnStatement(S.isExpression(u.body)?u.body:null)}]:S.isBlockStatement(u.body)&&(g=Nr(u.body.body));else{let R=u.body;S.isBlockStatement(R)&&(g=Nr(R.body))}if(g.length===0){f.skip();return}let h=new Map;qs(Zx(r.program.body),Zs(t,m,i,s,l,[h]),h);let b=new Map;for(let R of u.params)for(let P of Kt(R))na(b,P);let E=S.isBlockStatement(u.body)?u.body.body:[],v=g[0]?.statement??null;for(let R of E){if(v&&R===v)break;S.isVariableDeclaration(R)&&qs([R],Zs(t,m,i,s,l,[h,b]),b)}let I=Zs(t,m,i,s,l,[h,b]);for(let R of g){let P=Jt(R.argument,I,n);for(let T of P)a.includes(T)||a.push(T);if(R.condition){let T={kind:"conditional-branch",conditionExpression:St(R.condition,n),conditionSource:Le(R.condition,n,I)};oi(I,"conditional-region","",R.statement,P,[T])}}f.skip()}});let d=[...i.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function ra(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function li(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Qu(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??gn,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=E=>{let v=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(v)||(m.add(v),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:v,source:I,depth:R,diagnosticEntryFile:P,importStack:T}=E;if(h.has(v))continue;h.add(v),c.set(v,I);let C=a(v,I);if(!C.ok){u(li(C.diagnostic,P,T));continue}d.set(v,C.module);let{graph:A,localImports:F}=Zu(C.module);for(let M of A.elements.values())if(M.importedFrom&&wt(M.importedFrom)){let K=M.importedFrom,q=await wo(v,K,r);q.ok?(M.importedFrom=q.path,bn(q.path)&&(M.isPublicUiComponent=!0)):Rr(K,v)||u(li(q.diagnostic,P,ra(T,v,K,q.diagnostic.path)))}if(l.set(v,A),!(R>=i))for(let M of F){if(Hl(M))continue;let K=await wo(v,M,r);if(!K.ok){Rr(M,v)||u(li(K.diagnostic,P,ra(T,v,M,K.diagnostic.path)));continue}let q=K.path;if(h.has(q)||bn(q))continue;let Re=ra(T,v,M,q);try{let Z=await n(q);g.push({file:q,source:Z,depth:R+1,diagnosticEntryFile:P,importStack:Re})}catch(Z){u(li({path:q,code:"import-read-failed",message:`Failed to read imported file: ${q}`,details:{fromFile:v,specifier:M,reason:Z instanceof Error?Z.message:String(Z)}},P,Re))}}}let b=hb(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return b.diagnostics=f,{graph:b,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function hb(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[d,f]of l.elements)o.set(d,f);for(let d of l.regions)i.push(d);for(let[d,f]of l.fileIndex){let m=s.get(d)??[];s.set(d,[...m,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}import{SiteEditHistoryProvenanceSchema as yb}from"@vcp-dev/contracts";var xb={affectedCompositions:[]};function od(e){let t=null,n=new WeakMap;async function r(){return t??=bb(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(nd(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),d={kind:"undo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),d={kind:"redo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);qu(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(qu(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(d){throw i.redo.push(o),d}}let a=await e.append(nd(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function qu(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function bb(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>ed(e,o))),r=await Promise.all(t.redoIds.map(async o=>ed(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function ed(e,t){let n=await e.readEntry(t),r=Sb(n),o=r.provenance??xb;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await td(e,n,r.preSnapshots),postSnapshots:await td(e,n,r.postSnapshots)}}async function td(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(kb(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function nd(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let d=`${s}-${c}`;l.blobName=d,t.push({name:d,data:a.content})}return l}),r=Eb(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function Sb(e){if(!sd(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:id(t.provenance)}:{},preSnapshots:rd(t.preSnapshots,"preSnapshots"),postSnapshots:rd(t.postSnapshots,"postSnapshots")}}function Eb(e){if(e.provenance!==void 0)return id(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function id(e){let t=yb.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function rd(e,t){return e.map((n,r)=>{if(!sd(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!vb(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function vb(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function kb(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{COMPONENT_I18N_FILE_SUFFIX as Ib,parseComponentI18nResourcesJson as Cb,resolveSiteTextDirection as Rb,SiteLocaleSchema as wb}from"@vcp-dev/contracts";var Nb=["i18next","react-i18next"],Pb="components/ui/site-locale-provider.tsx",Ab="components/ui/component-i18n-provider.tsx",ad="app/layout.tsx";async function ia(e){let t=e.files.filter(m=>m.path.endsWith(Ib));if(t.length===0)return{ok:!0};for(let m of["package.json",ad,Pb,Ab])if(!await e.exists(m))return En(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return En("Target snapshot package.json is invalid.")}let r=cd(n)&&cd(n.dependencies)?n.dependencies:{},o=Nb.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return En(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(ad),s=oa(i,"html","lang"),a=oa(i,"html","dir"),c=oa(i,"SiteLocaleProvider","locale"),l=wb.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Rb(l.data))return En("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return En("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data,f=d.split("-")[0];for(let m of t){let u=Cb(m.content);if(!u.success)return En(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return En(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function oa(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function En(e){return{ok:!1,message:e}}import{randomBytes as Xb}from"node:crypto";import di from"node:path";import{parse as ua}from"@babel/parser";import zb from"@babel/traverse";import*as yd from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as aa,PageResourceArtifactSchema as Hb,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Wb,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Gb,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Yb,parseComponentI18nResourcesJson as Zb}from"@vcp-dev/contracts";var ud=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,dd=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,Tb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,Fb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,_b=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Ob=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Mb=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,Db=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,Lb=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,Bb=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,$b=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,jb=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,Vb=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,Ub=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Pr(e,t){let n=ui([...mt(e,Tb),...mt(e,Fb),...mt(e,_b),...mt(e,t.includeRgbBackgroundImage?Ob:Mb),...t.includeExtendedColorFunctions?[...mt(e,Db),...mt(e,Lb)]:[]]),r=ui([...mt(e,Bb),...mt(e,$b)]).filter(o=>t.colorMixPolicy==="always"||ud.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...mt(e,jb).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...mt(e,Ub).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ui(mt(e,dd)),hardCodedSurfaceOccurrences:Jb(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?ui(mt(e,Vb)):[]}}function mt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var ld=160,Kb=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function Jb(e){let t=new RegExp(dd.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
- `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),d=Kb.exec(l),f=r(i.index),m=e.indexOf(`
6
- `,i.index),u=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:d?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:u.length>ld?`${u.slice(0,ld-1)}\u2026`:u})}return o}function ui(e){return[...new Set(e)]}var ca="{{$INSTANCE}}",Qb=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,qb=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,la="components/site/generated",eS=/\.(?:tsx?|json)$/,tS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,nS=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],rS=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),sa=zb,oS=typeof sa=="function"?sa:sa.default;async function da(e){let t=Hb.safeParse(e.artifact);if(!t.success)return ge("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>Xb(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=gS(r());if(!i)return ge("Random instance suffix must be 8 lowercase hex chars.");let s=`${hS(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let I of n.pages){let R=I.final_route.slice(1);a.set(I.template_page_id,I.final_route),c.set(I.template_page_id,I.title),l.push({template_page_id:I.template_page_id,title:I.title,final_route:I.final_route,route_file_path:`app/${R}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(I=>I.components.map(R=>R.component_id)));for(let I of n.components){if(!b.has(I.component_id))continue;let R=fd({materialization:I.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!R.ok)return R;for(let P of R.files){let T=md(P,f,d);if(T)return T}m.add(R.entry),g.set(R.entry,R.entryExport),u.set(I.component_id,R.entry)}for(let[I,R]of n.pages.entries()){let P=l[I],T=fd({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:P.route_file_path,pageTitle:P.title});if(!T.ok)return T;for(let F of T.files){let M=md(F,f,d);if(M)return M}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(R.components.map(F=>F.component_id))});let C=d.find(F=>F.file===P.route_file_path);if(!C)return ge("Page materialization entry did not resolve to its final route file.",P.route_file_path);if(lS(C.content,P.route_file_path)!==P.final_route)return ge(`Page ${R.template_page_id} requires a static PAGE_SEO.path equal to ${P.final_route}.`,P.route_file_path)}let E=sS(d,m,s,u,h,g);if(!E.ok)return E;for(let I of d)if(await e.exists(I.file))return!I.file.startsWith("app/")&&o>1?da({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${I.file}`,path:I.file};let v=aS(d);return v||(d.sort((I,R)=>I.file.localeCompare(R.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function fd(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:pd(o.pathTemplate,e.packageInstanceId);if(!s)return ge("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=iS(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?uS(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??pd(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?ge("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function iS(e,t,n,r){let o,i=e.replace(Qb,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return ge(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(qb,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return ge(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ca,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ge("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function pd(e,t){let n=`${la}/${t}`;if(e.split(ca).length>2)return null;let o=e.replace(ca,t),i=`${la}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=di.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!eS.test(a)||tS.test(a)?null:a}function md(e,t,n){return t.has(e.file)?ge(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function sS(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${la}/${n}`,c=new Map(e.map(u=>[u.file,new Set])),l=new Map;for(let u of e){if(u.file.endsWith(".json")){try{JSON.parse(u.content)}catch{return ge("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(aa)&&!Zb(u.content).success)return ge("Materialization component i18n resources are invalid.",u.file);continue}try{let h=ua(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let v=E.source.value,I=pS(u.file,v,s,a);if(!I.allowed)return ge(`Materialization import is outside the controlled package: ${v}`,u.file);I.internalPath&&c.get(u.file).add(I.internalPath)}let b;if(oS(h,{Identifier(E){E.isReferencedIdentifier()&&rS.has(E.node.name)&&(b??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(b??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(b??="style element",E.stop())}}),b)return ge(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return ge("Materialization source must parse as TS/TSX.",u.file)}let g=Pr(u.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return ge("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return ge("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return ge("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!cS(h,g))return ge("Materialization entry does not declare its contracted export.",u)}let d=new Map([...r].map(([u,g])=>[g,u]));for(let u of o){let g=hd(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return ge(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let b=d.get(h);if(b&&!u.declaredComponentIds.has(b))return ge(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of hd(u,c))f.add(g);if(f.size!==e.length)return ge("Every materialization file must be reachable from a package entry.");let m=mS(e,l,c);return m||{ok:!0}}function aS(e){if(e.length>Wb)return ge("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>Gb)return ge("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>Yb?ge("Page resource exceeds the aggregate content byte limit."):null}function cS(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function lS(e,t){let n;try{n=ua(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=fi(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!dS(a.key))continue;let c=fi(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function uS(e,t,n){let r;try{r=ua(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return ge("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=fi(s.init);if(a?.type!=="ObjectExpression")return ge("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&fS(d.key));if(!c||c.type!=="ObjectProperty")return ge("Page materialization PAGE_SEO must declare a static title.",n);let l=fi(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?ge("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return ge("Page materialization must declare a top-level PAGE_SEO object.",n)}function fi(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&yd.isExpression(t)?t:null}function dS(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function fS(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function pS(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=gd(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:nS.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=di.posix.normalize(di.posix.join(di.posix.dirname(e),t)),i=gd(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function gd(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function mS(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(aa))continue;let i=o.file.slice(0,-aa.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return ge("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(d=>d.value.value==="use client"),l=[...n].filter(([,d])=>d.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return ge("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function hd(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function gS(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function hS(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function ge(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as yS}from"node:crypto";import Xt from"node:path";import{parse as xS}from"@babel/parser";import bS from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as pi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as xd,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as SS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as ES,SiteEditMaterializationSchema as vS,parseComponentI18nResourcesJson as kS}from"@vcp-dev/contracts";var ma="components/site/generated",bd="{{$INSTANCE}}",mi=5,IS=/^[a-z][a-z0-9-]{0,48}$/,CS=/^[a-f0-9]{8}$/,Sd=/\.tsx?$/,RS=/\.json$/,wS=/\.(?:tsx?|json)$/,NS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,PS=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],fa=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),pa=bS,AS=typeof pa=="function"?pa:pa.default;function TS(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>xd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=US(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=vS.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=$S(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ma}.`,path:e.generatedRoot}};if(!Rd(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=kd(r.data.files),s=kd(e.controlledFiles);if(!KS(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>xd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let d=Buffer.byteLength(l.content,"utf8");if(d>SS)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=d}return a>ES?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function FS(e){let t=TS(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Rd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(mi,e.maxAttempts??mi));for(let i=0;i<o;i+=1){let s=jS(e.instanceNameGenerator?.()??yS(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=Nd(n,a),l=_S({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??PS});if(!l.ok)return l;if(!await OS(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Cd(e){let t=Math.max(1,Math.min(mi,e.maxAttempts??mi));for(let n=0;n<t;n+=1){let r=await FS({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function _S(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Ed({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=Ed({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=MS(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function OS(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Ed(e){if(e.pathTemplate.split(bd).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(bd,e.instanceName),n=VS(t);return n?Nd(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!wS.test(n)||NS.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function MS(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(RS.test(f.path)){if(f.path.endsWith(pi)){let g=kS(f.content);if(!g.success)return vn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return vn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=xS(f.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:f.path}}}let u=Pr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(u.hardCodedSurfaceHits.length>0||u.rawColorHits.length>0||u.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!Sd.test(f.path))continue;let m=s.get(f.path),u=null;if(AS(m,{ImportDeclaration(g){let h=vd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(pi))){let b=DS({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});b.ok?c.get(h.internalPath).add(f.path):(u??=b.error,g.stop())}},ExportAllDeclaration(g){u??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=vd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=Id(g.node);h&&fa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Id(g.node);h&&fa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&fa.has(g.node.name)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),u)return{ok:!1,error:u}}if(!Sd.test(n))return vn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return vn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!LS(l,r))return vn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return vn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return BS(n,a).size!==e.length?vn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ma,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function vd(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Xt.posix.normalize(Xt.posix.join(Xt.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function DS(e){let t=Xt.posix.dirname(e.importer),n=Xt.posix.dirname(e.imported),r=Xt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Xt.posix.basename(e.imported).slice(0,-pi.length),i=`./${r}${pi}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function LS(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function BS(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function vn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function $S(e){let t=wd(e);return t===ma?t:null}function jS(e){let t=e.trim().toLowerCase();return CS.test(t)?t:null}function Rd(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return IS.test(t)?t:null}function wd(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Xt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function VS(e){let t=wd(e);return!t||t!==e?null:t}function Nd(...e){return Xt.posix.join(...e)}function kd(e){return new Set(e.map(t=>t.pathTemplate))}function US(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function KS(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Id(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{createHash as Pa}from"node:crypto";import va from"@babel/traverse";function ga(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(d=>d.anchorSourceRange!==null&&d.members.length>0)??c.find(d=>d.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(d=>d.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as JS}from"node:crypto";import Pd from"node:path";import*as Od from"@babel/parser";import ha from"@babel/generator";import*as je from"@babel/types";var Ad=typeof ha=="function"?ha:ha.default;function xa(e){let t=Dd(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ea(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement,i=HS(n,o),s={jsx:`<${e.component.localName} />`},a=XS(e);if(i){let u=ya(e);return u.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:u.locator,sourceHash:u.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:u.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(Sa(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Ar("Route page composition does not expose a verifiable container boundary.");let d=Fr(c),f=Fd(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Fr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Ar("Route page composition placement does not expose a verifiable anchor boundary.");let u=Fd(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!u.ok)return u.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:d,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function XS(e){let t=ZS(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function gi(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return kn(e.source,"Root expression rewrite requires an exact expression locator.");let t=gr(e.source,"value");if(!t.ok)return kn(e.source,t.diagnostic.message);let n=se(t.ast,e.locator);if(!n.ok)return kn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return kn(e.source,"Resolved value locator does not point to an expression.");let o=Zn(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return kn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(je.nullLiteral()),{ok:!0,source:Ad(t.ast,{}).code};let i;try{i=Od.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return kn(e.source,s instanceof Error?s.message:String(s))}return!je.isJSXElement(i)&&!je.isJSXFragment(i)?kn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(zS(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Ad(t.ast,{}).code})}function zS(e,t,n,r){if(je.isNullLiteral(e)||r)return t;let o=je.isJSXFragment(e)?[...e.children]:[je.isJSXElement(e)?e:je.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return je.jsxFragment(je.jsxOpeningFragment(),je.jsxClosingFragment(),s)}function kn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function ba(e){let t=Dd(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Ld(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};if(WS(n,o)){let h=ya(e);return h.ok?e.operation==="remove-node"&&!Td(n,o.placementUnitKey)?Ar("The last editable page unit cannot be deleted."):e.operation==="move-node"?Ar("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:h.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:h.locator,sourceHash:h.sourceHash}}}:h.result}let s=Fr(o.sourceRange),a=At(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[Tr(a.diagnostic)]}};if(Zn(e.source,a.match.node.start??null,a.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node"){let h=ya(e);return h.ok?Td(n,o.placementUnitKey)?{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:s}}}:Ar("The last editable page unit cannot be deleted."):h.result}if(e.operation==="replace-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"replace-node",locator:s}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!YS(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=Ea(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let d=l.placement;if(d.placementUnitKey!==e.targetPlacement.placementUnitKey||d.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let f=d.containerSourceRange;if(!f||!d.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let m=Fr(f),u=At(e.source,m);if(!u.ok||!u.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:u.ok===!1?u.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:u.ok?[]:[Tr(u.diagnostic)]}};if(Zn(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return _d("Route page composition target container hash no longer matches the current source.");if(d.relation==="before"||d.relation==="after"){let h=d.anchorSourceRange,b=d.anchorSourceHash;if(!h||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let E=Fr(h),v=At(e.source,E);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[Tr(v.diagnostic)]}}:Zn(e.source,v.match.node.start??null,v.match.node.end??null)!==b?_d("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,anchorLocator:E,placement:d.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,placement:d.relation}}}}function Td(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function HS(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Sa(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function WS(e,t){return e.container.kind!=="jsx-container"&&Sa(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ya(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=At(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[Tr(r.diagnostic)]}}}:Zn(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Md("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Fd(e,t,n,r){let o=At(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[Tr(o.diagnostic)]}}}:Zn(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Md(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Md(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ar(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function _d(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Tr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Dd(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!GS(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function GS(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function YS(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function ZS(e,t){let n=Pd.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Pd.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Fr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Zn(e,t,n){return t==null||n==null?null:`sha256:${JS("sha256").update(e.slice(t,n)).digest("hex")}`}function Sa(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var QS=typeof va=="function"?va:va.default;function Vd(e){if(!e.ast)return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=sE(e.ast);if(!t)return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=cE(t);if(!n.ok)return Et(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=uE(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(fE(r,t))return Et(e,[Be("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Ia(e,t,"virtual-route-root",r);if(dE(r)){let o=hE({input:e,source:e.source,expression:r});return ka(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Pe(r)&&!en(r)){let o=wa(r),i=jd({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return ka(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=mE(r);if(!o.ok)return Et(e,[o.diagnostic]);let i=Qn(o.path);if(i.unsupported)return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(pE(e.source,r,i.members))return Ia(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Pe(r);if(i.members.length===0&&s)return Ia(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=jd({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return ka(e,t,l,{kind:a,sourceKind:c},r)}return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Ea(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:Be("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Ld(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Be("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:Be("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Ud(e){return e.ok?qS(e.projection):eE(e.projection)}function qS(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,d]of t){let f=d.members.flatMap((h,b)=>Kd(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>nE(l,h,d.independent)),u=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,u.map(({sourceMember:h})=>h)),o.set(l,m);let g=u[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:d.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:tE(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function eE(e){let t=e.diagnostics.map(rE);return{status:"unsupported",version:e.version,composition:e.composition,reason:oE(e.diagnostics),diagnostics:t}}function tE(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function Kd(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>Kd(e,t,a,c,i))]}function nE(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function rE(e){return{code:iE(e),message:e.message}}function oE(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function iE(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function sE(e){let t=null;return QS(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=aE(o.path);i&&(t=i,n.stop())}}),t}function aE(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function cE(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Or(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Be("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:Be("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!lE(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Jd(s)||Xd(s))return{ok:!1,diagnostic:Be("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Or(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Be("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function lE(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(Jd(o)||Xd(o))return null;return r}function Jd(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Xd(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function uE(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=Or(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function dE(e){return e.isConditionalExpression()?Bd(Or(e.get("consequent")))&&Bd(Or(e.get("alternate"))):!1}function Bd(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Or(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function fE(e,t){if(e.isIdentifier())return $d(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return $d(n.node.name,t)}return!1}function $d(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function pE(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Ra(t)}function Ra(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Ra(t))return!1;continue}if(t.isJSXElement()&&!Ra(t))return!1}return!0}function mE(e){let t=e;if(e.isJSXFragment()||Pe(e)){let r=_r(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&en(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&en(t);){let r=_r(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!en(o))return{ok:!0,path:t};if(_r(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function _r(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(..._r(n));continue}n.isJSXElement()&&(Pe(n)?t.push(..._r(n)):t.push(n))}return t}function Qn(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Na(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:gt(r.node.loc),businessMemberCount:0,parentSourceRange:gt(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=Qn(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=en(o)?Qn(o):null;n||=i?.unsupported??!1,t.push({...wa(o,i?.members),sourceRange:gt(r.node.loc),parentSourceRange:gt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Na(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:gt(r.node.loc),businessMemberCount:1,parentSourceRange:gt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Pe(r)){let o=Qn(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=en(r)?Qn(r):null;n||=o?.unsupported??!1,t.push({...wa(r,o?.members),parentSourceRange:gt(e.node.loc)})}}return{members:t,unsupported:n}}function wa(e,t){let n=e.isJSXElement()&&en(e)?t??Qn(e).members:[],r=e.isJSXElement()&&!en(e)&&!Pe(e);return{memberKey:Na(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:gt(e.node.loc),businessMemberCount:r?1:zd(n),parentSourceRange:gt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:gE(e)}}function en(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function gE(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function zd(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function hi(e){return e.length===0?0:Math.max(1,zd(e))}function jd(e){let t=gt(e.containerPath.node.loc),n=Aa(e.source,e.containerPath.node.start,e.containerPath.node.end),r=ht(e.input,e.containerKind,e.sourceKind,t),o=ht(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:hi(e.members)<=1,memberCount:hi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function hE(e){let t=gt(e.expression.node.loc),n=Aa(e.source,e.expression.node.start,e.expression.node.end),r=ht(e.input,"virtual-route-root","atomic-expression",t),o=ht(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:ht(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function Hd(e,t){let n=gt(t.node.loc),r=Aa(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function ka(e,t,n,r,o){let i=Hd(e,o);if(!i)return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=yE(e,n,s),c=ga(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Gd(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function yE(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,d,f,m,u,g,h=n)=>({...t,placementKey:d,placementUnitKey:f,containerKey:t.placementKey,independent:hi(g)<=1,memberCount:hi(g),sourceRange:m,sourceHash:m?Ca(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?Ca(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?Ca(e.source,u):null,members:g}),i=t.placementKey,s=t.members.map(l=>ht(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",ht(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let d=l.parentSourceRange??n,f=ht(e,i,"placement-unit",l.sourceRange);r.push(o("before",ht(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d)),r.push(o("after",ht(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d))}return r.push(o("append",i,c,n,null,[])),r}function Ia(e,t,n,r){let o=Hd(e,r);if(!o)return Et(e,[Be("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=ht(e,n,"empty-container",void 0),s=ht(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=ga([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Gd(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function Et(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function Be(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function ht(e,t,n,r){return Wd([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Na(e,t,n){return Wd(["member",e,String(t??-1),String(n??-1)])}function Wd(e){return`pc_${Pa("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Aa(e,t,n){return t==null||n==null?null:`sha256:${Pa("sha256").update(e.slice(t,n)).digest("hex")}`}function Ca(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${Pa("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function gt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Gd(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{PageTemplateIdSchema as PE}from"@vcp-dev/contracts";import sT from"node:fs";import cT from"node:path";var bE=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Mr(e){let t=e.map(r=>NE(r.path)),n=SE(t);return n?t.filter(r=>vE(n,r)).map(r=>({routeId:kE(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Ta(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=wE(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function SE(e){return e.some(r=>r.startsWith("app/")&&!EE(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function EE(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function vE(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return bE.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function kE(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(CE).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function IE(e){return e.startsWith("(")&&e.endsWith(")")}function CE(e){return!e||e.startsWith("@")||e.startsWith("_")||IE(e)?null:RE(e)}function RE(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function wE(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function NE(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Dr=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ze(e,t={}){throw new Dr("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Fa(e){return PE.safeParse(e).success||Ze("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Yd(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ze("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ze("invalid-template-key",{path:e})}return Fa(t)!==e&&Ze("noncanonical-template-key",{path:e}),t}function AE(e){let t=Ta(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||TE(r)&&!Zd(r)))&&Ze("invalid-public-route",{routeId:e}),t}function TE(e){return e.includes("[")||e.includes("]")}function Zd(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Qd(e){return e.some(Zd)}function qd(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ze("invalid-app-root");let r=AE(e),o=Fa(t),i=Qd(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&Ze("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function ef(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function tf(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&Ze("invalid-file-path",{path:i}),n.has(i)&&Ze("duplicate-file-path",{path:i}),n.set(i,o)}return n}function xi(e){let t=tf(e.files),n=Mr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Dr("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!ef(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Ze("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Qd(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=Yd(d),u=f.length?`/${f.join("/")}`:"/";qd(u,m,a).templateEntryFile!==i&&Ze("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&Ze("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>yi(i.routeId,s.routeId)||yi(i.templateId,s.templateId))}function nf(e){let t=tf(e.files),n=xi({files:t}),r=Mr([...t.keys()].map(o=>({path:o}))).map(o=>({context:{routeId:o.routeId},entryFile:o.entryFile}));return r.push(...n.map(o=>({context:{routeId:o.routeId,effectiveTemplateId:o.templateId},entryFile:o.entryFile}))),r.sort((o,i)=>yi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:yi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function FE(e){let t=Ta(e.selector.routeId),n=nf({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ze("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||Ze("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function yi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as XE}from"@vcp-dev/contracts";import{parse as lF}from"@babel/parser";import{parse as yT}from"@babel/parser";import{FormBlockIdSchema as bT,FormSpecV1Schema as ST}from"@vcp-dev/contracts";var Lr="components/site/generated/forms",ET=`${Lr}/vcp-form-runtime.tsx`,bi="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",vT=new RegExp(`^${Lr}/form-(${bi})\\.spec\\.ts$`),kT=new RegExp(`^${Lr}/form-(${bi})\\.tsx$`),IT=new RegExp(`^@/${Lr}/form-(${bi})$`),CT=new RegExp(`(?:^|/)${Lr}/form-(${bi})(?:\\.tsx?)?$`);var RT=Symbol("invalid-literal");import{createHash as PT}from"node:crypto";import{posix as TT}from"node:path";import{parse as _T}from"@babel/parser";import{FormSpecV1Schema as MT}from"@vcp-dev/contracts";var DT=Symbol("dynamic");import{parse as _E}from"@babel/parser";function Si(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var OE=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function rf(e){let t=OE.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function ME(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function of(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function DE(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function _a(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(_a);if(t?.type==="ObjectExpression"){let n={};for(let r of Si(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=of(r.key);if(!o)throw new Error("unsupported object key");n[o]=_a(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Oa(e,t){let n=[],r=rf(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=_E(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of Si(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Si(d.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=DE(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of Si(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=of(l.key);if(!(d!=="path"&&d!=="title"&&d!=="description"&&d!=="keywords"&&d!=="meta_tags_json"&&d!=="schema_json"&&d!=="breadcrumbs_json")){if(d==="path"||d==="title"||d==="description"||d==="keywords"){let f=ME(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static string; skipped`});continue}a[d]=f;continue}try{let f=_a(l.value);d==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:d==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:d==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as LE}from"@babel/parser";var sf=["page","anchor","external","email","phone","group","file"],BE=["link","cta"],cf=["description","badge","iconKey"],Ma=["label","targetType","href","role","openInNewTab","nofollow","children",...cf],$E=new Set(Ma);function $r(e){return Array.isArray(e)?e:[]}function Br(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function jE(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function af(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Da(e){let t=[],n;try{n=LE(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of $r(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of $r(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return $r(r.elements).forEach((i,s)=>{let a=lf(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function lf(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of $r(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=jE(l.key);d&&(r[d]=l.value)}let o=Br(r.label),i=Br(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!sf.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${sf.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of cf){if(r[l]===void 0)continue;let d=Br(r[l]);d!==void 0?s[l]=d:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))$E.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${Ma.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];$r(r.children.elements).forEach((d,f)=>{let m=lf(d,`${t}.children[${f}]`,n);m&&l.push(m)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=Br(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=Br(r.role);if(c!==void 0&&(BE.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=af(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=af(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as VE}from"@babel/parser";function jr(e){return Array.isArray(e)?e:[]}function uf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function UE(e){let t;try{t=VE(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of jr(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of jr(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=uf(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function La(e,t){let n=df(t);if(!n)return{status:"unsupported",source:e};let r=UE(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Da(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=jr(l.elements);for(let[f,m]of d.entries()){if(JE(m,n)){let g=d[f+1],h=d[f-1],b=m.start,E=m.end;if(typeof b!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:b,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let v=/^\s*,/.exec(e.slice(E));s.push({start:b,end:v?E+v[0].length:E})}continue}let u=KE(m);u&&a(u)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((d,f)=>f.start-d.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function KE(e){if(e.type==="ObjectExpression")for(let t of jr(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return uf(t.value)}}function df(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function JE(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of jr(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&df(n??"")===t}import{estimateNavLabelWidth as zT}from"@vcp-dev/contracts";import{parse as GT}from"@babel/parser";var zE="components/site/generated/",Vr=[".tsx",".ts",".jsx",".js"];function ff(e){if(e.expectedUrlPath===XE)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Mr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,b])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let v=Oa(b,E);return v.found&&v.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let h=xi({files:new Map(Object.entries(e.files))});for(let b of h)b.canonicalEntryFile===r&&o.add(b.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=HE(e.files);if(!i.ok)return i.error;let s=i.graph,a=ZE(o,s),c=QE(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,b)=>h.localeCompare(b)),d=[...o,...[...c].sort((h,b)=>h.localeCompare(b))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,b]of Object.entries(e.files))if(!f.has(h)){if(b.includes("NAV_ITEMS")){let E=La(b,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),u.push(h)):E.status==="unsupported"&&g.push(`unsupported_navigation:${h}`)}b.includes(e.expectedUrlPath)&&!b.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function HE(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!WE(r))continue;let s=gn(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(GE(c))continue;let l=dn(r,c),d=YE(l,t);if(!d)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(d)}n.set(r,a)}return{ok:!0,graph:n}}function WE(e){let t=e.toLowerCase();return Vr.some(n=>t.endsWith(n))}function GE(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Vr.some(n=>e.endsWith(n)))}function YE(e,t){let n=e.replace(/\\/g,"/");return(Vr.some(o=>n.endsWith(o))?[n]:[...Vr.map(o=>`${n}${o}`),...Vr.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function ZE(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(zE)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function QE(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>!e.has(a)&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as dp from"@babel/parser";import*as de from"@babel/types";import*as Li from"node:path";import*as ye from"@babel/types";function pf(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function _t(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return In(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ye.isObjectPattern(n)||ye.isArrayPattern(n))return In(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(ev(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function In(e,t,n=!1){return ye.isIdentifier(e)?e.name===t&&n:ye.isObjectPattern(e)?e.properties.some(r=>ye.isObjectProperty(r)?In(r.value,t,n):In(r.argument,t,n)):ye.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ye.isRestElement(r)?r.argument:r;return In(o,t,n)}):ye.isAssignmentPattern(e)?In(e.left,t,!0):ye.isRestElement(e)?In(e.argument,t,n):!1}function qn(e,t){if(e.path.isObjectPattern()){if(t){let r=vt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:_t(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:_t(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=mf(r),i=!1,s=o?o.initBinding&&Ba(o.initBinding)?(i=_t(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=qn(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=vt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||_t(e)}}}}let n=rv(e);if(n){let r=qE(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||_t(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=tv(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:_t(e)}}let i=Ur(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:_t(e)}:null}if(Ba(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:_t(e)}}return null}function qE(e,t){let n=e.findParent(d=>d.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=mf(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ba(i)?(a=_t(i),[...s]):(()=>{let d=qn(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=vt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||_t(t)}:null}function mf(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=ov(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ba(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function ev(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function tv(e){let t=e.identifier.name,n=e.path.getFunctionParent();if(!n)return null;let r=n.get("params"),o=Array.isArray(r)?r:[r];for(let i of o){let a=vt(i.node,t);if(a)return a}return null}function gf(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ei(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=Ur(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let d=l.get("right");if(d.isExpression())return{propName:c,componentName:t,expressionPath:d,displayPath:`${t}.${c}.default`}}let r=nv(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Ur(o.node);if(!i||n&&i!==n)return null;let s=r.get("right");return s.isExpression()?{propName:i,componentName:t,expressionPath:s,displayPath:`${t}.${i}.default`}:null}function Ei(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Ur(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&vt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Ei(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Ei(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Ei(r,t);if(o)return o}}return null}function vt(e,t,n=[]){if(ye.isIdentifier(e))return e.name===t?n:null;if(ye.isObjectPattern(e)){for(let r of e.properties)if(ye.isObjectProperty(r)){let o=Ur(r);if(!o)continue;let i=vt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ye.isRestElement(r)){let o=vt(r.argument,t,n);if(o)return o}}if(ye.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ye.isRestElement(o)?o.argument:o,s=vt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ye.isAssignmentPattern(e)?vt(e.left,t,n):null}function nv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function rv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;if(t?.isObjectProperty()&&t.parentPath?.isObjectPattern())return t;let n=t?.isAssignmentPattern()?t.parentPath:null;return n?.isObjectProperty()&&n.parentPath?.isObjectPattern()?n:null}function Ur(e){return e.computed?null:ye.isIdentifier(e.key)?e.key.name:ye.isStringLiteral(e.key)?e.key.value:null}function ov(e){let t=[],n=e;for(;ye.isMemberExpression(n);){if(n.computed)if(ye.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ye.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ye.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ye.isIdentifier(n)?{base:n.name,path:t}:null}import*as Sf from"@babel/parser";import Va from"@babel/traverse";import*as er from"@babel/types";import*as ae from"@babel/types";function Ii(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?vi(n,t):null}if(e.isMemberExpression()){let n=uv(e.node),r=iv(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?vi(o,[...r,...t]):null}return e.isAwaitExpression()||ja(e.node)?tn(fv(e.node),t,"awaited or fetched expression"):null}function iv(e){let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ae.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ae.isIdentifier(n)?t:null}function vi(e,t=[]){let n=sv(e,t);if(n)return n;let r=av(e,t);if(r)return r;let o=cv(e,t);return o||null}function Jr(e){return e?.kind==="api-source"}function sv(e,t){if(e.path.isVariableDeclarator()&&ae.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&$a(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return tn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&ae.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ae.isObjectProperty(c)&&xf(c)==="data"&&Kr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&$a(a.node))return tn(e.identifier.name,t,"query hook data binding")}let n=lv(e);if(!n||xf(n.node)!=="data")return null;let o=n.findParent(s=>s.isVariableDeclarator());if(!o?.isVariableDeclarator())return null;let i=o.get("init");return!i?.isCallExpression()||!$a(i.node)?null:tn(e.identifier.name,t,"query hook data binding")}function av(e,t){if(e.path.isVariableDeclarator()&&ae.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!yf(a.node))return null;let[c,l]=e.path.node.id.elements;return!ae.isIdentifier(c)||c.name!==e.identifier.name||!ae.isIdentifier(l)?null:hf(e,l.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!yf(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ae.isIdentifier(s)&&hf(e,s.name)?tn(e.identifier.name,t,"state setter is updated by API data"):null}function cv(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?tn(e.identifier.name,t,"awaited binding result"):ja(r.node)?tn(e.identifier.name,t,"fetch-backed binding result"):null:null}function lv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isObjectProperty()?t:t?.isAssignmentPattern()&&t.parentPath?.isObjectProperty()?t.parentPath:null}function Kr(e,t){return ae.isIdentifier(e)?e.name===t:ae.isAssignmentPattern(e)?Kr(e.left,t):ae.isObjectPattern(e)?e.properties.some(n=>ae.isObjectProperty(n)?Kr(n.value,t):Kr(n.argument,t)):ae.isArrayPattern(e)?e.elements.some(n=>!!n&&Kr(ae.isRestElement(n)?n.argument:n,t)):!1}function hf(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){ja(i.node)&&(n=!0),(dv(i.node.callee,t)||i.node.arguments.some(s=>ae.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function $a(e){let t=Ci(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function yf(e){return Ci(e.callee)==="useState"}function ja(e){return ki(e,t=>ae.isCallExpression(t)&&Ci(t.callee)==="fetch")}function uv(e){let t=e;for(;ae.isMemberExpression(t);)t=t.object;return ae.isIdentifier(t)?t.name:null}function xf(e){return e.computed?null:ae.isIdentifier(e.key)?e.key.name:ae.isStringLiteral(e.key)?e.key.value:null}function Ci(e){return ae.isIdentifier(e)?e.name:ae.isMemberExpression(e)&&ae.isIdentifier(e.property)?e.property.name:null}function dv(e,t){return ki(e,n=>ae.isIdentifier(n)&&n.name===t)}function ki(e,t){if(t(e))return!0;let n=ae.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let o=e[r];if(Array.isArray(o)){for(let i of o)if(ae.isNode(i)&&ki(i,t))return!0;continue}if(ae.isNode(o)&&ki(o,t))return!0}return!1}function fv(e){return ae.isIdentifier(e)?e.name:ae.isCallExpression(e)?Ci(e.callee)??"api":ae.isAwaitExpression(e)?"awaited-api":"api"}function tn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:pv(e,t),reason:n}}function pv(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Ef=typeof Va=="function"?Va:Va.default;function vf(e,t){let n=If(e);if(!n)return{allowed:!0};let r=!1;return Ef(n,{CallExpression(o){if(!Cf(o.node,t.sourceRange)||!mv(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Jr(Ii(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function kf(e,t){let n=If(e);if(!n)return{allowed:!0};let r=!1;return Ef(n,{JSXExpressionContainer(o){Cf(o.node,t.sourceRange)&&(er.isJSXEmptyExpression(o.node.expression)||(r=!0,o.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function If(e){try{return Sf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function mv(e){let t=e.callee;return er.isMemberExpression(t)&&er.isIdentifier(t.property)&&t.property.name==="map"}function Cf(e,t){let n=e.loc;return n?bf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&bf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function bf(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as X from"@babel/types";import*as Rf from"@babel/parser";import Ua from"@babel/traverse";import*as Ne from"@babel/types";import*as tr from"node:path";var kt=typeof Ua=="function"?Ua:Ua.default;function Ve(e){try{return Rf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ka(e){return e.computed?Ne.isStringLiteral(e.key)||Ne.isNumericLiteral(e.key)?String(e.key.value):null:gv(e.key)}function gv(e){return Ne.isIdentifier(e)?e.name:Ne.isStringLiteral(e)||Ne.isNumericLiteral(e)?String(e.value):null}function Cn(e){return Ne.isParenthesizedExpression(e)||Ne.isTSAsExpression(e)||Ne.isTSSatisfiesExpression(e)||Ne.isTSNonNullExpression(e)||Ne.isTSTypeAssertion(e)?Cn(e.expression):Ne.isExpression(e)?e:null}function Ja(e){if(Ne.isIdentifier(e))return[e.name];if((Ne.isMemberExpression(e)||Ne.isOptionalMemberExpression(e))&&!e.computed&&Ne.isIdentifier(e.property)){let t=Cn(e.object),n=t?Ja(t):null;return n?[...n,e.property.name]:null}return null}function Rn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?tr.normalize(tr.join(tr.dirname(e),t)).replace(/\\/g,"/"):t}function nt(e,t){return Ri(e)===Ri(t)}function Ri(e){let t=nr(e);return t.endsWith("/index")?t.slice(0,-6):t}function nr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Pf(e,t,n){let r=_f(e,t);if(Of(e,r),Mf(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let o=[];return kt(e,{JSXElement(s){$f(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:wi(o[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:o[0]}}function Af(e,t){let n=new Map,r=i=>{let s=rr(i);return n.has(s)?!1:(n.set(s,i),!0)};r(t);let o=!0;for(;o;){o=!1;for(let i of e)for(let s of hv(i,n))o=r(s)||o}return[...n.values()]}function hv(e,t){let n=[],r=yv(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=Xr(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Rn(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=nn(s.exported);for(let d of t.values())nt(d.file,i)&&n.push({file:e.file,namespace:Xa(l,d.namespace),exportName:d.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=nn(s.local),c=[...t.values()].filter(l=>nt(l.file,i)&&wn(l.namespace,a));if(c.length>0){let l=nn(s.exported);for(let d of c){let f=Xr(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(rr({file:i,exportName:a}))&&n.push({file:e.file,exportName:nn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=nn(i.local),a=r.get(s)??[];if(a.length>0){let c=nn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=Xr(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Rn(e.file,o.source.value),s=o.exported;if(s){let a=nn(s);for(let c of t.values())nt(c.file,i)&&n.push({file:e.file,namespace:Xa(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())nt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Xa(e,t){return t?`${e}.${t}`:e}function wn(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Xr(e,t,n){return!wn(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function yv(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Rn(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(rr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>nt(d.file,s)&&wn(d.namespace,"default"));for(let d of l){let f=Xr(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=nn(a.imported),l=[...t.values()].filter(f=>nt(f.file,s)&&wn(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(rr({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())nt(c.file,s)&&r(a.local.name,{...c,namespace:Xa(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=Cn(s.init);if(!a||!X.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(rr));for(let f of c){let m=Xr(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=rr(u);d.has(g)||(r(s.id.name,u),d.add(g),o=!0)}}}return n}function rr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Ri(e.file)}#${t}`}function nn(e){return X.isIdentifier(e)?e.name:e.value}function Tf(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ha(e){let t=xv(e),n=[],r=Mf(e.ast,t);return kt(e.ast,{JSXElement(o){nt(e.file,e.sourceFile)&&wi(o)===e.sourceComponent||$f(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Ff(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function _f(e,t){let n=Ff();return kt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function xv(e){let t=Ff();return nt(e.file,e.sourceFile)&&bv(t,_f(e.ast,e.sourceComponent)),kt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Rn(e.file,o),s=e.componentIdentities.filter(a=>nt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(d=>wn(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=Nf(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>wn(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=Nf(m,l);u&&f.add(u)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let d=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(d),t.namespaceMembers.set(c,f)}}}}}),Of(e.ast,t),t}function bv(e,t){e.hasUnsupportedAlias||=t.hasUnsupportedAlias;for(let n of t.localBindings)e.localBindings.add(n);for(let[n,r]of t.namespaceMembers){let o=e.namespaceMembers.get(n)??new Set;for(let i of r)o.add(i);e.namespaceMembers.set(n,o)}}function Of(e,t){kt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Cn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=Nn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&za(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=Nn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Bf(n.node.id,o.namespaceMembers,t,n)}}}})}function Mf(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return kt(e,{ReferencedIdentifier(r){if(n){r.stop();return}Sv(r)||!r.isIdentifier()||!Df(r,t)||Ev(r,t)||vv(r)||(n=!0,r.stop())}}),n}function Sv(e){let t=e;for(;t.parentPath?.isJSXMemberExpression();)t=t.parentPath;let n=t.parentPath;return!!(n?.isJSXOpeningElement()&&n.node.name===t.node||n?.isJSXClosingElement()&&n.node.name===t.node)}function Df(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&Nn(r.node,t,r)?r:null}function Ev(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!wf(e,r))return!1;let o=Df(e,t);if(!o)return!1;if(Cn(r.node)===o.node)return!!Nn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&wf(e,a)&&!!Nn(a.node,t,a)}function vv(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function wf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Nn(e,t,n){let r=Cn(e);if(!r)return null;if(X.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(X.isObjectExpression(r))return kv(r,t,n);let o=Ja(r);if(!o||o.length===0)return null;let i=n.scope.getBinding(o[0]);if(!i)return null;let s=t.namespaceMembers.get(i);return s?Lf(s,o.slice(1).join(".")):null}function kv(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Ka(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=Nn(i.value,t,n)!==null);continue}let a=Nn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function Lf(e,t){if(!t)return{local:!1,namespaceMembers:new Set(e),unsupported:!1};let n=new Set,r=!1;for(let o of e){if(o===t){r=!0;continue}o.startsWith(`${t}.`)&&n.add(o.slice(t.length+1))}return r||n.size>0?{local:r,namespaceMembers:n,unsupported:!1}:null}function za(e,t,n){if(e.hasUnsupportedAlias||=n.unsupported,n.local&&e.localBindings.add(t),n.namespaceMembers.size>0){let r=e.namespaceMembers.get(t)??new Set;for(let o of n.namespaceMembers)r.add(o);e.namespaceMembers.set(t,r)}}function Bf(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&za(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Ka(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Lf(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&za(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){Bf(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Nf(e,t){if(!wn(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function $f(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=jf(n);if(r&&r.length>1){let o=e.scope.getBinding(r[0]);return o?t.namespaceMembers.get(o)?.has(r.slice(1).join("."))===!0:!1}return!1}function jf(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=jf(e.object);return t?[...t,e.property.name]:null}return null}function wi(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function Vf(e,t){let n=Ve(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ha({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function he(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function pe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Ot(e,t){let n=pe(e);return!!(n&&rt(t,n))}function rt(e,t){return t.start>=e.start&&t.end<=e.end}function yt(e,t){let n=se(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Ni(e,t)}function or(e,t){let n=pe(t);return n?e.slice(n.start,n.end):""}function Uf(e,t){return e.start===t.start&&e.end===t.end}function Ni(e,t){let n=null;return kt(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.sourceRange.startLine&&o.start.column===t.sourceRange.startColumn&&o.end.line===t.sourceRange.endLine&&o.end.column===t.sourceRange.endColumn&&(n=r,r.stop())}}),n}function Pi(e,t){return Wa(e,t).length>0}function Ai(e,t){let n=pe(e.node),r=pe(t.node);if(!n||!r)return!1;let o=e.parentPath;for(;o;){if((o.isIfStatement()||o.isSwitchCase())&&(!!!t.findParent(s=>s.node===o?.node)||o.isIfStatement()&&!Iv(o,n,r)))return!0;o=o.parentPath}return!1}function Iv(e,t,n){let r=pe(e.node.consequent);if(r&&rt(r,t)&&!rt(r,n))return!1;let o=e.node.alternate?pe(e.node.alternate):null;return!(o&&rt(o,t)&&!rt(o,n))}function Wa(e,t){let n=pe(e.node);if(!n)return[];let r=[],o=e.parentPath;for(;o;){let i=!!t.findParent(s=>s.node===o?.node);if(!i&&o.isConditionalExpression()){let s=pe(o.node.consequent),a=pe(o.node.alternate);s&&n.start>=s.start&&n.end<=s.end?r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"consequent"}):a&&n.start>=a.start&&n.end<=a.end&&r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"alternate"})}else if(!i&&o.isLogicalExpression()&&Ga(o.node.operator)){let s=pe(o.node.right);s&&n.start>=s.start&&n.end<=s.end&&r.push({kind:"logical",path:o,conditionPath:o.get("left"),operator:o.node.operator})}o=o.parentPath}return r}function Ga(e){return e==="&&"||e==="||"||e==="??"}function Kf(e,t){let n=pe(e.consequent);if(n&&rt(n,t))return n;let r=pe(e.alternate);return r&&rt(r,t)?r:null}function Jf(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>nr(a.file)));if(!t.has(nr(e.sourceFile))||!t.has(nr(e.targetFile)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without source and target file visibility"};for(let a of e.routeEntryFiles)if(!t.has(nr(a)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component until all registered route entries are loaded"};let n=Tf(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=Ve(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Af(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ha({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!nt(s.file,e.targetFile)||wi(s.path)!==e.targetComponent?{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the only call site is outside the target component"}:{ok:!0,callSitePath:s.path}}import{SiteEditSetPropsParamsSchema as Av}from"@vcp-dev/contracts";function Ti(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return zr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return zr();let d=Cv(a,l,o?.instanceCount);if(!d)return zr();c=d}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?zr():{ok:!0,target:{kind:"jsx-attribute"}}}function zr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function Cv(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Mt from"@babel/types";import{SiteEditSetPropsParamsSchema as Rv}from"@vcp-dev/contracts";function Xf(e){let t=e.changes??(e.change?[e.change]:[]);if(!Rv.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Hr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Hr("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return Hr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=se(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Hr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?wv(r):Nv(c.match.path.node,r.name);if(!l)return Hr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function wv(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function Nv(e,t){let n=e.properties.filter(i=>Mt.isObjectProperty(i)&&Pv(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Mt.isExpression(r.value))return null;let o=Ft(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function Pv(e){return Mt.isIdentifier(e)?e.name:Mt.isStringLiteral(e)?e.value:Mt.isNumericLiteral(e)?String(e.value):null}function Hr(e,t){return{ok:!1,errorCode:e,reason:t}}function zf(e){if(e.change.name!=="className"&&e.change.name!=="class")return Wr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Wr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Wr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Wr("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return Wr("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function Wr(e,t){return{ok:!1,errorCode:e,reason:t}}async function Wf(e){let t=Av.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return Pn("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await Tv(e,r);if(o){if(!o.ok)return Pn("owner-plan-failed",o.reason);Hf(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return Pn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return Pn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Ov(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Ti({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return Pn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Ya(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Xf({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return Pn("repeat-target-failed",l.reason);Hf(n,l.steps);continue}Ya(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:Fv(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),_v(n)?Pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function Tv(e,t){return t.name!=="className"&&t.name!=="class"?null:zf({node:e.node,change:t,classNameSource:e.classNameSource})}function Fv(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function _v(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function Hf(e,t){for(let n of t)Ya(e,{...n,order:e.length})}function Ya(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function Ov(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Za(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Za(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Za(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>Za(n[i],r[i]))}return!1}function Pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as sr from"@babel/types";import*as W from"@babel/types";function Qa(e,t,n){let r=yt(t,n);return r?Dt(e,r):null}function Dt(e,t){let n=t.findParent(h=>h.isArrowFunctionExpression()||h.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(h=>h===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!W.isIdentifier(l)||l.name!=="map"||c.computed)return null;let d=a.get("object"),f=or(e,d.node),m=r.node.params.map(h=>or(e,h)),u=pe(i.node),g=pe(r.node);return!f||m.some(h=>h.length===0)||!u||!g?null:{callStart:u.start,callEnd:u.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:W.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Fi(d.node),callbackPath:r,collectionPath:d}}function Gr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Mv(e,t){let n=pe(e.node);return n?Dv(t).some(r=>{let o=pe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function Dv(e){let t=e.callbackPath.node.body;return W.isBlockStatement(t)?rn(t.body):on(t)}function rn(e){let t=[];for(let n of e){if(W.isReturnStatement(n)){n.argument&&t.push(...on(n.argument));continue}if(W.isBlockStatement(n)){t.push(...rn(n.body));continue}if(W.isIfStatement(n)){let r=W.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...rn(r)),n.alternate){let o=W.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...rn(o))}continue}if(W.isSwitchStatement(n)){for(let r of n.cases)t.push(...rn(r.consequent));continue}W.isTryStatement(n)&&(t.push(...rn(n.block.body)),n.handler&&t.push(...rn(n.handler.body.body)),n.finalizer&&t.push(...rn(n.finalizer.body)))}return t}function on(e){return W.isJSXElement(e)?Lv(e)?Gf(e.children):[e]:W.isJSXFragment(e)?Gf(e.children):W.isParenthesizedExpression(e)||W.isTSAsExpression(e)||W.isTSSatisfiesExpression(e)||W.isTSNonNullExpression(e)||W.isTSTypeAssertion(e)?on(e.expression):W.isConditionalExpression(e)?[...on(e.consequent),...on(e.alternate)]:W.isLogicalExpression(e)&&Ga(e.operator)?on(e.right):[]}function Gf(e){return e.flatMap(t=>W.isJSXElement(t)||W.isJSXFragment(t)?on(t):W.isJSXExpressionContainer(t)&&(W.isJSXElement(t.expression)||W.isJSXFragment(t.expression)||W.isConditionalExpression(t.expression)||W.isLogicalExpression(t.expression))?on(t.expression):[])}function Lv(e){let t=e.openingElement.name;return W.isJSXIdentifier(t)?t.name==="Fragment":W.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Yf(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Fi(e){return!(W.isIdentifier(e)||W.isThisExpression(e)||W.isMemberExpression(e)||W.isOptionalMemberExpression(e)||W.isCallExpression(e)||W.isOptionalCallExpression(e))}function Zf(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(W.isMemberExpression(n)||W.isOptionalMemberExpression(n))&&W.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function ir(e,t){let n=Ve(e);if(!n)return t.isRepeatItemRoot===!0;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ni(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Dt(e,o);return i?Mv(o,i):t.isRepeatItemRoot===!0}function Qf(e,t){let n=Ve(e);if(!n)return!1;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ni(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(W.isMemberExpression(s)||W.isOptionalMemberExpression(s))&&W.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as ke from"@babel/types";function qa(e){if(ke.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(ke.isJSXMemberExpression(e)){let t=e;for(;ke.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Bv(e,t){let n=pe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Ot(a.path.node,n)||sn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=qa(i.node.name);s&&o(s,i)}}),[...r].sort()}function ec(e,t,n){let r=Ve(e);if(!r)return{ok:!0};let o=se(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=se(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=kr(o.match.path,i.match.path);if(Pi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Bv(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function ep(e){let t=e;for(;ke.isTSQualifiedName(t);)t=t.left;return ke.isIdentifier(t)?t.name:null}function Yr(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function _i(e){let t=[],n=r=>{if(r){if(ke.isIdentifier(r)){t.push(r.name);return}if(ke.isObjectPattern(r)){for(let o of r.properties){if(ke.isRestElement(o)){n(o.argument);continue}ke.isObjectProperty(o)&&n(o.value)}return}if(ke.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(ke.isAssignmentPattern(r)){n(r.left);return}if(ke.isRestElement(r)){n(r.argument);return}ke.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function tc(e,t){let n=pe(e.node),r=pe(t.node);if(!n||!r)return{ok:!1,reason:"Cannot move repeat-backed child out of a component without proving the component call-site render scope"};let o=qf(e),i=qf(t);if(!o||!i||!Uf(o,i))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is rendered in a different return branch"};let s=e.parentPath;for(;s;){if(s.isConditionalExpression()){let a=Kf(s.node,n);if(a&&!rt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=pe(s.node.right);if(a&&rt(a,n)&&!rt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&Zf(s)){let a=pe(s.node.body)??pe(s.node);if(a&&!rt(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function qf(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?pe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(ke.isJSXElement(t.node.body)||ke.isJSXFragment(t.node.body)||ke.isConditionalExpression(t.node.body)||ke.isLogicalExpression(t.node.body)))return pe(t.node.body);t=t.parentPath}return null}function sn(e,t,n){return n.scope.getBinding(t)===e}function nc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Pi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=pe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>_i(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let d=l.scope.getBinding(c);!d||Ot(d.path.node,o)||i.has(d.path.node)||sn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=qa(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function rc(e,t,n){let r=pe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>_i(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Yr(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Ot(a.path.node,r)||o.has(a.path.node)||sn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function tp(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>_i(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||sn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(sr.isIdentifier(l))o(l.name,c);else{let d=ep(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function oc(e,t){let n=pe(e.node),r=new Set;return Yr(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Ot(i.path.node,n)||sn(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function np(e){let t=[];for(let n of e.callbackPath.node.params){if(sr.isIdentifier(n)){t.push(n.name);continue}if(sr.isRestElement(n)&&sr.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function rp(e,t){return{...e,callbackParams:t}}function ic(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Zr(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function op(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function An(e){return{file:e.file,component:e.component}}function $v(e){return e.target.kind==="node"?e.target.key:null}function jv(e){return"kind"in e}function Oi(e){return!jv(e)}function uc(e,t){let n=Li.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Li.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function sc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=At(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function fc(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Vv(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function Uv(e){let t=e.trim();if(!/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function ac(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Kv(e){let t=Pf(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=tc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Jv({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=fp(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Fi(o):!0}}}function Jv(e){let t=pe(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move prop-backed repeat child because the collection expression cannot be mapped"};let n=new Map,r=new Set,o=null,i=s=>{if(o)return;let a=s.scope.getBinding(s.node.name);if(!a||Ot(a.path.node,t))return;let c=Hv(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=Gv(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=Xv(l.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=oc(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}sn(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:Yv(e.source,t,[...n.values()])}}function Xv(e,t){if(t.length===0)return e;let n=fp(e);if(!n)return null;let r=Fi(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=zv(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function zv(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function Hv(e,t,n){let r=Wv(e,n),o=r?{kind:"member-expression",expression:e.node.name,base:e.node.name,path:[{kind:"property",name:r.propertyName}]}:{kind:"identifier",expression:e.node.name,base:e.node.name,path:[]},i=qn(t,o);if(!i)return null;let s=r?.range??pe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Wv(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Ot(n.node,t)||n.node.computed||!de.isIdentifier(n.node.property))return null;let r=pe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Gv(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&de.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=or(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function Yv(e,t,n){let r=e.slice(t.start,t.end),o=[...n].sort((i,s)=>s.start-i.start);for(let i of o)r=r.slice(0,i.start-t.start)+i.text+r.slice(i.end-t.start);return r}function fp(e){try{let n=dp.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=de.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&de.isExpression(r)?r:null}catch{return null}}function Zv(e){let t=pe(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move cross-file repeat child because the collection expression cannot be inspected"};let n=new Map,r=new Set,o=i=>{let s=i.scope.getBinding(i.node.name);if(!s||Ot(s.path.node,t))return;let a=ip(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=ip(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!Qv(d.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(d=>JSON.stringify(d)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return Yr(e.sourceContext.collectionPath,o),r.size>0?{ok:!1,reason:`Cannot move cross-file repeat child because the collection depends on non-importable bindings: ${[...r].sort().join(", ")}`}:{ok:!0,imports:[...n.entries()].map(([i,s])=>({moduleSpecifier:i,imports:s}))}}function Qv(e,t){return e.kind!==t.kind?!1:e.kind==="named"&&t.kind==="named"?e.imported===t.imported&&e.local===t.local:e.kind==="default"&&t.kind==="default"||e.kind==="namespace"&&t.kind==="namespace"?e.local===t.local:!1}function ip(e,t,n){let r=qv(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Rn(t,i),a=i.startsWith(".")?uc(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=de.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function qv(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function sp(e,t,n,r){let o=Wa(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=or(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=ek(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${nk(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function ek(e,t){return tk(e.node)?t:`(${t})`}function tk(e){return de.isIdentifier(e)||de.isThisExpression(e)||de.isSuper(e)||de.isMemberExpression(e)||de.isOptionalMemberExpression(e)||de.isCallExpression(e)||de.isOptionalCallExpression(e)||de.isBooleanLiteral(e)||de.isNumericLiteral(e)||de.isStringLiteral(e)||de.isNullLiteral(e)||de.isUnaryExpression(e)}function nk(e){return e.trim().startsWith("<")?e:`(${e})`}var rk={table:new Set(["caption","colgroup","thead","tbody","tfoot","tr"]),thead:new Set(["tr"]),tbody:new Set(["tr"]),tfoot:new Set(["tr"]),tr:new Set(["th","td"]),ul:new Set(["li"]),ol:new Set(["li"]),select:new Set(["option","optgroup"]),optgroup:new Set(["option"])};function Mi(e,t){if(t.kind!=="native-tag")return null;let n=e.tag?.toLowerCase();if(!n||n!==e.tag||n.startsWith("component:"))return null;let r=rk[n];if(!r)return null;let o=t.tag.toLowerCase();return r.has(o)?null:`Cannot insert <${t.tag}> into <${e.tag}>; expected ${[...r].map(i=>`<${i}>`).join(", ")}`}function ok(e,t){for(let n of e.program.body){if(!de.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>de.isImportDefaultSpecifier(o));if(r&&de.isImportDefaultSpecifier(r))return r.local.name}return null}function ik(e,t,n){for(let r of e.program.body){if(!de.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>de.isImportSpecifier(i)&&(de.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&de.isImportSpecifier(o))return o.local.name}return null}function ap(e){let t=new Set;return kt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function cp(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function sk(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=fc(e),o=Ve(t);if(n.exportName!=="default"){let a=o?ik(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?cp(r,ap(o)):r;return{localName:c,importStep:cc(e,c)}}if(!o)return{localName:r,importStep:cc(e,r)};let i=ok(o,n.source);if(i)return{localName:i};let s=cp(r,ap(o));return{localName:s,importStep:cc(e,s)}}function ak(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??fc(e);if(e.props&&Object.keys(e.props).length>0){let r=Object.entries(e.props).map(([o,i])=>typeof i=="string"?`${o}="${i}"`:`${o}={${JSON.stringify(i)}}`).join(" ");return`<${n} ${r} />`}return`<${n} />`}function ck(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?lk(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function lk(e){return Object.fromEntries(Object.entries(e).filter(t=>dc(t[1])))}function dc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(dc):typeof e=="object"?Object.values(e).every(dc):!1}function cc(e,t=fc(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function lp(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function uk(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Qr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function pc(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function qr(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:pc(e,t.slice(0,n)),index:r.index}}return null}function lc(e,t){return e.locator?e.collectionPathMap?.[t]?pc(e.locator,e.collectionPathMap[t]):qr(e.locator)?fk(e.locator,pk(t,e.collectionIndexMap)):null:null}function dk(e,t){let n=e.path??[],r=n.findLastIndex(i=>i.kind==="index");if(r===-1)return;let o=n.slice(r+1);return o.length===0?t:pp(o,t)}function pp(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=pp(r,t);return o===void 0?void 0:{[n.name]:o}}function fk(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},pc(e,i)}return null}function pk(e,t){return t?.[e]??e}function up(e,t){return!t||t.length===0?e:e<=0?t[0]??0:e>=t.length?(t[t.length-1]??t.length-1)+1:t[e]??e}function mk(e,t){return gk(e.root,t.root)&&yk(e.path??[],t.path??[])}function gk(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case"binding":case"hook-state":case"named-export":return"name"in t&&e.name===t.name;case"default-export":return!0;case"expression":return"sourceRange"in t&&hk(e.sourceRange,t.sourceRange)}}function hk(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function yk(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}var Di=class{constructor(t){this.operationCounter=0,this.graph=t}async plan(t){let n=`op-${++this.operationCounter}-${Date.now()}`;switch(t.kind){case"update-text":{if(t.params.kind!=="update-text")return{ok:!1,errorCode:"unknown",reason:Qr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:Qr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:Qr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planRemoveNode(n,r,i,this.graph.getCapability(i.key))}case"insert-child":{if(t.params.kind!=="insert-child")return{ok:!1,errorCode:"unknown",reason:Qr(t.kind,t.params.kind)};let r=t;if(!Oi(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=lp(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};if(!o.parentNode)return{ok:!1,errorCode:"locator-miss",reason:`Insert target parent for request '${t.id}' not found in graph`};let i=this.graph.getFileVersion(o.parentNode.file);return t.documentVersion!==i?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${i})`}:this.planInsertChild(n,r,o.parentNode,this.graph.getCapability(o.parentNode.key),o.anchorNode)}case"move-node":{if(t.params.kind!=="move-node")return{ok:!1,errorCode:"unknown",reason:Qr(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planMoveNode(n,r,i,this.graph.getCapability(i.key))}case"set-class-name-source":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planNodeAttributeOperation(n,t,r.node)}case"set-props":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planSetProps(n,t,r.node)}case"apply-style-draft":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planApplyStyleDraft(n,t,r.node)}default:return{ok:!1,errorCode:"unknown",reason:`Unknown operation kind: ${t.kind}`}}}resolveNodeRequest(t){let n=$v(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):xk(i)}async planApplyStyleDraft(t,n,r){let o=r.file,i=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==o)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:o,type:"set-class-name-source",request:{kind:"set-class-name-source",...n.params.className,key:r.key}})}if(n.params.props){let a=await this.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?Wf({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(u=>u.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!d&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.value===l)){if(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(d?.kind==="value-binding"&&d.locator){let u=d.locator;if(d.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=lc(d,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};u=g}s.push({order:n+s.length,file:d.file,type:"update-value",locator:u,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:he(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=lc(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:he(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ve(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=se(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Vv(a.match.path))return{ok:!0,value:r};let c=Uv(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=lc(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=Ve(this.graph.getFileContent(t));if(!o)return!1;let i=se(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let f=i;if(f?.kind==="value-binding"&&f.locator){let m=qr(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Zr(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}],d=this.buildRemoveComponentImportStep(r);return d&&l.push({...d,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Vf(n,t)>1)return null;let r=uc(t.file,t.importedFrom);return{order:0,file:t.file,type:"remove-import",moduleSpecifier:r,imports:t.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:t.exportName}]}}async planInsertChild(t,n,r,o,i){if(!Oi(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=Zr(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let d=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(d)return d;let f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let u=vf(this.graph.getFileContent(r.file),r);if(!u.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:u.reason??"Cannot insert child into this node"};let g=Mi(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],b=0,E=n.params.node.kind==="component-call"?sk(n.params.node,this.graph.getFileContent(r.file)):void 0,v=E?.importStep;return v&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:ak(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Oi(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:ck(n.params.node)}}],o)}async findExternalInsertContext(t,n){if(n){let o=await this.graph.getTextWriteTarget(n.key,0);if(o?.kind==="external-entry")return o}if(!this.graph.getChildNodes)return null;let r=[...this.graph.getChildNodes(t.key)];for(;r.length>0;){let o=r.shift();if(!o)continue;let i=await this.graph.getTextWriteTarget(o.key,0);if(i?.kind==="external-entry")return i;let s=this.graph.getTextProvenance?.(o.key,0)?.finalSource?.externalSource;if(s)return{kind:"external-entry",file:`external:${s.sourceId}`,sourceType:s.sourceType,sourceId:s.sourceId,adapterId:s.adapterId,displayExpression:s.sourceId};r.push(...this.graph.getChildNodes(o.key))}return null}async planRepeatBackedInsertChild(t,n,r,o){if(!Oi(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=qr(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=dk(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let d=n.params.position.relation==="prepend"?up(0,a.collectionIndexMap):up(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:d,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=Zr(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return ir(this.graph.getFileContent(t.file),t)?"Cannot edit repeat-backed item template structure with a generic node operation":"Cannot edit repeat-backed child node structure with a generic node operation";if(t.structuralPath.includes("#repeat:")||Qf(this.graph.getFileContent(t.file),t))return"Cannot edit repeat-backed child node structure with a generic node operation";let n=t.parentKey;for(;n;){let r=this.graph.getNode(n);if(!r)return null;if(r.isRepeatItemRoot||r.isRepeatRegion)return"Cannot edit repeat-backed child node structure with a generic node operation";n=r.parentKey}return null}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ir(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ve(c);if(!l)return null;let d=yt(l,r),f=yt(l,o);if(!d||!f)return null;let m=Dt(c,d),u=Dt(c,f);if(!Gr(m,u))return null;if(a&&(s==="before"||s==="after")){let h=yt(l,a),b=h?Dt(c,h):null;if(!Gr(m,b))return null}if(Ai(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=ec(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:An(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ir(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ve(c);if(!l)return null;let d=yt(l,r),f=yt(l,o);if(!d||!f)return null;let m=Dt(c,d);if(!m)return null;let u=Dt(c,f);if(Gr(m,u))return null;if(u&&!Yf(u,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let I=Qa(c,l,a);if(u&&!Gr(u,I)||!u&&I)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Mi(o,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let g=sc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ai(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=sp(c,d,f,g);for(let I of h.conditionPaths){let R=rc(I,f,m);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${R.bindingNames.join(", ")}`}}let b=nc(d,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${b.bindingNames.join(", ")}`};let E=tp(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=m;if(r.component!==o.component){let I=Kv({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};v=I.context}else{let I=oc(m.collectionPath,f);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:ic(v,h.sourceJsx),selectionContext:An(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ir(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),d=Ve(c),f=Ve(l);if(!d||!f)return null;let m=Jf({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:d,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let u=yt(d,r),g=yt(f,o);if(!u||!g)return null;let h=tc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let b=Dt(c,u);if(!b)return null;if(Dt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Qa(l,f,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let F=Mi(o,{kind:"native-tag",tag:r.tag});if(F)return{ok:!1,errorCode:"unsupported-operation",reason:F}}let v=sc(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ai(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=sp(c,u,g,v);for(let F of I.conditionPaths){let M=rc(F,g,b);if(!M.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${M.bindingNames.join(", ")}`}}let R=nc(u,g,b,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${R.bindingNames.join(", ")}`};let P=Zv({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let T=np(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=rp(b,T.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let F of P.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:F.moduleSpecifier,imports:F.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:ic(C,I.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:An(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let I=n.params.target,R=this.graph.getNode(I.anchorKey);if(!R||r.file!==R.file||r.component!==R.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let P=this.graph.getFileVersion(r.file);if(n.documentVersion!==P)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${P})`};let T=this.graph.getFileContent(r.file),C=Ve(T),A=C?yt(C,r):null,F=C?yt(C,R):null,M=A?.parentPath,K=F?.parentPath;if(!A||!F||!M||!K||M.node!==K.node||!M.isJSXFragment()&&!(M.isJSXElement()&&Pe(M)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let q=M.node.loc;return q?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:q.start.line,startColumn:q.start.column,endLine:q.end.line,endColumn:q.end.column}},placement:I.relation,anchorLocator:he(R),selectionContext:An(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=lp(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(uk(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let I=n.params.target.relation,R=i.anchorNode&&(I==="before"||I==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:I,anchorSourceId:R?.kind==="external-entry"?R.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=Zr(r,c,m);if(u&&!ac(u)&&!op(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:u};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(d==="before"||d==="after")){let I=c,R=await this.graph.getTextWriteTarget(f.key,0);if(I?.kind==="value-binding"&&R?.kind==="value-binding"&&I.locator&&R.locator){let P=qr(I.locator),T=qr(R.locator);if(P&&T&&I.file===R.file&&mk(P.locator,T.locator)){let C=P.index,A=T.index,F=d==="before"?A-(C<A?1:0):A+(C<A?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:P.locator,fromIndex:C,toIndex:F}],o)}}}if(r.isRepeatItemRoot&&ir(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),h=ac(u)?u:g;if(h&&ac(h)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(I)return I;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(R)return R;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return P||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=Mi(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=ec(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:An(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=sc(this.graph,r)??`<${r.component} />`,m=kf(d,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,b={moduleSpecifier:uc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:b.moduleSpecifier,imports:b.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:An(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:An(o)});let u=this.buildRemoveComponentImportStep(r,d);return u&&c.push({...u,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ve(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function xk(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import xc from"@babel/generator";import{parse as _k}from"@babel/parser";import bc from"@babel/traverse";import*as w from"@babel/types";import*as Bt from"@babel/types";import mc from"@babel/generator";import*as xe from"@babel/types";var bk=typeof mc=="function"?mc:mc.default,Sk=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,Ek=/^((?:https?:)?\/\/)[^/@\s]+@/i,vk=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function gp(e,t){let n=Lt(e.callee);if(!n)return null;if(n==="fetch")return gc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(mp(r))return gc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(mp(r))return gc(e.arguments[0],r,t,["ky client contract"])}return null}function gc(e,t,n,r){if(!e||xe.isSpreadElement(e)||xe.isJSXNamespacedName(e))return Rk(t,n,r,"missing url argument");let o=eo(e);return{sourceKind:Ck(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function eo(e){if(xe.isStringLiteral(e))return Bi(e.value);if(xe.isTemplateLiteral(e))return Bi(kk(e));if(xe.isBinaryExpression(e)&&e.operator==="+"){let t=eo(e.left),n=eo(e.right);return!t&&!n?void 0:Bi(`${t??hc(e.left)}${n??hc(e.right)}`)}if(xe.isMemberExpression(e)){let t=hp(e);if(t)return`env:${t}`}if(!(xe.isCallExpression(e)&&Lt(e.callee)==="new URL")){if(xe.isNewExpression(e)&&xe.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!xe.isSpreadElement(t)?eo(t):void 0,o=n&&!xe.isSpreadElement(n)?eo(n):void 0;return o&&r?Bi(`${o} + ${r}`):r??o}if(xe.isIdentifier(e))return`:${e.name}`}}function kk(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=hc(r))}return t}function hc(e){if(xe.isIdentifier(e))return`:${e.name}`;if(xe.isMemberExpression(e)){let t=hp(e);if(t)return`env:${t}`}return`:${Ik(e)}`}function Ik(e){return bk(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Bi(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(Ek,"$1<redacted>@").replace(vk,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?Sk.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function Ck(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function Rk(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function mp(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function hp(e){return!xe.isMemberExpression(e.object)||!xe.isIdentifier(e.object.object,{name:"process"})||!wk(e.object.property,"env")?null:xe.isIdentifier(e.property)?e.property.name:xe.isStringLiteral(e.property)?e.property.value:null}function wk(e,t){return xe.isIdentifier(e)&&e.name===t}function Lt(e){if(xe.isIdentifier(e))return e.name;if(xe.isMemberExpression(e)){let t=Lt(e.object),n=xe.isIdentifier(e.property)?e.property.name:xe.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var Nk=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),Pk=new Set(["getConfig","submit"]);function yp(e,t){let n=Ak(Lt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!Nk.has(i))return null;let s=yc(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!Pk.has(i))return null;let s=yc(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=yc(e,0)??Tk(e,0,"path")??"/cms/:path",s=Fk(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function Ak(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function xp(e,t){let n=Lt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function bp(e){let t=Lt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function yc(e,t){let n=e.arguments[t];return Bt.isStringLiteral(n)?n.value:null}function Tk(e,t,n){let r=e.arguments[t];if(!Bt.isObjectExpression(r))return null;for(let o of r.properties)if(Bt.isObjectProperty(o)&&!o.computed&&(Bt.isIdentifier(o.key)&&o.key.name===n||Bt.isStringLiteral(o.key)&&o.key.value===n)&&Bt.isStringLiteral(o.value))return o.value.value;return null}function Fk(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Ec=typeof bc=="function"?bc:bc.default,H_=typeof xc=="function"?xc:xc.default,Ok={maxFunctionDepth:8,maxImportDepth:6},Mk=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Cp(e){let t=e.fileCache??new Map,n=Ic(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...Ok,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:$p(n,e.element.componentName)};await Rp(e.element.componentName,e.graph,r);let o=[];o.push(...await jk(e.element,e.graph,r),...await Vk(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await Uk(s,e.element,e.graph,r);a&&o.push(Vi(a,"text","children"))}for(let s of e.element.attributes??[]){let a=$k(s,e.element);if(!a)continue;let c=await Pp(s.source,e.element,e.graph,r);c&&o.push(Vi(c,a,s.name))}let i=rI(o).sort(Lp);return{hasDynamicData:i.length>0,bindings:i}}async function Rp(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await wp(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let d=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(d)){n.resolvingComponentProps.add(d);try{let f=await Np(l.sourceFile,n);if(!f)continue;let m=Ki(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=$p(f,l.componentName),await Rp(l.componentName,t,m);let u=await Dk(l,m);for(let[g,h]of u){if(!h)continue;let b=a.get(g)??[];b.push(h),a.set(g,b)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=Mp(d);f.length===1&&c.set(l,f[0])}Bk(o,c,n)}async function wp(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await Np(e,r))?.imports.get(t);if(!s||!wt(s.source))return!1;let a=await Up(e,s.source,r.exists);return a?a===n?!0:wp(a,s.importedName,n,r,o):!1}async function Dk(e,t){let n=new Map;Ec(t.analysis.ast,{JSXElement(o){if(Lk(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!w.isJSXAttribute(i)||!w.isJSXIdentifier(i.name)||!w.isJSXExpressionContainer(i.value)||!w.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await De(i,t);s&&r.set(o,s)}return r}function Lk(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function Np(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Ic(e,r,t.fileCache)}function Bk(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,kc(Object.fromEntries(t),n.file));return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=w.isAssignmentPattern(r.value)?r.value.left:r.value;w.isIdentifier(i)&&n.paramSources.set(i.name,Ke(o))}}function $k(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":Mk.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function jk(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await Ui(i.collectionSource,n);s&&r.push(Vi(Tn(s),"repeat-region",i.collectionExpression))}return r}async function Vk(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await Ui(i.conditionSource,n);s&&r.push(Vi(Tn(s),"conditional-region",i.conditionExpression))}return r}async function Uk(e,t,n,r){return Pp(e.source,t,n,r)}async function Pp(e,t,n,r){let o=await Kk(e,t,n,r);return o||Ui(e,r)}async function Kk(e,t,n,r){if(!e)return null;let o=Jk(e.base,t,n);if(!o)return null;let i=await Ui(o.collectionSource,r);return i?oo(i,e.path,!0):null}function Jk(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function Ui(e,t){if(!e)return null;let n=await Ap(e.base,t);return n?oo(n,e.path,!1):null}async function Ap(e,t){let n=t.paramSources.get(e);if(n)return Ke(n);if(t.variableCache.has(e))return oI(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await Xk(e,t);if(r)return t.variableCache.set(e,Ke(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await De(o,t);return t.variableCache.set(e,s?Ke(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await jp(i,t);if(s){let a=Ki(s,t,{importDepth:t.importDepth+1}),c=Vp(i,s);if(c){let f=(await Fn(c,[],a)).returnSource;return t.variableCache.set(e,f?Ke(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let d=await De(l,a);return t.variableCache.set(e,d?Ke(d):null),t.resolvingVariables.delete(e),d}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function Xk(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Ec(t.analysis.ast,{CallExpression(o){if(w.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];w.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>w.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await De(o,t);if(i)return i}return null}async function De(e,t){if(w.isIdentifier(e))return Ap(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?xp(e,{file:t.file}):null;if(n)return Op(n);let r=await zk(e,t);if(!r)return null;let o=tI(e);return oo(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?De(e.argument,t):null;if(w.isCallExpression(e))return Tp(e,t);if(w.isObjectExpression(e)){let n=await Fp(e,t);return Object.keys(n).length>0?kc(n,t.file):null}if(w.isConditionalExpression(e)){let n=await De(e.consequent,t),r=await De(e.alternate,t);return ro(Ep(n,r))}if(w.isLogicalExpression(e)){let n=await De(e.left,t),r=await De(e.right,t);return ro(Ep(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?De(e.expression,t):null}async function zk(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?De(n,t):null}async function Tp(e,t){let n=yp(e,{file:t.file,imports:t.analysis.imports});if(n)return Op(n);if(bp(e)){let f=e.arguments[0];if(f&&w.isExpression(f))return ro(await De(f,t))}let r=await Hk(e,t);if(r)return r;let o=gp(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await Yk(e,t);if(i)return i;let s=await Zk(e,t);if(s)return s;let a=await Qk(e,t);if(a)return a;let c=await qk(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(w.isExpression(f)){let m=await De(f,t);m&&l.push(m)}let d=Mp(l);return d.length===1?ro(d[0]):null}async function Hk(e,t){let n=Lt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=Gk(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await no(s.name,t);if(a)return(await Fn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return $i(t.file,`${n} without static options`);let o=Wk(r,"queryFn");if(!o)return $i(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await no(o.name,t);return i?(await Fn(i.node,[],i.context)).returnSource:$i(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await Fn(o,[],t)).returnSource:w.isCallExpression(o)?Tp(o,t):null}function Wk(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(_p(n)===t)return n.value}return null}function Gk(e,t,n){return w.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function Yk(e,t){if(!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=w.isExpression(e.callee.object)?await De(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Tn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await no(o.name,t);if(!i)return Tn(r);let s=await Fn(i.node,[r],i.context);return{...Tn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await Fn(o,[r],t);return{...Tn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Tn(r)}async function Zk(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:De(e.callee.object,t)}async function Qk(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:ro(await De(e.callee.object,t))}async function qk(e,t){if(!w.isIdentifier(e.callee))return null;let n=await no(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push($i(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await De(i,t);r.push(s)}return(await Fn(n.node,r,n.context)).returnSource}async function no(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await jp(r,t);if(!o)return null;let i=Ki(o,t,{importDepth:t.importDepth+1}),s=Vp(r,o);return s?{node:s,context:i}:no(r.importedName,i)}async function Fn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Ki(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&Sc(c,nI(d),r)});let o=eI(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Fp(c,r)},i=i??kc(s,n.file);continue}let l=await De(c,r);if(l){if(!i){i=l;continue}let d=vc(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function Sc(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,Ke(t));return}if(w.isAssignmentPattern(e)){Sc(e.left,t,n);return}if(w.isObjectPattern(e))for(let r of e.properties){if(!w.isObjectProperty(r)||r.computed||!w.isIdentifier(r.key))continue;let o=oo(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;Sc(i,o,n)}}function eI(e){if(w.isArrowFunctionExpression(e)&&w.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!w.isBlockStatement(n))return t;let r=o=>{if(w.isFunction(o)&&o!==e)return;if(w.isReturnStatement(o)){o.argument&&w.isExpression(o.argument)&&t.push(o.argument);return}let i=w.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)w.isNode(c)&&r(c);else w.isNode(a)&&r(a)}};return r(n),t}async function Fp(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=_p(r);if(!o||!w.isExpression(r.value))continue;let i=await De(r.value,t);i&&(n[o]=i)}return n}function _p(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function tI(e){let t=[],n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);){let r=n.property;n.computed?w.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):w.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):w.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return w.isIdentifier(n),t}function oo(e,t,n){if(t.length===0)return Ke(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return oo(e.fieldMap[r.name],t.slice(1),n);let o=Ke(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=to(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=to(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=to(o.fieldPath,i.join(".")),o):(o.valuePath=to(o.valuePath,Sp(t)),o)}return o.valuePath=to(o.valuePath,Sp(t)),o}function Sp(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function to(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Op(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function Tn(e){let t=Ke(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function nI(e){let t=Ke(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function ro(e){return e?{...Ke(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Ep(e,t){return e?t?vc(e,t):Ke(e):t?Ke(t):null}function vc(e,t){if(ji(e)!==ji(t))return null;let n=Bp(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Mp(e){let t=new Map;for(let n of e){let r=ji(n),o=t.get(r);t.set(r,o?vc(o,n):Ke(n))}return[...t.values()]}function ji(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ji(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function kc(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function $i(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Vi(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function Dp(e){let t=[...e].sort(Lp),n=t[0],r=[...new Set(t.flatMap(o=>o.sourceKind==="vcp-cms-collection"&&o.collection?[o.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(o=>o.sourceKind))],...r.length>0?{collections:r}:{},...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function rI(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function Lp(e,t){return vp(e.targetKind)-vp(t.targetKind)||Bp(e.confidence,t.confidence)||kp(e.sourceKind)-kp(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function vp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function kp(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Bp(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Ic(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=_k(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return Ec(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)w.isImportSpecifier(c)&&w.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:w.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):w.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(w.isFunctionDeclaration(a.node)||w.isFunctionExpression(a.node)||w.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let d of ar(s.node.id))l.set(d,w.isExpression(s.node.init)?s.node.init:null);if(w.isArrayPattern(s.node.id)&&w.isCallExpression(s.node.init)&&Lt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;w.isIdentifier(d)&&w.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}w.isIdentifier(s.node.id)&&Ip(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!w.isExportSpecifier(l))continue;let d=w.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(d,{source:c,importedName:f,localName:d,isDefault:f==="default"})}if(w.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),w.isVariableDeclaration(a))for(let l of a.declarations)w.isIdentifier(l.id)&&Ip(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((w.isFunctionDeclaration(a)||w.isFunctionExpression(a)||w.isArrowFunctionExpression(a))&&i.functions.set("default",a),w.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function ar(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?ar(t.value):ar(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?ar(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?ar(e.left):w.isRestElement(e)?ar(e.argument):[]}function Ip(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function $p(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function jp(e,t){let n=await Up(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Ic(n,r,t.fileCache)}function Vp(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Up(e,t,n){return wt(t)?fn(e,t,n):null}function Ki(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function oI(e){return e?Ke(e):null}function Ke(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ke(n)]))}:{}}}import*as Rc from"@babel/parser";import Cc from"@babel/traverse";import*as G from"@babel/types";import{classifySiteEditPropertyName as iI}from"@vcp-dev/contracts";var wc=typeof Cc=="function"?Cc:Cc.default;function Nc(e){let t=iI(e.propertyName);if(t.owner!=="generic")return ot("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ot("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ot("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ot("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Rc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return ot("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=sI(r,e.element.sourceRange);if(!o)return ot("repeat-not-found","The selected element is not inside a supported map repeat");if(!G.isIdentifier(o.callback.params[0]))return ot("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=aI(r,o.collection,e.file,e.sources);if(!i)return ot("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],d=[];for(let[b,E]of s.elements.entries()){if(!E||!G.isObjectExpression(E)||!Wp(E))return ot("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:b}];l.push(v),d.push({kind:"value",root:a.root,path:v})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return ot("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return ot("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!G.isObjectExpression(u))return ot("unsafe-collection","Selected repeat item is not an object");let g=pI(e.element,e.propertyName),h=dI(u,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:d,selectedParentObjectLocator:d[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(b,E)=>E),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:h,selectedResolution:fI(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:ot("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function sI(e,t){let n=[];return wc(e,{CallExpression(r){let o=Kp(r.node);o&&Xp(o.callback,t)&&n.push({...o,span:Jp(r.node)})},OptionalCallExpression(r){let o=Kp(r.node);o&&Xp(o.callback,t)&&n.push({...o,span:Jp(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Kp(e){let t=e.callee;if(!G.isMemberExpression(t)&&!G.isOptionalMemberExpression(t)||t.computed||!G.isIdentifier(t.property)||t.property.name!=="map"||!G.isExpression(t.object))return null;let n=e.arguments[0];return!n||!G.isExpression(n)||!G.isArrowFunctionExpression(n)&&!G.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function aI(e,t,n,r){let o=io(t);if(o&&G.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Yp(o)}},sourceFile:n};if(!G.isIdentifier(t))return null;let i=[];if(wc(e,{VariableDeclarator(s){G.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=io(i[0].init);return!s||!G.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return cI(e,t.name,n,r)}function cI(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!G.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!G.isStringLiteral(o.source)||!G.isImportSpecifier(i))continue;let s=uI(n,o.source.value,r);if(!s)return null;let a=G.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Rc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=lI(l,a),f=d?io(d):null;return!f||!G.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function lI(e,t){let n=null;return wc(e,{VariableDeclarator(r){n||!G.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!G.isExpression(r.node.init)||(n=r.node.init)}}),n}function uI(e,t,n){let r=dn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function io(e){return G.isParenthesizedExpression(e)?io(e.expression):G.isTSAsExpression(e)?Hp(e.typeAnnotation)?io(e.expression):null:G.isTSSatisfiesExpression(e)?null:e}function Hp(e){return G.isTSTypeReference(e)&&G.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Wp(e){return e.properties.every(t=>!G.isObjectProperty(t)||t.computed||!G.isExpression(t.value)?!1:Ji(t.value))}function Ji(e){if(G.isTSAsExpression(e)&&Hp(e.typeAnnotation))return Ji(e.expression);if(G.isTSSatisfiesExpression(e))return!1;if(G.isArrayExpression(e))return e.elements.every(n=>!n||G.isSpreadElement(n)||!G.isExpression(n)?!1:Ji(n));if(G.isObjectExpression(e))return Wp(e);let t=Ft(e);return t.status==="resolved"||t.status==="undefined"}function dI(e,t){let n=e.properties.filter(o=>G.isObjectProperty(o)&&Gp(o.key)===t);if(n.length>1)return null;let r=n[0];return r?G.isExpression(r.value)?Ji(r.value)?"static":G.isIdentifier(r.value)||G.isMemberExpression(r.value)?"binding":null:null:"missing"}function fI(e,t){let n=e.properties.filter(o=>G.isObjectProperty(o)&&Gp(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!G.isExpression(r.value)?{status:"undefined"}:Ft(r.value)}function pI(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Gp(e){return G.isIdentifier(e)?e.name:G.isStringLiteral(e)?e.value:G.isNumericLiteral(e)?String(e.value):null}function Yp(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function Jp(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function Xp(e,t){let n=Yp(e);return zp(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&zp(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function zp(e,t,n,r){return e===n?t-r:e-n}function ot(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as eC}from"@vcp-dev/contracts";import*as Y from"@babel/types";import lo from"node:path";import*as B from"@babel/types";import*as tm from"@babel/parser";import Pc from"@babel/traverse";import*as ne from"@babel/types";function Xi(e,t){let n=[],r=e;for(;ne.isMemberExpression(r);){if(r.computed)if(ne.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ne.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ne.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ne.isIdentifier(r)||r.name!==t?null:n}function Zp(e){if(ne.isIdentifier(e))return{base:e.name,path:[]};if(!ne.isMemberExpression(e))return null;let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ne.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}function Qe(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}function Qp(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(ne.isStringLiteral(i)||ne.isNumericLiteral(i)||ne.isBooleanLiteral(i))return i.value;if(ne.isNullLiteral(i))return null;if(ne.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(ne.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let u=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:d,visited:f});return u?.kind==="static"?u.value:void 0}if(ne.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||ne.isSpreadElement(u))return;let g=await r(u,s,a,c,l,d,f);if(g===void 0)return;m.push(g)}return m}if(ne.isObjectExpression(i)){let m={};for(let u of i.properties){if(!ne.isObjectProperty(u)||u.computed)return;let g=null;if(ne.isIdentifier(u.key)?g=u.key.name:ne.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!ne.isIdentifier(u.value))return;let b=await r(u.value,s,a,c,l,d,f);if(b===void 0)return;m[g]=b;continue}if(!ne.isExpression(u.value))return;let h=await r(u.value,s,a,c,l,d,f);h!==void 0&&(m[g]=h)}return m}if(ne.isMemberExpression(i)){let m=await o(i,s,a,c,l,d,f);if(!m)return;let u=s.getBinding(m.base);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return!g||g.kind!=="static"?void 0:Qe(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],u=i;for(;ne.isMemberExpression(u);){if(u.computed){let g=u.property;if(ne.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(ne.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=ne.isExpression(g)?await n(g,s,a,c,l,d,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!ne.isIdentifier(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return ne.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var nm=typeof Pc=="function"?Pc:Pc.default,qp=new WeakMap;function rm(e){try{return tm.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function zi(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=rm(n);return e.set(t,{source:n,ast:o}),o}function Hi(e,t){let n=null,r=-1;for(let o of so(e).expressions){let i=o.node.loc;if(!i||!Tc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function om(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of so(e).expressions){if(!mI(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Ac(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of so(e).jsxElements){let i=o.node.loc;if(!i||!Tc(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function so(e){let t=qp.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return nm(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),qp.set(e,n),n}function mI(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function Tc(e,t){let n=em({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=em({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function Wi(e){return e.loc?{startLine:e.loc.start.line,startColumn:e.loc.start.column,endLine:e.loc.end.line,endColumn:e.loc.end.column}:null}function em(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function cr(e,t){if(t)return Fc(e,t);let n=Zp(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Fc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function ao(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of so(e).expressions){if(Fc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function im(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of so(e).expressions){if(Fc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!Tc(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function lr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function co(e){let t=null;if(nm(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function $t(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=rm(o),s={source:o,ast:i};return n.set(e,s),s}function gI(e){return B.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:B.isMemberExpression(e.callee)&&B.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function hI(e){if(!B.isNewExpression(e)||!B.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!B.isIdentifier(e.arguments[0])||!B.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!B.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!B.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(B.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(B.isIfStatement(i)&&B.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=B.isIfStatement(i)?i.test:null,c=a&&B.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=B.isIfStatement(i)?B.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=B.isReturnStatement(s)?s.argument:null;return!a||!B.isLogicalExpression(a,{operator:"&&"})||!B.isBinaryExpression(a.left,{operator:"==="})||!B.isUnaryExpression(a.left.left,{operator:"typeof"})||!B.isIdentifier(a.left.left.argument,{name:r.name})||!B.isStringLiteral(a.left.right,{value:"string"})||!B.isUnaryExpression(c,{operator:"!"})||!B.isBinaryExpression(c.argument,{operator:"in"})||!B.isIdentifier(c.argument.left,{name:r.name})||!B.isIdentifier(c.argument.right,{name:n.name})||!B.isReturnStatement(l)||!B.isIfStatement(i)||i.alternate||!B.isCallExpression(d)||!B.isMemberExpression(d.callee)||!B.isIdentifier(d.callee.object,{name:"Reflect"})||!B.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!B.isIdentifier(d.arguments[0],{name:n.name})||!B.isIdentifier(d.arguments[1],{name:r.name})||!B.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function yI(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!B.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function xI(e,t){let n=yI(e.path);if(!n)return null;let r=qn(e,t);return r?{...n,...r}:null}function bI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function _c(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function Oc(e,t){for(let n of e.program.body){if(t==="default"&&B.isExportDefaultDeclaration(n))return B.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(B.isFunctionDeclaration(n.declaration)||B.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(B.isExportNamedDeclaration(n)){if(n.declaration){if(B.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(B.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((B.isFunctionDeclaration(n.declaration)||B.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((B.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&B.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function sm(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`${g}::${h.kind}::${h.identifier.name}`;if(I.has(R))return null;I.add(R);try{let P=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I});if(P)return P;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:v,visited:I});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!B.isExpression(T))return null;let C=hI(T);if(C&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let M=h.path.scope.getBinding(C),K=M?await s({...u,binding:M}):null;if(K?.kind==="static"&&K.value!==null&&!Array.isArray(K.value)&&typeof K.value=="object")return K}let A=h.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let M=await t({currentFile:g,expressionPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(M)return M;if(A.isCallExpression()){let K=await n({currentFile:g,callPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(K)return K}}let F=await r(T,h.path.scope,g,b,E,v,I);return F===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:F,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let T=h.path.parentPath.node.declaration;if(!B.isExpression(T))return null;let C=await r(T,h.path.scope,g,b,E,v,I);return C===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:C,sourceKind:"binding"}}return null}finally{I.delete(R)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let R=h.path,P=R.node.init;if(!P||!B.isCallExpression(P))return null;let T=gI(P);if(!T||!B.isArrayPattern(R.node.id)||R.node.id.elements.findIndex(K=>B.isIdentifier(K)&&K.name===h.identifier.name)!==0)return null;let A=T==="useReducer"?1:0,F=P.arguments[A];if(!F||!B.isExpression(F))return null;let M=await r(F,R.scope,g,b,E,v,I);return M===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:T},value:M,sourceKind:"binding"}}async function c(u){let g=xI(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>bI(T,u.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let b=h[0],E=b.attributes?.find(T=>T.name===g.propName);if(E&&!E.source){let T=await l({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,fileCache:u.fileCache});if(T)return _c(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile})}if(!E?.source){let T=await d({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return _c(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let C=gf(u.binding,g.componentName,g.propName);if(!C||C.propName!==g.propName)return null;let A=await r(C.expressionPath.node,C.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(A===void 0)return null;let F=g.remainingPath;return F.length>0&&Qe(A,F)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:F,sourceKind:"binding",semanticKind:"component-prop",displayExpression:C.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:C.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await $t(b.sourceFile,u.readFile,u.fileCache);if(!v.ast)return null;let I=im(v.ast,v.source,E.source.expression,E.sourceRange)??ao(v.ast,v.source,E.source.expression);if(!I)return null;let R={...E.source,expression:lr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},P=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:R,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return P?_c(P.kind==="external"?P:{...P,displayExpression:R.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await $t(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Ac(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(R=>R.isJSXAttribute()&&R.node.name.type==="JSXIdentifier"&&R.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),v=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!v?.isExpression())return null;let I=Wi(v.node);return I?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:I},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await $t(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Ac(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement");for(let E of b.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let v=E.get("argument");if(!v.isExpression())continue;let I=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)continue;let R=[{kind:"property",name:u.propName},...u.remainingPath],P={...I,expression:lr(I.expression,R),path:[...I.path,...R]},T=await o({currentFile:u.caller.sourceFile,expressionPath:v,sourceInfo:P,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return T.kind==="external"?T:{...T,displayExpression:P.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.path.parentPath;if(!R||!R.isImportDeclaration())return null;let P=R.node.source.value;if(typeof P!="string")return null;let T=await fn(g,P,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let q=await $t(T,b,v),Re=q.ast?Oc(q.ast,"default"):null,Z=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!Z||Z.kind!=="static"?null:{kind:"static",file:Re?.kind==="default-expression"?Z.file:T,root:Re?.kind==="default-expression"?Z.root:{kind:"default-export"},value:Z.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let C=h.path.node.imported,A=B.isIdentifier(C)?C.name:C.value,F=await $t(T,b,v),M=F.ast?Oc(F.ast,A):null,K=await m({file:T,exportName:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return K?K.kind==="external"?K:{kind:"static",file:M?.kind==="re-export"?K.file:T,root:M?.kind==="re-export"||K.root.kind==="binding"&&K.root.name!==M?.name?K.root:{kind:"named-export",name:A},value:K.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`export::${g}::${h}`;if(!I.has(R)){I.add(R);try{let P=await $t(g,b,v);if(!P.ast)return;let T=Oc(P.ast,h);if(!T)return;if(T.kind==="default-expression"){let M=T.expression;if(!M||!B.isIdentifier(M))return;let K=co(P.ast).getBinding(M.name);return K?await s({currentFile:g,binding:K,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let M=await fn(g,T.source,E);return M?m({...u,file:M,exportName:T.name}):void 0}let C=T.name;if(!C)return;let A=co(P.ast).getBinding(C);return A?await s({currentFile:g,binding:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}finally{I.delete(R)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as H from"@babel/types";function Dc(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=vt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!SI(s,r)?null:{callPath:s,basePath:i}}function SI(e,t){let n=e.node.callee;return!H.isMemberExpression(n)||!H.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function lm(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ii(r,t)}function am(e,t){return e?H.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function cm(e,t,n,r,o){let i=H.isExpression(e.body)?e.body:e.body.body.find(a=>H.isReturnStatement(a))?.argument;if(!i||!H.isExpression(i))return;let s=Mc(i,t,n,r,o);return typeof s=="number"?s:void 0}function Mc(e,t,n,r,o){if(H.isNumericLiteral(e)||H.isStringLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(H.isMemberExpression(e)){let i=Xi(e,t);if(i)return Qe(r,i);let s=Xi(e,n);return s?Qe(o,s):void 0}if(H.isBinaryExpression(e)&&e.operator==="-"){let i=H.isExpression(e.left)?Mc(e.left,t,n,r,o):void 0,s=H.isExpression(e.right)?Mc(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function EI(e){if(H.isExpression(e.body))return e.body;for(let t of e.body.body)if(H.isReturnStatement(t)&&t.argument&&H.isExpression(t.argument))return t.argument;return null}function vI(e,t,n){let r=_n(e,t,n);return typeof r=="boolean"?r:void 0}function _n(e,t,n){if(H.isStringLiteral(e)||H.isNumericLiteral(e)||H.isBooleanLiteral(e))return e.value;if(H.isNullLiteral(e))return null;if(H.isIdentifier(e))return e.name===t?n:void 0;if(H.isMemberExpression(e)){let r=Xi(e,t);return r?Qe(n,r):void 0}if(H.isUnaryExpression(e)&&e.operator==="!"){let r=_n(e.argument,t,n);return r===void 0?void 0:!r}if(H.isLogicalExpression(e)){let r=_n(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&_n(e.right,t,n);if(e.operator==="||")return r||_n(e.right,t,n)}if(H.isBinaryExpression(e)){let r=H.isExpression(e.left)?_n(e.left,t,n):void 0,o=H.isExpression(e.right)?_n(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function um(e){let t=[],n=e;for(;H.isMemberExpression(n)||H.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(H.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(H.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(H.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(H.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return H.isIdentifier(n)?{base:n.name,segments:t}:null}function dm(e){return e.some(t=>t.kind==="dynamic")}function kI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function fm(e,t){if(!Array.isArray(e.value))return null;let n=e.collectionPathMap?.length?e.collectionPathMap:e.value.map((r,o)=>[...e.pathPrefix??[],{kind:"index",index:e.collectionIndexMap?.[o]??o}]);return n.length>0?n.map(r=>[...r,...t]):null}function II(e,t){let n=[],r=[];for(let o of t){let i=Qe(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function pm(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.node.callee;if(!H.isMemberExpression(R)||!H.isIdentifier(R.property)||R.property.name!=="map")return null;let P=h.get("callee");if(!P.isMemberExpression())return null;let T=P.get("object");if(Array.isArray(T)||!T.isExpression())return null;let C=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!C||!Array.isArray(C.value)||C.value.length===0?null:C}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(h.isIdentifier()){let R=h.scope.getBinding(h.node.name);if(!R)return null;let P=await t({currentFile:g,binding:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return P?.kind==="static"?P:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let R=h.get("expression");if(!Array.isArray(R)&&R.isExpression())return s({...u,expressionPath:R})}if(h.isArrayExpression()){let R=Wi(h.node);if(!R)return null;let P=await n(h.node,h.scope,g,b,E,v,I);return Array.isArray(P)?{kind:"static",file:g,root:{kind:"expression",sourceRange:R},value:P,sourceKind:"binding"}:null}if(h.isMemberExpression()){let R=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:v,visited:I});if(!R)return null;let P=await o({currentFile:g,expressionPath:h,sourceInfo:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!P||P.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!T||T.kind!=="static")return null;if(P.collectionPathMap?.length){let A=II(T.value,P.collectionPathMap);if(A)return{kind:"static",file:P.file,root:P.root,value:A.value,sourceKind:P.sourceKind,collectionPathMap:A.collectionPathMap}}let C=Qe(T.value,P.path);return Array.isArray(C)?{kind:"static",file:P.file,root:P.root,value:C,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let v=u.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==u.currentFile){let I=await $t(g.file,u.readFile,u.fileCache);v=I.ast?co(I.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await $t(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=om(h.ast,g.root.sourceRange);if(!b)return null;let E=await n(b.node,b.scope,g.file,u.readFile,u.exists,u.fileCache,u.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(u){return await l(u)??await d(u)??await f(u)}async function l(u){let{callPath:g}=u,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="filter")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!H.isArrowFunctionExpression(I)&&!H.isFunctionExpression(I))return null;let R=I.params[0];if(!H.isIdentifier(R))return null;let P=EI(I);if(!P)return null;let T=[],C=[],A=[];for(let[F,M]of v.value.entries()){let K=vI(P,R.name,M);if(typeof K!="boolean")return null;if(K){T.push(M),C.push(v.collectionIndexMap?.[F]??F);let q=v.collectionPathMap?.[F];q&&A.push(q)}}return{...v,value:T,pathPrefix:v.pathPrefix,collectionIndexMap:C,...A.length>0?{collectionPathMap:A}:{}}}async function d(u){let{callPath:g}=u,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="slice")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I,R]=g.node.arguments,P=am(I,0),T=am(R,v.value.length);if(P===null||T===null)return null;let C=Math.max(0,P<0?v.value.length+P:P),A=Math.max(0,T<0?v.value.length+T:T),F=v.value.map((K,q)=>v.collectionIndexMap?.[q]??q).slice(C,A),M=v.collectionPathMap?.slice(C,A);return{...v,value:v.value.slice(C,A),pathPrefix:v.pathPrefix,collectionIndexMap:F,...M?{collectionPathMap:M}:{}}}async function f(u){let{callPath:g}=u,h=g.node.callee;if(!H.isMemberExpression(h)||!H.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!H.isArrowFunctionExpression(I)&&!H.isFunctionExpression(I))return null;let[R,P]=I.params;if(!H.isIdentifier(R)||!H.isIdentifier(P))return null;let T=v.value.map((A,F)=>({value:A,sourceIndex:v.collectionIndexMap?.[F]??F,originalIndex:F})),C=[...T];for(let A of T)for(let F of T)if(cm(I,R.name,P.name,A.value,F.value)===void 0)return null;return C.sort((A,F)=>{let M=cm(I,R.name,P.name,A.value,F.value)??0;return M===0?A.originalIndex-F.originalIndex:M}),{...v,value:C.map(A=>A.value),pathPrefix:v.pathPrefix,collectionIndexMap:C.map(A=>A.sourceIndex),...v.collectionPathMap?{collectionPathMap:C.map(A=>v.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function m(u){let g=null,h,b=[];for(let v of u.segments){if(v.kind!=="dynamic")continue;let I=await r({expression:v.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)return null;let R=Dc(u.expressionPath,I.base);if(!R)return null;let P=await i({currentFile:u.currentFile,callPath:R.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!P||!Array.isArray(P.value))return null;let T=P.value.map((C,A)=>{let F=Qe(P.value,[{kind:"index",index:A},...R.basePath,...I.path]);return kI(F)});if(T.some(C=>C===null)||g!==null&&g!==T.length)return null;g=T.length,h??=P.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let v=0;v<g;v+=1){let I=[...u.rootPath],R=0;for(let P of u.segments){if(P.kind==="dynamic"){let T=b[R]?.[v];if(!T)return null;I.push(T),R+=1;continue}I.push({...P})}E.push(I)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:CI,evaluateStaticExpression:Gi}=Qp({resolveBindingTarget:e=>Uc(e)}),{resolveRepeatCollectionTarget:RI,resolveCollectionCallTarget:wI,resolveDynamicMemberPathMap:NI}=pm({resolveBindingTarget:e=>Uc(e),evaluateStaticExpression:Gi,buildExpressionSourceInfo:jt,resolveSourceInfoProvenance:xt}),{resolveExportValue:PI,resolveComponentPropBinding:AI,resolveBindingTarget:Uc}=sm({resolveExternalExpression:Jc,resolveCollectionCallTarget:wI,evaluateStaticExpression:Gi,resolveSourceInfoProvenance:xt,buildExpressionSourceInfo:jt});function Em(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function mm(e,t,n){return{kind:"external",file:e,sourceType:"api-field",sourceId:t,displayPath:n,editMode:"readonly",diagnostics:[{code:"external-source-readonly",message:"Dynamic API data is read-only for content edits"}]}}async function vm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=zi(s,t,n);if(!a)return null;let c=Hi(a,r.sourceRange);if(!c)return null;let l=await jt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await Wc({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?$c(m,cr(c.node,n)):null}let d=new Set,f=await QI({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:d});return f?$c(f,l.expression):null}async function ur(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=zi(i,t,n);if(!s)return null;let a=e.sourceRange?Hi(s,e.sourceRange):e.expression!==void 0?ao(s,n,e.expression):null;if(!a)return null;let c=Gc(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await jt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=d?await xt({currentFile:t,expressionPath:c,sourceInfo:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await qI({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return $c(f,e.expression??cr(c.node,n))}async function Kc(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=zi(i,t,n);if(!s)return it("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?TI({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):FI({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function jt(e){if(Y.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Y.isMemberExpression(e.expression))return null;let t=await CI(e.expression,e.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);return t?{kind:t.path.some(n=>n.kind==="index")?"index-expression":"member-expression",expression:cr(e.expression,e.source),base:t.base,path:t.path}:null}function $c(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function TI(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Hi(r,o.sourceRange),d=l?await jt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!d){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return gm(t,o.value);let m=await Wc({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?Sm(t,m):Vc(t,cr(l.node,n),m):_I({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return it("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await xt({currentFile:t,expressionPath:l,sourceInfo:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=jc(l.node);if(m)return it(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=jc(u.path.node.init);if(g)return it(g.code,g.message)}return u?.path.isVariableDeclarator()&&Y.isCallExpression(u.path.node.init)?OI("unsupported-expression",wm(u.path.node.init,e.functionCallContracts)):it("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Sm(t,f):Vc(t,d.expression,f)}async function FI(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return it("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=ao(r,n,o.conditionExpression);if(!l)return it("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=await xt({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d)return it("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return it("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Vc(t,o.conditionExpression,d);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:d.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function gm(e,t){return{finalSource:{kind:"jsx-literal",file:e,locator:null,displayPath:t},chain:[{kind:"jsx-literal",file:e,displayName:t,canEditHere:!0}],confidence:"exact",editMode:"direct",diagnostics:[]}}async function _I(e){let t=await Im(e);if(t.length===0)return it("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(MI(e.expression))return km(t);if(Rm(e.expression))return it("unsupported-expression","i18n helpers require a static message id string");if(Y.isMemberExpression(e.expression)&&e.expression.computed&&!Y.isNumericLiteral(e.expression.property)&&!Y.isStringLiteral(e.expression.property))return it("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return it(n.code,n.message)}function it(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function OI(e,t){return km([{code:e,message:t}])}function km(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function MI(e){return Y.isCallExpression(e)||Y.isConditionalExpression(e)||Y.isLogicalExpression(e)||Y.isBinaryExpression(e)}function uo(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function Im(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=jc(t);if(l)return[l];if(Y.isCallExpression(t))return[{code:"unsupported-expression",message:wm(t,c)}];if(Y.isMemberExpression(t)&&t.computed){let d=t.property;if(!Y.isNumericLiteral(d)&&!Y.isStringLiteral(d)){if(!Y.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await Gi(d,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return Y.isBinaryExpression(t)?uo([...await Lc(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Y.isLogicalExpression(t)?uo([...await Lc(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):Y.isConditionalExpression(t)?uo([...await Lc(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function jc(e){return Rm(e)?hm("i18n helpers require a static message id string"):jI(e)?hm("CMS helpers require static entry id and field path string arguments"):null}async function Lc(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Im({...t,expression:o}));return r}function DI(e,t){let n=(t??[]).filter(r=>r.sourceType===e.sourceType&&(r.capabilities===void 0||r.capabilities.includes("write-text")));if(e.adapterId){let r=n.find(o=>o.adapterId===e.adapterId);if(r)return{adapterId:r.adapterId,editMode:"proxy",diagnostics:[]}}else if(n.length>0)return{adapterId:n[0]?.adapterId,editMode:"proxy",diagnostics:[]};return{adapterId:void 0,editMode:"readonly",diagnostics:[LI(e.sourceType)]}}async function Jc(e){for(let n of JI){if(!ym(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return bm(xm(r),e.externalAdapters)}let t={currentFile:e.currentFile,expressionPath:e.expressionPath,readFile:e.readFile,exists:e.exists,graph:e.graph};for(let n of e.externalSourceResolvers??[]){if(!ym(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return bm(xm(r),e.externalAdapters)}return null}function LI(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function BI(e){return{code:"external-source-readonly",message:e}}function hm(e){return{code:"unsupported-expression",message:e}}function Xc(e){return!e||!Y.isCallExpression(e)?null:Y.isIdentifier(e.callee)?e.callee.name:Y.isMemberExpression(e.callee)&&!e.callee.computed&&Y.isIdentifier(e.callee.object)&&Y.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function ym(e,t){if(!t||t.length===0)return!0;let n=Xc(e.node);return n?t.includes(n):!1}function xm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:uo(e.diagnostics??[])}:{match:e,diagnostics:[]}}function bm(e,t){let n=DI(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:uo([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function $I(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Y.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Y.isStringLiteral(n)||!Y.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function jI(e){return!!e&&Y.isCallExpression(e)&&Y.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Y.isStringLiteral(e.arguments[0])||!Y.isStringLiteral(e.arguments[1]))}function Cm(e){if(!(!e||!Y.isCallExpression(e))){if(Y.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Y.isStringLiteral(t)?t.value:null}if(Y.isMemberExpression(e.callee)&&!e.callee.computed&&Y.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Y.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Y.isObjectExpression(t))return null;for(let n of t.properties)if(Y.isObjectProperty(n)&&!n.computed&&(Y.isIdentifier(n.key)&&n.key.name==="id"||Y.isStringLiteral(n.key)&&n.key.value==="id")&&Y.isStringLiteral(n.value))return n.value.value;return null}}}function Rm(e){return Cm(e)===null}async function VI(e,t,n){let r=new Set,o=lo.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=lo.posix.dirname(o);if(i===o){r.add(".");break}o=i}r.add("src"),r.add(".");for(let i of r){let s=i==="."?["locales","messages"]:[lo.posix.join(i,"locales"),lo.posix.join(i,"messages")];for(let a of s){let c=lo.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function UI(e){let t=Cm(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await VI(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function KI(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Y.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Y.isExpression(n))return null;let o=await Gi(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[BI("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var JI=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>$I(e)},{helperNames:["apiField"],resolve:e=>KI(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>UI({currentFile:e,expressionPath:t,exists:n})}];function zc(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Sm(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function Vc(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=ZI(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var XI=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Hc(e,t){let n=[...XI,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function wm(e,t){let n=e.callee;return Y.isIdentifier(n)&&Hc(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function Wc(e){let t=await Jc(e);if(t)return t;let n=await Nm({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await jt({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await xt({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await GI(e)}async function Nm(e){let t=await It({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Gc(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:zc(t.provenance)}async function It(e){let t=Gc(e.expressionPath),n=WI(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await jt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await xt({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await jt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await xt({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await It({...e,expressionPath:r,allowComposed:!0}),a=await It({...e,expressionPath:o,allowComposed:!1}),c=await It({...e,expressionPath:i,allowComposed:!1});return Bc(s,a,c)}if(t.isCallExpression())return zI({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Bc(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await It({...e,expressionPath:r,allowComposed:!0}),s=await It({...e,expressionPath:o,allowComposed:!0});return Bc(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:It({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Gc(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function zI(e){let t=Xc(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:It({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Y.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:It({...e,expressionPath:o,allowComposed:!1})}}return null}function Bc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!HI(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function HI(e,t){return e.file===t.file&&e.sourceKind===t.sourceKind&&JSON.stringify(e.root)===JSON.stringify(t.root)&&JSON.stringify(e.path)===JSON.stringify(t.path)&&JSON.stringify(e.collectionIndexMap??null)===JSON.stringify(t.collectionIndexMap??null)&&JSON.stringify(e.collectionPathMap??null)===JSON.stringify(t.collectionPathMap??null)}function WI(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function GI(e){if(!e.expressionPath.isCallExpression())return null;let t=Xc(e.expressionPath.node);if(!t)return null;let n=Hc(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await Pm({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?zc(i):null}async function Pm(e){let t=await Jc({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await jt({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await xt({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await Wc({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function YI(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Y.isCallExpression(t))return null;let n=t.callee;if(!Y.isIdentifier(n))return null;let r=Hc(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await Pm({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?zc(a):null}function ZI(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=lr(t,e.path);return{sourceId:o,displayPath:o}}async function QI(e){let t=e.segment.source;return t?xt({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function xt(e){let t=e.sourceInfo,n=Dc(e.expressionPath,t.base);if(n){let l=await RI({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let h=lm(n.callPath,[...n.basePath,...t.path]);return Jr(h)?mm(e.currentFile,h.sourceId,h.displayPath):null}let d=fm(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return Qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await fn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await PI({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let u=t.path.slice(1);return Qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=pf(r);if(o){let l=o.expressionPath,d=await jt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(d){let f=await xt({...e,expressionPath:l,sourceInfo:{...d,expression:lr(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await Nm({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return AI({currentFile:e.currentFile,binding:r,sourceInfo:t,graph:e.graph,readFile:e.readFile,exists:e.exists,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});let i=await YI({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=vi(r,t.path);if(Jr(s))return mm(e.currentFile,s.sourceId,s.displayPath);let a=await Uc({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:Qe(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function qI(e){let t=um(e.expressionPath.node);if(!t||!dm(t.segments))return null;let n=await xt({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:{kind:"identifier",expression:t.base,base:t.base,path:[]},readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!n||n.kind==="external")return n;let r=await NI({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:cr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Am(e){let t=eC(e.propertyName);if(t.owner==="blocked")return an(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return an(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return an("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await nC(e,l)});o.sort((l,d)=>l.order-d.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return an("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:an("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?an("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):tC(e,s.attribute)}async function tC(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ur({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:an("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await ur({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?an("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function nC(e,t){let n=t.source?.expression;if(!n)return;let r=await ur({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:rC(r,e.propertyName)}}function rC(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function an(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Tm(e){let{key:t,element:n,graph:r,provenances:o}=e,i=iC(t,n,r),s=i?.tag??(On(n.tag)?n.tag:n.componentName),a=i?.identity.key??Fm(n,r)??t,c=cC(i),l=lC(t,n,r,o,i),d=oC(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:aC(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:uC(d),alternativeStrategies:dC(d)}}function oC(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Yc(e,n)?"instance":!On(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Fm(e,t){if(On(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&sC(r,e.componentName));return n.length!==1?null:n[0].identity.key}function iC(e,t,n){if(On(t.tag))return t;let r=Yc(e,n);if(r)return r;let o=Fm(t,n);return o?n.elements.get(o)??null:null}function sC(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function aC(e,t){return On(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function cC(e){if(!e?.attributes)return[];let t=new Set(["variant","size","tone"]);return e.attributes.filter(n=>t.has(n.name)).map(n=>n.name)}function lC(e,t,n,r,o){let i=new Set,s=Yc(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(d=>d.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&On(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Yc(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(On(r.tag))return r;n=r.parentKey}return null}function On(e){return/^[A-Z]/.test(e)}function uC(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function dC(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function Mm(e){let t=e.isRepeat??(e.graph?SC(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=bC(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>fC({attribute:d,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(d.name),repeatTarget:r.get(d.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((d,f)=>d.order-f.order).map(d=>({raw:d.raw,sourceRange:EC(d.sourceRange,e.source),order:d.order,diagnostics:d.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function fC(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=pC(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:Ti({state:n,scope:b,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:b})=>b.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,d=mC(t,n,l,e.isRepeat),f=c?yC(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?hC(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=xC(t,n,r);if(m.length===0&&h.length===0){let b=s.find(({result:E})=>!E.ok)?.result;b&&!b.ok&&h.push({code:b.code,message:b.reason})}return{name:t.name,source:i,resolution:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function pC(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function mC(e,t,n,r){return n?_m(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:_m(gC(e))}function gC(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function _m(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function hC(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function yC(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Om({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:Om(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function xC(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function bC(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function SC(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function Om(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function EC(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
- `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function vC(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var kC=160;function Dm(e,t,n,r={}){let o=Wn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function Lm(e,t,n,r,o,i,s,a,c,l,d){let f=Wn(t),m=t.elements.get(e),u=n.nodes.get(e),g=r.get(e);if(!m||!u||!g)throw new Error(`Node not found: ${e}`);let h=Um(m.textSegments,s),b=Km(e,t,m,g,h),E=h?RC(h):void 0,v=wC(i,h),I=m.textSegments.map(C=>({index:C.index,value:C.value,editable:Jm(C,g,s?.get(C.index)??null),source:o.get(C.index)??null})),R=jm(m,t),P=m.childKeys.map(C=>{let A=t.elements.get(C);return A?{key:C,tag:A.tag,label:A.tag}:null}).filter(C=>C!==null),T=[];if(m.parentKey){let C=t.elements.get(m.parentKey);if(C)for(let A of C.childKeys){if(A===e)continue;let F=t.elements.get(A);F&&T.push({key:A,tag:F.tag,label:F.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:$m(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:v,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:I,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:R,children:P,siblings:T}}function Bm(e,t,n,r,o,i,s,a){let c=Wn(t),l=t.elements.get(e),d=n.nodes.get(e),f=r.get(e);if(!l||!d||!f)throw new Error(`Node not found: ${e}`);let m=Um(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:$m(l),label:l.tag,capabilities:Km(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(u=>({code:u.code,message:u.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(u=>{let g=o.get(u.index);return{index:u.index,editable:Jm(u,f,i?.get(u.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:jm(l,t)}}function $m(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:IC(e.sourceRange),structuralPath:e.identity.structuralPath,...CC(e.textSegments)}}function jm(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function IC(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function CC(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,kC)}:{}}function Vm(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function Um(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Km(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(d=>d.kind==="repeat-region"&&d.childKeys.includes(e)),a=o?.diagnostics.find(d=>d.code==="missing-adapter"||d.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&Xm(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function Jm(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Xm(n.editMode):!0}function Xm(e){return e==="direct"||e==="proxy"||e==="upstream"}function RC(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function wC(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:vC(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var Zc=["set-class-name-source","apply-style-draft"];function zm(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Zc,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:Zc,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Zc}}function Hm(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),Wm(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Wm(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),Wm(s,t,n,r,o))}}import Gm from"node:path";function qc(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function Zm(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=TC(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function Yi(e){let t=()=>NC(e);return e.mutex?e.mutex.runExclusive(t):t()}async function NC(e){let t=await Zm(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=PC(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return Qc({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return Qc({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return Qc({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return Ym("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Ym("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function PC(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function Qc(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:AC(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function Ym(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function AC(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function TC(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||Gm.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Gm.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}var FC=50,_C=8*1024*1024;function tg(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??FC),s=Math.max(0,t.maxUndoBytes??_C);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(C){let A=[...C.steps].sort((Z,fe)=>Z.order-fe.order),F=A.filter(Z=>Z.type!=="invoke-external-adapter");if(F.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let M=new Set(F.map(Z=>Z.file)),K=await v(M),q=new Map(K.map(Z=>[Z.file,Z.exists===!1?"":Z.content])),Re;for(let Z of F){let fe=eg(Z,q.get(Z.file)??"");if(!fe.ok)return{ok:!1,errorCode:fe.errorCode,reason:fe.reason};q.set(Z.file,fe.source),Re=fe.selectionRef??Re}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...q].map(([Z,fe])=>({operation:"upsert",file:Z,content:fe,baseContentHash:K.find(Te=>Te.file===Z)?.sha256??null}))},...Re?{selectionRef:Re}:{}}}async function c(C){let A=[...C.steps].sort((Te,zt)=>Te.order-zt.order),F=A.filter(Te=>Te.type!=="invoke-external-adapter"),M=A.filter(Te=>Te.type==="invoke-external-adapter"),K=new Set(F.map(Te=>Te.file));if(F.length>0&&M.length>0)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(F.length===0)return b(C,M);let q=await v(K),Re=new Map;for(let Te of q)Re.set(Te.file,Te.exists===!1?"":Te.content);let Z;for(let Te of F){let zt=Re.get(Te.file)??"",Ht=eg(Te,zt);if(!Ht.ok)return{ok:!1,operationId:C.operationId,errorCode:Ht.errorCode,reason:Ht.reason,rolledBack:!1};Re.set(Te.file,Ht.source),Ht.selectionRef&&(Z=Ht.selectionRef)}let fe=await R([...Re].map(([Te,zt])=>({file:Te,content:zt,exists:!0,version:0,sha256:ve(zt)})),q);return fe.ok===!1?{ok:!1,operationId:C.operationId,errorCode:fe.rolledBack?"writeback-failed":"rollback-failed",reason:fe.reason,rolledBack:fe.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:q,postSnapshots:fe.snapshots,plan:C}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...fe.snapshots.map(Te=>Te.version)),affectedFiles:[...K],...Z?{selectionRef:Z}:{}})}async function l(C){let A=new Set(C.edits.map(fe=>fe.file)),F=await v(A),M=E(C,F);if(M)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:M.reason,affectedFiles:[M.file],rolledBack:!1};let K=new Map(F.map(fe=>[fe.file,fe])),q=C.edits.find(fe=>fe.operation==="create-only"&&K.get(fe.file)?.exists!==!1);if(q)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${q.file}`,affectedFiles:[q.file],rolledBack:!1};let Re=C.edits.map(fe=>fe.operation==="delete"?{file:fe.file,content:"",exists:!1,version:0}:{file:fe.file,content:fe.content,exists:!0,version:0,sha256:ve(fe.content)}),Z=await R(Re,F,new Set(C.edits.filter(fe=>fe.operation==="create-only").map(fe=>fe.file)));return Z.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:F,postSnapshots:Z.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:F}}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Z.snapshots.map(fe=>fe.version)),affectedFiles:[...A]})}async function d(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await R(C.preSnapshots,C.postSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(F=>F.version)),affectedFiles:C.preSnapshots.map(F=>F.file)})}async function f(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await R(C.postSnapshots,C.preSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(C),m(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(F=>F.version)),affectedFiles:C.postSnapshots.map(F=>F.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((C,A)=>C+g(A),0)}function g(C){return h(C.preSnapshots)+h(C.postSnapshots)}function h(C){return C.reduce((A,F)=>A+F.file.length+F.content.length,0)}async function b(C,A){let F=[];for(let M of A){let K=M.capability??"write-text",q=o.find(Z=>Z.sourceType===M.sourceType&&(M.adapterId===void 0||Z.adapterId===M.adapterId)&&(Z.capabilities===void 0||Z.capabilities.includes(K)));if(!q)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${M.sourceType}`,rolledBack:!1};let Re=await q.execute(M);if(!Re.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:Re.reason??`External adapter failed for ${M.sourceType}`,rolledBack:!1};F.push(M.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:F}}function E(C,A){if(C.conflictPolicy!=="compare-and-swap")return null;let F=new Map(A.map(M=>[M.file,M]));for(let M of C.edits){if(M.operation==="create-only")continue;if(M.baseContentHash===void 0)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};let K=F.get(M.file),q=M.baseContentHash;if(q===null){if(K?.exists!==!1)return{file:M.file,reason:`Source file ${M.file} was created or changed before save.`};continue}if(!q)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};if(K?.exists===!1||K?.sha256!==q)return{file:M.file,reason:`Source file ${M.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function v(C){let A=[];for(let F of C)A.push(await I(F));return A}async function I(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(C)),M=await e.readFile(C);return{file:C,content:M,version:F,exists:!0,sha256:ve(M)}}async function R(C,A,F=new Set){let M=[];try{for(let K of C){if(F.has(K.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(K.file,K.content)}else await P(K);let q=e.bumpVersion(K.file);M.push(K.file),K.version=q}}catch(K){let q=await T(A.filter(Z=>M.includes(Z.file)));if(q.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${q.failedFiles.join(", ")}: ${qm(K)}`,rolledBack:!1,instanceConflict:Qm(K)};let Re=Qm(K);return{ok:!1,reason:`${Re?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${qm(K)}`,rolledBack:!0,instanceConflict:Re}}return{ok:!0,snapshots:C.map(OC)}}async function P(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let A=[];for(let F of C)try{await P(F),e.bumpVersion(F.file)}catch{A.push(F.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function Qm(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function OC(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function qm(e){return e instanceof Error?e.message:String(e)}function eg(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return ze(zn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return ze(Hn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return ze(Un({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return ze(Kn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return ze(Uo({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return ze(Cr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return ze(Cr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return ze(Wo({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return ze(Jo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return ze(Go({source:t,locator:e.locator,index:e.index}));case"move-array-item":return ze(Yo({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return ze(Jn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return ze(Xo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return MC(e,t);case"set-property-changes":return ze(zo({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return ze(Ho({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return ze(Qo({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function MC(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Uu(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ve(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:Vu({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function ze(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as Zi,SiteEditCompositionContextSchema as DC,SiteEditCompositionSelectorSchema as LC}from"@vcp-dev/contracts";var He=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function ng(e,t){throw new He("INVALID_COMPOSITION",e,{value:t})}function Qi(e){let t=DC.safeParse(e);return t.success?t.data:ng("Invalid SiteEditCompositionContext.",e)}function rg(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=Qi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Zi(d);if(n.has(f))throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d});let m=r.get(l.entryFile);if(m)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let u={context:d,entryFile:l.entryFile,key:f};t.push(u),n.set(f,u),r.set(l.entryFile,f)}if(t.length===0)throw new He("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let d=Qi(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new He("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:d,version:l?.version});let f=Zi(d);if(!n.has(f))throw new He("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:d,key:f});if(o.has(f))throw new He("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:d,key:f});o.set(f,l.version)}function i(l){let d=LC.safeParse(l);if(!d.success)return ng("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===d.data.routeId&&(d.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===d.data.templateId));if(f.length===1)return f[0];throw f.length>1?new He("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:d.data}):new He("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:d.data})}function s(l){let d=Qi(l),f=Zi(d),m=n.get(f);if(!m)throw new He("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:d,key:f});return m}function a(l){let d=Qi(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=Zi(d),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d})}let u=[...n.values()].find(h=>h.entryFile===l.entryFile);if(u)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:u.context});let g={context:d,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let d=n.get(l);if(!d)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),d}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}import{composeSiteEditRepeatInstanceKey as BC,stripSiteEditRepeatInstanceKeys as og}from"@vcp-dev/contracts";function ig(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=og(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}function $C(e){let t=1;for(let n of e?.textTargets.values()??[])n?.kind==="value-binding"&&n.sourceKind==="repeat-template"&&(t=Math.max(t,n.collectionIndexMap?.length??0,n.collectionPathMap?.length??0));return t}function qi(e){return e?.map(t=>({...t}))}function el(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=qi(e.collectionPathMap?.[t])??qi(e.locator?.path);if(r)for(let o=r.length-1;o>=0;o-=1){let i=r[o];if(i.kind==="index"){i.index=n;break}}return{...e,path:qi(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>qi(o)??[])}}function sg(e,t,n){let r=new Set;for(let u of t.regions)if(u.kind==="repeat-region")for(let g of u.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(u=>[u.key,u])),i=[],s=new Map,a=(u,g)=>BC(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),v={...b,key:E,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=b.childKeys.flatMap(I=>l(I,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let v=0;v<b;v+=1)E.push(c(u,h,[...g,v]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let b of m(u)){let E=n.get(b);if(E){for(let v of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let I of jC(v))I.length<=g.length||VC(I,g)&&h.add(I[g.length])}}return h.size>0?h.size:$C(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],b=o.get(u);for(let E of b?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function ag(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function cg(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((og(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function jC(e){return e.collectionPathMap?.length?e.collectionPathMap.map(t=>t.filter(n=>n.kind==="index").map(n=>n.index)):e.collectionIndexMap?.length?e.collectionIndexMap.map(t=>[t]):[]}function VC(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function lg(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(d=>[d.key,d])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let d=o.get(a);if(!d)break;s.push({key:d.key,tag:d.tag,label:d.label}),a=d.parentKey}s.reverse();let c=i.childKeys.map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(d=>d!==i.key).map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function ug(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function dg(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function UC(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var fo=class extends Error{constructor(t){let n=t.map(dg);super(UC(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function fg(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof fo?{routeId:e,message:n,diagnostics:t.diagnostics.map(dg)}:{routeId:e,message:n}}function tl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function nl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function dr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function pg(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function rl(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function mg(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,d)=>l.preDigest===r[d]),i=t.files.every((l,d)=>l.postDigest===r[d]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var YC=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,ZC=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],gg=32,hg=256;function QC(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var yg={maxEntries:50,maxBytes:8*1024*1024};function qC(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async readFileBytes(t){return(await import("node:fs/promises")).readFile(t)},async getFileInfo(t){let n=await import("node:fs/promises");try{let r=await n.lstat(t);return!r.isFile()||r.isSymbolicLink()?null:{path:t,sizeBytes:r.size}}catch{return null}},async writeFile(t,n){await ei(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}function eR(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>yg.maxEntries||tR(e)>yg.maxBytes;)e.shift()}}function tR(e){return e.reduce((t,n)=>t+nR(n),0)}function nR(e){return xg(e.preSnapshots)+xg(e.postSnapshots)+rR(e.provenance)}function rR(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function xg(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function bg(e,t){return{key:JC(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var ts=class extends Error{constructor(t){super(t.reason),this.result=t}},Mn=class extends Error{constructor(t){super(tl(t)),this.failedRoutes=t}};function Sg(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=qe(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(qe(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function oR(e,t,n){if(!n)return;let r=qe(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var iR=/\.(?:[cm]?[jt]sx?)$/i,sR=/\.json$/i,aR=/\.(?:css|scss|sass)$/i,cR=/\.mdx$/i,lR=/\.ya?ml$/i;function uR(e){if(!e||e.kind!=="value-binding")return null;let t="path"in e?e.path:void 0,n=e.root,r=n&&(n.kind==="binding"||n.kind==="named-export")?n.name:void 0;return{kind:e.sourceKind,file:e.file,expression:e.displayExpression,bindingName:r,path:t?.map(o=>o.kind==="property"?o.name:o.index)}}function dR(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function fR(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=Rg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(pR(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function pR(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Rg(e){return Array.isArray(e)?{files:e}:e}function mR(e){if(!zC(e.path))return{ok:!1,errorCode:"invalid-params",message:`Source file is read-only: ${e.path}`,details:{path:e.path}};if(e.operation==="upsert"&&e.content.includes("\0"))return{ok:!1,errorCode:"invalid-params",message:`Source file content must be valid text: ${e.path}`,details:{path:e.path}};if(e.operation==="delete"){if(e.capability!==WC||e.confirmDelete!==!0||e.confirmPath!==e.path)return{ok:!1,errorCode:"capability-denied",message:`Source file delete requires explicit confirmation: ${e.path}`,details:{path:e.path}};let t=XC(e.path);return t?{ok:!1,errorCode:"capability-denied",message:`Protected source file cannot be deleted: ${e.path}`,details:{path:e.path,protectionReason:t}}:{ok:!0}}if(iR.test(e.path)){let t=Nt({source:e.content,profile:mn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(sR.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ge(t)}`,details:{path:e.path}}}if(aR.test(e.path)){let t=Eg({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(cR.test(e.path)){let t=Eg({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(lR.test(e.path))try{GC(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ge(t)}`,details:{path:e.path}}}return{ok:!0}}function Eg({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",u=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
1
+ import*as Dh from"@babel/parser";import*as Jn from"@babel/types";import*as Yt from"node:path";var Cs=[".tsx",".ts",".jsx",".js"],Lh=Cs.map(e=>`/index${e}`),Bh=new Set(["json","css","scss","sass","less","svg","png","jpg","jpeg","gif","webp","avif","ico","bmp","woff","woff2","ttf","otf","eot","mp4","webm","mp3","wav","ogg","pdf","txt","md","csv","xml","yaml","yml"]);function tu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Bh.has(n[1].toLowerCase())}function nu(e){let t=[];for(let n of e.program.body)Jn.isImportDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Jn.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value),Jn.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&wt(n.source.value)&&t.push(n.source.value);return Rs(e.program,t),t}function Rs(e,t){if(!e||typeof e!="object")return;let n=e;if(n.type==="CallExpression"&&n.callee?.type==="Import"){let r=n.arguments?.[0];r?.type==="StringLiteral"&&typeof r.value=="string"&&wt(r.value)&&t.push(r.value)}for(let r of Object.values(n))if(Array.isArray(r))for(let o of r)Rs(o,t);else r&&typeof r=="object"&&Rs(r,t)}function wt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function pn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Yt.dirname(e);return Yt.join(n,t).replace(/\\/g,"/")}async function $h(e,t){if(Cs.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Cs){let r=`${e}${n}`;if(await t(r))return r}for(let n of Lh){let r=`${e}${n}`;if(await t(r))return r}return null}async function mn(e,t,n){let r=await Po(e,t,n);return r.ok?r.path:null}async function Po(e,t,n){let r=pn(e,t);try{if(!jh(e,t,r))return{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}};let o=await $h(r,n);return o?{ok:!0,path:o}:{ok:!1,diagnostic:{path:r,code:"import-not-found",message:`Local import not found: ${t}`,details:{fromFile:e,specifier:t}}}}catch(o){return{ok:!1,diagnostic:{path:r,code:"import-resolve-failed",message:`Failed to resolve local import: ${t}`,details:{fromFile:e,specifier:t,reason:o instanceof Error?o.message:String(o)}}}}}function jh(e,t,n){if(!wt(t)||t.includes("\0")||t.includes("\\")||Yt.posix.isAbsolute(n))return!1;let r=Yt.posix.normalize(n);if(r===".."||r.startsWith("../"))return!1;if(t.startsWith("@/")){let o=t.slice(2);return o.length>0&&!o.split("/").some(i=>i==="..")}return!Yt.posix.isAbsolute(e)}import{createHash as Kh}from"node:crypto";import*as ru from"@babel/parser";function gn(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function J(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gn(t,n,r,o)}}function Ns(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gn(t,n,r,o)}}var Vh={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Pt(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:ru.parse(t,{sourceType:"module",plugins:Vh[n]})}}catch(r){return{ok:!1,source:t,diagnostic:gn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function ws(e,t){return Pt({source:e,profile:ou(t.kind)})}function xr(e,t){return Pt({source:e,profile:ou(t)})}function ou(e){return"next-app-entry"}function hn(e){let{filePath:t,source:n}=e,r=t.toLowerCase().split(".").pop()??"";return r==="tsx"?"tsx-module":r==="ts"?"ts-module":r==="jsx"||r==="js"||r===""&&/<\w[\s\S]*>/.test(n)?"tsx-module":"next-app-entry"}var yn=(e,t)=>{let n=Pt({source:t,profile:hn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Kh("sha256").update(t).digest("hex")}`,ast:n.ast,imports:nu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Uh(e,t){return yn(e,t)}function Jh(e,t){return pn(e,t)}import As from"@babel/generator";import*as uu from"@babel/parser";import Ts from"@babel/traverse";import*as Ie from"@babel/types";import{computeSiteEditSourceIdentityKey as zh}from"@vcp-dev/contracts";var iu="data-vcp-ui-component",Ao="components/ui";function Kt(e){if(!e)return!1;let t=Ps(e);return t===Ao||t.startsWith(`${Ao}/`)||t.includes(`/${Ao}/`)||t.endsWith(`/${Ao}`)}function xn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Kt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Kt(Ps(`${Xh(t)}/${e}`)):Kt(e):!1}function Ps(e){let n=(e.split("?")[0]??e).replace(/\\/g,"/").replace(/^\.\//,""),r=[];for(let o of n.split("/"))if(!(!o||o===".")){if(o===".."){r.pop();continue}r.push(o)}return r.join("/")}function Xh(e){let t=Ps(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as uw}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as fw,isSiteEditRuntimeTextTag as pw}from"@vcp-dev/contracts/site-edit-runtime-capability";var su={key:"data-vcp-edit-key",parentKey:"data-vcp-edit-parent-key",movable:"data-vcp-movable",removable:"data-vcp-removable",flags:"data-vcp-flags",publicUiComponent:"data-vcp-ui-component"};var Wh=typeof As=="function"?As:As.default,Hh=typeof Ts=="function"?Ts:Ts.default,Gh=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Yh="suppressHydrationWarning",Zh=new Set(["SiteEditBootstrap"]);function Qh(e){let t=ty(e.file,e.projectRoot);if(!ey(e.source)||Kt(t))return{code:e.source,elements:[]};let n=e.attributes??su,r=uu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=ry(r,t);return Hh(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!iy(c)||du(a,n.key))return;let l=ay(s)??"default",d=ly(s),f=zh(t,l,d),m=Fo(c)??"unknown",u=ny(c)?"jsx":"component-call";if(u==="component-call"&&!cy(s.node.children)&&Zh.has(m))return;let g=u==="component-call"&&oy(m,i);sy(a,n.key,f),g&&au(a,iu),qh(s)&&au(a,Yh),o.push({key:f,tag:m,componentName:l,sourceFile:t,sourceKind:u})}}),o.length===0?{code:e.source,elements:o}:{code:Wh(r,{jsescOption:{minimal:!0}}).code,elements:o}}function qh(e){return!e.findParent(t=>t.isJSXElement())}function ey(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function ty(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,""),r=t?.replace(/\\/g,"/").replace(/\/+$/,"");if(r&&n.startsWith(`${r}/`))return n.slice(r.length+1);for(let[i,s]of[["/src/app/",1],["/src/components/",1],["/app/",1],["/components/",1]]){let a=n.indexOf(i);if(a>=0)return n.slice(a+s)}return n.match(/(?:^|\/)((?:src\/app|src\/components|app|components)\/.+)$/)?.[1]??n}function ny(e){return Ie.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Fo(e){return Ie.isJSXIdentifier(e)?e.name:Ie.isJSXMemberExpression(e)?pu(e):null}function ry(e,t){let n=new Set;for(let r of e.program.body)if(!(!Ie.isImportDeclaration(r)||!xn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function oy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function iy(e){let t=Fo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Gh.has(t)}function du(e,t){return e.attributes.some(n=>Ie.isJSXAttribute(n)&&Ie.isJSXIdentifier(n.name,{name:t}))}function sy(e,t,n){fu(e,Ie.jsxAttribute(Ie.jsxIdentifier(t),Ie.stringLiteral(n)))}function au(e,t){du(e,t)||fu(e,Ie.jsxAttribute(Ie.jsxIdentifier(t),null))}function fu(e,t){let n=e.attributes.findIndex(r=>Ie.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function pu(e){return`${Ie.isJSXIdentifier(e.object)?e.object.name:pu(e.object)}.${e.property.name}`}function ay(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Ie.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}function cy(e){return e.some(t=>Ie.isJSXElement(t)||Ie.isJSXFragment(t))}var cu=new WeakMap,To=new WeakMap,Fs=new WeakMap;function ly(e){let t=cu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=uy(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return cu.set(e.node,o),o}function uy(e){let t=Fo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${lu(e,t)}`:`${t}#${lu(e,t)}`}function lu(e,t){let n=mu(e)??e.getFunctionParent();if(!n)return 0;let r=Fs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Fs.get(n.node);o||(o=new Map,Fs.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0,a=n.isJSXElement()||n.isJSXFragment()?_o(n):dy(n);for(let c of a)if(Fo(c.node.openingElement.name)===t){if(i.set(c.node,s),c.node===e.node)return s;s+=1}return i.get(e.node)??0}function dy(e){let t=To.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!mu(r)&&n.push(r)}}),To.set(e.node,n),n}function mu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement())return t;t=t.parentPath}return n}function _o(e){let t=To.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){n.push(o);continue}if(o.isJSXFragment()){n.push(..._o(o));continue}o.isJSXExpressionContainer()&&n.push(...bn(o.get("expression")))}return To.set(e.node,n),n}function bn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return _o(e);if(e.isParenthesizedExpression())return bn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return bn(e.get("right"));if(e.isConditionalExpression())return[...bn(e.get("consequent")),...bn(e.get("alternate"))];if(e.isCallExpression()&&py(e.node)){let t=e.get("arguments")[0];return fy(t)}return[]}function fy(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return _o(t);if(t.isParenthesizedExpression())return bn(t.get("expression"));if(!t.isBlockStatement())return[];for(let n of t.get("body")){if(!n.isReturnStatement())continue;let r=n.get("argument");return r.node?bn(r):[]}return[]}function py(e){return Ie.isMemberExpression(e.callee)&&Ie.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as xN,SiteEditPatchPlanSchema as bN}from"@vcp-dev/contracts";function Sn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Oo(e,t){let n=t[0]??"Site edit operation request failed contract validation.";return{ok:!1,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},error:{code:"INVALID_PARAMS",message:n},data:{requestId:e.id,kind:e.kind,composition:{routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}},target:e.target,resultVersion:e.documentVersion}}}function Mo(e,t){if(!e.pageComposition)throw new Error("RenderDocument is missing the required Page Composition projection.");return{siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,entries:e.entries.map(n=>({key:n.key,parentKey:n.parentKey,...n.pageCompositionUnitKey?{pageCompositionUnitKey:n.pageCompositionUnitKey}:{},...n.pageCompositionActionScope?{pageCompositionActionScope:n.pageCompositionActionScope}:{},operationSummary:{canUpdateText:n.operationSummary.canUpdateText,canInsertChild:n.operationSummary.canInsertChild,canMove:n.operationSummary.canMove,canRemove:n.operationSummary.canRemove},...n.dynamicDataSummary?{dynamicDataSummary:n.dynamicDataSummary}:{}})),pageComposition:e.pageComposition.status==="unsupported"?{status:"unsupported",reason:e.pageComposition.reason,diagnostics:e.pageComposition.diagnostics}:{status:"supported",containerKey:e.pageComposition.container.key,hasBusinessMembers:e.pageComposition.businessMembers.length>0,placementUnitKeys:e.pageComposition.placementUnits.map(n=>n.key),placements:e.pageComposition.placements.map(n=>({placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,relation:n.relation}))}}}function Do(e){return{composition:e.composition,key:e.key,tag:e.tag,label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:my(e.capabilities),provenanceChain:e.provenanceChain?{editMode:e.provenanceChain.editMode,diagnostics:e.provenanceChain.diagnostics}:void 0,dynamicData:e.dynamicData,...e.properties?{properties:e.properties}:{},textSegments:e.textSegments.map(t=>({index:t.index,editable:t.editable,sourceKind:t.source?.kind??null})),boundaryKind:e.boundaryKind}}function Lo(e,t){let n=new Date().toISOString();return e.type==="document-changed"?{type:"site-edit.document.changed",siteId:t.siteId,snapshotId:t.snapshotId,composition:e.composition,version:e.version,at:n}:e.type==="operation-completed"?{type:"site-edit.operation.completed",siteId:t.siteId,composition:e.composition,result:Sn(e.result),at:n}:e.type==="operation-failed"?{type:"site-edit.operation.failed",siteId:t.siteId,requestId:e.requestId,composition:e.composition,error:e.error,at:n}:e.type==="capability-changed"?{type:"site-edit.capability.changed",siteId:t.siteId,composition:e.composition,keys:e.keys,at:n}:e.type==="graph-invalidated"?{type:"site-edit.graph.invalidated",siteId:t.siteId,composition:e.composition,at:n}:e.type==="graph-ready"?{type:"site-edit.graph.ready",siteId:t.siteId,composition:e.composition,version:e.version,at:n}:e.type==="graph-error"?{type:"site-edit.graph.error",siteId:t.siteId,composition:e.composition,message:e.message,at:n}:null}function my(e){return{composition:e.composition,key:e.key,canUpdateText:e.canUpdateText,canInsertChild:e.canInsertChild,canMove:e.canMove,canRemove:e.canRemove,editModes:e.editModes?{updateText:e.editModes.updateText?{mode:e.editModes.updateText.mode,reasonCode:e.editModes.updateText.reasonCode}:void 0,insertChild:e.editModes.insertChild?{mode:e.editModes.insertChild.mode,reasonCode:e.editModes.insertChild.reasonCode}:void 0,move:e.editModes.move?{mode:e.editModes.move.mode,reasonCode:e.editModes.move.reasonCode}:void 0,remove:e.editModes.remove?{mode:e.editModes.remove.mode,reasonCode:e.editModes.remove.reasonCode}:void 0}:void 0,constraints:e.constraints}}import{checkGlobalsCssEdit as PR,computeSiteEditCompositionKey as AR,getSiteEditSourceDeleteProtectionReason as TR,isSiteEditTextSourcePath as FR,parseSiteEditRepeatInstanceKey as _R,SITE_EDIT_SOURCE_DELETE_CAPABILITY as OR,stripSiteEditRepeatInstanceKeys as et}from"@vcp-dev/contracts";import is from"node:path";import{parse as MR}from"yaml";import Ls from"node:path";import{TextDecoder as hy}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as hu,SITE_EDIT_SOURCE_ALLOWED_DIRS as yu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as xu,SiteEditCompositionContextSchema as yy,SiteEditSourceFileResponseSchema as _s,SiteEditSourceLocationSchema as xy,SiteEditSourcePathSchema as Bo,SiteEditSourceTreeResponseSchema as by,isSiteEditTextSourcePath as Sy}from"@vcp-dev/contracts";import{createHash as gy}from"node:crypto";var br=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ve(e){return`sha256:${gy("sha256").update(e).digest("hex")}`}var Ey=[...xu,...hu,...yu];function Bs(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return yy.parse(e.composition)}var Os=2e3,Ms=12,Ds=24*1024*1024,gu=512*1024,vy=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),ky={".avif":"image/avif",".bin":"application/octet-stream",".eot":"application/vnd.ms-fontobject",".gif":"image/gif",".glb":"model/gltf-binary",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".svg":"image/svg+xml",".ttf":"font/ttf",".wasm":"application/wasm",".webm":"video/webm",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2",".zip":"application/zip"},Iy={".cjs":"javascript",".css":"css",".cts":"typescript",".html":"html",".js":"javascript",".jsx":"javascript",".json":"json",".md":"markdown",".mdx":"markdown",".mjs":"javascript",".mts":"typescript",".ts":"typescript",".tsx":"typescript",".txt":"plaintext",".yaml":"yaml",".yml":"yaml"},Cy=new hy("utf-8",{fatal:!0});async function $o(e,t={}){let n=Bs(t),{files:r,truncated:o}=await Fy(e,t),i=My(r.map(s=>s.metadata));return by.parse({composition:n,nodes:i,defaultPath:Dy(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function jo(e,t,n={}){let r=Bs(n),o=Bo.parse(t.path),i=await Ny(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(js(o)){let a=Eu(o),c=await Py(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return _s.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await $s(e,o);return s.ok?_s.parse({composition:r,path:o,kind:"text",language:vu(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):_s.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function $s(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Ry(o);return i===null?{ok:!1,sizeBytes:o.byteLength}:{ok:!0,content:i,sizeBytes:o.byteLength}}let n=await e.readFile(t),r=Buffer.byteLength(n,"utf8");return n.includes("\0")?{ok:!1,sizeBytes:r}:{ok:!0,content:n,sizeBytes:r}}function Ry(e){if(e.includes(0))return null;try{return Cy.decode(e)}catch{return null}}async function Ny(e,t,n){if(!Ay(t,n))return null;let r=await wy(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function wy(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=bu(await e.listFiles({roots:[t],maxFiles:1,maxDepth:t.split("/").length})).files.find(i=>i.path===t);if(o)return o}if(!await e.exists(t))return null;if(e.readFileBytes){let r=await e.readFileBytes(t);return{path:t,sizeBytes:r.byteLength}}if(js(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Py(e,t){if(!vy.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>gu)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>gu?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Ay(e,t){return xu.some(n=>n===e)||hu.some(n=>n===e)||yu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Bo.safeParse(n);return r.success&&r.data===e})}function Vo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return xy.parse({key:e.key,composition:t.composition,sourceFile:t.sourceLocator.sourceFile,componentName:t.sourceLocator.componentName,openingElementRange:{startLine:t.sourceLocator.openingElementRange.startLine,startColumn:t.sourceLocator.openingElementRange.startColumn,endLine:t.sourceLocator.openingElementRange.endLine,endColumn:t.sourceLocator.openingElementRange.endColumn},structuralPath:t.sourceLocator.structuralPath,textPreview:t.sourceLocator.textPreview})}function bu(e){return Array.isArray(e)?{files:e}:e}function Ty(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Fy(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=bu(await e.listFiles({roots:_y(t),maxFiles:Os+1,maxDepth:Ms,maxTotalBytes:Ds+1})),r=new Map,o=new Set(n.truncated?.reasons),i=0;for(let a of[...n.files].sort((c,l)=>c.path.localeCompare(l.path))){let c=Bo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ms){o.add("max-depth");continue}if(r.size>=Os){o.add("max-files");break}if(i+a.sizeBytes>Ds){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Oy(l,a.sizeBytes,Bs(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Ty([...o]),maxFiles:Os,maxDepth:Ms,maxTotalBytes:Ds}}:{}}}function _y(e){let t=new Set(Ey);for(let n of e.routeEntryFiles??[]){let r=Bo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Oy(e,t,n){return js(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Eu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:vu(e),sizeBytes:t,readonly:!1}}function My(e){let t=[];for(let n of e){let r=n.path.split("/"),o=t,i="";for(let[s,a]of r.entries()){i=i?`${i}/${a}`:a;let c=s===r.length-1,l=o.find(d=>d.name===a);if(l||(l=c?{kind:"file",name:a,path:i,file:n}:{kind:"directory",name:a,path:i,children:[]},o.push(l)),c){if(l.kind!=="file")throw new Error(`Source tree path collision: ${n.path}`);l.file=n}else{if(l.kind!=="directory")throw new Error(`Source tree path collision: ${n.path}`);o=l.children}}}return Su(t)}function Su(e){return e.map(t=>t.kind==="directory"?{...t,children:Su(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Dy(e){let t=e.find(r=>r.path.toLowerCase()==="design.md");if(t)return t.path;let n=e.find(r=>r.path==="app/page.tsx");return n?n.path:e.find(r=>r.kind==="text")?.path??e.at(0)?.path}function js(e){return!Sy(e)}function Eu(e){let t=Ls.posix.extname(e).toLowerCase();return!t&&Ls.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":ky[t]??"application/octet-stream"}function vu(e){let t=Ls.posix.extname(e).toLowerCase();return Iy[t]??"plaintext"}import Vs from"@babel/traverse";import*as At from"@babel/types";function Ae(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(At.isJSXIdentifier(t)){let o=e.scope.getBinding(t.name);if(!o)return!1;let i=o.path;if(!i.isImportSpecifier())return!1;let s=i.node.imported;return(At.isIdentifier(s)&&s.name==="Fragment"||At.isStringLiteral(s)&&s.value==="Fragment")&&ku(i.parentPath)}if(!At.isJSXMemberExpression(t)||!At.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!At.isJSXIdentifier(t.object))return!1;let n=e.scope.getBinding(t.object.name);if(!n)return!1;let r=n.path;return(r.isImportDefaultSpecifier()||r.isImportNamespaceSpecifier())&&ku(r.parentPath)}function ku(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Zt=typeof Vs=="function"?Vs:Vs.default,Ko=new WeakMap,Uo=new WeakMap;function Tt(e,t){let n=ws(e,t);if(!n.ok)return Ns(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=se(n.ast,t);return r.ok?{ok:!0,match:{locatorKind:r.match.locatorKind,node:r.match.node,start:r.match.start,end:r.match.end}}:Ns(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function se(e,t){return t.kind==="jsx-node"?Nu(e,t):t.kind==="jsx-attribute"?Ky(e,t):t.kind==="value"?Uy(e,t):t.kind==="expression"?Jy(e,t):t.kind==="directive"?Xy(e,t):t.kind==="export"?zy(e,t):{ok:!1,diagnostic:gn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Nu(e,t){return t.strategy==="source-range"?Ly(e,t):By(e,t)}function Ly(e,t){let n=null;if(Zt(e,{JSXElement(o){if(!En(o.node,t.sourceRange))return;let i=Me("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!En(o.node,t.sourceRange))return;let i=Me("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!En(o.node,t.sourceRange))return;let i=Me("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!En(o.node,t.sourceRange))return;let i=Me("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return De("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!ox(r.path,t.expectedIdentity)?De("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function By(e,t){if(t.structuralPath===""){let r=jy(e,t.component);if(r){let o=Vy(r);if(o)return o}}let n=null;return Zt(e,{JSXElement(r){if(Er(r)!==t.component||Us(r)!==t.structuralPath)return;let i=Me("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Er(r)!==t.component||Us(r)!==t.structuralPath)return;let i=Me("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=$y(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:De("jsx-node","locator-miss","JSX node not found for structural-path locator")}function $y(e,t,n){let r=null;return Zt(e,{JSXElement(o){if(Er(o)!==t||!En(o.node,n))return;let i=Me("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Er(o)!==t||!En(o.node,n))return;let i=Me("jsx-node",o);i&&(r=i,o.stop())}}),r}function jy(e,t){let n=null;return Zt(e,{FunctionDeclaration(r){r.node.id?.name===t&&(n=r,r.stop())},VariableDeclarator(r){if(r.node.id.type==="Identifier"&&r.node.id.name===t){let o=r.get("init");(o.isArrowFunctionExpression()||o.isFunctionExpression())&&(n=o),r.stop()}}}),n}function Vy(e){if(e.isArrowFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let r=t.get("body").find(o=>o.isReturnStatement());if(r){let o=r.get("argument");if((o.isParenthesizedExpression()?o.get("expression"):o).isJSXFragment())return De("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?De("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target"):null}if(e.isFunctionDeclaration()||e.isFunctionExpression()){let t=e.get("body");if(t.isBlockStatement()){let n=t.get("body").find(r=>r.isReturnStatement());if(n){let r=n.get("argument");if((r.isParenthesizedExpression()?r.get("expression"):r).isJSXFragment())return De("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Ky(e,t){let n=Nu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>ix(c,t.name));if(!s||!s.isJSXAttribute())return De("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Me("jsx-attribute",s);return a?{ok:!0,match:a}:De("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Uy(e,t){let n=Wy(e,t);if(!n.ok)return n;let r=Hy(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Jt(r.match.path.node.loc,t.expectedRange)?De("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Jy(e,t){let n=null;return Zt(e,{Identifier(r){if(!ex(r))return;let o=Cu(r);if(!o||!Ru(o,t))return;let i=Me("expression",r);i&&(t.expectedRange&&!Jt(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Cu(r);if(!o||!Ru(o,t))return;let i=Me("expression",r);i&&(t.expectedRange&&!Jt(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:De("expression","locator-miss","Expression not found")}function Xy(e,t){let n=null;return Zt(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Jt(i.node.loc,t.expectedRange))return;let s=Me("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:De("directive","locator-miss",`Directive '${t.value}' not found`)}function zy(e,t){let n=null;return Zt(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Me("export",c);if(!m||t.expectedRange&&!Jt(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=Js(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let d=l.get("init");if(!d.node)return;let f=Me("export",d);if(!f||t.expectedRange&&!Jt(d.node.loc,t.expectedRange))return;n=f,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Js(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Jt(s.node.loc,t.expectedRange))return;let a=Me("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Me("export",o);i&&(t.expectedRange&&!Jt(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:De("export","export-not-found",`Export '${rx(t)}' not found`)}function Wy(e,t){let n=null;return Zt(e,{Expression(r){if(n||t.root.kind!=="expression"||!En(r.node,t.root.sourceRange))return;let o=Me("value",r);o&&(n=o,r.stop())},VariableDeclarator(r){if(n)return;if(t.root.kind==="binding"){if(r.node.id.type!=="Identifier"||r.node.id.name!==t.root.name)return;let u=r.get("init");if(!u.node)return;let g=Me("value",u);if(!g)return;n=g,r.stop();return}if(t.root.kind!=="hook-state")return;let o=t.root,i=r.get("id"),s=r.get("init");if(!i.isArrayPattern()||!s.isCallExpression()||i.node.elements.findIndex(u=>u?.type==="Identifier"&&u.name===o.name)!==0)return;let c=s.node.callee;if((c.type==="Identifier"?c.name:c.type==="MemberExpression"&&c.property.type==="Identifier"?c.property.name:null)!==o.hook)return;let d=o.hook==="useReducer"?1:0,f=r.get(`init.arguments.${d}`);if(!f||Array.isArray(f)||!f.node)return;let m=Me("value",f);m&&(n=m,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Js(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Me("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Me("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:De("value",t.root.kind==="named-export"||t.root.kind==="default-export"?"export-not-found":t.root.kind==="expression"?"locator-miss":"binding-not-found","Value root was not found")}function Hy(e,t){let n=Ks(e);for(let o of t){if(n=Ks(n),o.kind==="property"){if(!n.isObjectExpression())return De("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return De("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>sx(l,o.name));if(!c||!c.isObjectProperty())return De("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return De("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return De("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return De("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Ks(n);let r=Me("value",n);return r?{ok:!0,match:r}:De("value","locator-miss","Resolved value has no source range")}function Ks(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Me(e,t){let n=t.node;return n.start==null||n.end==null?null:{locatorKind:e,node:n,start:n.start,end:n.end,path:t}}function En(e,t){return Jt(e.loc,t)}function Jt(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function Us(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ae(n)){let o=Pu(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Iu(n,o)}`):t.unshift(`${o}#${Iu(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Qy(n.parentPath)&&!qy(n.parentPath))break;n=n.parentPath}return t.join("/")}function Iu(e,t){let n=wu(e)??e.getFunctionParent();if(!n)return 0;let r=Ko.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Ko.get(n.node)?.get(t);if(!i){let a=Ko.get(n.node);a||(a=new Map,Ko.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Sr(n):Gy(n);for(let a of s)if(Pu(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Gy(e){let t=Uo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!wu(r)&&n.push(r)}}),Uo.set(e.node,n),n}function wu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ae(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Sr(e){let t=Uo.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ae(o)){n.push(...Sr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Sr(o));continue}o.isJSXExpressionContainer()&&n.push(...Ut(o.get("expression")))}return Uo.set(e.node,n),n}function Ut(e){if(e.isJSXElement())return Ae(e)?Sr(e):[e];if(e.isJSXFragment())return Sr(e);if(e.isParenthesizedExpression())return Ut(e.get("expression"));if(e.isLogicalExpression()&&Yy(e.node.operator))return Ut(e.get("right"));if(e.isCallExpression()||e.isOptionalCallExpression()){let t=e.get("callee"),n=!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())?t.get("property"):null;if(!Array.isArray(t)&&(t.isMemberExpression()||t.isOptionalMemberExpression())&&!t.node.computed&&n!==null&&!Array.isArray(n)&&n.isIdentifier()&&n.node.name==="map"){let r=e.get("arguments").find(o=>!Array.isArray(o)&&(o.isArrowFunctionExpression()||o.isFunctionExpression()));if(r&&!Array.isArray(r)){let o=r.get("body");if(!Array.isArray(o)){if(o.isBlockStatement()){let i=[];for(let s of o.get("body")){if(s.isVariableDeclaration())for(let a of s.get("declarations")){let c=a.get("init");(c.isJSXElement()||c.isJSXFragment())&&i.push(...Ut(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Ut(a));break}}return i}else if(o.node&&o.isExpression())return Ut(o)}}}}return e.isConditionalExpression()?[...Ut(e.get("consequent")),...Ut(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ut(t)):[]}function Yy(e){return e==="&&"||e==="||"||e==="??"}function Pu(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Zy(e.name):null}function Zy(e){let t=[],n=e;for(;n.type==="JSXMemberExpression";)t.unshift(n.property.name),n=n.object;return t.unshift(n.name),t.join(".")}function Er(e){let t=e;for(;t;){if(t.isFunctionDeclaration())return t.node.id?.name??null;if((t.isArrowFunctionExpression()||t.isFunctionExpression())&&t.parentPath?.isVariableDeclarator()){let n=t.parentPath.node.id;return n.type==="Identifier"?n.name:null}t=t.parentPath}return null}function Qy(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function qy(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression())return!1;let n=t.get("callee"),r=!Array.isArray(n)&&(n.isMemberExpression()||n.isOptionalMemberExpression())?n.get("property"):null;if(Array.isArray(n)||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.computed||r===null||Array.isArray(r)||!r.isIdentifier()||r.node.name!=="map")return!1;let o=t.get("arguments");return Array.isArray(o)?o.some(i=>!Array.isArray(i)&&i.node===e.node):!1}function ex(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Cu(e){if(e.isIdentifier())return{base:e.node.name,path:[]};if(!e.isMemberExpression())return null;let t=[],n=e.node;for(;n.type==="MemberExpression";){if(n.computed)if(n.property.type==="NumericLiteral")t.unshift({kind:"index",index:n.property.value});else if(n.property.type==="StringLiteral")t.unshift({kind:"property",name:n.property.value});else return null;else if(n.property.type==="Identifier")t.unshift({kind:"property",name:n.property.name});else return null;if(n.object.type==="Identifier")return{base:n.object.name,path:t};if(n.object.type!=="MemberExpression")return null;n=n.object}return null}function Ru(e,t){return e.base===t.base&&tx(e.path,t.path??[])}function tx(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}function nx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function rx(e){return e.exportKind==="named"?e.name:e.exportKind}function De(e,t,n,r){return{ok:!1,diagnostic:gn(t,n,e,r)}}function ox(e,t){return Er(e)!==t.component?!1:Us(e)===t.structuralPath}function ix(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Js(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function sx(e,t){return e.isObjectProperty()?nx(e.node)===t:!1}import*as Tu from"@babel/parser";import{arrayExpression as dx,booleanLiteral as fx,identifier as px,jsxAttribute as mx,jsxExpressionContainer as gx,jsxIdentifier as hx,nullLiteral as yx,numericLiteral as xx,objectExpression as bx,objectProperty as Sx,stringLiteral as zs}from"@babel/types";import Xs from"@babel/generator";var ax=typeof Xs=="function"?Xs:Xs.default;function cx(e){let t=e.split(`
2
+ `),n=[],r=!1;for(let s of t){let a=s.match(/^(\s+)/);if(a){let c=a[1];c.includes(" ")?r=!0:c.length>0&&n.push(c.length)}}if(r&&t.every(a=>{let c=a.match(/^(\s+)/);return!c||c[1].includes(" ")}))return"tab";if(n.length===0)return"2";function o(s,a){return a===0?s:o(a,s%a)}let i=n[0];for(let s=1;s<n.length;s++)i=o(i,n[s]);return i>=4?"4":"2"}function lx(e,t){let n=e.match(/^(\s+)(.*)/s);if(!n)return e;let r=n[1],o=n[2];if(r.length===0)return e;let i=r.includes(" ")?r.split(" ").length-1:Math.max(1,Math.round(r.length/2)),s=Math.min(Math.max(i,0),20);return t==="tab"?" ".repeat(s)+o:t==="4"?" ".repeat(s)+o:" ".repeat(s)+o}function ux(e,t){return e.split(`
3
+ `).map(r=>lx(r,t)).join(`
4
+ `)}function Jo(e){let{ast:t,source:n}=e;try{let r=cx(n),i=ax(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=ux(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Au(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t|=0}return`0x${Math.abs(t).toString(16)}`}function vr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Au(e),afterSourceHash:Au(t),inverse:n.inverse}}}function me(e,t,n){let r=Jo({ast:e,source:t});return r.ok?vr(t,r.source,n):r}function we(e,t){let n=xr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Xo(e,t){return Jo({ast:e,source:t})}function Ex(e,t,n){let r=se(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function zo(e,t,n){let r=Ex(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:J(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Qt(e){return typeof e=="string"?zs(e):typeof e=="number"?xx(e):typeof e=="boolean"?fx(e):e===null?yx():Array.isArray(e)?dx(e.map(t=>Qt(t))):bx(Object.entries(e).map(([t,n])=>{let r=Sx(Ws(t),Qt(n));return t==="__proto__"&&(r.computed=!0),r}))}function vx(e){return typeof e=="string"?zs(e):gx(Qt(e))}function kr(e,t){return mx(hx(e),vx(t))}function Wo(e,t){try{let r=Tu.parse(`const __VD_NODE__ = (${t});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return r?.type!=="VariableDeclaration"||r.declarations[0]?.type!=="VariableDeclarator"||!r.declarations[0].init||r.declarations[0].init.type!=="JSXElement"&&r.declarations[0].init.type!=="JSXFragment"?{ok:!1,result:J(e,"unsupported-syntax","Provided JSX source does not resolve to a JSX node","jsx-node")}:{ok:!0,node:r.declarations[0].init}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Ws(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?px(e):zs(e)}function Ho(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=we(t,"jsx-node");if(!i.ok)return i.result;let s=se(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=kx(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":c.path.node.value=Ix(c.path.node.value,o);break;case"string-literal":c.path.node.value=o;break;case"template-literal":{let l=c.quasiIndex;c.path.node.quasis[l].value.raw=o,c.path.node.quasis[l].value.cooked=o;break}}return me(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function kx(e){let t=[],n=e.isJSXElement()||e.isJSXFragment()?e.get("children"):[];for(let r of n){if(r.isJSXText()){r.node.value.trim().length>0&&t.push({kind:"jsx-text",path:r});continue}if(r.isJSXExpressionContainer()){let o=Cx(r.get("expression"));o.length>0&&t.push(...o)}}return t}function Ix(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Cx(e){if(e.isStringLiteral())return[{kind:"string-literal",path:e}];if(e.isTemplateLiteral()){let t=[],n=e.node.quasis;for(let r=0;r<n.length;r++)n[r].value.raw.trim().length>0&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as Hs}from"@babel/types";function Xn(e){let{source:t,locator:n}=e,r=we(t,"jsx-node");if(!r.ok)return r.result;let o=se(r.ast,n);return o.ok?(Rx(o.match.path),me(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Rx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Hs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Hs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Hs());return}e.remove()}import{cloneNode as Nx}from"@babel/types";function Go(e){let t=we(e.source,"jsx-node");if(!t.ok)return t.result;let n=se(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Wo(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(Nx(r.node,!0)),me(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Bx}from"@babel/types";import Gs from"@babel/traverse";import*as Q from"@babel/types";function Ir(e,t,n){return`${e}::${t}::${n}`}var $={NODE_NOT_FOUND:"NODE_NOT_FOUND",HOME_PAGE_LOCKED:"HOME_PAGE_LOCKED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",CAPABILITY_REJECTED:"CAPABILITY_REJECTED",CONSTRAINT_VIOLATED:"CONSTRAINT_VIOLATED",INVALID_PARAMS:"INVALID_PARAMS",PLAN_FAILED:"PLAN_FAILED",TRANSACTION_PREFLIGHT_FAILED:"TRANSACTION_PREFLIGHT_FAILED",ROUTE_REBUILD_FAILED:"ROUTE_REBUILD_FAILED",HISTORY_COMMIT_FAILED:"HISTORY_COMMIT_FAILED",MATERIALIZATION_CONFLICT:"MATERIALIZATION_CONFLICT",MATERIALIZATION_REJECTED:"MATERIALIZATION_REJECTED",MUTATION_ASSERTION_REQUIRED:"MUTATION_ASSERTION_REQUIRED",MUTATION_ASSERTION_INVALID:"MUTATION_ASSERTION_INVALID",VERSION_STALE:"VERSION_STALE",AST_PARSE_ERROR:"AST_PARSE_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",LOCATOR_FAILED:"LOCATOR_FAILED",INVALID_TARGET:"INVALID_TARGET",WRITE_IO_ERROR:"WRITE_IO_ERROR",CONCURRENT_MODIFIED:"CONCURRENT_MODIFIED",ROLLBACK_FAILED:"ROLLBACK_FAILED",RECOVERY_REQUIRED:"RECOVERY_REQUIRED",RECOVERY_PERSIST_FAILED:"RECOVERY_PERSIST_FAILED",MUTATION_SESSION_REQUIRED:"MUTATION_SESSION_REQUIRED",LEASE_ASSERTION_INVALID:"LEASE_ASSERTION_INVALID",LEASE_ASSERTION_EXPIRED:"LEASE_ASSERTION_EXPIRED",LEASE_ASSERTION_SCOPE_MISMATCH:"LEASE_ASSERTION_SCOPE_MISMATCH",CROSS_PAGE_MOVE_UNSUPPORTED:"CROSS_PAGE_MOVE_UNSUPPORTED",INTERNAL_ERROR:"INTERNAL_ERROR"};var wx=typeof Gs=="function"?Gs:Gs.default;function mt(e,t,n,r){if(!e.ok)return e;let o=pt(n,t);if(!o)return e;let i=Px(t,o,r);return i?{...e,selectionRef:i}:e}function Px(e,t,n){let r=Ax(e,t);if(!r)return;let o=n.sourceLocator?Fu(n.sourceLocator):void 0,i=n.targetParentLocator?Fu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??Fx(r)??i?.component??o?.component;if(!(!s||!a))return{key:Ir(s,a,_x(r))}}function Fu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Ax(e,t){let n=Bu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Bu(e,t){let n=null;return wx(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function pt(e,t){if(!e)return null;if(Q.isJSXElement(e))return Lx(t,e)?_u(e.children,t):e;if(Q.isJSXFragment(e))return _u(e.children,t);if(Q.isJSXExpressionContainer(e)||Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSTypeAssertion(e)||Q.isTSNonNullExpression(e))return pt(e.expression,t);if(Q.isLogicalExpression(e))return pt(e.right,t);if(Q.isConditionalExpression(e))return pt(e.consequent,t)??pt(e.alternate,t);if(Q.isCallExpression(e)||Q.isOptionalCallExpression(e))return $u(e)?Tx(e.arguments[0],t):null;if(Q.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=pt(n,t);if(r)return r}return null}function _u(e,t){for(let n of e){let r=pt(n,t);if(r)return r}return null}function Tx(e,t){return!e||!Q.isArrowFunctionExpression(e)&&!Q.isFunctionExpression(e)?null:Q.isBlockStatement(e.body)?Cr(e.body.body,t):pt(e.body,t)}function Cr(e,t){for(let n of e){if(Q.isReturnStatement(n)){let r=pt(n.argument,t);if(r)return r;continue}if(Q.isBlockStatement(n)){let r=Cr(n.body,t);if(r)return r;continue}if(Q.isIfStatement(n)){let r=Ou(n.consequent,t);if(r)return r;let o=n.alternate?Ou(n.alternate,t):null;if(o)return o;continue}if(Q.isSwitchStatement(n))for(let r of n.cases){let o=Cr(r.consequent,t);if(o)return o}}return null}function Ou(e,t){return Q.isBlockStatement(e)?Cr(e.body,t):Cr([e],t)}function Fx(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isExportDefaultDeclaration()){let n=t.node.declaration;if(Q.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Q.isIdentifier(t.node.id)){let n=t.get("init");if(!Array.isArray(n)&&(n.isArrowFunctionExpression()||n.isFunctionExpression()))return t.node.id.name}t=t.parentPath}return null}var Mu=new WeakMap,Du=new WeakMap,Ys=new WeakMap;function _x(e){let t=Mu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Ox(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Mu.set(e.node,o),o}function Ox(e){let t=ju(e.node.openingElement.name);return!t||Ae(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Lu(e,t)}`:`${t}#${Lu(e,t)}`}function Lu(e,t){let n=Mx(e);if(!n)return 0;let r=Ys.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Ys.get(n.node);o||(o=new Map,Ys.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of vn(n))if(ju(a.node.openingElement.name)===t){if(i.set(a.node,s),a.node===e.node)return s;s+=1}return i.get(e.node)??0}function Mx(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ae(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function vn(e){let t=Du.get(e.node);if(t)return t;let n=[],r=e.get("children");for(let o of r)if(!Array.isArray(o)){if(o.isJSXElement()){if(Ae(o)){n.push(...vn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...vn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ft(o.get("expression")))}return Du.set(e.node,n),n}function Ft(e){if(e.isJSXElement())return Ae(e)?vn(e):[e];if(e.isJSXFragment())return vn(e);if(e.isParenthesizedExpression())return Ft(e.get("expression"));if(e.isLogicalExpression())return Ft(e.get("right"));if(e.isConditionalExpression())return[...Ft(e.get("consequent")),...Ft(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ft(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&$u(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Dx(n):[]}return[]}function Dx(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ae(t)?vn(t):[t];if(t.isJSXFragment())return vn(t);if(t.isParenthesizedExpression())return Ft(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Ft(t);if(!t.isBlockStatement())return[];let n=[];for(let r of t.get("body")){if(r.isVariableDeclaration())for(let i of r.get("declarations")){let s=i.get("init");(s.isJSXElement()||s.isJSXFragment())&&n.push(...Ft(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Ft(o)),n}return n}function $u(e){let t=e.callee;return(Q.isMemberExpression(t)||Q.isOptionalMemberExpression(t))&&Q.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Lx(e,t){let n=Bu(e,t);return n?Ae(n):!1}function ju(e){return Q.isJSXIdentifier(e)?e.name:Q.isJSXMemberExpression(e)?Vu(e):Q.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Vu(e){return`${Q.isJSXIdentifier(e.object)?e.object.name:Vu(e.object)}.${e.property.name}`}function qt(e,t){if(t.parentPath===e&&t.listKey==="children"&&Zs(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Zs(n))return null;let r=n;for(;r&&r!==e;){if(!Zs(r)||!Ae(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Zs(e){return e.isJSXElement()||e.isJSXFragment()}function zn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-child target must be a JSXElement or JSXFragment","jsx-node");let l=c.match.path;if(c.match.path.isJSXElement()){let I=c.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=Wo(t,r.jsx);if(!d.ok)return d.result;let f=Bx(d.node,!0),m=l.node.children,u={...s,targetParentLocator:n},g=I=>s?mt(I,a.ast,f,u):I;if(o==="append")return m.push(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=se(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let b=qt(c.match.path,h.match.path);if(!b)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=b;let E=l.node.children,v=E.findIndex(I=>I===h.match.path.node);return v===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,f),g(me(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Ku from"@babel/parser";import{cloneNode as $x}from"@babel/types";function Yo(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=jx(t,r);if(!c.ok)return c.result;let l=se(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let E=l.match.path.node;if(!E.closingElement||E.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let d=l.match.path,f=null;if(i){let E=se(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let v=qt(l.match.path,E.match.path);if(!v)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=v,f=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=$x(c.node,!0),u=d.node.children,g={...s,targetParentLocator:n},h=E=>s?mt(E,a.ast,m,g):E;if(o==="append")return u.push(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return u.unshift(m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let b=u.findIndex(E=>E===f);return b===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(u.splice(o==="before"?b:b+1,0,m),h(me(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function jx(e,t){try{let r=Ku.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as Vx,nullLiteral as Qs}from"@babel/types";import*as en from"@babel/types";import*as Uu from"@babel/types";function Rr(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Uu.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Wn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=we(t,"jsx-node");if(!a.ok)return a.result;let c=se(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=se(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-node target parent must be a JSXElement or JSXFragment","jsx-node");let d=l.match.path;if(l.match.path.isJSXElement()){let I=l.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let f=null;if(i){let I=se(a.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=I.match.path.isJSXElement()?Rr(I.match.path,l.match.path):I.match.path,P=qt(l.match.path,R);if(!P)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");d=P,f=R}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=f&&typeof f.key=="number"?f.key:-1;if(f&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let u=c.match.path.isJSXElement()?Rr(c.match.path,l.match.path):c.match.path,g=Vx(u.node,!0);if(!en.isJSXElement(g)&&!en.isJSXExpressionContainer(g)&&!en.isJSXFragment(g)&&!en.isJSXText(g))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=u.parentPath?.node===d.node&&typeof u.key=="number"?u.key:-1;if(f&&u.parentPath?.node===f.parentPath?.node&&u.key===f.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Kx(u);let b=d.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return b.push(g),mt(Xo(a.ast,t),a.ast,g,E);if(o==="prepend")return b.unshift(g),mt(Xo(a.ast,t),a.ast,g,E);let v=m-(h!==-1&&h<m?1:0);return b.splice(o==="before"?v:v+1,0,g),mt(Xo(a.ast,t),a.ast,g,E)}function Kx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Qs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Qs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Qs());return}e.remove()}import*as Ju from"@babel/parser";import{cloneNode as Ux,nullLiteral as qs}from"@babel/types";function Zo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=we(t,"jsx-node");if(!c.ok)return c.result;let l=Jx(t,s);if(!l.ok)return l.result;let d=se(c.ast,n);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};let f=se(c.ast,r);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};if(!f.match.path.isJSXElement()&&!f.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(f.match.path.isJSXElement()){let I=f.match.path.node;if(!I.closingElement||I.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=f.match.path,u=null;if(i){let I=se(c.ast,i);if(!I.ok)return{ok:!1,source:t,diagnostic:I.diagnostic};let R=qt(f.match.path,I.match.path);if(!R)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=R,u=I.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!d.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let g=m.node,h=Ux(l.node,!0);Xx(d.match.path);let b={...a,sourceLocator:n,targetParentLocator:r},E=g.children;if(o==="append")return E.push(h),mt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);if(o==="prepend")return E.unshift(h),mt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b);let v=E.findIndex(I=>I===u);return v===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?v:v+1,0,h),mt(me(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,b))}function Jx(e,t){try{let r=Ju.parse(`const __VD_EXPR__ = <>{${t}}</>;`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],o=r?.type==="VariableDeclaration"?r.declarations[0]?.init:null,i=o?.type==="JSXFragment"?o.children[0]:void 0;return i?.type!=="JSXExpressionContainer"?{ok:!1,result:J(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:J(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Xx(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(qs());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(qs());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(qs());return}e.remove()}import{SiteEditSetPropsParamsSchema as zx,classifySiteEditPropertyName as Wx}from"@vcp-dev/contracts";import*as Hn from"@babel/types";function Qo(e){let t=zx.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return J(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=we(e.source,"jsx-node");if(!n.ok)return n.result;let r=zo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Wx(a.name);if(c.owner!=="generic")return J(e.source,"unsupported-syntax",c.diagnostic?.message??`Property '${a.name}' is not owned by the generic JSX primitive`,"jsx-node")}let o=r.match.path.node.openingElement,i=o.attributes.filter(Hn.isJSXAttribute),s=new Map;for(let a of i){let c=Hx(a);if(!c)continue;let l=s.get(c)??[];l.push(a),s.set(c,l)}for(let a of t.data.changes)if((s.get(a.name)??[]).length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${a.name}' has multiple sources`,"jsx-node");for(let a of t.data.changes){let c=s.get(a.name)?.[0];if(a.operation==="remove"){c&&(o.attributes=o.attributes.filter(d=>d!==c));continue}let l=kr(a.name,a.value).value;c?c.value=l:o.attributes.push(kr(a.name,a.value))}return me(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Hx(e){return Hn.isJSXIdentifier(e.name)?e.name.name:Hn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import*as je from"@babel/types";import{classifySiteEditPropertyName as Xu}from"@vcp-dev/contracts";function qo(e){let t=Xu(e.name),n=Xu(e.property);if(t.owner!=="generic"||n.owner!=="generic")return J(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!zu(e.object))return J(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return J(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=we(e.source,"jsx-node");if(!r.ok)return r.result;let o=zo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>je.isJSXAttribute(l)&&Yx(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Gx(e.object,e.property),c=s[0];if(c)c.value=je.jsxExpressionContainer(a);else{let l=kr(e.name,"");l.value=je.jsxExpressionContainer(a),i.attributes.push(l)}return me(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Gx(e,t){return zu(t)?je.memberExpression(je.identifier(e),je.identifier(t)):je.memberExpression(je.identifier(e),je.stringLiteral(t),!0)}function zu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Yx(e){return je.isJSXIdentifier(e.name)?e.name.name:je.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as Qx,identifier as Nr,importDeclaration as qx,importDefaultSpecifier as eb,importNamespaceSpecifier as tb,importSpecifier as nb,isImportDefaultSpecifier as Wu,isImportNamespaceSpecifier as Hu,isImportSpecifier as Gu,stringLiteral as rb}from"@babel/types";function Gn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(b=>!fb(b));if(o!==-1){let b=r[o],E=b&&typeof b=="object"&&"kind"in b?b.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=lb(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=we(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(b=>b.type==="ImportDeclaration"&&b.source.value===n),d=new Set(l.flatMap(b=>b.specifiers.flatMap(E=>{let v=pb(b,E);return v?[v]:[]}))),f=i.imports.filter(b=>!d.has(td(b)));if(f.length===0)return vr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=ub(c.body),u=f.find(b=>m.has(ea(b)));if(u)return J(t,"unsupported-syntax",`Import local binding already exists: ${ea(u)}`);let g=cb(f);if(g.reduce((b,E)=>b+E.length,0)!==f.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let b of g){if(!qu(Zu(b)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(v=>ob(v,b));if(E)ib(E,b);else{let v=qx(Yu(b),rb(n));db(c.body,v),l.push(v)}}return me(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function ob(e,t){return e.importKind==="type"?!1:qu(ab(sb(e),Zu(t)))}function ib(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ta(o)));for(let o of Yu(t)){let i=ta(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return ed(e.specifiers),{changed:n}}function Yu(e){let t=e.map(n=>{switch(n.kind){case"named":return nb(n.local?Nr(n.local):Nr(n.imported),Nr(n.imported));case"default":return eb(Nr(n.local));case"namespace":return tb(Nr(n.local));default:return n}});return ed(t),t}function Zu(e){let t=Qu();for(let n of e)n.kind==="default"?t.defaultLocals.add(n.local):n.kind==="named"?t.hasNamed=!0:t.namespaceLocals.add(n.local);return t}function sb(e){let t=Qu();for(let n of e.specifiers)Wu(n)?t.defaultLocals.add(n.local.name):Hu(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Qu(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function ab(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function qu(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function ed(e){let t=[...e.filter(n=>Wu(n)),...e.filter(n=>Hu(n)),...e.filter(n=>Gu(n))];e.splice(0,e.length,...t)}function cb(e){let t=e.filter(i=>i.kind==="default"),n=e.filter(i=>i.kind==="namespace"),r=e.filter(i=>i.kind==="named"),o=[];if(n.length>0){let i=Math.max(t.length,n.length);for(let s=0;s<i;s+=1){let a=[],c=t[s],l=n[s];c&&a.push(c),l&&a.push(l),o.push(a)}return r.length>0&&o.push(r),o}if(t.length>0){o.push([t[0],...r]);for(let i of t.slice(1))o.push([i])}else r.length>0&&o.push(r);return o}function lb(e){let t=new Map,n=new Map;for(let r of e){let o=td(r);if(t.has(o))continue;let i=ea(r),s=n.get(i);if(s&&s!==o)return{ok:!1,message:`Import local binding is requested more than once: ${i}`};t.set(o,r),n.set(i,o)}return{ok:!0,imports:[...t.values()]}}function ub(e){let t=new Set;for(let n of e){if(n.type==="ImportDeclaration"){for(let o of n.specifiers)t.add(o.local.name);continue}let r=(n.type==="ExportNamedDeclaration"||n.type==="ExportDefaultDeclaration")&&n.declaration?n.declaration:n;if(r.type==="VariableDeclaration")for(let o of r.declarations)for(let i of Object.keys(Qx(o.id)))t.add(i);else(r.type==="FunctionDeclaration"||r.type==="ClassDeclaration"||r.type==="TSEnumDeclaration")&&r.id&&t.add(r.id.name)}return t}function db(e,t){let n=[...e].reverse().findIndex(r=>r.type==="ImportDeclaration");if(n===-1)e.unshift(t);else{let r=e.length-n;e.splice(r,0,t)}}function fb(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string"&&(e.local===void 0||typeof e.local=="string"):t==="default"||t==="namespace"?typeof e.local=="string":!1}function td(e){switch(e.kind){case"default":return`default:${e.local}`;case"namespace":return`namespace:${e.local}`;case"named":return`named:${e.imported}:${e.local??e.imported}`;default:return e}}function ea(e){return e.kind==="named"?e.local??e.imported:e.local}function pb(e,t){return e.importKind==="type"||Gu(t)&&t.importKind==="type"?null:ta(t)}function ta(e){if(e.type==="ImportDefaultSpecifier")return`default:${e.local.name}`;if(e.type==="ImportNamespaceSpecifier")return`namespace:${e.local.name}`;let t=e.imported.type==="Identifier"?e.imported.name:e.imported.value,n=e.local.name;return`named:${t}:${n}`}function Yn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(d=>!gb(d));if(o!==-1){let d=r[o],f=d&&typeof d=="object"&&"kind"in d?d.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(f)}`)}let i=we(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(d=>d.type==="ImportDeclaration"&&d.source.value===n);if(c===-1)return vr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(d=>!r.some(f=>mb(d,f))),l.specifiers.length===0&&a.body.splice(c,1),me(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function mb(e,t){return t.kind==="default"?e.type==="ImportDefaultSpecifier":t.kind==="namespace"?e.type==="ImportNamespaceSpecifier":e.type!=="ImportSpecifier"?!1:(e.imported.type==="Identifier"?e.imported.name:e.imported.value)===t.imported}function gb(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e.kind;return t==="named"?typeof e.imported=="string":t==="default"||t==="namespace"}function wr(e){let{source:t,locator:n,next:r}=e,o=ri(t,n);return o.ok?(o.path.replaceWith(Qt(r)),me(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ei(e){let{source:t,locator:n,index:r,value:o}=e,i=ri(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Qt(o)),me(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ti(e){let{source:t,locator:n,index:r}=e,o=ri(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?J(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?J(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),me(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):J(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function ni(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ri(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return J(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return J(t,"unsupported-syntax","Spread array elements are not supported","value");if(r<0||r>=i.path.node.elements.length||o<0||o>i.path.node.elements.length)return J(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),me(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ri(e,t){let n=we(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=se(n.ast,t);return r.ok?{ok:!0,ast:n.ast,path:r.match.path}:{ok:!1,result:{ok:!1,source:e,diagnostic:r.diagnostic}}}import*as Ue from"@babel/types";function oi(e){let t=we(e.source,"value");if(!t.ok)return t.result;let n=se(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return J(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Ue.isSpreadElement(a)||Ue.isObjectProperty(a)&&a.computed))return J(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ue.isObjectProperty(a)&&hb(a.key)===e.name);if(o.length>1)return J(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ue.unaryExpression("void",Ue.numericLiteral(0)):Qt(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ue.objectProperty(Ws(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return me(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function hb(e){return Ue.isIdentifier(e)?e.name:Ue.isStringLiteral(e)?e.value:Ue.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as yb,isSiteEditRuntimeVoidElementTag as xb}from"@vcp-dev/contracts/site-edit-runtime-capability";function Zn(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function bb(e,t,n){let r=Zn(n),o=t.nodes.get(e),i=n.elements.get(e);if(!o||!i)return{composition:r,key:e,canUpdateText:!1,canInsertChild:!1,canMove:!1,canRemove:!1,constraints:[{kind:"opaque-region",message:"Node not found in graph"}]};let s=o.constraints.map(R=>({kind:R.kind,message:R.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",d=i.tag.toLowerCase(),f=i.tag!==d,m=!f&&xb(d),u=f||yb(d),g=f&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(R=>R.editable);m&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!u&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let b=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&u&&(!a||g);return{composition:r,key:e,canUpdateText:b,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function nd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,bb(r,e,t));return n}function na(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Sb(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:od(r),version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:rd(e.route.source,o),valueRaw:s?rd(e.route.source,s):null,attrRange:od(o),diagnostics:[]}}function id(e){let{source:t,oldAttrRange:n,openingElementRange:r,newAttrRaw:o}=e;if(n){let a=n.start>0&&/\s/.test(t[n.start-1]??"")?n.start-1:n.start,c=o?`${a<n.start?" ":""}${o}`:"";return t.slice(0,a)+c+t.slice(n.end)}if(!o)return t;let i=r.end,s=t.slice(Math.max(0,i-2),i)==="/>"?i-2:i-1;return t.slice(0,s)+` ${o}`+t.slice(s)}function Sb(e,t){let n=Pt({source:e,profile:hn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=se(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Eb(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function sd(e){let t=Pt({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function rd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function od(e){if(e.start==null||e.end==null)throw new Error("AST node does not include offsets.");return{start:e.start,end:e.end}}function Eb(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function ad(){let e=new Set;return{emit(t){for(let n of Array.from(e))try{n(t)}catch{}},subscribe(t){return e.add(t),()=>{e.delete(t)}}}}import{randomUUID as vb}from"node:crypto";import ii from"node:fs/promises";import ra from"node:path";import{setTimeout as kb}from"node:timers/promises";var Ib={async mkdir(e,t){await ii.mkdir(e,t)},async writeFile(e,t,n){await ii.writeFile(e,t,n)},async rename(e,t){await ii.rename(e,t)},async rm(e,t){await ii.rm(e,t)}},Cb=new Set(["EACCES","EBUSY","EPERM"]),Rb=[10,20,40,80,160];async function Nb(e,t,n){for(let r of Rb)try{await e.rename(t,n);return}catch(o){if(!wb(o))throw o;await kb(r)}await e.rename(t,n)}function wb(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Cb.has(e.code)}async function si(e,t,n=Ib){let r=ra.dirname(e),o=ra.basename(e),i=ra.join(r,`.${o}.${process.pid}.${vb()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Nb(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import oa from"@babel/traverse";import*as S from"@babel/types";import*as ue from"@babel/types";function _t(e,t={}){if(ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSNonNullExpression(e)||ue.isTypeCastExpression(e)||ue.isParenthesizedExpression(e))return _t(e.expression,t);if(ue.isStringLiteral(e))return{status:"resolved",value:e.value};if(ue.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(ue.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(ue.isNullLiteral(e))return{status:"resolved",value:null};if(ue.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?{status:"resolved",value:e.quasis[0].value.cooked??e.quasis[0].value.raw}:{status:"unresolved"};if(ue.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(ue.isUnaryExpression(e)&&e.operator==="void"&&ue.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(ue.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||ue.isSpreadElement(r))return{status:"unresolved"};let o=_t(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(ue.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!ue.isObjectProperty(r)||r.computed||!ue.isExpression(r.value))return{status:"unresolved"};let o=Pb(r.key);if(o===null)return{status:"unresolved"};let i=_t(r.value,t);if(i.status!=="resolved")return{status:"unresolved"};Object.defineProperty(n,o,{configurable:!0,enumerable:!0,value:i.value,writable:!0})}return{status:"resolved",value:n}}return ue.isMemberExpression(e)||ue.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Pb(e){return ue.isIdentifier(e)?e.name:ue.isStringLiteral(e)?e.value:ue.isNumericLiteral(e)?String(e.value):null}var Ab=typeof oa=="function"?oa:oa.default;function ze(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function Tb(e){return/^[A-Z]/.test(e)}function la(e){let t=e.openingElement;return S.isJSXIdentifier(t.name)?t.name.name==="Fragment":S.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function qn(e){return S.isJSXFragment(e)}function ld(e){return S.isJSXIdentifier(e.name)?e.name.name:S.isJSXMemberExpression(e.name)?ud(e.name):S.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function ud(e){return S.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:S.isJSXMemberExpression(e.object)?`${ud(e.object)}.${e.property.name}`:e.property.name}function Fb(e){return e.split(".")[0]??e}function _b(e){let t=e;for(;t;){let n=t.node;if(S.isFunctionDeclaration(n)&&n.id||S.isVariableDeclarator(n)&&S.isIdentifier(n.id))return n.id.name;if(S.isExportDefaultDeclaration(n)){let r=n.declaration;if(S.isFunctionDeclaration(r)&&r.id)return r.id.name;if(S.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function Ob(){let e=new Map;return{getOrdinal(t,n){let r=t??"__root__";e.has(r)||e.set(r,new Map);let o=e.get(r),i=o.get(n)??0;return o.set(n,i+1),i}}}function Mb(e){let t=new Map;for(let n of e.program.body){if(!S.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(S.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(S.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(S.isImportSpecifier(o)){let i=S.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Xt(e,t=[]){if(S.isIdentifier(e))return t.push(e.name),t;if(S.isObjectPattern(e)){for(let n of e.properties)S.isObjectProperty(n)?Xt(n.value,t):S.isRestElement(n)&&Xt(n.argument,t);return t}if(S.isArrayPattern(e)){for(let n of e.elements)n&&(S.isRestElement(n)?Xt(n.argument,t):Xt(n,t));return t}return S.isAssignmentPattern(e)?(Xt(e.left,t),t):(S.isRestElement(e)&&Xt(e.argument,t),t)}function Et(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Pr(e,t){for(let n=t.length-1;n>=0;n-=1){let r=t[n].get(e);if(r)return r.resolved?{kind:"resolved",value:r.value}:{kind:"unresolved"}}return{kind:"unresolved"}}function Db(e,t,n){e.set(t,{resolved:!0,value:n})}function ua(e,t){e.set(t,{resolved:!1})}function dd(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n==null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return{kind:"known-empty"};n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return{kind:"known-empty"};n=n[r.index]}return{kind:"resolved",value:n}}function Be(e,t,n){if(S.isTSAsExpression(e)||S.isTSSatisfiesExpression(e)||S.isTSNonNullExpression(e)||S.isTypeCastExpression(e)||S.isParenthesizedExpression(e))return Be(e.expression,t,n);if(S.isLogicalExpression(e))return ai([Be(e.left,t,n),Be(e.right,t,n)]);if(S.isBinaryExpression(e))return ai([S.isExpression(e.left)?Be(e.left,t,n):null,S.isExpression(e.right)?Be(e.right,t,n):null]);if(S.isConditionalExpression(e))return ai([Be(e.consequent,t,n),Be(e.alternate,t,n)]);if(S.isTemplateLiteral(e))return ai(e.expressions.filter(S.isExpression).map(i=>Be(i,t,n)));if(S.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!S.isMemberExpression(e)&&!S.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;S.isMemberExpression(o)||S.isOptionalMemberExpression(o);){if(o.computed)if(S.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(S.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&S.isExpression(o.property)){let i=tn(o.property,n);if(typeof i=="string")r.unshift({kind:"property",name:i});else if(Number.isInteger(i))r.unshift({kind:"index",index:i});else return null}else return null;else{if(!S.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return S.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Et(e,t),base:o.name,path:r}:null}function ai(e){let t=e.filter(r=>r!==null);if(t.length===0)return null;let n=t[0];return t.some(r=>r.base!==n.base||JSON.stringify(r.path)!==JSON.stringify(n.path))?null:{...n}}function tn(e,t){if(S.isStringLiteral(e)||S.isNumericLiteral(e)||S.isBooleanLiteral(e))return e.value;if(S.isNullLiteral(e))return null;if(S.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(S.isIdentifier(e)){let n=Pr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return;let o=tn(r,t);if(o===void 0)return;n.push(o)}return n}if(S.isObjectExpression(e)){let n={};for(let r of e.properties){if(!S.isObjectProperty(r)||r.computed||!S.isExpression(r.value))return;let o=null;if(S.isIdentifier(r.key)?o=r.key.name:S.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!S.isIdentifier(r.value))return;let s=Pr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=tn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(S.isMemberExpression(e)){let n=Be(e,"",t);if(!n)return;let r=Pr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=dd(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(S.isCallExpression(e))return pd(e,t)??void 0}function fd(e,t,n){let r=Be(e,n,t);if(!r)return S.isMemberExpression(e)||S.isBinaryExpression(e)||S.isLogicalExpression(e)||S.isConditionalExpression(e)||S.isCallExpression(e)?{value:Et(e,n),source:null}:null;let o=Pr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?dd(o.value,r.path):o;return i.kind==="resolved"&&(typeof i.value=="string"||typeof i.value=="number")?{value:String(i.value),source:r}:i.kind==="resolved"&&(typeof i.value=="boolean"||i.value===null)||i.kind==="known-empty"?null:{value:r.expression,source:r}}function ia(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Ob(),parentStack:[],valueScopes:i,importMap:o}}function aa(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Xt(o.id))ua(n,s);if(!S.isIdentifier(o.id)||!o.init||!S.isExpression(o.init))continue;let i=tn(o.init,t);i!==void 0&&Db(n,o.id.name,i)}}function Lb(e){let t=[];for(let n of e){if(S.isVariableDeclaration(n)){t.push(n);continue}S.isExportNamedDeclaration(n)&&n.declaration&&S.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function Bb(e,t,n){let r=[],o=0;for(let i of e)if(S.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:ze(i),editable:!0,source:null})}else if(S.isJSXExpressionContainer(i)&&S.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:ze(i),editable:!0,source:null});else if(S.isJSXExpressionContainer(i)&&S.isTemplateLiteral(i.expression)){let s=i.expression;s.expressions.length===0&&s.quasis.length===1?r.push({index:o++,value:s.quasis[0].value.cooked??s.quasis[0].value.raw,sourceRange:ze(i),editable:!0,source:null}):r.push({index:o++,value:Et(s,n),sourceRange:ze(i),editable:!0,source:Be(s,n,t)})}else if(S.isJSXExpressionContainer(i)&&S.isExpression(i.expression)){let s=fd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:ze(i),editable:!0,source:s.source})}return r}function $b(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!S.isJSXAttribute(i))continue;let s=Vb(i.name);if(!s)continue;let a=Et(i,n);if(S.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:ze(i),source:null,syntaxKind:"literal",raw:a,order:o,resolution:{status:"resolved",value:i.value.value}});continue}if(i.value===null){r.push({name:s,value:"true",sourceRange:ze(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(S.isJSXExpressionContainer(i.value)&&S.isExpression(i.value.expression)){let c=tn(i.value.expression,t);if(s==="className"){let u=typeof c=="string"?c:c===void 0?pd(i.value.expression,t):null;if(u){r.push({name:s,value:u,sourceRange:ze(i),source:null,resolvedValue:u,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:u}});continue}}let l=fd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:Hb(c),sourceRange:ze(i),source:Be(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let d=Kb(i.value.expression,t),f=Be(i.value.expression,n,t),m=l?.value??Et(i.value.expression,n);r.push({name:s,value:d.status==="undefined"?"undefined":m,sourceRange:ze(i),source:l?.source??f,syntaxKind:"expression",raw:a,order:o,resolution:d})}}return r}function jb(e,t,n){return e.attributes.flatMap((r,o)=>!S.isJSXSpreadAttribute(r)||!S.isExpression(r.argument)?[]:[{raw:Et(r.argument,n),sourceRange:ze(r),order:o,source:Be(r.argument,n,t)}])}function Vb(e){return S.isJSXIdentifier(e)?e.name:S.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Kb(e,t){return _t(e,{resolveIdentifier(n){let r=Pr(n,t.valueScopes);return r.kind==="resolved"?{status:"resolved",value:r.value}:n==="undefined"&&!t.valueScopes.some(o=>o.has(n))?{status:"undefined"}:{status:"unresolved"}},resolveMember(n){let r=tn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function pd(e,t){let n=Qn(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Qn(e,t){if(S.isStringLiteral(e))return[e.value];if(S.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(S.isNullLiteral(e))return[];if(S.isBooleanLiteral(e))return e.value?null:[];if(S.isIdentifier(e)||S.isMemberExpression(e)){if(S.isIdentifier(e)&&e.name==="undefined")return[];let n=tn(e,t);return typeof n=="string"?[n]:null}if(S.isConditionalExpression(e)){let n=Qn(e.consequent,t),r=Qn(e.alternate,t);return!n||!r?null:[...n,...r]}if(S.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=tn(e.left,t);return n===!1||n===null?[]:Qn(e.right,t)}if(S.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||S.isSpreadElement(r))return null;let o=Qn(r,t);if(!o)return null;n.push(...o)}return n}if(S.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!S.isObjectProperty(r))return null;let o=Jb(r.key);if(!o)return null;n.push(o)}return n}if(S.isCallExpression(e)){let n=Ub(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!S.isExpression(o))return null;let i=Qn(o,t);if(!i)return null;r.push(...i)}return r}return null}function Ub(e){return S.isIdentifier(e)?e.name:S.isMemberExpression(e)&&S.isIdentifier(e.property)?e.property.name:null}function Jb(e){return S.isIdentifier(e)?e.name:S.isStringLiteral(e)?e.value:null}function Xb(e,t){let n=e.attributes.find(r=>S.isJSXAttribute(r)&&S.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!S.isJSXAttribute(n)||!S.isJSXExpressionContainer(n.value)?null:n.value.expression}function zb(e,t){for(let n of t){let r=Xb(e,n);if(r)return r}return null}function Wb(e){return S.isJSXIdentifier(e.name)?e.name.name:null}function Hb(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function Gb(e){if(!S.isCallExpression(e)&&!S.isOptionalCallExpression(e))return null;let t=e.callee;return!S.isMemberExpression(t)&&!S.isOptionalMemberExpression(t)||!S.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!S.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function sa(e){return S.isArrowFunctionExpression(e)||S.isFunctionExpression(e)}function Yb(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function Zb(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function cd(e,t,n,r){if(!e||!S.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Et(e,n),collectionSource:Be(e,n,r)};if(t){let i=t.params[0],s=t.params[1];S.isIdentifier(i)&&(o.itemParamName=i.name),S.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function zt(e,t,n){if(!e)return[];if(S.isJSXElement(e)){if(la(e))return fi(e.children,t,n);let r=ui(e,t,n);return r?[r]:[]}return qn(e)?di(e,t,n):S.isParenthesizedExpression(e)?zt(e.expression,t,n):S.isExpression(e)?pi(e,t,n):[]}function ci(e,t,n){let r=new Map;for(let o of e.params)for(let i of Xt(o))ua(r,i);t.valueScopes.push(r);try{if(!S.isBlockStatement(e.body))return zt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return md(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function md(e,t,n){let r=[];for(let o of e){if(S.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){aa([o],t,i);for(let s of o.declarations)S.isIdentifier(s.id)&&(S.isJSXElement(s.init)||S.isJSXFragment(s.init))&&r.push(...zt(s.init,t,n))}continue}r.push(...ca(o,t,n))}return r}function ca(e,t,n){if(S.isReturnStatement(e))return e.argument?zt(e.argument,t,n):[];if(S.isBlockStatement(e))return kn(e.body,t,n);if(S.isIfStatement(e)){let r=S.isBlockStatement(e.consequent)?kn(e.consequent.body,t,n):ca(e.consequent,t,n),o=e.alternate?S.isBlockStatement(e.alternate)?kn(e.alternate.body,t,n):ca(e.alternate,t,n):[];return[...r,...o]}if(S.isSwitchStatement(e))return kn(e.cases.flatMap(r=>r.consequent),t,n);if(S.isTryStatement(e)){let r=kn(e.block.body,t,n);return e.handler&&r.push(...kn(e.handler.body.body,t,n)),e.finalizer&&r.push(...kn(e.finalizer.body,t,n)),r}return[]}function kn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return md(e,t,n)}finally{t.valueScopes.pop()}}function li(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:ze(r),sourceCandidates:i&&i.length>0?i:void 0})}function Qb(e,t,n,r){let o=zb(e.openingElement,["items","dataSource","data"]),i={key:t,tag:ld(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!S.isJSXAttribute(s))continue;let a=Wb(s);if(!a||!S.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!S.isJSXEmptyExpression(c)){if(Yb(a)&&sa(c)){let l=ci(c,n,r),d=cd(o,c,r,n);li(n,"repeat-region",t,s,l,d?[d]:void 0);continue}if(Zb(a)){let l=sa(c)?ci(c,n,r):zt(c,n,r);li(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!S.isJSXExpressionContainer(s)||!sa(s.expression))continue;let a=ci(s.expression,n,r),c=cd(o,s.expression,r,n);li(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ui(e,t,n){let r=ld(e.openingElement);if(r==="Fragment"||la(e))return fi(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=Tb(r),a;if(s){let R=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${R}`}else{let R=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${R}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,d=Ir(t.file,t.componentName,l),f={file:t.file,component:t.componentName,structuralPath:l,key:d},m=s?"component-boundary":null,u=Bb(e.children,t,n),g=$b(e.openingElement,t,n),h=jb(e.openingElement,t,n),b,E,v=!1;if(s){let R=t.importMap.get(r)??t.importMap.get(Fb(r));R&&(b=R.specifier,E=R.exportName,v=xn(R.specifier,t.file))}let I={identity:f,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:ze(e),parentKey:i,childKeys:[],textSegments:u,attributes:g.length>0?g:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...v?{isPublicUiComponent:!0}:{},importedFrom:b,exportName:E};return t.elements.set(d,I),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(d),Qb(e,d,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:d,tag:r}),qb(e.children,t,n),t.parentStack.pop()),d}function di(e,t,n){return fi(e.children,t,n)}function fi(e,t,n){let r=[];for(let o of e)if(S.isJSXElement(o))if(la(o))r.push(...fi(o.children,t,n));else{let i=ui(o,t,n);i&&r.push(i)}else qn(o)?r.push(...di(o,t,n)):S.isJSXExpressionContainer(o)&&r.push(...pi(o.expression,t,n));return r}function qb(e,t,n){for(let r of e)S.isJSXElement(r)?ui(r,t,n):qn(r)?di(r,t,n):S.isJSXExpressionContainer(r)&&pi(r.expression,t,n)}function eS(e){return e==="&&"||e==="||"||e==="??"}function pi(e,t,n){if(S.isJSXEmptyExpression(e))return[];let r=Gb(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Et(r.collection,n),collectionSource:Be(r.collection,n,t)};if(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a)){let d=a.params[0],f=a.params[1];S.isIdentifier(d)&&(c.itemParamName=d.name),S.isIdentifier(f)&&(c.indexParamName=f.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:ze(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(S.isArrowFunctionExpression(a)||S.isFunctionExpression(a))&&l.childKeys.push(...ci(a,t,n)),l.childKeys}if(S.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.test,n),conditionSource:Be(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...zt(e.consequent,t,n)),s.childKeys.push(...zt(e.alternate,t,n)),s.childKeys}if(S.isLogicalExpression(e)&&eS(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Et(e.left,n),conditionSource:Be(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:ze(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...zt(e.right,t,n)),s.childKeys}if(S.isParenthesizedExpression(e))return pi(e.expression,t,n);if(S.isJSXElement(e)){let o=ui(e,t,n);return o?[o]:[]}return qn(e)?di(e,t,n):[]}function tS(e){let t=e.argument;return t&&(S.isExpression(t)||qn(t))?t:null}function Ar(e,t){let n=[];for(let r of e){if(S.isReturnStatement(r)){let o=tS(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(S.isIfStatement(r)){let o=S.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Ar(o,r.test)),r.alternate){let i=S.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ar(i,r.test))}continue}if(S.isSwitchStatement(r))for(let o of r.cases){let i=o.test?S.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Ar(o.consequent,i))}}return n}function gd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier),i=new Map,s=[],a=[],c=new Map,l=Mb(r);Ab(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let m=_b(f);if(!m)return;let u=f.node,g=[];if(S.isArrowFunctionExpression(u))S.isExpression(u.body)||qn(u.body)?g=[{argument:u.body,statement:S.returnStatement(S.isExpression(u.body)?u.body:null)}]:S.isBlockStatement(u.body)&&(g=Ar(u.body.body));else{let R=u.body;S.isBlockStatement(R)&&(g=Ar(R.body))}if(g.length===0){f.skip();return}let h=new Map;aa(Lb(r.program.body),ia(t,m,i,s,l,[h]),h);let b=new Map;for(let R of u.params)for(let P of Xt(R))ua(b,P);let E=S.isBlockStatement(u.body)?u.body.body:[],v=g[0]?.statement??null;for(let R of E){if(v&&R===v)break;S.isVariableDeclaration(R)&&aa([R],ia(t,m,i,s,l,[h,b]),b)}let I=ia(t,m,i,s,l,[h,b]);for(let R of g){let P=zt(R.argument,I,n);for(let T of P)a.includes(T)||a.push(T);if(R.condition){let T={kind:"conditional-branch",conditionExpression:Et(R.condition,n),conditionSource:Be(R.condition,n,I)};li(I,"conditional-region","",R.statement,P,[T])}}f.skip()}});let d=[...i.keys()];return d.length>0&&c.set(t,d),{graph:{routeId:t,rootKeys:a,elements:i,regions:s,fileIndex:c,version:1,diagnostics:[]},localImports:o}}function da(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function mi(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function hd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??yn,c=new Map,l=new Map,d=new Map,f=[],m=new Set,u=E=>{let v=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(v)||(m.add(v),f.push(E))},g=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(E=>({file:E.file,source:E.source,depth:0,diagnosticEntryFile:E.file,importStack:[]}))],h=new Set;for(;g.length>0;){let E=g.shift(),{file:v,source:I,depth:R,diagnosticEntryFile:P,importStack:T}=E;if(h.has(v))continue;h.add(v),c.set(v,I);let C=a(v,I);if(!C.ok){u(mi(C.diagnostic,P,T));continue}d.set(v,C.module);let{graph:A,localImports:F}=gd(C.module);for(let M of A.elements.values())if(M.importedFrom&&wt(M.importedFrom)){let U=M.importedFrom,q=await Po(v,U,r);q.ok?(M.importedFrom=q.path,Kt(q.path)&&(M.isPublicUiComponent=!0)):xn(U,v)||u(mi(q.diagnostic,P,da(T,v,U,q.diagnostic.path)))}if(l.set(v,A),!(R>=i))for(let M of F){if(tu(M))continue;let U=await Po(v,M,r);if(!U.ok){xn(M,v)||u(mi(U.diagnostic,P,da(T,v,M,U.diagnostic.path)));continue}let q=U.path;if(h.has(q)||Kt(q))continue;let Ne=da(T,v,M,q);try{let Z=await n(q);g.push({file:q,source:Z,depth:R+1,diagnosticEntryFile:P,importStack:Ne})}catch(Z){u(mi({path:q,code:"import-read-failed",message:`Failed to read imported file: ${q}`,details:{fromFile:v,specifier:M,reason:Z instanceof Error?Z.message:String(Z)}},P,Ne))}}}let b=nS(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return b.diagnostics=f,{graph:b,allSources:c,diagnostics:f,parsedModules:d,entryModule:d.get(e)??null}}function nS(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[d,f]of l.elements)o.set(d,f);for(let d of l.regions)i.push(d);for(let[d,f]of l.fileIndex){let m=s.get(d)??[];s.set(d,[...m,...f])}if(c===e){a=l.rootKeys;continue}r.includes(c)&&(a=[...a,...l.rootKeys])}return{routeId:e,rootKeys:a,elements:o,regions:i,fileIndex:s,version:n}}import{SiteEditHistoryProvenanceSchema as rS}from"@vcp-dev/contracts";var oS={affectedCompositions:[]};function vd(e){let t=null,n=new WeakMap;async function r(){return t??=iS(e),t}return{async prepareAppend(o){let i=await e.readIndex(),s=await e.stageAppend(Sd(o),{durableManifest:!1}),a;try{a=await e.previewStagedAppend(s.entryId,i.digest)}catch(l){throw await e.discardStage(s.stageId),l}let c={kind:"append",entry:o,historyTransition:a};return n.set(c,{expectedDigest:i.digest,stageId:s.stageId,entryId:s.entryId}),c},async prepareUndo(){let i=(await r()).undo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("undo entry is missing from index");let c=a-1,l=await e.previewCursor(c,s.digest),d={kind:"undo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async prepareRedo(){let i=(await r()).redo.at(-1);if(!i?.historyId)return null;let s=await e.readIndex(),a=s.entryIds.indexOf(i.historyId);if(a<0)throw new Error("redo entry is missing from index");let c=a,l=await e.previewCursor(c,s.digest),d={kind:"redo",entry:i,historyTransition:l};return n.set(d,{expectedDigest:s.digest,cursor:c}),d},async publishPrepared(o){let i=n.get(o);if(!i)throw new Error("history mutation was not prepared");let s=await r();if(o.kind==="append"){if(!i.entryId)throw new Error("staged entry id is missing");let a=await e.publishStagedAppend(i.entryId,i.expectedDigest,i.stageId);yd(a,o.historyTransition),o.entry.historyId=i.entryId,s.entryIds=[...a.entryIds],s.cursor=a.cursor,s.undo.push(o.entry),s.redo.length=0}else{if(i.cursor===void 0)throw new Error("prepared cursor is missing");let a=await e.setCursor(i.cursor,i.expectedDigest);if(yd(a,o.historyTransition),o.kind==="undo"){if(s.undo.at(-1)!==o.entry)throw new Error("undo state changed before publish");s.undo.pop(),s.redo.push(o.entry)}else{if(s.redo.at(-1)!==o.entry)throw new Error("redo state changed before publish");s.redo.pop(),s.undo.push(o.entry)}s.cursor=i.cursor}n.delete(o)},async discardPrepared(o){let i=n.get(o);if(!i)return;let s=o.historyTransition;if(s){let a=await e.readIndex();if(a.digest===s.publishedIndexDigest&&a.cursor===s.publishedCursor&&a.currentId===s.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}i.stageId&&await e.discardStage(i.stageId),n.delete(o)},async peekUndo(){return(await r()).undo.at(-1)??null},async pushUndo(o){let i=await r(),s=o;if(s.historyId){let l=i.entryIds.indexOf(s.historyId);if(l>=0)try{await e.setCursor(l),i.undo.push(o),i.cursor=l;return}catch(d){throw i.redo.push(o),d}}let a=await e.append(Sd(o)),c=a.currentId;if(!c)throw new Error("history store did not publish an entry");o.historyId=c,i.entryIds=[...a.entryIds],i.cursor=a.cursor,i.undo.push(o),i.redo.length=0},async popUndo(){return(await r()).undo.pop()??null},async peekRedo(){return(await r()).redo.at(-1)??null},async pushRedo(o){let i=await r(),s=o;if(!s.historyId)throw i.undo.push(o),new Error("cannot move an unpersisted history entry to redo");let a=i.entryIds.indexOf(s.historyId);if(a<0)throw i.undo.push(o),new Error("history entry is missing from the durable index");try{await e.setCursor(a-1),i.cursor=a-1,i.redo.push(o)}catch(c){throw i.undo.push(o),c}},async popRedo(){return(await r()).redo.pop()??null},async clearRedo(){(await r()).redo.length=0},async getStatus(){let o=await e.readStatus();return{canUndo:o.canUndo,canRedo:o.canRedo,undoDepth:o.undoDepth,redoDepth:o.redoDepth,recoveryRequired:o.recoveryRequired}},async markRecoveryRequired(o){await e.markRecoveryRequired(o)}}}function yd(e,t){if(!t)throw new Error("durable history transition is missing");if(e.digest!==t.publishedIndexDigest||e.cursor!==t.publishedCursor||e.currentId!==t.publishedCurrentId)throw new Error("durable history published an unexpected index state")}async function iS(e){let t=await e.readIndex(),n=await Promise.all(t.undoIds.map(async o=>xd(e,o))),r=await Promise.all(t.redoIds.map(async o=>xd(e,o)));return{undo:n.reverse(),redo:r.reverse(),entryIds:[...t.entryIds],cursor:t.cursor}}async function xd(e,t){let n=await e.readEntry(t),r=sS(n),o=r.provenance??oS;return{historyId:t,...o.initiatingComposition?{composition:o.initiatingComposition}:{},operationId:r.operationId,kind:r.kind,target:r.target,provenance:o,...r.selectionRef?{selectionRef:r.selectionRef}:{},...r.output?{output:r.output}:{},preSnapshots:await bd(e,n,r.preSnapshots),postSnapshots:await bd(e,n,r.postSnapshots)}}async function bd(e,t,n){let r=new Map(t.blobs.map(o=>[o.name,o.digest]));return Promise.all(n.map(async o=>{let i=o.exists&&o.blobName?Buffer.from(await e.readBlob(lS(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Sd(e){let t=[],n=(i,s)=>i.map((a,c)=>{let l={file:a.file,exists:a.exists!==!1,version:a.version,...a.sha256?{sha256:a.sha256}:{}};if(l.exists){let d=`${s}-${c}`;l.blobName=d,t.push({name:d,data:a.content})}return l}),r=aS(e),o={operationId:e.operationId,kind:e.kind,target:e.target,...r?{provenance:r}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{},...e.output?{output:e.output}:{},preSnapshots:n(e.preSnapshots,"pre"),postSnapshots:n(e.postSnapshots,"post")};return{kind:"site-edit-operation",manifest:JSON.parse(JSON.stringify(o)),blobs:t}}function sS(e){if(!Id(e.manifest))throw new Error("durable history manifest is not an object");let t=e.manifest,n=new Set(["operationId","kind","target","selectionRef","output","provenance","preSnapshots","postSnapshots"]);if(Object.keys(t).some(r=>!n.has(r)))throw new Error("durable history manifest contains unknown fields");if(typeof t.operationId!="string"||t.operationId.length===0||typeof t.kind!="string"||t.kind.length===0||!Array.isArray(t.preSnapshots)||!Array.isArray(t.postSnapshots))throw new Error("durable history manifest has an invalid shape");return{operationId:t.operationId,kind:t.kind,target:t.target,...t.selectionRef!==void 0?{selectionRef:t.selectionRef}:{},...t.output!==void 0?{output:t.output}:{},...t.provenance!==void 0?{provenance:kd(t.provenance)}:{},preSnapshots:Ed(t.preSnapshots,"preSnapshots"),postSnapshots:Ed(t.postSnapshots,"postSnapshots")}}function aS(e){if(e.provenance!==void 0)return kd(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function kd(e){let t=rS.safeParse(e);if(!t.success)throw new Error("durable history provenance is invalid");return{...t.data.initiatingComposition?{initiatingComposition:t.data.initiatingComposition}:{},affectedCompositions:t.data.affectedCompositions.map(n=>({routeId:n.routeId,...n.effectiveTemplateId?{effectiveTemplateId:n.effectiveTemplateId}:{}}))}}function Ed(e,t){return e.map((n,r)=>{if(!Id(n))throw new Error(`durable history ${t}[${r}] is invalid`);if(typeof n.file!="string"||n.file.length===0||!Number.isInteger(n.version)||n.exists!==void 0&&typeof n.exists!="boolean"||n.sha256!==void 0&&!cS(n.sha256)||n.blobName!==void 0&&typeof n.blobName!="string")throw new Error(`durable history ${t}[${r}] is invalid`);return{file:n.file,exists:n.exists!==!1,version:n.version,...n.sha256?{sha256:n.sha256}:{},...n.blobName?{blobName:n.blobName}:{}}})}function cS(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function lS(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Id(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{COMPONENT_I18N_FILE_SUFFIX as uS,parseComponentI18nResourcesJson as dS,resolveSiteTextDirection as fS,SiteLocaleSchema as pS}from"@vcp-dev/contracts";var mS=["i18next","react-i18next"],gS="components/ui/site-locale-provider.tsx",hS="components/ui/component-i18n-provider.tsx",Cd="app/layout.tsx";async function pa(e){let t=e.files.filter(m=>m.path.endsWith(uS));if(t.length===0)return{ok:!0};for(let m of["package.json",Cd,gS,hS])if(!await e.exists(m))return In(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return In("Target snapshot package.json is invalid.")}let r=Rd(n)&&Rd(n.dependencies)?n.dependencies:{},o=mS.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return In(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Cd),s=fa(i,"html","lang"),a=fa(i,"html","dir"),c=fa(i,"SiteLocaleProvider","locale"),l=pS.safeParse(s);if(!l.success||!a||!c||s!==c||a!==fS(l.data))return In("Target snapshot app/layout.tsx must keep html lang/dir and SiteLocaleProvider locale consistent.");if(!i.includes('from "@/components/ui/site-locale-provider"')||!/<SiteLocaleProvider\b/.test(i)||!/<\/SiteLocaleProvider>/.test(i))return In("Target snapshot root layout is not wired to SiteLocaleProvider.");let d=l.data,f=d.split("-")[0];for(let m of t){let u=dS(m.content);if(!u.success)return In(`Component i18n resource is invalid: ${m.path}.`);if(!Object.hasOwn(u.data,d)&&!Object.hasOwn(u.data,f))return In(`Component i18n resource ${m.path} has no locale for ${d} or ${f}.`)}return{ok:!0}}function fa(e,t,n){let r=e.match(new RegExp(`<${t}\\b[^>]*>`))?.[0];if(!r)return null;let o=[...r.matchAll(new RegExp(`\\b${n}=(?:"([^"]+)"|\\{"([^"]+)"\\})`,"g"))];return o.length!==1?null:o[0]?.[1]??o[0]?.[2]??null}function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function In(e){return{ok:!1,message:e}}import{randomBytes as TS}from"node:crypto";import hi from"node:path";import{parse as xa}from"@babel/parser";import FS from"@babel/traverse";import*as Md from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as ga,PageResourceArtifactSchema as _S,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as OS,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as MS,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as DS,parseComponentI18nResourcesJson as LS}from"@vcp-dev/contracts";var wd=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Pd=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,yS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,xS=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,bS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,SS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,ES=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,vS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,kS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,IS=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,CS=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,RS=/\b(?:bg|text|border|ring|outline|fill|stroke)-(?:black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-\d{2,3})?(?:\b|\/)/g,NS=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,wS=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Tr(e,t){let n=gi([...gt(e,yS),...gt(e,xS),...gt(e,bS),...gt(e,t.includeRgbBackgroundImage?SS:ES),...t.includeExtendedColorFunctions?[...gt(e,vS),...gt(e,kS)]:[]]),r=gi([...gt(e,IS),...gt(e,CS)]).filter(o=>t.colorMixPolicy==="always"||wd.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...gt(e,RS).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...gt(e,wS).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:gi(gt(e,Pd)),hardCodedSurfaceOccurrences:AS(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?gi(gt(e,NS)):[]}}function gt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Nd=160,PS=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function AS(e){let t=new RegExp(Pd.source,"g"),n=[0];for(let s=0;s<e.length;s+=1)e[s]===`
5
+ `&&n.push(s+1);let r=s=>{let a=0,c=n.length-1;for(;a<c;){let l=Math.ceil((a+c)/2);(n[l]??0)<=s?a=l:c=l-1}return a},o=[],i;for(;(i=t.exec(e))!==null;){let s=i[0],a=s.endsWith("/")?s.slice(0,-1):s,c=/^\/(\d+)/.exec(e.slice(i.index+a.length)),l=e.slice(Math.max(0,i.index-64),i.index),d=PS.exec(l),f=r(i.index),m=e.indexOf(`
6
+ `,i.index),u=e.slice(n[f]??0,m===-1?void 0:m).trim();o.push({token:a,variant:d?.[1]??"",alpha:c?Number(c[1]):null,line:f+1,snippet:u.length>Nd?`${u.slice(0,Nd-1)}\u2026`:u})}return o}function gi(e){return[...new Set(e)]}var ha="{{$INSTANCE}}",BS=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,$S=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ya="components/site/generated",jS=/\.(?:tsx?|json)$/,VS=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,KS=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],US=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),ma=FS,JS=typeof ma=="function"?ma:ma.default;async function ba(e){let t=_S.safeParse(e.artifact);if(!t.success)return ge("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>TS(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=tE(r());if(!i)return ge("Random instance suffix must be 8 lowercase hex chars.");let s=`${nE(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let I of n.pages){let R=I.final_route.slice(1);a.set(I.template_page_id,I.final_route),c.set(I.template_page_id,I.title),l.push({template_page_id:I.template_page_id,title:I.title,final_route:I.final_route,route_file_path:`app/${R}/page.tsx`})}let d=[],f=new Set,m=new Set,u=new Map,g=new Map,h=[],b=new Set(n.pages.flatMap(I=>I.components.map(R=>R.component_id)));for(let I of n.components){if(!b.has(I.component_id))continue;let R=Ad({materialization:I.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!R.ok)return R;for(let P of R.files){let T=Fd(P,f,d);if(T)return T}m.add(R.entry),g.set(R.entry,R.entryExport),u.set(I.component_id,R.entry)}for(let[I,R]of n.pages.entries()){let P=l[I],T=Ad({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:P.route_file_path,pageTitle:P.title});if(!T.ok)return T;for(let F of T.files){let M=Fd(F,f,d);if(M)return M}m.add(T.entry),g.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(R.components.map(F=>F.component_id))});let C=d.find(F=>F.file===P.route_file_path);if(!C)return ge("Page materialization entry did not resolve to its final route file.",P.route_file_path);if(GS(C.content,P.route_file_path)!==P.final_route)return ge(`Page ${R.template_page_id} requires a static PAGE_SEO.path equal to ${P.final_route}.`,P.route_file_path)}let E=zS(d,m,s,u,h,g);if(!E.ok)return E;for(let I of d)if(await e.exists(I.file))return!I.file.startsWith("app/")&&o>1?ba({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${I.file}`,path:I.file};let v=WS(d);return v||(d.sort((I,R)=>I.file.localeCompare(R.file)),{ok:!0,packageInstanceId:s,pages:l,files:d})}function Ad(e){let t=e.materialization.entry.pathTemplate,n=[];for(let o of e.materialization.files){let i=o.pathTemplate===t,s=i&&e.pageEntryTarget?e.pageEntryTarget:Td(o.pathTemplate,e.packageInstanceId);if(!s)return ge("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=XS(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?YS(a.data,e.pageTitle,s):a;if(!c.ok)return c;n.push({operation:"create-only",file:s,content:c.data})}let r=e.pageEntryTarget??Td(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?ge("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function XS(e,t,n,r){let o,i=e.replace(BS,(c,l)=>{let d=n.get(l);return d||(o=l,c)});if(o)return ge(`Page route placeholder references unknown template page: ${o}`);let s=i.replace($S,(c,l)=>{let d=r.get(l);return d?JSON.stringify(d):(o=l,c)});if(o)return ge(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ha,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ge("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Td(e,t){let n=`${ya}/${t}`;if(e.split(ha).length>2)return null;let o=e.replace(ha,t),i=`${ya}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=hi.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!jS.test(a)||VS.test(a)?null:a}function Fd(e,t,n){return t.has(e.file)?ge(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function zS(e,t,n,r,o,i){let s=new Set(e.map(u=>u.file)),a=`${ya}/${n}`,c=new Map(e.map(u=>[u.file,new Set])),l=new Map;for(let u of e){if(u.file.endsWith(".json")){try{JSON.parse(u.content)}catch{return ge("Materialization JSON file must contain valid JSON.",u.file)}if(u.file.endsWith(ga)&&!LS(u.content).success)return ge("Materialization component i18n resources are invalid.",u.file);continue}try{let h=xa(u.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(u.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let v=E.source.value,I=qS(u.file,v,s,a);if(!I.allowed)return ge(`Materialization import is outside the controlled package: ${v}`,u.file);I.internalPath&&c.get(u.file).add(I.internalPath)}let b;if(JS(h,{Identifier(E){E.isReferencedIdentifier()&&US.has(E.node.name)&&(b??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(b??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(b??="style element",E.stop())}}),b)return ge(`Materialization source uses forbidden capability: ${b}`,u.file)}catch{return ge("Materialization source must parse as TS/TSX.",u.file)}let g=Tr(u.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(g.hardCodedSurfaceHits.length>0||g.rawColorHits.length>0||g.privateTokenHits.length>0)return ge("Materialization source violates the public theme token policy.",u.file)}if([...t].some(u=>!s.has(u)))return ge("Materialization entry is outside the controlled package.");for(let u of t)if(u.endsWith(".json"))return ge("Materialization JSON files cannot be package entries.");for(let[u,g]of i){let h=l.get(u);if(!h||!HS(h,g))return ge("Materialization entry does not declare its contracted export.",u)}let d=new Map([...r].map(([u,g])=>[g,u]));for(let u of o){let g=Od(u.entry,c);for(let h of u.declaredComponentIds){let b=r.get(h);if(!b||!g.has(b))return ge(`Page entry does not reach declared component: ${h}`,u.entry)}for(let h of g){let b=d.get(h);if(b&&!u.declaredComponentIds.has(b))return ge(`Page entry imports undeclared component: ${b}`,u.entry)}}let f=new Set;for(let u of t)for(let g of Od(u,c))f.add(g);if(f.size!==e.length)return ge("Every materialization file must be reachable from a package entry.");let m=eE(e,l,c);return m||{ok:!0}}function WS(e){if(e.length>OS)return ge("Page resource exceeds the aggregate source file limit.");let t=0;for(let n of e){let r=Buffer.byteLength(n.content,"utf8");if(r>MS)return ge("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>DS?ge("Page resource exceeds the aggregate content byte limit."):null}function HS(e,t){for(let n of e.program.body){if(t.kind==="default"){if(n.type==="ExportDefaultDeclaration")return!0;continue}if(n.type==="ExportNamedDeclaration"&&(n.declaration?.type==="VariableDeclaration"&&n.declaration.declarations.some(r=>r.id.type==="Identifier"&&r.id.name===t.name)||(n.declaration?.type==="FunctionDeclaration"||n.declaration?.type==="ClassDeclaration")&&n.declaration.id?.name===t.name||n.specifiers.some(r=>r.exported.type==="Identifier"&&r.exported.name===t.name)))return!0}return!1}function GS(e,t){let n;try{n=xa(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}for(let r of n.program.body){let o=r.type==="VariableDeclaration"?r:r.type==="ExportNamedDeclaration"&&r.declaration?.type==="VariableDeclaration"?r.declaration:null;if(o)for(let i of o.declarations){if(i.id.type!=="Identifier"||i.id.name!=="PAGE_SEO")continue;let s=yi(i.init);if(s?.type!=="ObjectExpression")return null;for(let a of s.properties){if(a.type!=="ObjectProperty"||a.computed||!ZS(a.key))continue;let c=yi(a.value);return c?.type==="StringLiteral"?c.value:c?.type==="TemplateLiteral"&&c.expressions.length===0?c.quasis[0]?.value.cooked??null:null}return null}}return null}function YS(e,t,n){let r;try{r=xa(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return ge("Page materialization PAGE_SEO must parse as TS/TSX.",n)}for(let o of r.program.body){let i=o.type==="VariableDeclaration"?o:o.type==="ExportNamedDeclaration"&&o.declaration?.type==="VariableDeclaration"?o.declaration:null;if(i)for(let s of i.declarations){if(s.id.type!=="Identifier"||s.id.name!=="PAGE_SEO")continue;let a=yi(s.init);if(a?.type!=="ObjectExpression")return ge("Page materialization PAGE_SEO must be a static object.",n);let c=a.properties.find(d=>d.type==="ObjectProperty"&&!d.computed&&QS(d.key));if(!c||c.type!=="ObjectProperty")return ge("Page materialization PAGE_SEO must declare a static title.",n);let l=yi(c.value);return!l||l.type!=="StringLiteral"&&l.type!=="TemplateLiteral"||l.type==="TemplateLiteral"&&l.expressions.length>0||typeof l.start!="number"||typeof l.end!="number"?ge("Page materialization PAGE_SEO.title must be a static string.",n):{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}}}return ge("Page materialization must declare a top-level PAGE_SEO object.",n)}function yi(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Md.isExpression(t)?t:null}function ZS(e){return e.type==="Identifier"&&e.name==="path"||e.type==="StringLiteral"&&e.value==="path"}function QS(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function qS(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=_d(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:KS.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=hi.posix.normalize(hi.posix.join(hi.posix.dirname(e),t)),i=_d(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function _d(e,t){return[e,`${e}.ts`,`${e}.tsx`,`${e}.json`,`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.json`].find(n=>t.has(n))}function eE(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(ga))continue;let i=o.file.slice(0,-ga.length),s=[`${i}.tsx`,`${i}.ts`].find(d=>r.has(d));if(!s)return ge("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(d=>d.value.value==="use client"),l=[...n].filter(([,d])=>d.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return ge("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Od(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();if(!n.has(o)){n.add(o);for(let i of t.get(o)??[])r.push(i)}}return n}function tE(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function nE(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function ge(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as rE}from"node:crypto";import Wt from"node:path";import{parse as oE}from"@babel/parser";import iE from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as xi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Dd,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as sE,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as aE,SiteEditMaterializationSchema as cE,parseComponentI18nResourcesJson as lE}from"@vcp-dev/contracts";var va="components/site/generated",Ld="{{$INSTANCE}}",bi=5,uE=/^[a-z][a-z0-9-]{0,48}$/,dE=/^[a-f0-9]{8}$/,Bd=/\.tsx?$/,fE=/\.json$/,pE=/\.(?:tsx?|json)$/,mE=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,gE=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],Sa=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ea=iE,hE=typeof Ea=="function"?Ea:Ea.default;function yE(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Dd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=wE(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=cE.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=CE(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${va}.`,path:e.generatedRoot}};if(!Jd(r.data.instanceBaseName))return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instanceBaseName must contain at least one safe word.",path:r.data.instanceBaseName}};let i=Vd(r.data.files),s=Vd(e.controlledFiles);if(!PE(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Dd)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let a=0;for(let[c,l]of r.data.files.entries()){let d=Buffer.byteLength(l.content,"utf8");if(d>sE)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file exceeds the per-file content limit.",file:l.pathTemplate,path:`files[${c}]`}};a+=d}return a>aE?{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab exceeds the reusable total content limit."}}:{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:o,instanceRoot:"",entry:{path:"",export:r.data.entry.export},files:[]}}}async function xE(e){let t=yE(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Jd(e.manifest.instanceBaseName),o=Math.max(1,Math.min(bi,e.maxAttempts??bi));for(let i=0;i<o;i+=1){let s=RE(e.instanceNameGenerator?.()??rE(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=zd(n,a),l=bE({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,allowedExternalImports:e.allowedExternalImports??gE});if(!l.ok)return l;if(!await SE(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Ud(e){let t=Math.max(1,Math.min(bi,e.maxAttempts??bi));for(let n=0;n<t;n+=1){let r=await xE({...e,maxAttempts:1});if(!r.ok){if(r.error.code==="MATERIALIZATION_INSTANCE_CONFLICT")continue;return r}let o=await e.commit(r.data);if(o.ok)return{ok:!0,plan:r.data,data:o.data};if(o.error.code!=="MATERIALIZATION_INSTANCE_CONFLICT")return o}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to commit a complete static prefab instance after repeated conflicts."}}}function bE(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=$d({pathTemplate:i.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!s.ok)return s;if(n.has(s.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${s.data}`,path:s.data}};n.add(s.data),t.push({kind:"create-only",path:s.data,content:i.content,...i.role?{role:i.role}:{},sourcePathTemplate:i.pathTemplate})}t.sort((i,s)=>i.path.localeCompare(s.path));let r=$d({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!r.ok)return r;if(!t.some(i=>i.path===r.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:r.data}};let o=EE(t,e.instanceRoot,r.data,e.manifest.entry.export,e.allowedExternalImports);return o.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:r.data,export:e.manifest.entry.export},files:t}}:o}async function SE(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function $d(e){if(e.pathTemplate.split(Ld).length!==2)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path templates must include the instance placeholder exactly once.",path:e.pathTemplate}};let t=e.pathTemplate.replaceAll(Ld,e.instanceName),n=NE(t);return n?zd(e.generatedRoot,e.instanceName)!==e.instanceRoot?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab instance root normalization failed.",path:e.pathTemplate}}:n!==e.instanceRoot&&!n.startsWith(`${e.instanceRoot}/`)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path must stay under components/site/generated/<instance>.",path:n}}:n!==t?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template cannot rely on path normalization semantics.",path:e.pathTemplate}}:n===e.instanceRoot||!pE.test(n)||mE.test(n)?{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab files must be .ts/.tsx/.json files and cannot be config, layout, provider, or global source files.",path:n}}:{ok:!0,data:n}:{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:"Static prefab path template resolves to an unsafe path.",path:e.pathTemplate}}}function EE(e,t,n,r,o){let i=new Set(e.map(f=>f.path)),s=new Map,a=new Map(e.map(f=>[f.path,new Set])),c=new Map;for(let f of e){if(fE.test(f.path)){if(f.path.endsWith(xi)){let g=lE(f.content);if(!g.success)return Cn("MATERIALIZATION_DATA_UNSUPPORTED",g.error.message,f.path);c.set(f.path,new Set)}else try{JSON.parse(f.content)}catch{return Cn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",f.path)}continue}let m;try{m=oE(f.content,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files must parse as plain module source.",file:f.path}}}let u=Tr(f.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(u.hardCodedSurfaceHits.length>0||u.rawColorHits.length>0||u.privateTokenHits.length>0)return{ok:!1,error:{code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source must use public semantic design tokens instead of raw colors or private tokens.",file:f.path}};s.set(f.path,m)}for(let f of e){if(!Bd.test(f.path))continue;let m=s.get(f.path),u=null;if(hE(m,{ImportDeclaration(g){let h=jd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:f.path},g.stop();else if(h.internalPath&&(a.get(f.path).add(h.internalPath),h.internalPath.endsWith(xi))){let b=vE({importer:f.path,imported:h.internalPath,source:g.node.source.value,ast:m});b.ok?c.get(h.internalPath).add(f.path):(u??=b.error,g.stop())}},ExportAllDeclaration(g){u??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:f.path},g.stop()},ExportNamedDeclaration(g){if(g.node.source){let h=jd({importer:f.path,source:g.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:f.path},g.stop()):a.get(f.path).add(h.internalPath)}},CallExpression(g){if(g.node.callee.type==="Import"){u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:f.path},g.stop();return}g.node.callee.type==="Identifier"&&g.node.callee.name==="require"&&(u??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:f.path},g.stop())},NewExpression(g){g.node.callee.type==="Identifier"&&g.node.callee.name==="Function"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:f.path},g.stop())},MetaProperty(g){g.node.meta.type==="Identifier"&&g.node.meta.name==="import"&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:f.path},g.stop())},MemberExpression(g){let h=Kd(g.node);h&&Sa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},OptionalMemberExpression(g){let h=Kd(g.node);h&&Sa.has(h)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:f.path},g.stop())},Identifier(g){g.isReferencedIdentifier()&&Sa.has(g.node.name)&&(u??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${g.node.name}.`,file:f.path},g.stop())},JSXAttribute(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name==="style"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:f.path},g.stop())},JSXOpeningElement(g){g.node.name.type==="JSXIdentifier"&&g.node.name.name.toLowerCase()==="style"&&(u??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:f.path},g.stop())}}),u)return{ok:!1,error:u}}if(!Bd.test(n))return Cn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Cn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!kE(l,r))return Cn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[f,m]of c)if(m.size!==1)return Cn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",f);return IE(n,a).size!==e.length?Cn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:va,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function jd(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return e.source.startsWith("@/components/site/generated/")?{allowed:!1}:{allowed:e.allowedExternalImports.some(o=>o.endsWith("/")?e.source.startsWith(o):e.source===o)};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Wt.posix.normalize(Wt.posix.join(Wt.posix.dirname(e.importer),e.source));if(t===e.instanceRoot||!t.startsWith(`${e.instanceRoot}/`))return{allowed:!1};let r=[t,`${t}.ts`,`${t}.tsx`,`${t}.json`,...["ts","tsx","json"].map(o=>`${t}/index.${o}`)].find(o=>e.filePaths.has(o));return r?{allowed:!0,internalPath:r}:{allowed:!1}}function vE(e){let t=Wt.posix.dirname(e.importer),n=Wt.posix.dirname(e.imported),r=Wt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Wt.posix.basename(e.imported).slice(0,-xi.length),i=`./${r}${xi}`;return!e.importer.endsWith(".tsx")||t!==n||r!==o||e.source!==i?{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Component i18n resources must use an explicit same-directory, same-name import from a .tsx file.",file:e.importer}}:e.ast.program.directives.some(a=>a.value.value==="use client")?{ok:!0}:{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:'A component that imports .i18n.json must declare the top-level "use client" directive.',file:e.importer}}}function kE(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration")return!0;if(t.kind!=="named"||n.type!=="ExportNamedDeclaration")continue;if(n.specifiers.some(o=>o.exported.type==="Identifier"&&o.exported.name===t.name))return!0;let r=n.declaration;if((r?.type==="FunctionDeclaration"||r?.type==="ClassDeclaration")&&r.id?.name===t.name||r?.type==="VariableDeclaration"&&r.declarations.some(o=>o.id.type==="Identifier"&&o.id.name===t.name))return!0}return!1}function IE(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=r.pop();n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Cn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function CE(e){let t=Xd(e);return t===va?t:null}function RE(e){let t=e.trim().toLowerCase();return dE.test(t)?t:null}function Jd(e){let t=e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,49).replace(/-+$/g,"");return uE.test(t)?t:null}function Xd(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Wt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function NE(e){let t=Xd(e);return!t||t!==e?null:t}function zd(...e){return Wt.posix.join(...e)}function Vd(e){return new Set(e.map(t=>t.pathTemplate))}function wE(e){let t=new Set;for(let n of e){if(t.has(n.pathTemplate))return n.pathTemplate;t.add(n.pathTemplate)}return null}function PE(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Kd(e){let t=e;for(;;){if(!t||typeof t!="object"||!("type"in t))return null;if(t.type==="Identifier"&&"name"in t&&typeof t.name=="string")return t.name;if(t.type==="MemberExpression"||t.type==="OptionalMemberExpression"){t=t.object;continue}return null}}import{createHash as La}from"node:crypto";import Aa from"@babel/traverse";function ka(e){let t=new Map,n=new Map;for(let s of e){if(t.has(s.placementKey))throw new Error(`Duplicate placement key in page composition projection: ${s.placementKey}`);t.set(s.placementKey,s);let a=n.get(s.placementUnitKey)??[];a.push(s),n.set(s.placementUnitKey,a)}let r=new Map,o=new Map,i=new Map;for(let[s,a]of n){let c=Object.freeze([...a]),l=c.find(d=>d.anchorSourceRange!==null&&d.members.length>0)??c.find(d=>d.members.length>0)??c[0];l&&(o.set(s,c),i.set(s,l),r.set(s,Object.freeze({placementUnitKey:s,placementKeys:Object.freeze(c.map(d=>d.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as AE}from"node:crypto";import Wd from"node:path";import*as Qd from"@babel/parser";import Ia from"@babel/generator";import*as Ve from"@babel/types";var Hd=typeof Ia=="function"?Ia:Ia.default;function Ra(e){let t=ef(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Pa(n,e.placementKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"RUNTIME_ANCHOR_UNRESOLVED",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement,i=_E(n,o),s={jsx:`<${e.component.localName} />`},a=TE(e);if(i){let u=Ca(e);return u.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-root-expression",locator:u.locator,sourceHash:u.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:u.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(wa(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Fr("Route page composition does not expose a verifiable container boundary.");let d=Or(c),f=Yd(e.source,d,l,"Route page composition container");if(!f.ok)return f.result;let m=o.anchorSourceRange?Or(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Fr("Route page composition placement does not expose a verifiable anchor boundary.");let u=Yd(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!u.ok)return u.result}return{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:a,rewriteStep:{kind:"insert-child",parentLocator:d,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function TE(e){let t=LE(e.entryFile,e.component.source);return e.component.exportName==="default"?{kind:"add-import",moduleSpecifier:t,imports:[{kind:"default",local:e.component.localName}]}:{kind:"add-import",moduleSpecifier:t,imports:[{kind:"named",imported:e.component.exportName,local:e.component.localName===e.component.exportName?void 0:e.component.localName}]}}function Si(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Rn(e.source,"Root expression rewrite requires an exact expression locator.");let t=xr(e.source,"value");if(!t.ok)return Rn(e.source,t.diagnostic.message);let n=se(t.ast,e.locator);if(!n.ok)return Rn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Rn(e.source,"Resolved value locator does not point to an expression.");let o=er(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Rn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ve.nullLiteral()),{ok:!0,source:Hd(t.ast,{}).code};let i;try{i=Qd.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Rn(e.source,s instanceof Error?s.message:String(s))}return!Ve.isJSXElement(i)&&!Ve.isJSXFragment(i)?Rn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(FE(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Hd(t.ast,{}).code})}function FE(e,t,n,r){if(Ve.isNullLiteral(e)||r)return t;let o=Ve.isJSXFragment(e)?[...e.children]:[Ve.isJSXElement(e)?e:Ve.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ve.jsxFragment(Ve.jsxOpeningFragment(),Ve.jsxClosingFragment(),s)}function Rn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Na(e){let t=ef(e);if(t)return{ok:!1,error:t};let n=e.projection,r=tf(n,e.placementUnitKey,e.expectedDocumentVersion);if(!r.ok)return{ok:!1,error:{code:r.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:r.diagnostic.message,diagnostics:[r.diagnostic]}};let o=r.placement;if(!o.sourceRange||!o.sourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition source placement does not expose a safe boundary.",diagnostics:[]}};if(OE(n,o)){let h=Ca(e);return h.ok?e.operation==="remove-node"&&!Gd(n,o.placementUnitKey)?Fr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Fr("A singleton root expression cannot be moved without a safe parent boundary."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:h.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:h.locator,sourceHash:h.sourceHash}}}:h.result}let s=Or(o.sourceRange),a=Tt(e.source,s);if(!a.ok||!a.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:a.ok===!1?a.diagnostic.message:"Route page composition source anchor could not be resolved.",diagnostics:a.ok?[]:[_r(a.diagnostic)]}};if(er(e.source,a.match.node.start??null,a.match.node.end??null)!==o.sourceHash)return{ok:!1,error:{code:"VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition source placement hash no longer matches the current source."}]}};if(e.operation==="remove-node"){let h=Ca(e);return h.ok?Gd(n,o.placementUnitKey)?{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"remove-node",locator:s}}}:Fr("The last editable page unit cannot be deleted."):h.result}if(e.operation==="replace-node")return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"replace-node",locator:s}}};if(!e.targetPlacement)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit move requires a target placement.",diagnostics:[]}};if(e.targetPlacement.composition.routeId!==e.routeId||!DE(e.targetPlacement.composition,e.composition))return{ok:!1,error:{code:"CROSS_PAGE_MOVE_UNSUPPORTED",message:"Page-unit move across routes or composition templates is not supported.",diagnostics:[]}};if(e.targetPlacement.documentVersion!==e.expectedDocumentVersion)return{ok:!1,error:{code:"VERSION_STALE",message:"Page-unit target placement belongs to a different document version.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Page-unit target placement belongs to a different document version."}]}};let l=Pa(n,e.targetPlacement.placementKey,e.expectedDocumentVersion);if(!l.ok)return{ok:!1,error:{code:l.diagnostic.code==="DOCUMENT_VERSION_STALE"?"VERSION_STALE":"NO_SAFE_PAGE_PLACEMENT",message:l.diagnostic.message,diagnostics:[l.diagnostic]}};let d=l.placement;if(d.placementUnitKey!==e.targetPlacement.placementUnitKey||d.relation!==e.targetPlacement.relation)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Page-unit target placement metadata does not match the cached projection.",diagnostics:[]}};let f=d.containerSourceRange;if(!f||!d.containerSourceHash)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable container boundary.",diagnostics:[]}};let m=Or(f),u=Tt(e.source,m);if(!u.ok||!u.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:u.ok===!1?u.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:u.ok?[]:[_r(u.diagnostic)]}};if(er(e.source,u.match.node.start??null,u.match.node.end??null)!==d.containerSourceHash)return Zd("Route page composition target container hash no longer matches the current source.");if(d.relation==="before"||d.relation==="after"){let h=d.anchorSourceRange,b=d.anchorSourceHash;if(!h||!b)return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:"Route page composition target placement does not expose a verifiable anchor boundary.",diagnostics:[]}};let E=Or(h),v=Tt(e.source,E);return!v.ok||!v.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:v.ok===!1?v.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:v.ok?[]:[_r(v.diagnostic)]}}:er(e.source,v.match.node.start??null,v.match.node.end??null)!==b?Zd("Route page composition target anchor hash no longer matches the current source."):{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,anchorLocator:E,placement:d.relation}}}}return{ok:!0,plan:{kind:"page-unit-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:o.placementKey,placementUnitKey:o.placementUnitKey,sourceHash:o.sourceHash,rewriteStep:{kind:"move-node",locator:s,targetParentLocator:m,placement:d.relation}}}}function Gd(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function _E(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&wa(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function OE(e,t){return e.container.kind!=="jsx-container"&&wa(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Ca(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Tt(e.source,n);return!r.ok||!r.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:r.ok===!1?r.diagnostic.message:"Route mutation target could not be resolved.",diagnostics:r.ok?[]:[_r(r.diagnostic)]}}}:er(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:qd("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Yd(e,t,n,r){let o=Tt(e,t);return!o.ok||!o.match.node?{ok:!1,result:{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:o.ok===!1?o.diagnostic.message:`${r} could not be resolved.`,diagnostics:o.ok?[]:[_r(o.diagnostic)]}}}:er(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:qd(`${r} hash no longer matches the current source.`)}:{ok:!0}}function qd(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Fr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Zd(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function _r(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function ef(e){let{projection:t}=e;return t.route!==e.routeId||t.entryFile!==e.entryFile?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different route.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different route.",details:{expectedRouteId:e.routeId,projectedRouteId:t.route,expectedEntryFile:e.entryFile,projectedEntryFile:t.entryFile}}]}:e.composition&&!ME(t.composition,e.composition)?{code:"VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Cached page composition projection belongs to a different composition.",details:{expectedComposition:e.composition,projectedComposition:t.composition}}]}:e.currentDocumentVersion!==e.expectedDocumentVersion||t.documentVersion!==e.currentDocumentVersion?{code:"VERSION_STALE",message:"Route page composition version is stale.",diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:"Route page composition version is stale.",details:{expectedDocumentVersion:e.expectedDocumentVersion,currentDocumentVersion:e.currentDocumentVersion,projectedDocumentVersion:t.documentVersion}}]}:null}function ME(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function DE(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function LE(e,t){let n=Wd.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Wd.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Or(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function er(e,t,n){return t==null||n==null?null:`sha256:${AE("sha256").update(e.slice(t,n)).digest("hex")}`}function wa(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}var BE=typeof Aa=="function"?Aa:Aa.default;function sf(e){if(!e.ast)return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=zE(e.ast);if(!t)return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=HE(t);if(!n.ok)return vt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=YE(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(QE(r,t))return vt(e,[$e("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Fa(e,t,"virtual-route-root",r);if(ZE(r)){let o=nv({input:e,source:e.source,expression:r});return Ta(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ae(r)&&!nn(r)){let o=Ma(r),i=of({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Ta(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=ev(r);if(!o.ok)return vt(e,[o.diagnostic]);let i=tr(o.path);if(i.unsupported)return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(qE(e.source,r,i.members))return Fa(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ae(r);if(i.members.length===0&&s)return Fa(e,t,"virtual-route-root",r);let a=o.path===r&&s?"virtual-route-root":"jsx-container",c=o.path.isJSXFragment()?"jsx-fragment":"jsx-element",l=of({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Ta(e,t,l,{kind:a,sourceKind:c},r)}return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Pa(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$e("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:$e("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function tf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:$e("DOCUMENT_VERSION_STALE","Placement lookup is stale for the requested document version",{expectedDocumentVersion:e.documentVersion,requestedDocumentVersion:n})};let r=e.placementUnitByKey.get(t)??null;return r?{ok:!0,placement:r}:{ok:!1,diagnostic:$e("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function af(e){return e.ok?$E(e.projection):jE(e.projection)}function $E(e){let t=new Map,n=[];for(let l of e.placements)l.members.length===0&&e.placements.length>1||l.members.length>0&&!l.anchorSourceRange||t.has(l.placementUnitKey)||t.set(l.placementUnitKey,l);let r=new Map,o=new Map;for(let[l,d]of t){let f=d.members.flatMap((h,b)=>cf(e,d,h,b,e.container.placementKey)),m=f.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>KE(l,h,d.independent)),u=f.length>0?f:[{sourceMember:{key:`source:${l}:empty`,kind:e.container.kind==="starter-placeholder"?"starter-placeholder":"null-return",containerKey:e.container.placementKey,label:"empty-page",sourceFile:e.entryFile,isAtomic:!0},member:null}];r.set(l,u.map(({sourceMember:h})=>h)),o.set(l,m);let g=u[0]?.sourceMember.key??l;n.push({key:l,containerKey:g,businessMemberKeys:m.map(h=>h.key),isMultiMember:d.memberCount>1})}let i=[...r.values()].flat(),s=[...o.values()].flat(),a=i[0]?.key??null,c=e.placements.map(l=>({kind:"page-composition",placementKey:l.placementKey,documentVersion:e.documentVersion,composition:e.composition,placementUnitKey:l.placementUnitKey,relation:l.relation}));return{status:"supported",version:e.version,composition:e.composition,container:VE(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function jE(e){let t=e.diagnostics.map(UE);return{status:"unsupported",version:e.version,composition:e.composition,reason:JE(e.diagnostics),diagnostics:t}}function VE(e,t){switch(e.container.kind){case"jsx-container":return{kind:"jsx-container",key:e.container.placementKey,sourceMemberKey:t??e.container.placementKey,sourceFile:e.entryFile,componentName:e.defaultExportName??void 0};case"starter-placeholder":return{kind:"starter-placeholder",key:e.container.placementKey,sourceFile:e.entryFile};case"virtual-route-root":return{kind:"virtual-route-root",key:e.container.placementKey}}}function cf(e,t,n,r,o){let i=`source:${t.placementUnitKey}:${r}:${n.memberKey}`;return[{sourceMember:{key:i,kind:n.kind==="jsx-element"?"jsx-element":"jsx-expression",containerKey:o,label:n.label,sourceFile:e.entryFile,isAtomic:n.kind!=="jsx-element"},member:n},...n.children.flatMap((a,c)=>cf(e,t,a,c,i))]}function KE(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function UE(e){return{code:XE(e),message:e.message}}function JE(e){let t=e[0];if(!t)return"UNSUPPORTED_ROUTE_STRUCTURE";switch(t.code){case"ROUTE_RETURN_NOT_FOUND":return"ROUTE_RETURN_NOT_FOUND";case"MULTIPLE_PAGE_RETURNS":return"MULTIPLE_PAGE_RETURNS";case"INDIRECT_RETURN_ONLY":return"INDIRECT_RETURN_ONLY";case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return t.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return"UNSUPPORTED_ROUTE_STRUCTURE"}}function XE(e){switch(e.code){case"PLACEMENT_KEY_NOT_FOUND":return"RUNTIME_ANCHOR_UNRESOLVED";case"DOCUMENT_VERSION_STALE":return"VERSION_STALE";case"UNSUPPORTED_PAGE_SHAPE":return e.details?.reason==="ambiguous-placement"?"PAGE_CONTAINER_AMBIGUOUS":"UNSUPPORTED_ROUTE_STRUCTURE";default:return e.code}}function zE(e){let t=null;return BE(e,{ExportDefaultDeclaration(n){let r=n.get("declaration");if(r.isArrowFunctionExpression()||r.isFunctionDeclaration()||r.isFunctionExpression()){t=r,n.stop();return}if(!r.isIdentifier())return;let o=n.scope.getBinding(r.node.name);if(!o)return;let i=WE(o.path);i&&(t=i,n.stop())}}),t}function WE(e){if(e.isArrowFunctionExpression()||e.isFunctionDeclaration()||e.isFunctionExpression())return e;if(e.isVariableDeclarator()){let t=e.get("init");if(t.isArrowFunctionExpression()||t.isFunctionExpression())return t}return null}function HE(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Dr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:$e("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")}}let n=t.get("body"),r=n.at(-1);if(!r)return{ok:!1,diagnostic:$e("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:$e("UNSUPPORTED_PAGE_SHAPE","Route default export must end with a direct terminal return",{reason:"terminal-return-required"})};for(let s of n.slice(0,-1)){if(s.isIfStatement()){if(!GE(s))return{ok:!1,diagnostic:$e("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(lf(s)||uf(s))return{ok:!1,diagnostic:$e("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Dr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:$e("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function GE(e){if(e.node.alternate)return null;let t=e.get("consequent");if(t.isReturnStatement())return t;if(!t.isBlockStatement())return null;let n=t.get("body"),r=n.at(-1);if(!r?.isReturnStatement())return null;for(let o of n.slice(0,-1))if(lf(o)||uf(o))return null;return r}function lf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function uf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function YE(e,t){let n=t.scope.getBinding(e.node.name);if(!n||n.scope.path.node!==t.node)return{status:"not-local"};if(!n.path.isVariableDeclarator())return{status:"not-local"};let r=n.path.parentPath;if(!r?.isVariableDeclaration()||r.node.kind!=="const")return{status:"invalid"};let o=n.path.get("init");if(Array.isArray(o)||!o.node)return{status:"invalid"};let i=Dr(o);return!i||!i.isJSXElement()&&!i.isJSXFragment()?{status:"invalid"}:n.referencePaths.length!==1||n.referencePaths[0]?.node!==e.node||n.constantViolations.length!==0?{status:"invalid"}:{status:"resolved",expression:i}}function ZE(e){return e.isConditionalExpression()?nf(Dr(e.get("consequent")))&&nf(Dr(e.get("alternate"))):!1}function nf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Dr(e){if(!e.node)return null;let t=e;for(;;){if(t.isParenthesizedExpression()){t=t.get("expression");continue}if(t.isTSAsExpression()||t.isTSTypeAssertion()){t=t.get("expression");continue}if(t.isTSNonNullExpression()||t.isTypeCastExpression()){t=t.get("expression");continue}break}return t.isExpression()?t:null}function QE(e,t){if(e.isIdentifier())return rf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return rf(n.node.name,t)}return!1}function rf(e,t){let n=t.scope.getBinding(e);if(!n)return!1;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())return!0;if(r.isVariableDeclarator()){let o=r.get("init");return o.isFunctionExpression()||o.isArrowFunctionExpression()}return!1}function qE(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Oa(t)}function Oa(e){for(let t of e.get("children")){if(t.isJSXText()){if(t.node.value.trim())return!1;continue}if(t.isJSXExpressionContainer()){let n=t.get("expression");if(n.isJSXEmptyExpression()||n.isNullLiteral())continue;return!1}if(t.isJSXFragment()){if(!Oa(t))return!1;continue}if(t.isJSXElement()&&!Oa(t))return!1}return!0}function ev(e){let t=e;if(e.isJSXFragment()||Ae(e)){let r=Mr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&nn(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&nn(t);){let r=Mr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!nn(o))return{ok:!0,path:t};if(Mr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Mr(e){let t=[];for(let n of e.get("children"))if(!Array.isArray(n)){if(n.isJSXText()){n.node.value.trim()&&t.push(n);continue}if(n.isJSXExpressionContainer()){let r=n.get("expression");!r.isJSXEmptyExpression()&&!r.isNullLiteral()&&t.push(n);continue}if(n.isJSXFragment()){t.push(...Mr(n));continue}n.isJSXElement()&&(Ae(n)?t.push(...Mr(n)):t.push(n))}return t}function tr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Da(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:ht(r.node.loc),businessMemberCount:0,parentSourceRange:ht(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=tr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=nn(o)?tr(o):null;n||=i?.unsupported??!1,t.push({...Ma(o,i?.members),sourceRange:ht(r.node.loc),parentSourceRange:ht(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Da(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:ht(r.node.loc),businessMemberCount:1,parentSourceRange:ht(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ae(r)){let o=tr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=nn(r)?tr(r):null;n||=o?.unsupported??!1,t.push({...Ma(r,o?.members),parentSourceRange:ht(e.node.loc)})}}return{members:t,unsupported:n}}function Ma(e,t){let n=e.isJSXElement()&&nn(e)?t??tr(e).members:[],r=e.isJSXElement()&&!nn(e)&&!Ae(e);return{memberKey:Da(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:ht(e.node.loc),businessMemberCount:r?1:df(n),parentSourceRange:ht(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:tv(e)}}function nn(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function tv(e){if(e.isJSXFragment())return"Fragment";let t=e.node.openingElement.name;if(t.type==="JSXIdentifier")return t.name;if(t.type==="JSXMemberExpression"){let n=t.object;return`${n.type==="JSXIdentifier"?n.name:"member"}.${t.property.name}`}return t.name.name}function df(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Ei(e){return e.length===0?0:Math.max(1,df(e))}function of(e){let t=ht(e.containerPath.node.loc),n=Ba(e.source,e.containerPath.node.start,e.containerPath.node.end),r=yt(e.input,e.containerKind,e.sourceKind,t),o=yt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Ei(e.members)<=1,memberCount:Ei(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function nv(e){let t=ht(e.expression.node.loc),n=Ba(e.source,e.expression.node.start,e.expression.node.end),r=yt(e.input,"virtual-route-root","atomic-expression",t),o=yt(e.input,"virtual-route-root","placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:!0,memberCount:1,sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:[{memberKey:yt(e.input,"virtual-route-root","atomic-member",t),kind:"atomic-expression",nodeType:e.expression.node.type,sourceRange:t,businessMemberCount:1,parentSourceRange:null,children:[],isBusinessMember:!0,label:e.expression.node.type}]}}function ff(e,t){let n=ht(t.node.loc),r=Ba(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Ta(e,t,n,r,o){let i=ff(e,o);if(!i)return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=rv(e,n,s),c=ka(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:mf(t),container:{kind:r.kind,placementKey:n.placementKey,placementUnitKey:n.placementUnitKey,version:e.version,isEmptyPage:n.memberCount===0,sourceKind:r.sourceKind,sourceRange:s,sourceHash:n.sourceHash},placements:a,diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:i};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function rv(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,d,f,m,u,g,h=n)=>({...t,placementKey:d,placementUnitKey:f,containerKey:t.placementKey,independent:Ei(g)<=1,memberCount:Ei(g),sourceRange:m,sourceHash:m?_a(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?_a(e.source,h):null,anchorSourceRange:u,anchorSourceHash:u?_a(e.source,u):null,members:g}),i=t.placementKey,s=t.members.map(l=>yt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",yt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let d=l.parentSourceRange??n,f=yt(e,i,"placement-unit",l.sourceRange);r.push(o("before",yt(e,f,"before",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d)),r.push(o("after",yt(e,f,"after",l.sourceRange),f,l.sourceRange,l.sourceRange,[l],d))}return r.push(o("append",i,c,n,null,[])),r}function Fa(e,t,n,r){let o=ff(e,r);if(!o)return vt(e,[$e("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=yt(e,n,"empty-container",void 0),s=yt(e,n,"empty-unit",void 0),a={placementKey:i,placementUnitKey:s,version:e.version,containerKey:i,independent:!0,memberCount:0,sourceRange:null,sourceHash:null,relation:"append",containerSourceRange:null,containerSourceHash:null,anchorSourceRange:null,anchorSourceHash:null,members:[]},c=ka([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:mf(t),container:{kind:n,placementKey:i,placementUnitKey:s,version:e.version,isEmptyPage:!0,sourceKind:n==="starter-placeholder"?"starter-placeholder":"jsx-fragment",sourceRange:null,sourceHash:null},placements:[a],diagnostics:[],placementByKey:new Map,unitByKey:new Map,placementsByUnitKey:new Map,placementUnitByKey:new Map,mutationTarget:o};return Object.defineProperties(l,{placementByKey:{value:c.placementByKey,enumerable:!1},unitByKey:{value:c.unitByKey,enumerable:!1},placementsByUnitKey:{value:c.placementsByUnitKey,enumerable:!1},placementUnitByKey:{value:c.sourcePlacementByUnitKey,enumerable:!1}}),{ok:!0,projection:l}}function vt(e,t){return{ok:!1,projection:{status:"unsupported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,diagnostics:t}}}function $e(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function yt(e,t,n,r){return pf([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Da(e,t,n){return pf(["member",e,String(t??-1),String(n??-1)])}function pf(e){return`pc_${La("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Ba(e,t,n){return t==null||n==null?null:`sha256:${La("sha256").update(e.slice(t,n)).digest("hex")}`}function _a(e,t){let n=[0];for(let i=0;i<e.length;i+=1)e.charCodeAt(i)===10&&n.push(i+1);let r=n[t.startLine-1],o=n[t.endLine-1];return r===void 0||o===void 0?null:`sha256:${La("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function ht(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function mf(e){if(e.isFunctionDeclaration())return e.node.id?.name??null;let t=e.parentPath;return t?.isVariableDeclarator()&&t.node.id.type==="Identifier"?t.node.id.name:null}import{PageTemplateIdSchema as gv}from"@vcp-dev/contracts";import oF from"node:fs";import sF from"node:path";var iv=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Lr(e){let t=e.map(r=>mv(r.path)),n=sv(t);return n?t.filter(r=>cv(n,r)).map(r=>({routeId:lv(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function $a(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=pv(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function sv(e){return e.some(r=>r.startsWith("app/")&&!av(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function av(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function cv(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return iv.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function lv(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(dv).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function uv(e){return e.startsWith("(")&&e.endsWith(")")}function dv(e){return!e||e.startsWith("@")||e.startsWith("_")||uv(e)?null:fv(e)}function fv(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function pv(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function mv(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Br=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Qe(e,t={}){throw new Br("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function ja(e){return gv.safeParse(e).success||Qe("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function gf(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Qe("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Qe("invalid-template-key",{path:e})}return ja(t)!==e&&Qe("noncanonical-template-key",{path:e}),t}function hv(e){let t=$a(e),n=t.slice(1).split("/");return(!e.startsWith("/")||/[?#\\%\u0000-\u001f]/.test(e)||t.startsWith("/.vcp")||t!=="/"&&n.some(r=>!r||r==="."||r===".."||r.startsWith("@")||r.startsWith("_")||r.startsWith("(")||yv(r)&&!hf(r)))&&Qe("invalid-public-route",{routeId:e}),t}function yv(e){return e.includes("[")||e.includes("]")}function hf(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function yf(e){return e.some(hf)}function xf(e,t,n="app"){n!=="app"&&n!=="src/app"&&Qe("invalid-app-root");let r=hv(e),o=ja(t),i=yf(r.slice(1).split("/")),s=i?`${n}/.vcp/page-templates/${o}${r}`:`${n}/.vcp/page-templates${r==="/"?"":r}`,a=i?`${s}/page.tsx`:`${s}/${o}/page.tsx`;return(Buffer.byteLength(a,"utf8")>4095||a.split("/").some(c=>Buffer.byteLength(c,"utf8")>255))&&Qe("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function bf(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Sf(e){let t=Array.isArray(e)?e.map(r=>[r.path,r.content]):[...e],n=new Map;for(let[r,o]of t){let i=r.replace(/\\/g,"/").replace(/^\.\//,"");i.split("/").some(s=>s===".."||s===".")&&Qe("invalid-file-path",{path:i}),n.has(i)&&Qe("duplicate-file-path",{path:i}),n.set(i,o)}return n}function ki(e){let t=Sf(e.files),n=Lr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Br("PAGE_TEMPLATE_ROUTE_AMBIGUOUS",`Multiple canonical entries for ${i.routeId}`,{reason:"duplicate-route-id",routeId:i.routeId,candidates:n.filter(s=>s.routeId===i.routeId).map(s=>s.entryFile)});r.set(i.routeId,i.entryFile)}let o=[];for(let i of t.keys()){if(!bf(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Qe("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=yf(c),d=l?c[0]:c.pop(),f=l?c.slice(1):c,m=gf(d),u=f.length?`/${f.join("/")}`:"/";xf(u,m,a).templateEntryFile!==i&&Qe("candidate-path-mismatch",{path:i,routeId:u});let h=r.get(u);(!h||!h.startsWith(`${a}/`))&&Qe("canonical-entry-missing",{path:i,routeId:u}),o.push({routeId:u,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>vi(i.routeId,s.routeId)||vi(i.templateId,s.templateId))}function Ef(e){let t=Sf(e.files),n=ki({files:t}),r=Lr([...t.keys()].map(o=>({path:o}))).map(o=>({context:{routeId:o.routeId},entryFile:o.entryFile}));return r.push(...n.map(o=>({context:{routeId:o.routeId,effectiveTemplateId:o.templateId},entryFile:o.entryFile}))),r.sort((o,i)=>vi(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:vi(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function xv(e){let t=$a(e.selector.routeId),n=Ef({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Qe("canonical-entry-mismatch",{routeId:t,path:e.canonicalEntryFile});let o=e.selector.templateId===void 0?r:n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===e.selector.templateId);return o||Qe("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function vi(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Tv}from"@vcp-dev/contracts";import{parse as a_}from"@babel/parser";import{parse as gF}from"@babel/parser";import{FormBlockIdSchema as yF,FormSpecV1Schema as xF}from"@vcp-dev/contracts";var $r="components/site/generated/forms",bF=`${$r}/vcp-form-runtime.tsx`,Ii="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",SF=new RegExp(`^${$r}/form-(${Ii})\\.spec\\.ts$`),EF=new RegExp(`^${$r}/form-(${Ii})\\.tsx$`),vF=new RegExp(`^@/${$r}/form-(${Ii})$`),kF=new RegExp(`(?:^|/)${$r}/form-(${Ii})(?:\\.tsx?)?$`);var IF=Symbol("invalid-literal");import{createHash as NF}from"node:crypto";import{posix as PF}from"node:path";import{parse as TF}from"@babel/parser";import{FormSpecV1Schema as _F}from"@vcp-dev/contracts";var OF=Symbol("dynamic");import{parse as bv}from"@babel/parser";function Ci(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Sv=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function vf(e){let t=Sv.exec(e);if(!t)return null;let r=(t[1]??"").split("/").filter(o=>o.length>0&&!/^\(.+\)$/.test(o));return r.length===0?"/":`/${r.join("/")}`}function Ev(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function kf(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function vv(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Va(e){let t=e;if(t?.type==="StringLiteral"||t?.type==="NumericLiteral"||t?.type==="BooleanLiteral")return t.value;if(t?.type==="NullLiteral")return null;if(t?.type==="ArrayExpression")return(t.elements??[]).map(Va);if(t?.type==="ObjectExpression"){let n={};for(let r of Ci(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=kf(r.key);if(!o)throw new Error("unsupported object key");n[o]=Va(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Ka(e,t){let n=[],r=vf(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=bv(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(l){return n.push({code:"page-seo.parse-failed",message:l instanceof Error?l.message:String(l)}),{found:!1,seo:null,diagnostics:n}}let i;for(let l of Ci(o.program.body)){let d=l.type==="ExportNamedDeclaration"?l.declaration:l;if(d?.type==="VariableDeclaration")for(let f of Ci(d.declarations)){let m=f.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=f.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=vv(i);if(!s)return{found:!1,seo:null,diagnostics:n};if(s.type!=="ObjectExpression")return n.push({code:"page-seo.dynamic-declaration",message:"PAGE_SEO is not a static object literal"}),{found:!1,seo:null,diagnostics:n};let a={};for(let l of Ci(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=kf(l.key);if(!(d!=="path"&&d!=="title"&&d!=="description"&&d!=="keywords"&&d!=="meta_tags_json"&&d!=="schema_json"&&d!=="breadcrumbs_json")){if(d==="path"||d==="title"||d==="description"||d==="keywords"){let f=Ev(l.value);if(f===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static string; skipped`});continue}a[d]=f;continue}try{let f=Va(l.value);d==="meta_tags_json"&&f!==null&&typeof f=="object"&&!Array.isArray(f)?a.meta_tags_json=f:d==="schema_json"&&f!==null&&typeof f=="object"?a.schema_json=f:d==="breadcrumbs_json"&&Array.isArray(f)?a.breadcrumbs_json=f:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} has unsupported static shape; skipped`})}catch(f){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${d} is not a static JSON-like value; skipped: ${f instanceof Error?f.message:String(f)}`})}}}let c=r;return a.path!==void 0&&(a.path!==r&&n.push({code:"page-seo.path-mismatch",message:`PAGE_SEO.path "${a.path}" != derived "${r}"; using PAGE_SEO.path`}),c=a.path),{found:!0,seo:{path:c,...a.title!==void 0?{title:a.title}:{},...a.description!==void 0?{description:a.description}:{},...a.keywords!==void 0?{keywords:a.keywords}:{},...a.meta_tags_json!==void 0?{meta_tags_json:a.meta_tags_json}:{},...a.schema_json!==void 0?{schema_json:a.schema_json}:{},...a.breadcrumbs_json!==void 0?{breadcrumbs_json:a.breadcrumbs_json}:{}},diagnostics:n}}import{parse as kv}from"@babel/parser";var If=["page","anchor","external","email","phone","group","file"],Iv=["link","cta"],Rf=["description","badge","iconKey"],Ua=["label","targetType","href","role","openInNewTab","nofollow","children",...Rf],Cv=new Set(Ua);function Vr(e){return Array.isArray(e)?e:[]}function jr(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Rv(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Cf(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ja(e){let t=[],n;try{n=kv(e,{sourceType:"module",plugins:["typescript","jsx"]})}catch(i){return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:`parse failed: ${String(i)}`}]}}let r;for(let i of Vr(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Vr(s.declarations)){let c=a.id;c?.type==="Identifier"&&c.name==="NAV_ITEMS"&&(r=a.init)}}for(;r&&(r.type==="TSAsExpression"||r.type==="TSSatisfiesExpression"||r.type==="TSInstantiationExpression");)r=r.expression;if(!r||r.type!=="ArrayExpression")return{items:[],diagnostics:[{severity:"fatal",path:"NAV_ITEMS",message:"missing top-level NAV_ITEMS array literal"}]};let o=[];return Vr(r.elements).forEach((i,s)=>{let a=Nf(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Nf(e,t,n){if(e?.type!=="ObjectExpression")return n.push({severity:"fatal",path:t,message:"nav item must be an object literal"}),null;let r={};for(let l of Vr(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let d=Rv(l.key);d&&(r[d]=l.value)}let o=jr(r.label),i=jr(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!If.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${If.join("/")}`}),null;r.group!==void 0&&n.push({severity:"warning",code:"leaf-group-field",path:`${t}.group`,message:'unsupported leaf group field ignored; use a canonical targetType: "group" node with children'});let s={label:o,targetType:i};for(let l of Rf){if(r[l]===void 0)continue;let d=jr(r[l]);d!==void 0?s[l]=d:n.push({severity:"warning",path:`${t}.${l}`,message:`${l} ignored: not a static string`})}r.icon!==void 0&&n.push({severity:"warning",path:`${t}.icon`,message:"icon component ref ignored; use static iconKey"});for(let l of Object.keys(r))Cv.has(l)||l==="group"||l==="icon"||n.push({severity:"warning",code:"unknown-field",path:`${t}.${l}`,message:`unsupported field \`${l}\` ignored; NAV_ITEMS only carries ${Ua.join("/")}`});if(r.children!==void 0){if(r.children.type!=="ArrayExpression")return n.push({severity:"fatal",path:`${t}.children`,message:"children must be a static array"}),null;let l=[];Vr(r.children.elements).forEach((d,f)=>{let m=Nf(d,`${t}.children[${f}]`,n);m&&l.push(m)}),s.children=l}if(i==="group")return s.children?s:(n.push({severity:"fatal",path:`${t}.children`,message:"group item requires children"}),null);let a=jr(r.href);if(!a)return n.push({severity:"fatal",path:`${t}.href`,message:"href must be a static string for non-group item"}),null;s.href=a;let c=jr(r.role);if(c!==void 0&&(Iv.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Cf(r.openInNewTab);l!==void 0?s.openInNewTab=l:n.push({severity:"warning",path:`${t}.openInNewTab`,message:"openInNewTab ignored: not a static boolean"})}if(r.nofollow!==void 0){let l=Cf(r.nofollow);l!==void 0?s.nofollow=l:n.push({severity:"warning",path:`${t}.nofollow`,message:"nofollow ignored: not a static boolean"})}return s}import{parse as Nv}from"@babel/parser";function Kr(e){return Array.isArray(e)?e:[]}function wf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function wv(e){let t;try{t=Nv(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Kr(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Kr(i.declarations)){let a=s.id;a?.type==="Identifier"&&a.name==="NAV_ITEMS"&&n.push(s)}}if(n.length===0)return{status:"navigation_not_found"};if(n.length!==1)return{status:"unsupported"};let r=wf(n[0]?.init);return!r||typeof r.start!="number"||typeof r.end!="number"?{status:"unsupported"}:{status:"ok",array:r,start:r.start,end:r.end}}function Xa(e,t){let n=Pf(t);if(!n)return{status:"unsupported",source:e};let r=wv(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ja(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let d=Kr(l.elements);for(let[f,m]of d.entries()){if(Av(m,n)){let g=d[f+1],h=d[f-1],b=m.start,E=m.end;if(typeof b!="number"||typeof E!="number")continue;if(g&&typeof g.start=="number")s.push({start:b,end:g.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let v=/^\s*,/.exec(e.slice(E));s.push({start:b,end:v?E+v[0].length:E})}continue}let u=Pv(m);u&&a(u)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((d,f)=>f.start-d.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Pv(e){if(e.type==="ObjectExpression")for(let t of Kr(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return wf(t.value)}}function Pf(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Av(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Kr(e.properties)){if(o.type!=="ObjectProperty")continue;let i=o.key,s=o.value,a=i?.name??i?.value;s?.type==="StringLiteral"&&(a==="href"&&(n=String(s.value)),a==="targetType"&&(r=String(s.value)))}return r==="page"&&Pf(n??"")===t}import{estimateNavLabelWidth as JF}from"@vcp-dev/contracts";import{parse as WF}from"@babel/parser";var Fv="components/site/generated/",Ur=[".tsx",".ts",".jsx",".js"];function Af(e){if(e.expectedUrlPath===Tv)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Lr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,b])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let v=Ka(b,E);return v.found&&v.seo?.path===e.expectedUrlPath});if(n.length===0)return{ok:!1,code:"ROUTE_NOT_FOUND",message:"No route uniquely matches the requested page identity."};if(n.length>1)return{ok:!1,code:"ROUTE_AMBIGUOUS",message:"Multiple routes match the requested page identity."};let[r]=n[0],o=new Set([r]);try{let h=ki({files:new Map(Object.entries(e.files))});for(let b of h)b.canonicalEntryFile===r&&o.add(b.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=_v(e.files);if(!i.ok)return i.error;let s=i.graph,a=Lv(o,s),c=Bv(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,b)=>h.localeCompare(b)),d=[...o,...[...c].sort((h,b)=>h.localeCompare(b))],f=new Set(d),m=d.map(h=>({operation:"delete",file:h})),u=[],g=[];for(let[h,b]of Object.entries(e.files))if(!f.has(h)){if(b.includes("NAV_ITEMS")){let E=Xa(b,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),u.push(h)):E.status==="unsupported"&&g.push(`unsupported_navigation:${h}`)}b.includes(e.expectedUrlPath)&&!b.includes("NAV_ITEMS")&&g.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:d,updatedFiles:u,preservedSharedFiles:l,warnings:g}}function _v(e){let t=new Set(Object.keys(e)),n=new Map;for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/");if(i==="next-env.d.ts"||i.endsWith("/next-env.d.ts")||!Ov(r))continue;let s=yn(r,o);if(!s.ok)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} (parse-failed).`}};let a=new Set;for(let{specifier:c}of s.module.imports){if(Mv(c))continue;let l=pn(r,c),d=Dv(l,t);if(!d)return{ok:!1,error:{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:`Page source dependencies could not be proven safe: ${r} -> ${c} (import-not-found).`}};a.add(d)}n.set(r,a)}return{ok:!0,graph:n}}function Ov(e){let t=e.toLowerCase();return Ur.some(n=>t.endsWith(n))}function Mv(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Ur.some(n=>e.endsWith(n)))}function Dv(e,t){let n=e.replace(/\\/g,"/");return(Ur.some(o=>n.endsWith(o))?[n]:[...Ur.map(o=>`${n}${o}`),...Ur.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Lv(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Fv)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Bv(e,t,n){let r=new Set(t),o=!0;for(;o;){o=!1;for(let i of[...r])[...n].some(([a,c])=>!e.has(a)&&!r.has(a)&&c.has(i))&&(r.delete(i),o=!0)}return r}import*as Pp from"@babel/parser";import*as de from"@babel/types";import*as Ki from"node:path";import*as ye from"@babel/types";function Tf(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Ot(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Nn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ye.isObjectPattern(n)||ye.isArrayPattern(n))return Nn(n,e.identifier.name)}if(!e.path.isIdentifier())return!1;let t=e.path.parentPath;for(;t;){if(t.isAssignmentPattern()){let n=t.get("left");if(jv(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Nn(e,t,n=!1){return ye.isIdentifier(e)?e.name===t&&n:ye.isObjectPattern(e)?e.properties.some(r=>ye.isObjectProperty(r)?Nn(r.value,t,n):Nn(r.argument,t,n)):ye.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ye.isRestElement(r)?r.argument:r;return Nn(o,t,n)}):ye.isAssignmentPattern(e)?Nn(e.left,t,!0):ye.isRestElement(e)?Nn(e.argument,t,n):!1}function nr(e,t){if(e.path.isObjectPattern()){if(t){let r=kt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Ot(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Ot(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Ff(r),i=!1,s=o?o.initBinding&&za(o.initBinding)?(i=Ot(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=nr(o.initBinding,{kind:"identifier",expression:o.initBinding.identifier.name,base:o.initBinding.identifier.name,path:[]});return i=c?.hasDefault??!1,c?[{kind:"property",name:c.propName},...c.remainingPath,...o.initPathPrefix]:null})():null:null,a=kt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...d]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...d,...t?.path??[]],hasDefault:i||Ot(e)}}}}let n=Uv(e);if(n){let r=$v(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Ot(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=Vv(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Ot(e)}}let i=Jr(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Ot(e)}:null}if(za(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Ot(e)}}return null}function $v(e,t){let n=e.findParent(d=>d.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Ff(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=za(i)?(a=Ot(i),[...s]):(()=>{let d=nr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=d?.hasDefault??!1,d?[{kind:"property",name:d.propName},...d.remainingPath,...s]:null})();if(!c)return null;let l=kt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Ot(t)}:null}function Ff(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=Jv(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function za(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function jv(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Vv(e){let t=e.identifier.name,n=e.path.getFunctionParent();if(!n)return null;let r=n.get("params"),o=Array.isArray(r)?r:[r];for(let i of o){let a=kt(i.node,t);if(a)return a}return null}function _f(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Ri(a,e.identifier.name);if(c&&(!n||c.propName===n))return{propName:c.propName,componentName:t,expressionPath:c.expressionPath,displayPath:`${t}.${c.propName}.default`}}}if(e.path.isObjectPattern())for(let a of e.path.get("properties")){if(!a.isObjectProperty())continue;let c=Jr(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let d=l.get("right");if(d.isExpression())return{propName:c,componentName:t,expressionPath:d,displayPath:`${t}.${c}.default`}}let r=Kv(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Jr(o.node);if(!i||n&&i!==n)return null;let s=r.get("right");return s.isExpression()?{propName:i,componentName:t,expressionPath:s,displayPath:`${t}.${i}.default`}:null}function Ri(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Jr(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&kt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Ri(o,t);if(i)return i}}else if(n.isRestElement()){let r=n.get("argument");if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Ri(r,t);if(o)return o}}}if(e.isArrayPattern())for(let n of e.get("elements")){if(!n)continue;let r=n.isRestElement()&&!Array.isArray(n.get("argument"))?n.get("argument"):n;if(!Array.isArray(r)&&(r.isObjectPattern()||r.isArrayPattern())){let o=Ri(r,t);if(o)return o}}return null}function kt(e,t,n=[]){if(ye.isIdentifier(e))return e.name===t?n:null;if(ye.isObjectPattern(e)){for(let r of e.properties)if(ye.isObjectProperty(r)){let o=Jr(r);if(!o)continue;let i=kt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ye.isRestElement(r)){let o=kt(r.argument,t,n);if(o)return o}}if(ye.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ye.isRestElement(o)?o.argument:o,s=kt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ye.isAssignmentPattern(e)?kt(e.left,t,n):null}function Kv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function Uv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;if(t?.isObjectProperty()&&t.parentPath?.isObjectPattern())return t;let n=t?.isAssignmentPattern()?t.parentPath:null;return n?.isObjectProperty()&&n.parentPath?.isObjectPattern()?n:null}function Jr(e){return e.computed?null:ye.isIdentifier(e.key)?e.key.name:ye.isStringLiteral(e.key)?e.key.value:null}function Jv(e){let t=[],n=e;for(;ye.isMemberExpression(n);){if(n.computed)if(ye.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ye.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ye.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ye.isIdentifier(n)?{base:n.name,path:t}:null}import*as Bf from"@babel/parser";import Ga from"@babel/traverse";import*as rr from"@babel/types";import*as ae from"@babel/types";function Pi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Ni(n,t):null}if(e.isMemberExpression()){let n=Yv(e.node),r=Xv(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Ni(o,[...r,...t]):null}return e.isAwaitExpression()||Ha(e.node)?rn(Qv(e.node),t,"awaited or fetched expression"):null}function Xv(e){let t=[],n=e;for(;ae.isMemberExpression(n);){if(n.computed)if(ae.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ae.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ae.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ae.isIdentifier(n)?t:null}function Ni(e,t=[]){let n=zv(e,t);if(n)return n;let r=Wv(e,t);if(r)return r;let o=Hv(e,t);return o||null}function zr(e){return e?.kind==="api-source"}function zv(e,t){if(e.path.isVariableDeclarator()&&ae.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Wa(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return rn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&ae.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>ae.isObjectProperty(c)&&Df(c)==="data"&&Xr(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Wa(a.node))return rn(e.identifier.name,t,"query hook data binding")}let n=Gv(e);if(!n||Df(n.node)!=="data")return null;let o=n.findParent(s=>s.isVariableDeclarator());if(!o?.isVariableDeclarator())return null;let i=o.get("init");return!i?.isCallExpression()||!Wa(i.node)?null:rn(e.identifier.name,t,"query hook data binding")}function Wv(e,t){if(e.path.isVariableDeclarator()&&ae.isArrayPattern(e.path.node.id)){let a=e.path.get("init");if(!a?.isCallExpression()||!Mf(a.node))return null;let[c,l]=e.path.node.id.elements;return!ae.isIdentifier(c)||c.name!==e.identifier.name||!ae.isIdentifier(l)?null:Of(e,l.name)?rn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let n=e.path.parentPath;if(!n?.isArrayPattern())return null;let r=n.parentPath;if(!r?.isVariableDeclarator())return null;let o=r.get("init");if(!o?.isCallExpression()||!Mf(o.node)||n.node.elements.findIndex(a=>a===e.path.node)!==0)return null;let s=n.node.elements[1];return ae.isIdentifier(s)&&Of(e,s.name)?rn(e.identifier.name,t,"state setter is updated by API data"):null}function Hv(e,t){let n=e.path.isVariableDeclarator()?e.path:e.path.findParent(o=>o.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");return r?.isExpression()?r.isAwaitExpression()?rn(e.identifier.name,t,"awaited binding result"):Ha(r.node)?rn(e.identifier.name,t,"fetch-backed binding result"):null:null}function Gv(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isObjectProperty()?t:t?.isAssignmentPattern()&&t.parentPath?.isObjectProperty()?t.parentPath:null}function Xr(e,t){return ae.isIdentifier(e)?e.name===t:ae.isAssignmentPattern(e)?Xr(e.left,t):ae.isObjectPattern(e)?e.properties.some(n=>ae.isObjectProperty(n)?Xr(n.value,t):Xr(n.argument,t)):ae.isArrayPattern(e)?e.elements.some(n=>!!n&&Xr(ae.isRestElement(n)?n.argument:n,t)):!1}function Of(e,t){let n=!1,r=!1;return e.scope.path.traverse({CallExpression(i){Ha(i.node)&&(n=!0),(Zv(i.node.callee,t)||i.node.arguments.some(s=>ae.isIdentifier(s)&&s.name===t))&&(r=!0)}}),n&&r}function Wa(e){let t=Ai(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Mf(e){return Ai(e.callee)==="useState"}function Ha(e){return wi(e,t=>ae.isCallExpression(t)&&Ai(t.callee)==="fetch")}function Yv(e){let t=e;for(;ae.isMemberExpression(t);)t=t.object;return ae.isIdentifier(t)?t.name:null}function Df(e){return e.computed?null:ae.isIdentifier(e.key)?e.key.name:ae.isStringLiteral(e.key)?e.key.value:null}function Ai(e){return ae.isIdentifier(e)?e.name:ae.isMemberExpression(e)&&ae.isIdentifier(e.property)?e.property.name:null}function Zv(e,t){return wi(e,n=>ae.isIdentifier(n)&&n.name===t)}function wi(e,t){if(t(e))return!0;let n=ae.VISITOR_KEYS[e.type];if(!n)return!1;for(let r of n){let o=e[r];if(Array.isArray(o)){for(let i of o)if(ae.isNode(i)&&wi(i,t))return!0;continue}if(ae.isNode(o)&&wi(o,t))return!0}return!1}function Qv(e){return ae.isIdentifier(e)?e.name:ae.isCallExpression(e)?Ai(e.callee)??"api":ae.isAwaitExpression(e)?"awaited-api":"api"}function rn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:qv(e,t),reason:n}}function qv(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var $f=typeof Ga=="function"?Ga:Ga.default;function jf(e,t){let n=Kf(e);if(!n)return{allowed:!0};let r=!1;return $f(n,{CallExpression(o){if(!Uf(o.node,t.sourceRange)||!ek(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||zr(Pi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Vf(e,t){let n=Kf(e);if(!n)return{allowed:!0};let r=!1;return $f(n,{JSXExpressionContainer(o){Uf(o.node,t.sourceRange)&&(rr.isJSXEmptyExpression(o.node.expression)||(r=!0,o.stop()))}}),r?{allowed:!1,reason:"Cannot move subtree across files because it depends on local binding expressions"}:{allowed:!0}}function Kf(e){try{return Bf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ek(e){let t=e.callee;return rr.isMemberExpression(t)&&rr.isIdentifier(t.property)&&t.property.name==="map"}function Uf(e,t){let n=e.loc;return n?Lf({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Lf({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Lf(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}import*as X from"@babel/types";import*as Jf from"@babel/parser";import Ya from"@babel/traverse";import*as Pe from"@babel/types";import*as or from"node:path";var It=typeof Ya=="function"?Ya:Ya.default;function Ke(e){try{return Jf.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Za(e){return e.computed?Pe.isStringLiteral(e.key)||Pe.isNumericLiteral(e.key)?String(e.key.value):null:tk(e.key)}function tk(e){return Pe.isIdentifier(e)?e.name:Pe.isStringLiteral(e)||Pe.isNumericLiteral(e)?String(e.value):null}function wn(e){return Pe.isParenthesizedExpression(e)||Pe.isTSAsExpression(e)||Pe.isTSSatisfiesExpression(e)||Pe.isTSNonNullExpression(e)||Pe.isTSTypeAssertion(e)?wn(e.expression):Pe.isExpression(e)?e:null}function Qa(e){if(Pe.isIdentifier(e))return[e.name];if((Pe.isMemberExpression(e)||Pe.isOptionalMemberExpression(e))&&!e.computed&&Pe.isIdentifier(e.property)){let t=wn(e.object),n=t?Qa(t):null;return n?[...n,e.property.name]:null}return null}function Pn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?or.normalize(or.join(or.dirname(e),t)).replace(/\\/g,"/"):t}function rt(e,t){return Ti(e)===Ti(t)}function Ti(e){let t=ir(e);return t.endsWith("/index")?t.slice(0,-6):t}function ir(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Wf(e,t,n){let r=Zf(e,t);if(Qf(e,r),qf(e,r))return{ok:!1,reason:"Cannot move prop-backed repeat child because the component is referenced through an unsupported value usage"};let o=[];return It(e,{JSXElement(s){rp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Fi(o[0])!==n?{ok:!1,reason:"Cannot move prop-backed repeat child because the call site is outside the target component"}:{ok:!0,path:o[0]}}function Hf(e,t){let n=new Map,r=i=>{let s=sr(i);return n.has(s)?!1:(n.set(s,i),!0)};r(t);let o=!0;for(;o;){o=!1;for(let i of e)for(let s of nk(i,n))o=r(s)||o}return[...n.values()]}function nk(e,t){let n=[],r=rk(e,t);for(let o of e.ast.program.body){if(X.isExportDefaultDeclaration(o)&&X.isIdentifier(o.declaration)&&(r.get(o.declaration.name)?.length??0)>0){let i=r.get(o.declaration.name)??[];for(let s of i){if(s.namespace){let a=Wr(s.namespace,o.declaration.name,"default");a&&n.push({file:e.file,namespace:a,exportName:s.exportName});continue}n.push({file:e.file,exportName:"default"})}continue}if(X.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Pn(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=on(s.exported);for(let d of t.values())rt(d.file,i)&&n.push({file:e.file,namespace:qa(l,d.namespace),exportName:d.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=on(s.local),c=[...t.values()].filter(l=>rt(l.file,i)&&An(l.namespace,a));if(c.length>0){let l=on(s.exported);for(let d of c){let f=Wr(d.namespace,a,l);f&&n.push({file:e.file,namespace:f,exportName:d.exportName})}continue}t.has(sr({file:i,exportName:a}))&&n.push({file:e.file,exportName:on(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=on(i.local),a=r.get(s)??[];if(a.length>0){let c=on(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let d=Wr(l.namespace,s,c);d&&n.push({file:e.file,namespace:d,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Pn(e.file,o.source.value),s=o.exported;if(s){let a=on(s);for(let c of t.values())rt(c.file,i)&&n.push({file:e.file,namespace:qa(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())rt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function qa(e,t){return t?`${e}.${t}`:e}function An(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Wr(e,t,n){return!An(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function rk(e,t){let n=new Map,r=(i,s)=>{let a=n.get(i)??[];a.push(s),n.set(i,a)};for(let i of e.ast.program.body){if(!X.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Pn(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(sr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(d=>rt(d.file,s)&&An(d.namespace,"default"));for(let d of l){let f=Wr(d.namespace,"default",a.local.name);f&&r(a.local.name,{...d,namespace:f})}continue}if(X.isImportSpecifier(a)){let c=on(a.imported),l=[...t.values()].filter(f=>rt(f.file,s)&&An(f.namespace,c));for(let f of l)r(a.local.name,f);let d=t.get(sr({file:s,exportName:c}));d&&r(a.local.name,d);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())rt(c.file,s)&&r(a.local.name,{...c,namespace:qa(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(X.isVariableDeclaration(i))for(let s of i.declarations){if(!X.isIdentifier(s.id)||!s.init)continue;let a=wn(s.init);if(!a||!X.isIdentifier(a))continue;let c=n.get(a.name)??[];if(c.length===0)continue;let l=n.get(s.id.name)??[],d=new Set(l.map(sr));for(let f of c){let m=Wr(f.namespace,a.name,s.id.name),u=m?{...f,namespace:m}:f,g=sr(u);d.has(g)||(r(s.id.name,u),d.add(g),o=!0)}}}return n}function sr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Ti(e.file)}#${t}`}function on(e){return X.isIdentifier(e)?e.name:e.value}function Gf(e,t){for(let n of e.program.body){if(X.isExportDefaultDeclaration(n)){let o=n.declaration;if((X.isFunctionDeclaration(o)||X.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(X.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!X.isExportNamedDeclaration(n))continue;let r=n.declaration;if((X.isFunctionDeclaration(r)||X.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(X.isVariableDeclaration(r)){for(let o of r.declarations)if(X.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!X.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:X.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function tc(e){let t=ok(e),n=[],r=qf(e.ast,t);return It(e.ast,{JSXElement(o){rt(e.file,e.sourceFile)&&Fi(o)===e.sourceComponent||rp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Yf(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Zf(e,t){let n=Yf();return It(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function ok(e){let t=Yf();return rt(e.file,e.sourceFile)&&ik(t,Zf(e.ast,e.sourceComponent)),It(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Pn(e.file,o),s=e.componentIdentities.filter(a=>rt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(X.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),X.isImportDefaultSpecifier(a)){let l=s.filter(d=>An(d.namespace,"default"));if(l.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of l){let m=zf(f,"default");m&&d.add(m)}t.namespaceMembers.set(c,d)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,d=s.filter(f=>An(f.namespace,l));if(d.length>0){let f=t.namespaceMembers.get(c)??new Set;for(let m of d){let u=zf(m,l);u&&f.add(u)}t.namespaceMembers.set(c,f);continue}s.some(f=>!f.namespace&&f.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let d=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,f=t.namespaceMembers.get(c)??new Set;f.add(d),t.namespaceMembers.set(c,f)}}}}}),Qf(e.ast,t),t}function ik(e,t){e.hasUnsupportedAlias||=t.hasUnsupportedAlias;for(let n of t.localBindings)e.localBindings.add(n);for(let[n,r]of t.namespaceMembers){let o=e.namespaceMembers.get(n)??new Set;for(let i of r)o.add(i);e.namespaceMembers.set(n,o)}}function Qf(e,t){It(e,{VariableDeclarator(n){if(!n.node.init)return;let r=wn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=Tn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&ec(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=Tn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&np(n.node.id,o.namespaceMembers,t,n)}}}})}function qf(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return It(e,{ReferencedIdentifier(r){if(n){r.stop();return}sk(r)||!r.isIdentifier()||!ep(r,t)||ak(r,t)||ck(r)||(n=!0,r.stop())}}),n}function sk(e){let t=e;for(;t.parentPath?.isJSXMemberExpression();)t=t.parentPath;let n=t.parentPath;return!!(n?.isJSXOpeningElement()&&n.node.name===t.node||n?.isJSXClosingElement()&&n.node.name===t.node)}function ep(e,t){let n=e.scope.getBinding(e.node.name);if(!n)return null;let r=e;for(;r.parentPath?.isMemberExpression()&&r.parentPath.node.object===r.node&&!r.parentPath.node.computed;)r=r.parentPath;return t.localBindings.has(n)||t.namespaceMembers.has(n)&&Tn(r.node,t,r)?r:null}function ak(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Xf(e,r))return!1;let o=ep(e,t);if(!o)return!1;if(wn(r.node)===o.node)return!!Tn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Xf(e,a)&&!!Tn(a.node,t,a)}function ck(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Xf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Tn(e,t,n){let r=wn(e);if(!r)return null;if(X.isIdentifier(r)){let a=n.scope.getBinding(r.name);if(!a)return null;let c=t.namespaceMembers.get(a);return t.localBindings.has(a)?{local:!0,namespaceMembers:new Set,unsupported:!1}:c?{local:!1,namespaceMembers:new Set(c),unsupported:!1}:null}if(X.isObjectExpression(r))return lk(r,t,n);let o=Qa(r);if(!o||o.length===0)return null;let i=n.scope.getBinding(o[0]);if(!i)return null;let s=t.namespaceMembers.get(i);return s?tp(s,o.slice(1).join(".")):null}function lk(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Za(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=Tn(i.value,t,n)!==null);continue}let a=Tn(i.value,t,n);if(a){o||=a.unsupported,a.local&&r.add(s);for(let c of a.namespaceMembers)r.add(`${s}.${c}`)}}return r.size>0||o?{local:!1,namespaceMembers:r,unsupported:o}:null}function tp(e,t){if(!t)return{local:!1,namespaceMembers:new Set(e),unsupported:!1};let n=new Set,r=!1;for(let o of e){if(o===t){r=!0;continue}o.startsWith(`${t}.`)&&n.add(o.slice(t.length+1))}return r||n.size>0?{local:r,namespaceMembers:n,unsupported:!1}:null}function ec(e,t,n){if(e.hasUnsupportedAlias||=n.unsupported,n.local&&e.localBindings.add(t),n.namespaceMembers.size>0){let r=e.namespaceMembers.get(t)??new Set;for(let o of n.namespaceMembers)r.add(o);e.namespaceMembers.set(t,r)}}function np(e,t,n,r){for(let o of e.properties){if(X.isRestElement(o)){if(X.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&ec(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Za(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=tp(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=X.isAssignmentPattern(o.value)?o.value.left:o.value;if(X.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&ec(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){np(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function zf(e,t){if(!An(e.namespace,t))return null;if(e.namespace===t)return e.exportName;let n=e.namespace?.slice(t.length+1);return n?`${n}.${e.exportName}`:e.exportName}function rp(e,t){let n=e.node.openingElement.name;if(X.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=op(n);if(r&&r.length>1){let o=e.scope.getBinding(r[0]);return o?t.namespaceMembers.get(o)?.has(r.slice(1).join("."))===!0:!1}return!1}function op(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=op(e.object);return t?[...t,e.property.name]:null}return null}function Fi(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration())return t.node.id?.name??null;if(t.isArrowFunctionExpression()||t.isFunctionExpression()){let n=t.parentPath;if(n?.isVariableDeclarator()&&X.isIdentifier(n.node.id))return n.node.id.name}return null}function ip(e,t){let n=Ke(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=tc({ast:n,file:t.file,sourceFile:t.file,sourceComponent:t.tag,componentIdentities:[{file:t.importedFrom,exportName:t.exportName}]});return r.hasUnsafeReference?Number.POSITIVE_INFINITY:r.callSites.length}function he(e){return e.structuralPath.includes("#repeat:")||e.isRepeatItemRoot||e.isRepeatRegion?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function pe(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Mt(e,t){let n=pe(e);return!!(n&&ot(t,n))}function ot(e,t){return t.start>=e.start&&t.end<=e.end}function xt(e,t){let n=se(e,he(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:_i(e,t)}function ar(e,t){let n=pe(t);return n?e.slice(n.start,n.end):""}function sp(e,t){return e.start===t.start&&e.end===t.end}function _i(e,t){let n=null;return It(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.sourceRange.startLine&&o.start.column===t.sourceRange.startColumn&&o.end.line===t.sourceRange.endLine&&o.end.column===t.sourceRange.endColumn&&(n=r,r.stop())}}),n}function Oi(e,t){return nc(e,t).length>0}function Mi(e,t){let n=pe(e.node),r=pe(t.node);if(!n||!r)return!1;let o=e.parentPath;for(;o;){if((o.isIfStatement()||o.isSwitchCase())&&(!!!t.findParent(s=>s.node===o?.node)||o.isIfStatement()&&!uk(o,n,r)))return!0;o=o.parentPath}return!1}function uk(e,t,n){let r=pe(e.node.consequent);if(r&&ot(r,t)&&!ot(r,n))return!1;let o=e.node.alternate?pe(e.node.alternate):null;return!(o&&ot(o,t)&&!ot(o,n))}function nc(e,t){let n=pe(e.node);if(!n)return[];let r=[],o=e.parentPath;for(;o;){let i=!!t.findParent(s=>s.node===o?.node);if(!i&&o.isConditionalExpression()){let s=pe(o.node.consequent),a=pe(o.node.alternate);s&&n.start>=s.start&&n.end<=s.end?r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"consequent"}):a&&n.start>=a.start&&n.end<=a.end&&r.push({kind:"conditional",path:o,conditionPath:o.get("test"),branch:"alternate"})}else if(!i&&o.isLogicalExpression()&&rc(o.node.operator)){let s=pe(o.node.right);s&&n.start>=s.start&&n.end<=s.end&&r.push({kind:"logical",path:o,conditionPath:o.get("left"),operator:o.node.operator})}o=o.parentPath}return r}function rc(e){return e==="&&"||e==="||"||e==="??"}function ap(e,t){let n=pe(e.consequent);if(n&&ot(n,t))return n;let r=pe(e.alternate);return r&&ot(r,t)?r:null}function cp(e){if(!e.knownSourceFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without project-wide source visibility"};if(!e.routeEntryFiles)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without registered route visibility"};let t=new Set(e.knownSourceFiles.map(a=>ir(a.file)));if(!t.has(ir(e.sourceFile))||!t.has(ir(e.targetFile)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without source and target file visibility"};for(let a of e.routeEntryFiles)if(!t.has(ir(a)))return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component until all registered route entries are loaded"};let n=Gf(e.sourceAst,e.sourceComponent);if(!n)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without an exported source component identity"};let r=[];for(let a of e.knownSourceFiles){let c=Ke(a.content);if(!c)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because a loaded source file cannot be parsed"};r.push({file:a.file,ast:c})}let o=Hf(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=tc({ast:a.ast,file:a.file,sourceFile:e.sourceFile,sourceComponent:e.sourceComponent,componentIdentities:o});if(c.hasUnsafeReference)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the component has unsupported value usages"};i.push(...c.callSites)}if(i.length!==1)return{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component without a single project-wide component call site"};let[s]=i;return!rt(s.file,e.targetFile)||Fi(s.path)!==e.targetComponent?{ok:!1,reason:"Cannot move repeat-backed child out of a cross-file component because the only call site is outside the target component"}:{ok:!0,callSitePath:s.path}}import{SiteEditSetPropsParamsSchema as hk}from"@vcp-dev/contracts";function Di(e){let{state:t,scope:n,operation:r,selectionRef:o,repeatTarget:i}=e;if(!t||t.status==="blocked")return{ok:!1,code:"readonly-property",reason:t?.diagnostic?.message??"No safe property write target is available"};if(t.status==="binding"){let s=t.target;if(s?.kind!=="value-binding"||!s.target.locator||n!=="selection"||r!=="set")return Hr();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Hr();let d=dk(a,l,o?.instanceCount);if(!d)return Hr();c=d}return{ok:!0,target:{kind:"value-binding",file:a.file,locator:c}}}return o?.instanceIndex!==void 0?n!=="selection"||!i?.ok?{ok:!1,code:"repeat-target-failed",reason:i&&!i.ok?i.reason:"No safe selected repeat property target is available"}:{ok:!0,target:{kind:"repeat-property",target:i}}:e.isRepeat&&n!=="template"||t.status==="direct"&&t.target?.kind!=="jsx-attribute"?Hr():{ok:!0,target:{kind:"jsx-attribute"}}}function Hr(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function dk(e,t,n){if(!e.locator||!Number.isInteger(t)||t<0)return null;let r=e.collectionPathMap?.length??e.collectionIndexMap?.length;if(r!==void 0&&(t>=r||n!==void 0&&n!==r))return null;let o=e.collectionPathMap?.[t];if(o)return{...e.locator,path:o};let i=e.locator.path??[],s=i.findLastIndex(c=>c.kind==="index");if(s<0)return null;let a=i.map((c,l)=>l===s&&c.kind==="index"?{kind:"index",index:e.collectionIndexMap?.[t]??t}:c);return{...e.locator,path:a}}import*as Dt from"@babel/types";import{SiteEditSetPropsParamsSchema as fk}from"@vcp-dev/contracts";function lp(e){let t=e.changes??(e.change?[e.change]:[]);if(!fk.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Gr("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Gr("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=we(e.source,"value");if(!o.ok)return Gr("invalid-target","Repeat property source could not be parsed");let i=[{type:"set-property-binding",order:0,file:e.target.templateFile,locator:e.target.targetElementLocator,name:r.name,object:e.target.callbackItemName,property:r.name}];for(let[s,a]of e.target.parentObjectLocators.entries()){let c=se(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Gr("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?pk(r):mk(c.match.path.node,r.name);if(!l)return Gr("unsupported-property-value",`Repeat item ${s} has an unsupported value for '${r.name}'`);i.push({type:"upsert-object-property",order:i.length,file:e.target.sourceFile,locator:a,name:r.name,value:l})}return{ok:!0,steps:i}}function pk(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function mk(e,t){let n=e.properties.filter(i=>Dt.isObjectProperty(i)&&gk(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Dt.isExpression(r.value))return null;let o=_t(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function gk(e){return Dt.isIdentifier(e)?e.name:Dt.isStringLiteral(e)?e.value:Dt.isNumericLiteral(e)?String(e.value):null}function Gr(e,t){return{ok:!1,errorCode:e,reason:t}}function up(e){if(e.change.name!=="className"&&e.change.name!=="class")return Yr("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Yr("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Yr("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Yr("owner-source-dynamic","Dynamic className expressions are not writable by the generic property owner");if(e.change.operation==="set"&&typeof e.change.value!="string")return Yr("owner-value-invalid","The className owner accepts only string values");if(e.change.operation==="remove"&&t.sourceKind==="missing")return{ok:!0,steps:[]};let n=t.sourceKind==="missing",r=e.change.operation==="set"?`className=${JSON.stringify(e.change.value)}`:null,o=e.change.operation==="remove"?"remove-attribute":n?"create-attribute":"replace-static-classname";return{ok:!0,steps:[{type:"set-class-name-source",order:0,file:e.node.file,request:{kind:"set-class-name-source",key:e.node.key,filePath:e.node.file,expectedVersion:t.version,oldAttrRaw:t.attrRaw,oldAttrRange:t.attrRange,openingElementRange:t.openingElementRange,newAttrRaw:r,intent:{source:"style-panel",operation:o}}}]}}function Yr(e,t){return{ok:!1,errorCode:e,reason:t}}async function fp(e){let t=hk.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return Fn("invalid-change","Typed property changes are invalid");let n=[];for(let r of t.data.changes){let o=await yk(e,r);if(o){if(!o.ok)return Fn("owner-plan-failed",o.reason);dp(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return Fn("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return Fn("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(Sk(i,r)||r.operation==="remove"&&i.status==="missing")continue;let s=e.selectionRef?.instanceIndex!==void 0&&i.status!=="binding"?await e.getRepeatPropertyTarget?.(e.node.key,r.name,e.selectionRef):void 0,a=Di({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return Fn(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){oc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=lp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return Fn("repeat-target-failed",l.reason);dp(n,l.steps);continue}oc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:xk(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),bk(n)?Fn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function yk(e,t){return t.name!=="className"&&t.name!=="class"?null:up({node:e.node,change:t,classNameSource:e.classNameSource})}function xk(e){return e.structuralPath.includes("#repeat:")||e.key.includes("::repeat-item#")?{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange}:{kind:"jsx-node",strategy:"structural-path",file:e.file,component:e.component,structuralPath:e.structuralPath,expectedRange:e.sourceRange}}function bk(e){let t=new Set;for(let n of e){let{order:r,...o}=n,i=`${n.file}:${n.type}:${JSON.stringify(o)}`;if(t.has(i))return!0;t.add(i)}return!1}function dp(e,t){for(let n of t)oc(e,{...n,order:e.length})}function oc(e,t){if(t.type==="set-property-changes"){let n=e.find(r=>r.type==="set-property-changes"&&r.file===t.file&&JSON.stringify(r.locator)===JSON.stringify(t.locator)&&r.scope===t.scope);if(n){n.changes.push(...t.changes);return}}e.push(t)}function Sk(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?ic(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function ic(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>ic(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){let n=e,r=t,o=Object.keys(n);return o.length===Object.keys(r).length&&o.every(i=>ic(n[i],r[i]))}return!1}function Fn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as lr from"@babel/types";import*as H from"@babel/types";function sc(e,t,n){let r=xt(t,n);return r?Lt(e,r):null}function Lt(e,t){let n=t.findParent(h=>h.isArrowFunctionExpression()||h.isFunctionExpression());if(!n||!n.isArrowFunctionExpression()&&!n.isFunctionExpression())return null;let r=n,o=r.parentPath;if(!o||!o.isCallExpression()&&!o.isOptionalCallExpression())return null;let i=o;if(i.node.arguments.findIndex(h=>h===r.node)!==0)return null;let a=i.get("callee");if(!a.isMemberExpression()&&!a.isOptionalMemberExpression())return null;let c=a.node,l=c.property;if(!H.isIdentifier(l)||l.name!=="map"||c.computed)return null;let d=a.get("object"),f=ar(e,d.node),m=r.node.params.map(h=>ar(e,h)),u=pe(i.node),g=pe(r.node);return!f||m.some(h=>h.length===0)||!u||!g?null:{callStart:u.start,callEnd:u.end,callbackStart:g.start,callbackEnd:g.end,collectionExpression:f,callbackParams:m,mapOperator:H.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Li(d.node),callbackPath:r,collectionPath:d}}function Zr(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function Ek(e,t){let n=pe(e.node);return n?vk(t).some(r=>{let o=pe(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function vk(e){let t=e.callbackPath.node.body;return H.isBlockStatement(t)?sn(t.body):an(t)}function sn(e){let t=[];for(let n of e){if(H.isReturnStatement(n)){n.argument&&t.push(...an(n.argument));continue}if(H.isBlockStatement(n)){t.push(...sn(n.body));continue}if(H.isIfStatement(n)){let r=H.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...sn(r)),n.alternate){let o=H.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...sn(o))}continue}if(H.isSwitchStatement(n)){for(let r of n.cases)t.push(...sn(r.consequent));continue}H.isTryStatement(n)&&(t.push(...sn(n.block.body)),n.handler&&t.push(...sn(n.handler.body.body)),n.finalizer&&t.push(...sn(n.finalizer.body)))}return t}function an(e){return H.isJSXElement(e)?kk(e)?pp(e.children):[e]:H.isJSXFragment(e)?pp(e.children):H.isParenthesizedExpression(e)||H.isTSAsExpression(e)||H.isTSSatisfiesExpression(e)||H.isTSNonNullExpression(e)||H.isTSTypeAssertion(e)?an(e.expression):H.isConditionalExpression(e)?[...an(e.consequent),...an(e.alternate)]:H.isLogicalExpression(e)&&rc(e.operator)?an(e.right):[]}function pp(e){return e.flatMap(t=>H.isJSXElement(t)||H.isJSXFragment(t)?an(t):H.isJSXExpressionContainer(t)&&(H.isJSXElement(t.expression)||H.isJSXFragment(t.expression)||H.isConditionalExpression(t.expression)||H.isLogicalExpression(t.expression))?an(t.expression):[])}function kk(e){let t=e.openingElement.name;return H.isJSXIdentifier(t)?t.name==="Fragment":H.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function mp(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Li(e){return!(H.isIdentifier(e)||H.isThisExpression(e)||H.isMemberExpression(e)||H.isOptionalMemberExpression(e)||H.isCallExpression(e)||H.isOptionalCallExpression(e))}function gp(e){let t=e.parentPath;if(!t||!t.isCallExpression()&&!t.isOptionalCallExpression()||t.node.arguments[0]!==e.node)return!1;let n=t.node.callee;return(H.isMemberExpression(n)||H.isOptionalMemberExpression(n))&&H.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function cr(e,t){let n=Ke(e);if(!n)return t.isRepeatItemRoot===!0;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:_i(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Lt(e,o);return i?Ek(o,i):t.isRepeatItemRoot===!0}function hp(e,t){let n=Ke(e);if(!n)return!1;let r=se(n,he(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:_i(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(H.isMemberExpression(s)||H.isOptionalMemberExpression(s))&&H.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as ke from"@babel/types";function ac(e){if(ke.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(ke.isJSXMemberExpression(e)){let t=e;for(;ke.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function Ik(e,t){let n=pe(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Mt(a.path.node,n)||cn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=ac(i.node.name);s&&o(s,i)}}),[...r].sort()}function cc(e,t,n){let r=Ke(e);if(!r)return{ok:!0};let o=se(r,he(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=se(r,he(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Rr(o.match.path,i.match.path);if(Oi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=Ik(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function xp(e){let t=e;for(;ke.isTSQualifiedName(t);)t=t.left;return ke.isIdentifier(t)?t.name:null}function Qr(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Bi(e){let t=[],n=r=>{if(r){if(ke.isIdentifier(r)){t.push(r.name);return}if(ke.isObjectPattern(r)){for(let o of r.properties){if(ke.isRestElement(o)){n(o.argument);continue}ke.isObjectProperty(o)&&n(o.value)}return}if(ke.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(ke.isAssignmentPattern(r)){n(r.left);return}if(ke.isRestElement(r)){n(r.argument);return}ke.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function lc(e,t){let n=pe(e.node),r=pe(t.node);if(!n||!r)return{ok:!1,reason:"Cannot move repeat-backed child out of a component without proving the component call-site render scope"};let o=yp(e),i=yp(t);if(!o||!i||!sp(o,i))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is rendered in a different return branch"};let s=e.parentPath;for(;s;){if(s.isConditionalExpression()){let a=ap(s.node,n);if(a&&!ot(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if(s.isLogicalExpression()){let a=pe(s.node.right);if(a&&ot(a,n)&&!ot(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is conditionally rendered outside the target scope"}}else if((s.isArrowFunctionExpression()||s.isFunctionExpression())&&gp(s)){let a=pe(s.node.body)??pe(s.node);if(a&&!ot(a,r))return{ok:!1,reason:"Cannot move repeat-backed child out of a component because the component call site is repeated outside the target scope"}}s=s.parentPath}return{ok:!0}}function yp(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?pe(t.node.argument):null;if(t.isArrowFunctionExpression()&&(ke.isJSXElement(t.node.body)||ke.isJSXFragment(t.node.body)||ke.isConditionalExpression(t.node.body)||ke.isLogicalExpression(t.node.body)))return pe(t.node.body);t=t.parentPath}return null}function cn(e,t,n){return n.scope.getBinding(t)===e}function uc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Oi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=pe(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Bi(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let d=l.scope.getBinding(c);!d||Mt(d.path.node,o)||i.has(d.path.node)||cn(d,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=ac(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function dc(e,t,n){let r=pe(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Bi(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Qr(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Mt(a.path.node,r)||o.has(a.path.node)||cn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function bp(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Bi(a)).map(a=>e.callbackPath.scope.getBinding(a)?.path.node).filter(Boolean)),r=new Set,o=(a,c)=>{let l=c.scope.getBinding(a);!l||n.has(l.path.node)||cn(l,a,t)||r.add(a)},i=e.callbackPath.get("params"),s=Array.isArray(i)?i:[i];for(let a of s)a.traverse({ReferencedIdentifier(c){o(c.node.name,c)},TSTypeReference(c){let l=c.node.typeName;if(lr.isIdentifier(l))o(l.name,c);else{let d=xp(l);d&&o(d,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function fc(e,t){let n=pe(e.node),r=new Set;return Qr(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Mt(i.path.node,n)||cn(i,o.node.name,t)||r.add(o.node.name))}),r.size>0?{ok:!1,bindingNames:[...r].sort(),reason:"Cannot move repeat-backed child because the repeat collection is not visible at the target"}:{ok:!0}}function Sp(e){let t=[];for(let n of e.callbackPath.node.params){if(lr.isIdentifier(n)){t.push(n.name);continue}if(lr.isRestElement(n)&&lr.isIdentifier(n.argument)){t.push(`...${n.argument.name}`);continue}return{ok:!1,reason:"Cannot move cross-file repeat child because the callback parameters are not portable to the target file"}}return{ok:!0,callbackParams:t}}function Ep(e,t){return{...e,callbackParams:t}}function pc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function qr(e,t,n){return n?.finalSource?.kind==="component-prop"?"Cannot edit prop-backed node structure with a generic node operation":t?.kind==="value-binding"&&t.sourceKind==="repeat-template"&&!e.isRepeatItemRoot?"Cannot edit repeat-backed child node structure with a generic node operation":t?.kind==="value-binding"&&t.file!==e.file&&t.sourceKind!=="repeat-template"?"Cannot edit upstream-bound node structure with a generic node operation":null}function vp(e,t,n,r){return e.parentKey===t.key&&e.file===t.file&&n?.kind==="value-binding"&&n.file!==e.file&&n.sourceKind!=="repeat-template"&&r?.finalSource?.kind!=="component-prop"}function _n(e){return{file:e.file,component:e.component}}function Ck(e){return e.target.kind==="node"?e.target.key:null}function Rk(e){return"kind"in e}function $i(e){return!Rk(e)}function xc(e,t){let n=Ki.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Ki.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function mc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Tt(n,he(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Sc(e){if(!e.component)return"Component";if(e.component.exportName!=="default")return e.component.exportName;let t=e.component.source.replace(/\\/g,"/").replace(/\/$/,""),n=t.split("/").pop()||"Component",i=(n==="index"?t.split("/").slice(-2,-1)[0]||"Component":n).replace(/\.[^.]+$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean);return i.length===0?"Component":i.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Nk(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function wk(e){let t=e.trim();if(!/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}function gc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function Pk(e){let t=Wf(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=lc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=Ak({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Ap(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Li(o):!0}}}function Ak(e){let t=pe(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move prop-backed repeat child because the collection expression cannot be mapped"};let n=new Map,r=new Set,o=null,i=s=>{if(o)return;let a=s.scope.getBinding(s.node.name);if(!a||Mt(a.path.node,t))return;let c=_k(s,a,t);if(c){if(c.hasDefault){o="Cannot move prop-backed repeat child because the collection prop has a default value that cannot be preserved safely";return}let l=Mk(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let d=Tk(l.expression,c.remainingPath);if(!d){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let f=fc(l.expressionPath,e.targetParentPath);if(!f.ok){o=f.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${f.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:d});return}cn(a,s.node.name,e.targetParentPath)||r.add(s.node.name)};return e.sourceContext.collectionPath.isIdentifier()&&e.sourceContext.collectionPath.isReferencedIdentifier()&&i(e.sourceContext.collectionPath),e.sourceContext.collectionPath.traverse({ReferencedIdentifier(s){s.isIdentifier()&&i(s)}}),o?{ok:!1,reason:o}:r.size>0?{ok:!1,reason:`Cannot move prop-backed repeat child because the collection depends on bindings outside the target scope: ${[...r].sort().join(", ")}`}:n.size===0?{ok:!1,reason:"Cannot move repeat-backed child out of its component without an explicit prop mapping"}:{ok:!0,collectionExpression:Dk(e.source,t,[...n.values()])}}function Tk(e,t){if(t.length===0)return e;let n=Ap(e);if(!n)return null;let r=Li(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=Fk(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function Fk(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function _k(e,t,n){let r=Ok(e,n),o=r?{kind:"member-expression",expression:e.node.name,base:e.node.name,path:[{kind:"property",name:r.propertyName}]}:{kind:"identifier",expression:e.node.name,base:e.node.name,path:[]},i=nr(t,o);if(!i)return null;let s=r?.range??pe(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function Ok(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Mt(n.node,t)||n.node.computed||!de.isIdentifier(n.node.property))return null;let r=pe(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function Mk(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&de.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=ar(n,s.node);return a?{ok:!0,expression:a,expressionPath:s}:{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' cannot be read`}}function Dk(e,t,n){let r=e.slice(t.start,t.end),o=[...n].sort((i,s)=>s.start-i.start);for(let i of o)r=r.slice(0,i.start-t.start)+i.text+r.slice(i.end-t.start);return r}function Ap(e){try{let n=Pp.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=de.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&de.isExpression(r)?r:null}catch{return null}}function Lk(e){let t=pe(e.sourceContext.collectionPath.node);if(!t)return{ok:!1,reason:"Cannot move cross-file repeat child because the collection expression cannot be inspected"};let n=new Map,r=new Set,o=i=>{let s=i.scope.getBinding(i.node.name);if(!s||Mt(s.path.node,t))return;let a=kp(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let d=kp(c,e.targetFile,e.targetFile);(!d||d.moduleFile!==a.moduleFile||!Bk(d.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(d=>JSON.stringify(d)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return Qr(e.sourceContext.collectionPath,o),r.size>0?{ok:!1,reason:`Cannot move cross-file repeat child because the collection depends on non-importable bindings: ${[...r].sort().join(", ")}`}:{ok:!0,imports:[...n.entries()].map(([i,s])=>({moduleSpecifier:i,imports:s}))}}function Bk(e,t){return e.kind!==t.kind?!1:e.kind==="named"&&t.kind==="named"?e.imported===t.imported&&e.local===t.local:e.kind==="default"&&t.kind==="default"||e.kind==="namespace"&&t.kind==="namespace"?e.local===t.local:!1}function kp(e,t,n){let r=$k(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Pn(t,i),a=i.startsWith(".")?xc(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=de.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function $k(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Ip(e,t,n,r){let o=nc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=ar(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=jk(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${Kk(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function jk(e,t){return Vk(e.node)?t:`(${t})`}function Vk(e){return de.isIdentifier(e)||de.isThisExpression(e)||de.isSuper(e)||de.isMemberExpression(e)||de.isOptionalMemberExpression(e)||de.isCallExpression(e)||de.isOptionalCallExpression(e)||de.isBooleanLiteral(e)||de.isNumericLiteral(e)||de.isStringLiteral(e)||de.isNullLiteral(e)||de.isUnaryExpression(e)}function Kk(e){return e.trim().startsWith("<")?e:`(${e})`}var Uk={table:new Set(["caption","colgroup","thead","tbody","tfoot","tr"]),thead:new Set(["tr"]),tbody:new Set(["tr"]),tfoot:new Set(["tr"]),tr:new Set(["th","td"]),ul:new Set(["li"]),ol:new Set(["li"]),select:new Set(["option","optgroup"]),optgroup:new Set(["option"])};function ji(e,t){if(t.kind!=="native-tag")return null;let n=e.tag?.toLowerCase();if(!n||n!==e.tag||n.startsWith("component:"))return null;let r=Uk[n];if(!r)return null;let o=t.tag.toLowerCase();return r.has(o)?null:`Cannot insert <${t.tag}> into <${e.tag}>; expected ${[...r].map(i=>`<${i}>`).join(", ")}`}function Jk(e,t){for(let n of e.program.body){if(!de.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>de.isImportDefaultSpecifier(o));if(r&&de.isImportDefaultSpecifier(r))return r.local.name}return null}function Xk(e,t,n){for(let r of e.program.body){if(!de.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>de.isImportSpecifier(i)&&(de.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&de.isImportSpecifier(o))return o.local.name}return null}function Cp(e){let t=new Set;return It(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Rp(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function zk(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Sc(e),o=Ke(t);if(n.exportName!=="default"){let a=o?Xk(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Rp(r,Cp(o)):r;return{localName:c,importStep:hc(e,c)}}if(!o)return{localName:r,importStep:hc(e,r)};let i=Jk(o,n.source);if(i)return{localName:i};let s=Rp(r,Cp(o));return{localName:s,importStep:hc(e,s)}}function Wk(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Sc(e);if(e.props&&Object.keys(e.props).length>0){let r=Object.entries(e.props).map(([o,i])=>typeof i=="string"?`${o}="${i}"`:`${o}={${JSON.stringify(i)}}`).join(" ");return`<${n} ${r} />`}return`<${n} />`}function Hk(e){if(e.kind==="native-tag")return e.text===void 0?{kind:e.kind,tag:e.tag}:{kind:e.kind,tag:e.tag,text:e.text};if(!e.component)return{kind:e.kind};let t=e.props?Gk(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function Gk(e){return Object.fromEntries(Object.entries(e).filter(t=>bc(t[1])))}function bc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(bc):typeof e=="object"?Object.values(e).every(bc):!1}function hc(e,t=Sc(e)){if(!e.component)throw new Error("Materialized component calls do not have a component import");return{moduleSpecifier:e.component.source,imports:e.component.exportName==="default"?[{kind:"default",local:t}]:[{kind:"named",imported:e.component.exportName,...t!==e.component.exportName?{local:t}:{}}]}}function Np(e,t){if("kind"in e)return{parentNode:null,anchorNode:null,placement:e.relation};if(e.relation==="prepend"||e.relation==="append"){let o=t.getNode(e.parentKey);return{parentNode:o,anchorNode:null,placement:e.relation,...o?{}:{error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}}}if(!("anchorKey"in e))return{parentNode:null,anchorNode:null,placement:e.relation,error:{errorCode:"invalid-target",reason:`Sibling target '${e.relation}' requires an anchor`}};let n=t.getNode(e.anchorKey),r=t.getNode(e.parentKey);return n?r?n.parentKey!==r.key?{parentNode:r,anchorNode:n,placement:e.relation,error:{errorCode:"invalid-target",reason:`Target anchor '${n.key}' belongs to parent '${n.parentKey??"<root>"}', expected '${r.key}'`}}:{parentNode:r,anchorNode:n,placement:e.relation}:{parentNode:null,anchorNode:n,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target parent '${e.parentKey}' not found in graph`}}:{parentNode:r,anchorNode:null,placement:e.relation,error:{errorCode:"locator-miss",reason:`Target anchor '${e.anchorKey}' not found in graph`}}}function Yk(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function eo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Ec(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function to(e){let t=e.path??[];for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r.kind==="index")return{locator:Ec(e,t.slice(0,n)),index:r.index}}return null}function yc(e,t){return e.locator?e.collectionPathMap?.[t]?Ec(e.locator,e.collectionPathMap[t]):to(e.locator)?Qk(e.locator,qk(t,e.collectionIndexMap)):null:null}function Zk(e,t){let n=e.path??[],r=n.findLastIndex(i=>i.kind==="index");if(r===-1)return;let o=n.slice(r+1);return o.length===0?t:Tp(o,t)}function Tp(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Tp(r,t);return o===void 0?void 0:{[n.name]:o}}function Qk(e,t){let n=e.path??[];for(let r=n.length-1;r>=0;r-=1)if(n[r].kind==="index"){let i=[...n];return i[r]={kind:"index",index:t},Ec(e,i)}return null}function qk(e,t){return t?.[e]??e}function wp(e,t){return!t||t.length===0?e:e<=0?t[0]??0:e>=t.length?(t[t.length-1]??t.length-1)+1:t[e]??e}function eI(e,t){return tI(e.root,t.root)&&rI(e.path??[],t.path??[])}function tI(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case"binding":case"hook-state":case"named-export":return"name"in t&&e.name===t.name;case"default-export":return!0;case"expression":return"sourceRange"in t&&nI(e.sourceRange,t.sourceRange)}}function nI(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function rI(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.kind!==o.kind)return!1;if(r.kind==="property"){if(o.kind!=="property"||r.name!==o.name)return!1;continue}if(o.kind!=="index"||r.index!==o.index)return!1}return!0}var Vi=class{constructor(t){this.operationCounter=0,this.graph=t}async plan(t){let n=`op-${++this.operationCounter}-${Date.now()}`;switch(t.kind){case"update-text":{if(t.params.kind!=="update-text")return{ok:!1,errorCode:"unknown",reason:eo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateText(n,r,i,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"update-array-item":{if(t.params.kind!=="update-array-item")return{ok:!1,errorCode:"unknown",reason:eo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planUpdateArrayItem(n,r,this.graph.getCapability(i.key),await this.graph.getTextWriteTarget(i.key,r.params.segmentIndex))}case"remove-node":{if(t.params.kind!=="remove-node")return{ok:!1,errorCode:"unknown",reason:eo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planRemoveNode(n,r,i,this.graph.getCapability(i.key))}case"insert-child":{if(t.params.kind!=="insert-child")return{ok:!1,errorCode:"unknown",reason:eo(t.kind,t.params.kind)};let r=t;if(!$i(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Np(r.params.position,this.graph);if(o.error)return{ok:!1,errorCode:o.error.errorCode,reason:o.error.reason};if(!o.parentNode)return{ok:!1,errorCode:"locator-miss",reason:`Insert target parent for request '${t.id}' not found in graph`};let i=this.graph.getFileVersion(o.parentNode.file);return t.documentVersion!==i?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${i})`}:this.planInsertChild(n,r,o.parentNode,this.graph.getCapability(o.parentNode.key),o.anchorNode)}case"move-node":{if(t.params.kind!=="move-node")return{ok:!1,errorCode:"unknown",reason:eo(t.kind,t.params.kind)};let r=t,o=this.resolveNodeRequest(t);if(!o.ok)return o.result;let i=o.node,s=this.graph.getFileVersion(i.file);return t.documentVersion!==s?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${s})`}:this.planMoveNode(n,r,i,this.graph.getCapability(i.key))}case"set-class-name-source":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:this.planNodeAttributeOperation(n,t,r.node)}case"set-props":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planSetProps(n,t,r.node)}case"apply-style-draft":{let r=this.resolveNodeRequest(t);if(!r.ok)return r.result;let o=this.graph.getFileVersion(r.node.file);return t.documentVersion!==o?{ok:!1,errorCode:"stale-version",reason:`Document version ${t.documentVersion} is stale or otherwise does not match current version (current: ${o})`}:await this.planApplyStyleDraft(n,t,r.node)}default:return{ok:!1,errorCode:"unknown",reason:`Unknown operation kind: ${t.kind}`}}}resolveNodeRequest(t){let n=Ck(t);if(!n)return{ok:!1,result:{ok:!1,errorCode:"invalid-target",reason:`Operation '${t.kind}' requires a node target`}};let r=this.graph.getNode(n);return r?{ok:!0,node:r}:{ok:!1,result:{ok:!1,errorCode:"locator-miss",reason:`Target key '${n}' not found in graph`}}}planNodeAttributeOperation(t,n,r){let o=r.file,i=this.graph.getCapability(r.key);return n.params.filePath!==o?{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."}:this.buildPlan(t,n,[{order:0,file:o,type:"set-class-name-source",request:{...n.params,key:r.key}}],i)}async planSetProps(t,n,r){let o=this.graph.getCapability(r.key),i=await this.buildTypedPropertySteps({node:r,scope:n.params.scope,changes:n.params.changes,selectionRef:n.selectionRef});return i.ok?this.buildPlan(t,n,i.steps,o):oI(i)}async planApplyStyleDraft(t,n,r){let o=r.file,i=this.graph.getCapability(r.key),s=[];if(n.params.className){if(n.params.className.filePath!==o)return{ok:!1,errorCode:"stale-version",reason:"The className source file changed before save."};s.push({order:s.length,file:o,type:"set-class-name-source",request:{kind:"set-class-name-source",...n.params.className,key:r.key}})}if(n.params.props){let a=await this.buildStyleDraftPropertySteps({initialOrder:s.length,node:r,props:n.params.props,selectionRef:n.selectionRef});if(!a.ok)return a;s.push(...a.steps)}return this.buildPlan(t,n,s,i)}async buildTypedPropertySteps(t){let n=this.graph.getPropertyState;return n?fp({node:t.node,scope:t.scope,changes:t.changes,selectionRef:t.selectionRef,getPropertyState:n,getRepeatPropertyTarget:this.graph.getRepeatPropertyTarget,getFileContent:r=>this.graph.getFileContent(r),getFileVersion:r=>this.graph.getFileVersion(r),classNameSource:this.graph.getClassNameSource?.(t.node.key)??void 0}):{ok:!1,errorCode:"missing-property-state",reason:"Typed property planning requires authoritative property provenance"}}async buildStyleDraftPropertySteps(t){let{initialOrder:n,node:r,props:o,selectionRef:i}=t,s=[],a=[];for(let[c,l]of Object.entries(o)){if(l===void 0)continue;let d=await this.graph.getElementPropertyWriteTarget?.(r.key,c),f=r.attributes?.find(u=>u.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!d&&f?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof f?.resolvedValue=="string"&&f.resolvedValue===l||f?.source===null&&f.value===l)){if(d?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(d?.kind==="value-binding"&&d.locator){let u=d.locator;if(d.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let g=yc(d,i.instanceIndex);if(!g)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};u=g}s.push({order:n+s.length,file:d.file,type:"update-value",locator:u,value:l});continue}a.push({operation:"set",name:c,value:l})}}return a.length>0&&s.push({order:n+s.length,file:r.file,type:"set-property-changes",locator:he(r),scope:"selection",changes:a}),{ok:!0,steps:s}}buildTextRewriteSteps(t,n,r,o,i){if(o?.kind==="value-binding"&&o.locator){if(o.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let a=yc(o,i.instanceIndex);if(!a)return{ok:!1,errorCode:"invalid-params",reason:"update-text could not resolve the selected repeat item"};let c=this.coerceTextValueForValueTarget(o.file,a,r);return c.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-array-item",locator:a,value:c.value}]}:c}let s=this.coerceTextValueForValueTarget(o.file,o.locator,r);return s.ok?{ok:!0,steps:[{order:0,file:o.file,type:"update-value",locator:o.locator,value:s.value}]}:s}return{ok:!0,steps:o?.kind==="external-entry"?[{order:0,file:`external:${o.sourceId}`,type:"invoke-external-adapter",sourceType:o.sourceType,sourceId:o.sourceId,adapterId:o.adapterId,capability:"write-text",value:r}]:[{order:0,file:t.file,type:"update-text",locator:he(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Ke(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=se(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!Nk(a.match.path))return{ok:!0,value:r};let c=wk(r);return c===null?{ok:!1,errorCode:"invalid-params",reason:`${o} value must be a valid number for numeric source`}:{ok:!0,value:c}}planUpdateArrayItem(t,n,r,o){if(!r.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update repeated text on this node"};if(o?.kind!=="value-binding"||o.sourceKind!=="repeat-template"||!o.locator)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item requires a writable repeat-template source"};let{index:i,value:s}=n.params,a=o.collectionPathMap?.length??o.collectionIndexMap?.length;if(a!==void 0&&i>=a)return{ok:!1,errorCode:"invalid-params",reason:`update-array-item index ${i} is outside the repeated source`};let c=yc(o,i);if(!c)return{ok:!1,errorCode:"invalid-params",reason:"update-array-item could not resolve the selected repeat item"};let l=this.coerceTextValueForValueTarget(o.file,c,s,"update-array-item");return l.ok?this.isValueTargetUnchanged(o.file,c,l.value)?{ok:!1,errorCode:"invalid-params",reason:"update-array-item value is unchanged"}:this.buildPlan(t,n,[{order:0,file:o.file,type:"update-array-item",locator:c,value:l.value}],r):l}isValueTargetUnchanged(t,n,r){let o=Ke(this.graph.getFileContent(t));if(!o)return!1;let i=se(o,n);if(!i.ok)return!1;let s=i.match.path;if(s.isStringLiteral())return typeof r=="string"&&s.node.value===r;if(s.isNumericLiteral())return typeof r=="number"&&Object.is(s.node.value,r);if(s.isBooleanLiteral())return typeof r=="boolean"&&s.node.value===r;if(s.isNullLiteral())return r===null;if(s.isUnaryExpression({operator:"-"})){let a=s.get("argument");return typeof r=="number"&&!Array.isArray(a)&&a.isNumericLiteral()&&Object.is(-a.node.value,r)}return!1}planUpdateText(t,n,r,o,i){let s=this.graph.getTextProvenance?.(r.key,n.params.segmentIndex);if(s&&(s.editMode==="readonly"||s.editMode==="unsupported"))return{ok:!1,errorCode:"unsupported-operation",reason:"Text has no identity-preserving write target"};if(!o.canUpdateText)return{ok:!1,errorCode:"capability-denied",reason:"Cannot update text on this node"};let a=this.buildTextRewriteSteps(r,n.params.segmentIndex,n.params.value,i,n.selectionRef);return a.ok?this.buildPlan(t,n,a.steps,o):a}async planRemoveNode(t,n,r,o){if(!o.canRemove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot remove this node"};let i=await this.graph.getTextWriteTarget(r.key,0);if(i?.kind==="external-entry")return this.buildPlan(t,n,[{order:0,file:`external:${i.sourceId}`,type:"invoke-external-adapter",sourceType:i.sourceType,sourceId:i.sourceId,adapterId:i.adapterId,capability:"remove-node",value:{operation:"remove-node"}}],o);if(r.isRepeatItemRoot){let f=i;if(f?.kind==="value-binding"&&f.locator){let m=to(f.locator);if(m)return this.buildPlan(t,n,[{order:0,file:f.file,type:"remove-bound-array-item",locator:m.locator,index:m.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=qr(r,i,this.graph.getTextProvenance?.(r.key,0)??null);if(s)return{ok:!1,errorCode:"unsupported-operation",reason:s};let a=this.getRepeatBackedTemplateStructureReason(r);if(a)return{ok:!1,errorCode:"unsupported-operation",reason:a};let c=await this.getUpstreamBackedDescendantReason(r);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}],d=this.buildRemoveComponentImportStep(r);return d&&l.push({...d,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||ip(n,t)>1)return null;let r=xc(t.file,t.importedFrom);return{order:0,file:t.file,type:"remove-import",moduleSpecifier:r,imports:t.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:t.exportName}]}}async planInsertChild(t,n,r,o,i){if(!$i(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.node.kind==="component-call"&&!n.params.node.component)return{ok:!1,errorCode:"unsupported-operation",reason:"Materialized component insertion requires the materialization transaction planner"};if(!o.canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot insert child into this node"};let s=this.graph.getEditableTextSegmentIndex(r.key),a=s!==null?await this.graph.getTextWriteTarget(r.key,s):null,c=qr(r,a,s!==null?this.graph.getTextProvenance?.(r.key,s)??null:null);if(c)return{ok:!1,errorCode:"unsupported-operation",reason:c};let l=await this.getUpstreamBackedDescendantReason(r);if(l)return{ok:!1,errorCode:"unsupported-operation",reason:l};let d=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(d)return d;let f=await this.planRepeatBackedInsertChild(t,n,r,o);if(f)return f;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let u=jf(this.graph.getFileContent(r.file),r);if(!u.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:u.reason??"Cannot insert child into this node"};let g=ji(r,n.params.node);if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let h=[],b=0,E=n.params.node.kind==="component-call"?zk(n.params.node,this.graph.getFileContent(r.file)):void 0,v=E?.importStep;return v&&h.push({order:b++,file:r.file,type:"add-import",moduleSpecifier:v.moduleSpecifier,imports:v.imports}),h.push({order:b++,file:r.file,type:"insert-child",parentLocator:he(r),node:{jsx:Wk(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?he(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!$i(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let a=s?.kind==="external-entry"?s:await this.findExternalInsertContext(r,i);if(!a)return null;let c=i?await this.graph.getTextWriteTarget(i.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${a.sourceId}`,type:"invoke-external-adapter",sourceType:a.sourceType,sourceId:a.sourceId,adapterId:a.adapterId,capability:"insert-child",value:{operation:"insert-child",relation:n.params.position.relation,parentKey:r.key,anchorSourceId:c?.kind==="external-entry"?c.sourceId:null,node:Hk(n.params.node)}}],o)}async findExternalInsertContext(t,n){if(n){let o=await this.graph.getTextWriteTarget(n.key,0);if(o?.kind==="external-entry")return o}if(!this.graph.getChildNodes)return null;let r=[...this.graph.getChildNodes(t.key)];for(;r.length>0;){let o=r.shift();if(!o)continue;let i=await this.graph.getTextWriteTarget(o.key,0);if(i?.kind==="external-entry")return i;let s=this.graph.getTextProvenance?.(o.key,0)?.finalSource?.externalSource;if(s)return{kind:"external-entry",file:`external:${s.sourceId}`,sourceType:s.sourceType,sourceId:s.sourceId,adapterId:s.adapterId,displayExpression:s.sourceId};r.push(...this.graph.getChildNodes(o.key))}return null}async planRepeatBackedInsertChild(t,n,r,o){if(!$i(n.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};if(n.params.position.relation!=="append"&&n.params.position.relation!=="prepend")return null;let i=n.params.node;if(i.kind!=="native-tag"||i.text===void 0||!this.graph.getChildNodes)return null;let s=this.graph.getChildNodes(r.key).find(f=>f.isRepeatItemRoot&&f.tag?.toLowerCase()===i.tag.toLowerCase());if(!s)return null;let a=await this.graph.getTextWriteTarget(s.key,0);if(!a||a.kind!=="value-binding"||!a.locator)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires a writable value target"};let c=to(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=Zk(a.locator,i.text);if(l===void 0)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child could not infer an item shape from the template"};let d=n.params.position.relation==="prepend"?wp(0,a.collectionIndexMap):wp(a.collectionIndexMap?.length??c.index+1,a.collectionIndexMap);return this.buildPlan(t,n,[{order:0,file:a.file,type:"insert-bound-array-item",locator:c.locator,index:d,value:l}],o)}async getUpstreamBackedDescendantReason(t){if(!this.graph.getChildNodes)return null;let n=[...this.graph.getChildNodes(t.key)];for(;n.length>0;){let r=n.shift();if(!r)continue;let o=this.graph.getEditableTextSegmentIndex(r.key),i=o!==null?await this.graph.getTextWriteTarget(r.key,o):null,s=qr(r,i,o!==null?this.graph.getTextProvenance?.(r.key,o)??null:null);if(s)return s;n.push(...this.graph.getChildNodes(r.key))}return null}getRepeatBackedTemplateStructureReason(t){if(t.isRepeatItemRoot)return cr(this.graph.getFileContent(t.file),t)?"Cannot edit repeat-backed item template structure with a generic node operation":"Cannot edit repeat-backed child node structure with a generic node operation";if(t.structuralPath.includes("#repeat:")||hp(this.graph.getFileContent(t.file),t))return"Cannot edit repeat-backed child node structure with a generic node operation";let n=t.parentKey;for(;n;){let r=this.graph.getNode(n);if(!r)return null;if(r.isRepeatItemRoot||r.isRepeatRegion)return"Cannot edit repeat-backed child node structure with a generic node operation";n=r.parentKey}return null}planRepeatTemplateInternalMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&cr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ke(c);if(!l)return null;let d=xt(l,r),f=xt(l,o);if(!d||!f)return null;let m=Lt(c,d),u=Lt(c,f);if(!Zr(m,u))return null;if(a&&(s==="before"||s==="after")){let h=xt(l,a),b=h?Lt(c,h):null;if(!Zr(m,b))return null}if(Mi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let g=cc(c,r,o);return g.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,selectionContext:_n(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:g.reason??`Cannot move node because it depends on bindings outside the target scope: ${g.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&cr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Ke(c);if(!l)return null;let d=xt(l,r),f=xt(l,o);if(!d||!f)return null;let m=Lt(c,d);if(!m)return null;let u=Lt(c,f);if(Zr(m,u))return null;if(u&&!mp(u,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let I=sc(c,l,a);if(u&&!Zr(u,I)||!u&&I)return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"}}if(r.tag&&r.tag.toLowerCase()===r.tag){let I=ji(o,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}let g=mc(this.graph,r);if(!g)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Mi(d,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Ip(c,d,f,g);for(let I of h.conditionPaths){let R=dc(I,f,m);if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${R.bindingNames.join(", ")}`}}let b=uc(d,f,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${b.bindingNames.join(", ")}`};let E=bp(m,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=m;if(r.component!==o.component){let I=Pk({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:f});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};v=I.context}else{let I=fc(m.collectionPath,f);if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${I.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:he(r),targetParentLocator:he(o),placement:s,anchorLocator:a?he(a):void 0,repeatExpression:pc(v,h.sourceJsx),selectionContext:_n(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&cr(this.graph.getFileContent(r.file),r)||r.file===o.file)return null;let c=this.graph.getFileContent(r.file),l=this.graph.getFileContent(o.file),d=Ke(c),f=Ke(l);if(!d||!f)return null;let m=cp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:d,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let u=xt(d,r),g=xt(f,o);if(!u||!g)return null;let h=lc(m.callSitePath,g);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let b=Lt(c,u);if(!b)return null;if(Lt(l,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&sc(l,f,a))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child relative to a repeat-template anchor outside the target scope"};if(r.tag&&r.tag.toLowerCase()===r.tag){let F=ji(o,{kind:"native-tag",tag:r.tag});if(F)return{ok:!1,errorCode:"unsupported-operation",reason:F}}let v=mc(this.graph,r);if(!v)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Mi(u,g))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let I=Ip(c,u,g,v);for(let F of I.conditionPaths){let M=dc(F,g,b);if(!M.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${M.bindingNames.join(", ")}`}}let R=uc(u,g,b,{preserveConditionalBoundary:I.conditionPaths.length>0});if(!R.ok)return{ok:!1,errorCode:"unsupported-operation",reason:R.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${R.bindingNames.join(", ")}`};let P=Lk({sourceFile:r.file,targetFile:o.file,sourceContext:b,targetParentPath:g});if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let T=Sp(b);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=Ep(b,T.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}];for(let F of P.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:F.moduleSpecifier,imports:F.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:he(o),expression:pc(C,I.sourceJsx),placement:s,anchorLocator:a?he(a):void 0,selectionContext:_n(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let I=n.params.target,R=this.graph.getNode(I.anchorKey);if(!R||r.file!==R.file||r.component!==R.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let P=this.graph.getFileVersion(r.file);if(n.documentVersion!==P)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${P})`};let T=this.graph.getFileContent(r.file),C=Ke(T),A=C?xt(C,r):null,F=C?xt(C,R):null,M=A?.parentPath,U=F?.parentPath;if(!A||!F||!M||!U||M.node!==U.node||!M.isJSXFragment()&&!(M.isJSXElement()&&Ae(M)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let q=M.node.loc;return q?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:q.start.line,startColumn:q.start.column,endLine:q.end.line,endColumn:q.end.column}},placement:I.relation,anchorLocator:he(R),selectionContext:_n(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Np(n.params.target,this.graph);if(i.error)return{ok:!1,errorCode:i.error.errorCode,reason:i.error.reason};let s=i.parentNode;if(!s)return{ok:!1,errorCode:"locator-miss",reason:`Target parent for request '${n.id}' not found in graph`};let a=this.graph.getFileVersion(s.file);if(n.documentVersion!==a)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match target parent version (current: ${a})`};if(Yk(s.key,r.key,this.graph))return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into its own subtree"};if(r.isRepeatRegion&&s.isBoundary)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move repeat-region node across boundary"};if(!this.graph.getCapability(s.key).canInsertChild)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move node into this parent"};let c=await this.graph.getTextWriteTarget(r.key,0);if(c?.kind==="external-entry"){let I=n.params.target.relation,R=i.anchorNode&&(I==="before"||I==="after")?await this.graph.getTextWriteTarget(i.anchorNode.key,0):null;return this.buildPlan(t,n,[{order:0,file:`external:${c.sourceId}`,type:"invoke-external-adapter",sourceType:c.sourceType,sourceId:c.sourceId,adapterId:c.adapterId,capability:"move-node",value:{operation:"move-node",relation:I,anchorSourceId:R?.kind==="external-entry"?R.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,d=n.params.target.relation,f=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,u=qr(r,c,m);if(u&&!gc(u)&&!vp(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:u};if(r.isRepeatItemRoot&&f?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===f.repeatOwnerKey&&(d==="before"||d==="after")){let I=c,R=await this.graph.getTextWriteTarget(f.key,0);if(I?.kind==="value-binding"&&R?.kind==="value-binding"&&I.locator&&R.locator){let P=to(I.locator),T=to(R.locator);if(P&&T&&I.file===R.file&&eI(P.locator,T.locator)){let C=P.index,A=T.index,F=d==="before"?A-(C<A?1:0):A+(C<A?0:1);return this.buildPlan(t,n,[{order:0,file:I.file,type:"move-array-item",locator:P.locator,fromIndex:C,toIndex:F}],o)}}}if(r.isRepeatItemRoot&&cr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let g=this.getRepeatBackedTemplateStructureReason(r),h=gc(u)?u:g;if(h&&gc(h)){let I=this.planRepeatTemplateInternalMove(t,n,r,s,o,d,f);if(I)return I;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,d,f);if(R)return R;let P=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,d,f);return P||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(g)return{ok:!1,errorCode:"unsupported-operation",reason:g};let b=await this.getUpstreamBackedDescendantReason(r);if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b};if(r.tag&&r.tag.toLowerCase()===r.tag){let I=ji(s,{kind:"native-tag",tag:r.tag});if(I)return{ok:!1,errorCode:"unsupported-operation",reason:I}}if(l)return this.planCrossFileMove(t,n,r,s,o,d,f);let E=cc(this.graph.getFileContent(r.file),r,s);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move node because it depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`};let v=[{order:0,file:r.file,type:"move-node",locator:he(r),targetParentLocator:he(s),placement:d,anchorLocator:f?he(f):void 0,selectionContext:_n(s)}];return this.buildPlan(t,n,v,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,d=this.graph.getFileContent(r.file),f=mc(this.graph,r)??`<${r.component} />`,m=Vf(d,r);if(!m.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:he(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let g=r.tag??r.component,b={moduleSpecifier:xc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:g}]:[{kind:"named",imported:r.exportName,local:g===r.exportName?void 0:g}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:b.moduleSpecifier,imports:b.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:_n(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:he(o),node:{jsx:f},placement:s,anchorLocator:a?he(a):void 0,selectionContext:_n(o)});let u=this.buildRemoveComponentImportStep(r,d);return u&&c.push({...u,order:l++}),this.buildPlan(t,n,c,i)}buildPlan(t,n,r,o){let s=[...new Set(r.map(a=>a.file))].map(a=>({file:a,content:this.graph.getFileContent(a),version:this.graph.getFileVersion(a),exists:!0,sha256:ve(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function oI(e){return{ok:!1,errorCode:e.errorCode==="readonly-property"?"capability-denied":e.errorCode==="missing-property-state"||e.errorCode==="repeat-target-failed"||e.errorCode==="unsupported-binding"?"unsupported-operation":"invalid-params",reason:e.reason}}import Rc from"@babel/generator";import{parse as bI}from"@babel/parser";import Nc from"@babel/traverse";import*as N from"@babel/types";import*as $t from"@babel/types";import vc from"@babel/generator";import*as xe from"@babel/types";var iI=typeof vc=="function"?vc:vc.default,sI=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,aI=/^((?:https?:)?\/\/)[^/@\s]+@/i,cI=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function _p(e,t){let n=Bt(e.callee);if(!n)return null;if(n==="fetch")return kc(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Fp(r))return kc(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Fp(r))return kc(e.arguments[0],r,t,["ky client contract"])}return null}function kc(e,t,n,r){if(!e||xe.isSpreadElement(e)||xe.isJSXNamespacedName(e))return fI(t,n,r,"missing url argument");let o=no(e);return{sourceKind:dI(o),...o?{endpointPattern:o}:{},method:t,confidence:o?"exact":"partial",evidence:[{file:n.file,reason:[...r,o?"endpoint pattern resolved":"endpoint pattern unresolved"].join("; ")}]}}function no(e){if(xe.isStringLiteral(e))return Ui(e.value);if(xe.isTemplateLiteral(e))return Ui(lI(e));if(xe.isBinaryExpression(e)&&e.operator==="+"){let t=no(e.left),n=no(e.right);return!t&&!n?void 0:Ui(`${t??Ic(e.left)}${n??Ic(e.right)}`)}if(xe.isMemberExpression(e)){let t=Op(e);if(t)return`env:${t}`}if(!(xe.isCallExpression(e)&&Bt(e.callee)==="new URL")){if(xe.isNewExpression(e)&&xe.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!xe.isSpreadElement(t)?no(t):void 0,o=n&&!xe.isSpreadElement(n)?no(n):void 0;return o&&r?Ui(`${o} + ${r}`):r??o}if(xe.isIdentifier(e))return`:${e.name}`}}function lI(e){let t="";for(let n=0;n<e.quasis.length;n+=1){t+=e.quasis[n]?.value.cooked??e.quasis[n]?.value.raw??"";let r=e.expressions[n];r&&(t+=Ic(r))}return t}function Ic(e){if(xe.isIdentifier(e))return`:${e.name}`;if(xe.isMemberExpression(e)){let t=Op(e);if(t)return`env:${t}`}return`:${uI(e)}`}function uI(e){return iI(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Ui(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(aI,"$1<redacted>@").replace(cI,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?sI.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function dI(e){return e?e.startsWith("/api/")?"site-api-route":/^(?:https?:)?\/\//.test(e)||e.startsWith("env:")?"external-api":e.startsWith("/")?"site-api-route":"unknown-api":"unknown-api"}function fI(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Fp(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Op(e){return!xe.isMemberExpression(e.object)||!xe.isIdentifier(e.object.object,{name:"process"})||!pI(e.object.property,"env")?null:xe.isIdentifier(e.property)?e.property.name:xe.isStringLiteral(e.property)?e.property.value:null}function pI(e,t){return xe.isIdentifier(e)&&e.name===t}function Bt(e){if(xe.isIdentifier(e))return e.name;if(xe.isMemberExpression(e)){let t=Bt(e.object),n=xe.isIdentifier(e.property)?e.property.name:xe.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var mI=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),gI=new Set(["getConfig","submit"]);function Mp(e,t){let n=hI(Bt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!mI.has(i))return null;let s=Cc(e,0),a=i==="getByUrl"||i==="getByUrlStrict",c=a?void 0:s,l=a?s??"/:record-url":c?`/collections/${c}`:"/collections/:collection";return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:i,...c?{collection:c}:{},endpointPattern:l,confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS collection facade"}]}}let o="cms.forms.";if(n.startsWith(o)){let i=n.slice(o.length);if(!gI.has(i))return null;let s=Cc(e,0);return{sourceKind:"vcp-cms-form",sourceType:"cms-field",operation:i,...s?{collection:s}:{},endpointPattern:s?`/forms/${s}`:"/forms/:form",confidence:s?"exact":"partial",evidence:[{file:t.file,symbol:n,reason:"VCP CMS form facade"}]}}if(n==="cmsFetch"||n==="cmsFetchResult"||n==="cmsFetchEnvelope"){let i=Cc(e,0)??yI(e,0,"path")??"/cms/:path",s=xI(i);return{sourceKind:"vcp-cms-collection",sourceType:"cms-field",operation:n,...s?{collection:s}:{},endpointPattern:i,confidence:i==="/cms/:path"?"partial":"safe-derived",evidence:[{file:t.file,symbol:n,reason:"VCP CMS fetch helper"}]}}return null}function hI(e,t){let n=e?.indexOf(".")??-1;if(!e||n<1)return e;let r=t.imports?.get(e.slice(0,n));return r?.importedName==="collections"&&/(?:^|\/)lib\/cms\/collections(?:\.js)?$/.test(r.source)?`cms.collections${e.slice(n)}`:e}function Dp(e,t){let n=Bt(e);return n==="cms.settings"?{sourceKind:"vcp-cms-settings",sourceType:"cms-field",operation:"settings",endpointPattern:"/settings",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS settings facade"}]}:n==="cms.navigation"?{sourceKind:"vcp-cms-navigation",sourceType:"cms-field",operation:"navigation",endpointPattern:"/navigation",confidence:"exact",evidence:[{file:t.file,symbol:n,reason:"VCP CMS navigation facade"}]}:null}function Lp(e){let t=Bt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function Cc(e,t){let n=e.arguments[t];return $t.isStringLiteral(n)?n.value:null}function yI(e,t,n){let r=e.arguments[t];if(!$t.isObjectExpression(r))return null;for(let o of r.properties)if($t.isObjectProperty(o)&&!o.computed&&($t.isIdentifier(o.key)&&o.key.name===n||$t.isStringLiteral(o.key)&&o.key.value===n)&&$t.isStringLiteral(o.value))return o.value.value;return null}function xI(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}var Pc=typeof Nc=="function"?Nc:Nc.default,XO=typeof Rc=="function"?Rc:Rc.default,SI={maxFunctionDepth:8,maxImportDepth:6},EI=new Set(["src","href","alt","poster","content","title","aria-label"]);async function Up(e){let t=e.fileCache??new Map,n=Fc(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...SI,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:rm(n,e.element.componentName)};await Jp(e.element.componentName,e.graph,r);let o=[];o.push(...await RI(e.element,e.graph,r),...await NI(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await wI(s,e.element,e.graph,r);a&&o.push(zi(a,"text","children"))}for(let s of e.element.attributes??[]){let a=CI(s,e.element);if(!a)continue;let c=await Wp(s.source,e.element,e.graph,r);c&&o.push(zi(c,a,s.name))}let i=UI(o).sort(tm);return{hasDynamicData:i.length>0,bindings:i}}async function Jp(e,t,n){if(n.importDepth>=n.options.maxImportDepth)return;let r=n.analysis.functions.get(e)??n.analysis.functions.get("default"),o=r?.params[0];if(!r||!o)return;let i=n.analysis.functions.get("default")===r?"default":e,s=[];for(let l of t.elements.values()){if(l.sourceFile===n.file&&l.tag===e){s.push(l);continue}!l.importedFrom||!l.exportName||l.importedFrom===n.file&&l.exportName!==i||(l.importedFrom===n.file||await Xp(l.importedFrom,l.exportName,n.file,n))&&s.push(l)}if(s.length===0)return;let a=new Map;for(let l of s){let d=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(d)){n.resolvingComponentProps.add(d);try{let f=await zp(l.sourceFile,n);if(!f)continue;let m=Hi(f,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=rm(f,l.componentName),await Jp(l.componentName,t,m);let u=await vI(l,m);for(let[g,h]of u){if(!h)continue;let b=a.get(g)??[];b.push(h),a.set(g,b)}}finally{n.resolvingComponentProps.delete(d)}}}let c=new Map;for(let[l,d]of a){let f=qp(d);f.length===1&&c.set(l,f[0])}II(o,c,n)}async function Xp(e,t,n,r,o=new Set){if(e===n)return!0;if(o.size>=r.options.maxImportDepth||o.has(`${e}#${t}`))return!1;o.add(`${e}#${t}`);let s=(await zp(e,r))?.imports.get(t);if(!s||!wt(s.source))return!1;let a=await sm(e,s.source,r.exists);return a?a===n?!0:Xp(a,s.importedName,n,r,o):!1}async function vI(e,t){let n=new Map;Pc(t.analysis.ast,{JSXElement(o){if(kI(o.node,e.sourceRange)){for(let i of o.node.openingElement.attributes)!N.isJSXAttribute(i)||!N.isJSXIdentifier(i.name)||!N.isJSXExpressionContainer(i.value)||!N.isExpression(i.value.expression)||n.set(i.name.name,i.value.expression);o.stop()}}});let r=new Map;for(let[o,i]of n){let s=await Le(i,t);s&&r.set(o,s)}return r}function kI(e,t){return e.loc?.start.line===t.startLine&&e.loc.start.column===t.startColumn&&e.loc.end.line===t.endLine&&e.loc.end.column===t.endColumn}async function zp(e,t){let n=t.fileCache.get(e);if(n)return n;if(!await t.exists(e))return null;let r=await t.readFile(e);return Fc(e,r,t.fileCache)}function II(e,t,n){if(N.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Tc(Object.fromEntries(t),n.file));return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=N.isAssignmentPattern(r.value)?r.value.left:r.value;N.isIdentifier(i)&&n.paramSources.set(i.name,Je(o))}}function CI(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":EI.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function RI(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="repeat-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="repeat-template");if(!i)continue;let s=await Wi(i.collectionSource,n);s&&r.push(zi(On(s),"repeat-region",i.collectionExpression))}return r}async function NI(e,t,n){let r=[];for(let o of t.regions){if(o.kind!=="conditional-region"||o.ownerKey!==e.identity.key)continue;let i=o.sourceCandidates?.find(a=>a.kind==="conditional-branch");if(!i)continue;let s=await Wi(i.conditionSource,n);s&&r.push(zi(On(s),"conditional-region",i.conditionExpression))}return r}async function wI(e,t,n,r){return Wp(e.source,t,n,r)}async function Wp(e,t,n,r){let o=await PI(e,t,n,r);return o||Wi(e,r)}async function PI(e,t,n,r){if(!e)return null;let o=AI(e.base,t,n);if(!o)return null;let i=await Wi(o.collectionSource,r);return i?so(i,e.path,!0):null}function AI(e,t,n){let r=t.identity.key;for(;r;){for(let o of n.regions){if(o.kind!=="repeat-region"||!o.childKeys.includes(r))continue;let i=o.sourceCandidates?.find(s=>s.kind==="repeat-template"&&s.itemParamName===e);if(i)return i}r=n.elements.get(r)?.parentKey??null}return null}async function Wi(e,t){if(!e)return null;let n=await Hp(e.base,t);return n?so(n,e.path,!1):null}async function Hp(e,t){let n=t.paramSources.get(e);if(n)return Je(n);if(t.variableCache.has(e))return JI(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await TI(e,t);if(r)return t.variableCache.set(e,Je(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await Le(o,t);return t.variableCache.set(e,s?Je(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await om(i,t);if(s){let a=Hi(s,t,{importDepth:t.importDepth+1}),c=im(i,s);if(c){let f=(await Mn(c,[],a)).returnSource;return t.variableCache.set(e,f?Je(f):null),t.resolvingVariables.delete(e),f}let l=s.variables.get(i.importedName);if(l){let d=await Le(l,a);return t.variableCache.set(e,d?Je(d):null),t.resolvingVariables.delete(e),d}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function TI(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=[];Pc(t.analysis.ast,{CallExpression(o){if(N.isIdentifier(o.node.callee,{name:n})){let i=o.node.arguments[0];N.isExpression(i)&&r.push(i);return}o.node.arguments.some(i=>N.isIdentifier(i)&&i.name===n)&&r.push(o.node)}});for(let o of r){let i=await Le(o,t);if(i)return i}return null}async function Le(e,t){if(N.isIdentifier(e))return Hp(e.name,t);if(N.isMemberExpression(e)||N.isOptionalMemberExpression(e)){let n=N.isMemberExpression(e)?Dp(e,{file:t.file}):null;if(n)return Qp(n);let r=await FI(e,t);if(!r)return null;let o=VI(e);return so(r,o,!1)}if(N.isAwaitExpression(e))return N.isExpression(e.argument)?Le(e.argument,t):null;if(N.isCallExpression(e))return Gp(e,t);if(N.isObjectExpression(e)){let n=await Yp(e,t);return Object.keys(n).length>0?Tc(n,t.file):null}if(N.isConditionalExpression(e)){let n=await Le(e.consequent,t),r=await Le(e.alternate,t);return io($p(n,r))}if(N.isLogicalExpression(e)){let n=await Le(e.left,t),r=await Le(e.right,t);return io($p(n,r))}return N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSNonNullExpression(e)||N.isTypeCastExpression(e)||N.isParenthesizedExpression(e)?Le(e.expression,t):null}async function FI(e,t){let n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);)n=n.object;return N.isExpression(n)?Le(n,t):null}async function Gp(e,t){let n=Mp(e,{file:t.file,imports:t.analysis.imports});if(n)return Qp(n);if(Lp(e)){let f=e.arguments[0];if(f&&N.isExpression(f))return io(await Le(f,t))}let r=await _I(e,t);if(r)return r;let o=_p(e,{file:t.file});if(o)return{sourceKind:o.sourceKind,sourceType:"api-field",endpointPattern:o.endpointPattern,valuePath:o.valuePath,confidence:o.confidence,readonly:!0,evidence:o.evidence};let i=await DI(e,t);if(i)return i;let s=await LI(e,t);if(s)return s;let a=await BI(e,t);if(a)return a;let c=await $I(e,t);if(c)return c;let l=[];for(let f of e.arguments)if(N.isExpression(f)){let m=await Le(f,t);m&&l.push(m)}let d=qp(l);return d.length===1?io(d[0]):null}async function _I(e,t){let n=Bt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=MI(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(N.isIdentifier(s)){let a=await oo(s.name,t);if(a)return(await Mn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!N.isObjectExpression(r))return Ji(t.file,`${n} without static options`);let o=OI(r,"queryFn");if(!o)return Ji(t.file,`${n} without queryFn`);if(N.isIdentifier(o)){let i=await oo(o.name,t);return i?(await Mn(i.node,[],i.context)).returnSource:Ji(t.file,`${n} queryFn unresolved`)}return N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)?(await Mn(o,[],t)).returnSource:N.isCallExpression(o)?Gp(o,t):null}function OI(e,t){for(let n of e.properties){if(!N.isObjectProperty(n)||!N.isExpression(n.value))continue;if(Zp(n)===t)return n.value}return null}function MI(e,t,n){return N.isStringLiteral(e)?{sourceKind:e.value.startsWith("/api/")?"site-api-route":"external-api",sourceType:"api-field",endpointPattern:e.value,confidence:"exact",readonly:!0,evidence:[{file:t,reason:n}]}:null}async function DI(e,t){if(!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=N.isExpression(e.callee.object)?await Le(e.callee.object,t):null;if(!r)return null;if(n!=="map")return On(r);let o=e.arguments[0];if(N.isIdentifier(o)){let i=await oo(o.name,t);if(!i)return On(r);let s=await Mn(i.node,[r],i.context);return{...On(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(N.isArrowFunctionExpression(o)||N.isFunctionExpression(o)){let i=await Mn(o,[r],t);return{...On(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return On(r)}async function LI(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"json"})||!N.isExpression(e.callee.object)?null:Le(e.callee.object,t)}async function BI(e,t){return!N.isMemberExpression(e.callee)||!N.isIdentifier(e.callee.property,{name:"then"})||!N.isExpression(e.callee.object)?null:io(await Le(e.callee.object,t))}async function $I(e,t){if(!N.isIdentifier(e.callee))return null;let n=await oo(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!N.isExpression(i)){r.push(Ji(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await Le(i,t);r.push(s)}return(await Mn(n.node,r,n.context)).returnSource}async function oo(e,t){let n=t.analysis.functions.get(e);if(n)return{node:n,context:t};let r=t.analysis.imports.get(e);if(!r||t.importDepth>=t.options.maxImportDepth)return null;let o=await om(r,t);if(!o)return null;let i=Hi(o,t,{importDepth:t.importDepth+1}),s=im(r,o);return s?{node:s,context:i}:oo(r.importedName,i)}async function Mn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Hi(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let d=t[l];d&&wc(c,KI(d),r)});let o=jI(e),i=null,s,a=!1;for(let c of o){if(N.isObjectExpression(c)){s={...s??{},...await Yp(c,r)},i=i??Tc(s,n.file);continue}let l=await Le(c,r);if(l){if(!i){i=l;continue}let d=Ac(i,l);if(!d){a=!0,i=null;continue}i=d}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function wc(e,t,n){if(N.isIdentifier(e)){n.paramSources.set(e.name,Je(t));return}if(N.isAssignmentPattern(e)){wc(e.left,t,n);return}if(N.isObjectPattern(e))for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isIdentifier(r.key))continue;let o=so(t,[{kind:"property",name:r.key.name}],!0),i=N.isAssignmentPattern(r.value)?r.value.left:r.value;wc(i,o,n)}}function jI(e){if(N.isArrowFunctionExpression(e)&&N.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!N.isBlockStatement(n))return t;let r=o=>{if(N.isFunction(o)&&o!==e)return;if(N.isReturnStatement(o)){o.argument&&N.isExpression(o.argument)&&t.push(o.argument);return}let i=N.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)N.isNode(c)&&r(c);else N.isNode(a)&&r(a)}};return r(n),t}async function Yp(e,t){let n={};for(let r of e.properties){if(!N.isObjectProperty(r))continue;let o=Zp(r);if(!o||!N.isExpression(r.value))continue;let i=await Le(r.value,t);i&&(n[o]=i)}return n}function Zp(e){return N.isIdentifier(e.key)&&!e.computed?e.key.name:N.isStringLiteral(e.key)?e.key.value:null}function VI(e){let t=[],n=e;for(;N.isMemberExpression(n)||N.isOptionalMemberExpression(n);){let r=n.property;n.computed?N.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):N.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):N.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return N.isIdentifier(n),t}function so(e,t,n){if(t.length===0)return Je(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return so(e.fieldMap[r.name],t.slice(1),n);let o=Je(e);if(o.sourceType==="cms-field"){let i=t.filter(s=>s.kind==="property").map(s=>s.name);return i[0]==="data"&&i[1]==="items"?(o.valuePath=ro(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=ro(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=ro(o.fieldPath,i.join(".")),o):(o.valuePath=ro(o.valuePath,Bp(t)),o)}return o.valuePath=ro(o.valuePath,Bp(t)),o}function Bp(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function ro(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Qp(e){return{sourceKind:e.sourceKind,sourceType:e.sourceType,operation:e.operation,collection:e.collection,endpointPattern:e.endpointPattern,valuePath:e.valuePath,confidence:e.confidence,readonly:!0,evidence:e.evidence}}function On(e){let t=Je(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function KI(e){let t=Je(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function io(e){return e?{...Je(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function $p(e,t){return e?t?Ac(e,t):Je(e):t?Je(t):null}function Ac(e,t){if(Xi(e)!==Xi(t))return null;let n=nm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function qp(e){let t=new Map;for(let n of e){let r=Xi(n),o=t.get(r);t.set(r,o?Ac(o,n):Je(n))}return[...t.values()]}function Xi(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Xi(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function Tc(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function Ji(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function zi(e,t,n){return{sourceKind:e.sourceKind,sourceType:e.sourceType,...e.endpointPattern?{endpointPattern:e.endpointPattern}:{},...e.operation?{operation:e.operation}:{},...e.collection?{collection:e.collection}:{},...e.fieldPath?{fieldPath:e.fieldPath}:{},...e.valuePath?{valuePath:e.valuePath}:{},targetKind:t,targetName:n,confidence:e.confidence,readonly:!0,evidence:e.evidence.map(r=>({...r}))}}function em(e){let t=[...e].sort(tm),n=t[0],r=[...new Set(t.flatMap(o=>o.sourceKind==="vcp-cms-collection"&&o.collection?[o.collection]:[]))];return{hasDynamicData:t.length>0,sourceKinds:[...new Set(t.map(o=>o.sourceKind))],...r.length>0?{collections:r}:{},...n?.endpointPattern?{primaryEndpoint:n.endpointPattern}:{},...n?.collection?{primaryCollection:n.collection}:{},...n?.fieldPath?{primaryFieldPath:n.fieldPath}:{}}}function UI(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify({sourceKind:r.sourceKind,endpointPattern:r.endpointPattern,collection:r.collection,fieldPath:r.fieldPath,valuePath:r.valuePath,targetKind:r.targetKind,targetName:r.targetName});t.has(o)||(t.add(o),n.push(r))}return n}function tm(e,t){return jp(e.targetKind)-jp(t.targetKind)||nm(e.confidence,t.confidence)||Vp(e.sourceKind)-Vp(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function jp(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Vp(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function nm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Fc(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=bI(t,{sourceType:"module",plugins:["jsx","typescript"]}),i={file:e,source:t,ast:o,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,functionVariables:new WeakMap};return Pc(o,{ImportDeclaration(s){let a=s.node.source.value;for(let c of s.node.specifiers)N.isImportSpecifier(c)&&N.isIdentifier(c.local)?i.imports.set(c.local.name,{source:a,importedName:N.isIdentifier(c.imported)?c.imported.name:c.imported.value,localName:c.local.name,isDefault:!1}):N.isImportDefaultSpecifier(c)&&i.imports.set(c.local.name,{source:a,importedName:"default",localName:c.local.name,isDefault:!0})},FunctionDeclaration(s){s.node.id?.name&&i.functions.set(s.node.id.name,s.node)},VariableDeclarator(s){let a=s.getFunctionParent(),c=a&&(N.isFunctionDeclaration(a.node)||N.isFunctionExpression(a.node)||N.isArrowFunctionExpression(a.node))?a.node:null,l=c?i.functionVariables.get(c)??new Map:i.variables;c&&!i.functionVariables.has(c)&&i.functionVariables.set(c,l);for(let d of ur(s.node.id))l.set(d,N.isExpression(s.node.init)?s.node.init:null);if(N.isArrayPattern(s.node.id)&&N.isCallExpression(s.node.init)&&Bt(s.node.init.callee)==="useState"){let[d,f]=s.node.id.elements;N.isIdentifier(d)&&N.isIdentifier(f)&&i.stateSetters.set(d.name,f.name)}N.isIdentifier(s.node.id)&&Kp(s.node.init)&&i.functions.set(s.node.id.name,s.node.init)},ExportNamedDeclaration(s){let a=s.node.declaration,c=s.node.source?.value;if(c)for(let l of s.node.specifiers){if(!N.isExportSpecifier(l))continue;let d=N.isIdentifier(l.exported)?l.exported.name:l.exported.value,f=l.local.name;i.imports.set(d,{source:c,importedName:f,localName:d,isDefault:f==="default"})}if(N.isFunctionDeclaration(a)&&a.id?.name&&i.functions.set(a.id.name,a),N.isVariableDeclaration(a))for(let l of a.declarations)N.isIdentifier(l.id)&&Kp(l.init)&&i.functions.set(l.id.name,l.init)},ExportDefaultDeclaration(s){let a=s.node.declaration;if((N.isFunctionDeclaration(a)||N.isFunctionExpression(a)||N.isArrowFunctionExpression(a))&&i.functions.set("default",a),N.isIdentifier(a)){let c=i.functions.get(a.name);c&&i.functions.set("default",c)}}}),n.set(e,i),i}function ur(e){return!e||N.isVoidPattern(e)?[]:N.isIdentifier(e)?[e.name]:N.isObjectPattern(e)?e.properties.flatMap(t=>N.isObjectProperty(t)?ur(t.value):ur(t.argument)):N.isArrayPattern(e)?e.elements.flatMap(t=>t?ur(N.isRestElement(t)?t.argument:t):[]):N.isAssignmentPattern(e)?ur(e.left):N.isRestElement(e)?ur(e.argument):[]}function Kp(e){return N.isFunctionExpression(e)||N.isArrowFunctionExpression(e)}function rm(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function om(e,t){let n=await sm(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Fc(n,r,t.fileCache)}function im(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function sm(e,t,n){return wt(t)?mn(e,t,n):null}function Hi(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0}}function JI(e){return e?Je(e):null}function Je(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Je(n)]))}:{}}}import*as Oc from"@babel/parser";import _c from"@babel/traverse";import*as G from"@babel/types";import{classifySiteEditPropertyName as XI}from"@vcp-dev/contracts";var Mc=typeof _c=="function"?_c:_c.default;function Dc(e){let t=XI(e.propertyName);if(t.owner!=="generic")return it("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return it("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return it("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return it("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Oc.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(b){return it("repeat-not-found",`Unable to parse repeat source: ${b instanceof Error?b.message:String(b)}`)}let o=zI(r,e.element.sourceRange);if(!o)return it("repeat-not-found","The selected element is not inside a supported map repeat");if(!G.isIdentifier(o.callback.params[0]))return it("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=WI(r,o.collection,e.file,e.sources);if(!i)return it("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],d=[];for(let[b,E]of s.elements.entries()){if(!E||!G.isObjectExpression(E)||!fm(E))return it("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let v=[{kind:"index",index:b}];l.push(v),d.push({kind:"value",root:a.root,path:v})}let f=d.length;if(n.instanceCount!==void 0&&n.instanceCount!==f)return it("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${f}`);let m=n.instanceIndex;if(m>=f)return it("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let u=s.elements[m];if(!u||!G.isObjectExpression(u))return it("unsafe-collection","Selected repeat item is not an object");let g=qI(e.element,e.propertyName),h=ZI(u,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:d,selectedParentObjectLocator:d[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:f},(b,E)=>E),callbackItemName:o.callback.params[0].name,targetElementLocator:{kind:"jsx-node",strategy:"structural-path",file:e.element.identity.file,component:e.element.identity.component,structuralPath:e.element.identity.structuralPath,expectedRange:e.element.sourceRange},propertyName:e.propertyName,propertyState:h,selectedResolution:QI(u,e.propertyName),...g?{property:g}:{},selectionRef:n}:it("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function zI(e,t){let n=[];return Mc(e,{CallExpression(r){let o=am(r.node);o&&lm(o.callback,t)&&n.push({...o,span:cm(r.node)})},OptionalCallExpression(r){let o=am(r.node);o&&lm(o.callback,t)&&n.push({...o,span:cm(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function am(e){let t=e.callee;if(!G.isMemberExpression(t)&&!G.isOptionalMemberExpression(t)||t.computed||!G.isIdentifier(t.property)||t.property.name!=="map"||!G.isExpression(t.object))return null;let n=e.arguments[0];return!n||!G.isExpression(n)||!G.isArrowFunctionExpression(n)&&!G.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function WI(e,t,n,r){let o=ao(t);if(o&&G.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:mm(o)}},sourceFile:n};if(!G.isIdentifier(t))return null;let i=[];if(Mc(e,{VariableDeclarator(s){G.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ao(i[0].init);return!s||!G.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return HI(e,t.name,n,r)}function HI(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!G.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!G.isStringLiteral(o.source)||!G.isImportSpecifier(i))continue;let s=YI(n,o.source.value,r);if(!s)return null;let a=G.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Oc.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let d=GI(l,a),f=d?ao(d):null;return!f||!G.isArrayExpression(f)?null:{array:f,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function GI(e,t){let n=null;return Mc(e,{VariableDeclarator(r){n||!G.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!G.isExpression(r.node.init)||(n=r.node.init)}}),n}function YI(e,t,n){let r=pn(e,t);return[r,r+".tsx",r+".ts",r+".jsx",r+".js",r+"/index.tsx",r+"/index.ts",r+"/index.jsx",r+"/index.js"].find(i=>n.has(i))??null}function ao(e){return G.isParenthesizedExpression(e)?ao(e.expression):G.isTSAsExpression(e)?dm(e.typeAnnotation)?ao(e.expression):null:G.isTSSatisfiesExpression(e)?null:e}function dm(e){return G.isTSTypeReference(e)&&G.isIdentifier(e.typeName)&&e.typeName.name==="const"}function fm(e){return e.properties.every(t=>!G.isObjectProperty(t)||t.computed||!G.isExpression(t.value)?!1:Gi(t.value))}function Gi(e){if(G.isTSAsExpression(e)&&dm(e.typeAnnotation))return Gi(e.expression);if(G.isTSSatisfiesExpression(e))return!1;if(G.isArrayExpression(e))return e.elements.every(n=>!n||G.isSpreadElement(n)||!G.isExpression(n)?!1:Gi(n));if(G.isObjectExpression(e))return fm(e);let t=_t(e);return t.status==="resolved"||t.status==="undefined"}function ZI(e,t){let n=e.properties.filter(o=>G.isObjectProperty(o)&&pm(o.key)===t);if(n.length>1)return null;let r=n[0];return r?G.isExpression(r.value)?Gi(r.value)?"static":G.isIdentifier(r.value)||G.isMemberExpression(r.value)?"binding":null:null:"missing"}function QI(e,t){let n=e.properties.filter(o=>G.isObjectProperty(o)&&pm(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!G.isExpression(r.value)?{status:"undefined"}:_t(r.value)}function qI(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function pm(e){return G.isIdentifier(e)?e.name:G.isStringLiteral(e)?e.value:G.isNumericLiteral(e)?String(e.value):null}function mm(e){return{startLine:e.loc?.start.line??0,startColumn:e.loc?.start.column??0,endLine:e.loc?.end.line??0,endColumn:e.loc?.end.column??0}}function cm(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function lm(e,t){let n=mm(e);return um(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&um(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function um(e,t,n,r){return e===n?t-r:e-n}function it(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as jC}from"@vcp-dev/contracts";import*as Y from"@babel/types";import fo from"node:path";import*as B from"@babel/types";import*as bm from"@babel/parser";import Lc from"@babel/traverse";import*as ne from"@babel/types";function Yi(e,t){let n=[],r=e;for(;ne.isMemberExpression(r);){if(r.computed)if(ne.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ne.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ne.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ne.isIdentifier(r)||r.name!==t?null:n}function gm(e){if(ne.isIdentifier(e))return{base:e.name,path:[]};if(!ne.isMemberExpression(e))return null;let t=[],n=e;for(;ne.isMemberExpression(n);){if(n.computed)if(ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ne.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ne.isIdentifier(n)?{base:n.name,path:t}:null}function qe(e,t){let n=e;for(let r of t){if(r.kind==="property"){if(n===null||Array.isArray(n)||typeof n!="object"||!(r.name in n))return;n=n[r.name];continue}if(!Array.isArray(n)||r.index<0||r.index>=n.length)return;n=n[r.index]}return n}function hm(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,d,f){if(ne.isStringLiteral(i)||ne.isNumericLiteral(i)||ne.isBooleanLiteral(i))return i.value;if(ne.isNullLiteral(i))return null;if(ne.isTemplateLiteral(i))return i.expressions.length===0&&i.quasis.length===1?i.quasis[0].value.cooked??i.quasis[0].value.raw:void 0;if(ne.isTSAsExpression(i)||ne.isTSSatisfiesExpression(i)||ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,d,f);if(ne.isIdentifier(i)){let m=s.getBinding(i.name);if(!m)return;let u=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:d,visited:f});return u?.kind==="static"?u.value:void 0}if(ne.isArrayExpression(i)){let m=[];for(let u of i.elements){if(!u||ne.isSpreadElement(u))return;let g=await r(u,s,a,c,l,d,f);if(g===void 0)return;m.push(g)}return m}if(ne.isObjectExpression(i)){let m={};for(let u of i.properties){if(!ne.isObjectProperty(u)||u.computed)return;let g=null;if(ne.isIdentifier(u.key)?g=u.key.name:ne.isStringLiteral(u.key)&&(g=u.key.value),!g)return;if(u.shorthand){if(!ne.isIdentifier(u.value))return;let b=await r(u.value,s,a,c,l,d,f);if(b===void 0)return;m[g]=b;continue}if(!ne.isExpression(u.value))return;let h=await r(u.value,s,a,c,l,d,f);h!==void 0&&(m[g]=h)}return m}if(ne.isMemberExpression(i)){let m=await o(i,s,a,c,l,d,f);if(!m)return;let u=s.getBinding(m.base);if(!u)return;let g=await t({currentFile:a,binding:u,readFile:c,exists:l,fileCache:d,visited:f});return!g||g.kind!=="static"?void 0:qe(g.value,m.path)}}async function r(i,s,a,c,l,d,f){if(!ne.isSpreadElement(i))return await n(i,s,a,c,l,d,f)}async function o(i,s,a,c,l,d,f){if(ne.isIdentifier(i))return{base:i.name,path:[]};if(!ne.isMemberExpression(i))return null;let m=[],u=i;for(;ne.isMemberExpression(u);){if(u.computed){let g=u.property;if(ne.isNumericLiteral(g))m.unshift({kind:"index",index:g.value});else if(ne.isStringLiteral(g))m.unshift({kind:"property",name:g.value});else{let h=ne.isExpression(g)?await n(g,s,a,c,l,d,f):void 0;if(typeof h=="string")m.unshift({kind:"property",name:h});else if(Number.isInteger(h))m.unshift({kind:"index",index:h});else return null}}else{if(!ne.isIdentifier(u.property))return null;m.unshift({kind:"property",name:u.property.name})}u=u.object}return ne.isIdentifier(u)?{base:u.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var Sm=typeof Lc=="function"?Lc:Lc.default,ym=new WeakMap;function Em(e){try{return bm.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Zi(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Em(n);return e.set(t,{source:n,ast:o}),o}function Qi(e,t){let n=null,r=-1;for(let o of co(e).expressions){let i=o.node.loc;if(!i||!$c(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s>=r&&(n=o,r=s)}return n}function vm(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of co(e).expressions){if(!eC(o.node.loc,t))continue;let i=(o.node.end??0)-(o.node.start??0);i<=r&&(n=o,r=i)}return n}function Bc(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let o of co(e).jsxElements){let i=o.node.loc;if(!i||!$c(i,t))continue;let s=(o.node.end??0)-(o.node.start??0);s<=r&&(n=o,r=s)}return n}function co(e){let t=ym.get(e);if(t)return t;let n={expressions:[],jsxElements:[]};return Sm(e,{Expression(r){n.expressions.push(r)},JSXElement(r){n.jsxElements.push(r)}}),ym.set(e,n),n}function eC(e,t){return e?e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn:!1}function $c(e,t){let n=xm({line:e.start.line,column:e.start.column},{line:t.startLine,column:t.startColumn}),r=xm({line:e.end.line,column:e.end.column},{line:t.endLine,column:t.endColumn});return n>=0&&r<=0}function qi(e){return e.loc?{startLine:e.loc.start.line,startColumn:e.loc.start.column,endLine:e.loc.end.line,endColumn:e.loc.end.column}:null}function xm(e,t){return e.line!==t.line?e.line<t.line?-1:1:e.column!==t.column?e.column<t.column?-1:1:0}function dr(e,t){if(t)return jc(e,t);let n=gm(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function jc(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function lo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of co(e).expressions){if(jc(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function km(e,t,n,r){let o=null,i=Number.POSITIVE_INFINITY;for(let s of co(e).expressions){if(jc(s.node,t)!==n)continue;let a=s.node.loc;if(!a||!$c(a,r))continue;let c=(s.node.end??0)-(s.node.start??0);c<=i&&(o=s,i=c)}return o}function fr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function uo(e){let t=null;if(Sm(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function jt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Em(o),s={source:o,ast:i};return n.set(e,s),s}function tC(e){return B.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:B.isMemberExpression(e.callee)&&B.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function nC(e){if(!B.isNewExpression(e)||!B.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!B.isIdentifier(e.arguments[0])||!B.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!B.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!B.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(B.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(B.isIfStatement(i)&&B.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=B.isIfStatement(i)?i.test:null,c=a&&B.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=B.isIfStatement(i)?B.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,d=B.isReturnStatement(s)?s.argument:null;return!a||!B.isLogicalExpression(a,{operator:"&&"})||!B.isBinaryExpression(a.left,{operator:"==="})||!B.isUnaryExpression(a.left.left,{operator:"typeof"})||!B.isIdentifier(a.left.left.argument,{name:r.name})||!B.isStringLiteral(a.left.right,{value:"string"})||!B.isUnaryExpression(c,{operator:"!"})||!B.isBinaryExpression(c.argument,{operator:"in"})||!B.isIdentifier(c.argument.left,{name:r.name})||!B.isIdentifier(c.argument.right,{name:n.name})||!B.isReturnStatement(l)||!B.isIfStatement(i)||i.alternate||!B.isCallExpression(d)||!B.isMemberExpression(d.callee)||!B.isIdentifier(d.callee.object,{name:"Reflect"})||!B.isIdentifier(d.callee.property,{name:"get"})||d.arguments.length!==3||!B.isIdentifier(d.arguments[0],{name:n.name})||!B.isIdentifier(d.arguments[1],{name:r.name})||!B.isIdentifier(d.arguments[2],{name:o.name})?null:e.arguments[0].name}function rC(e){let t=e.getFunctionParent();if(!t)return null;if(t.isFunctionDeclaration()){let s=t.node.id?.name;if(!s)return null;let a=t.parentPath?.isExportDefaultDeclaration()?"default":(t.parentPath?.isExportNamedDeclaration(),s);return{componentName:s,exportName:a}}if(!t.isArrowFunctionExpression()&&!t.isFunctionExpression())return null;let n=t.parentPath;if(!n?.isVariableDeclarator()||!B.isIdentifier(n.node.id))return null;let r=n.node.id.name,o=n.parentPath,i=o?.parentPath?.isExportDefaultDeclaration()?"default":(o?.parentPath?.isExportNamedDeclaration(),r);return{componentName:r,exportName:i}}function oC(e,t){let n=rC(e.path);if(!n)return null;let r=nr(e,t);return r?{...n,...r}:null}function iC(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Vc(e,t){let n=[{kind:"component-prop",file:t.file,displayName:`${t.componentName}.${t.propName}`,canEditHere:!0}];return e.kind==="external"?{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:e.editMode==="readonly"?"readonly":"upstream"}:{...e,chainPrefix:[...n,...e.chainPrefix??[]],editMode:"upstream"}}function Kc(e,t){for(let n of e.program.body){if(t==="default"&&B.isExportDefaultDeclaration(n))return B.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(B.isFunctionDeclaration(n.declaration)||B.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(B.isExportNamedDeclaration(n)){if(n.declaration){if(B.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(B.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((B.isFunctionDeclaration(n.declaration)||B.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((B.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&B.isExportSpecifier(r))return n.source?{kind:"re-export",name:r.local.name,source:n.source.value}:{kind:"local-binding",name:r.local.name}}}return null}function Im(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`${g}::${h.kind}::${h.identifier.name}`;if(I.has(R))return null;I.add(R);try{let P=await a({currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I});if(P)return P;if(h.path.isImportSpecifier()||h.path.isImportDefaultSpecifier())return await f({currentFile:g,binding:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,fileCache:v,visited:I});if(h.kind==="param")return null;if(h.path.isVariableDeclarator()){let T=h.path.node.init;if(!T||!B.isExpression(T))return null;let C=nC(T);if(C&&!h.path.scope.getBinding("Proxy")&&!h.path.scope.getBinding("Reflect")){let M=h.path.scope.getBinding(C),U=M?await s({...u,binding:M}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let A=h.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let M=await t({currentFile:g,expressionPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(M)return M;if(A.isCallExpression()){let U=await n({currentFile:g,callPath:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(U)return U}}let F=await r(T,h.path.scope,g,b,E,v,I);return F===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:F,sourceKind:"binding"}}if(h.path.isIdentifier()&&h.path.parentPath?.isExportDefaultDeclaration()){let T=h.path.parentPath.node.declaration;if(!B.isExpression(T))return null;let C=await r(T,h.path.scope,g,b,E,v,I);return C===void 0?null:{kind:"static",file:g,root:{kind:"binding",name:h.identifier.name},value:C,sourceKind:"binding"}}return null}finally{I.delete(R)}}async function a(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(!h.path.isVariableDeclarator()||!h.path.get("id").isArrayPattern())return null;let R=h.path,P=R.node.init;if(!P||!B.isCallExpression(P))return null;let T=tC(P);if(!T||!B.isArrayPattern(R.node.id)||R.node.id.elements.findIndex(U=>B.isIdentifier(U)&&U.name===h.identifier.name)!==0)return null;let A=T==="useReducer"?1:0,F=P.arguments[A];if(!F||!B.isExpression(F))return null;let M=await r(F,R.scope,g,b,E,v,I);return M===void 0?null:{kind:"static",file:g,root:{kind:"hook-state",name:h.identifier.name,hook:T},value:M,sourceKind:"binding"}}async function c(u){let g=oC(u.binding,u.sourceInfo);if(!g||!u.graph)return null;let h=[...u.graph.elements.values()].filter(T=>iC(T,u.currentFile,g.componentName,g.exportName));if(h.length!==1)return null;let b=h[0],E=b.attributes?.find(T=>T.name===g.propName);if(E&&!E.source){let T=await l({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,fileCache:u.fileCache});if(T)return Vc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile})}if(!E?.source){let T=await d({caller:b,propName:g.propName,remainingPath:g.remainingPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return Vc(T,{componentName:g.componentName,propName:g.propName,file:b.sourceFile});let C=_f(u.binding,g.componentName,g.propName);if(!C||C.propName!==g.propName)return null;let A=await r(C.expressionPath.node,C.expressionPath.scope,u.currentFile,u.readFile,u.exists,u.fileCache,u.visited);if(A===void 0)return null;let F=g.remainingPath;return F.length>0&&qe(A,F)===void 0?null:{kind:"value",file:u.currentFile,root:{kind:"binding",name:g.propName},path:F,sourceKind:"binding",semanticKind:"component-prop",displayExpression:C.displayPath,chainPrefix:[{kind:"component-prop",file:u.currentFile,displayName:C.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await jt(b.sourceFile,u.readFile,u.fileCache);if(!v.ast)return null;let I=km(v.ast,v.source,E.source.expression,E.sourceRange)??lo(v.ast,v.source,E.source.expression);if(!I)return null;let R={...E.source,expression:fr(E.source.expression,g.remainingPath),path:[...E.source.path,...g.remainingPath]},P=await o({currentFile:b.sourceFile,expressionPath:I,sourceInfo:R,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});return P?Vc(P.kind==="external"?P:{...P,displayExpression:R.expression},{componentName:g.componentName,propName:g.propName,file:b.sourceFile}):null}async function l(u){let g=await jt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Bc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement").get("attributes").find(R=>R.isJSXAttribute()&&R.node.name.type==="JSXIdentifier"&&R.node.name.name===u.propName);if(!b?.isJSXAttribute())return null;let E=b.get("value"),v=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!v?.isExpression())return null;let I=qi(v.node);return I?{kind:"value",file:u.caller.sourceFile,root:{kind:"expression",sourceRange:I},path:u.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:u.propName,editMode:"upstream",diagnostics:[]}:null}async function d(u){let g=await jt(u.caller.sourceFile,u.readFile,u.fileCache);if(!g.ast)return null;let h=Bc(g.ast,u.caller.sourceRange);if(!h)return null;let b=h.get("openingElement");for(let E of b.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let v=E.get("argument");if(!v.isExpression())continue;let I=await i({expression:v.node,scope:v.scope,source:g.source,currentFile:u.caller.sourceFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)continue;let R=[{kind:"property",name:u.propName},...u.remainingPath],P={...I,expression:fr(I.expression,R),path:[...I.path,...R]},T=await o({currentFile:u.caller.sourceFile,expressionPath:v,sourceInfo:P,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(T)return T.kind==="external"?T:{...T,displayExpression:P.expression}}return null}async function f(u){let{currentFile:g,binding:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.path.parentPath;if(!R||!R.isImportDeclaration())return null;let P=R.node.source.value;if(typeof P!="string")return null;let T=await mn(g,P,E);if(!T)return null;if(h.path.isImportDefaultSpecifier()){let q=await jt(T,b,v),Ne=q.ast?Kc(q.ast,"default"):null,Z=await m({file:T,exportName:"default",readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!Z||Z.kind!=="static"?null:{kind:"static",file:Ne?.kind==="default-expression"?Z.file:T,root:Ne?.kind==="default-expression"?Z.root:{kind:"default-export"},value:Z.value,sourceKind:"imported-binding"}}if(!h.path.isImportSpecifier())return null;let C=h.path.node.imported,A=B.isIdentifier(C)?C.name:C.value,F=await jt(T,b,v),M=F.ast?Kc(F.ast,A):null,U=await m({file:T,exportName:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return U?U.kind==="external"?U:{kind:"static",file:M?.kind==="re-export"?U.file:T,root:M?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==M?.name?U.root:{kind:"named-export",name:A},value:U.value,sourceKind:"imported-binding"}:null}async function m(u){let{file:g,exportName:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=`export::${g}::${h}`;if(!I.has(R)){I.add(R);try{let P=await jt(g,b,v);if(!P.ast)return;let T=Kc(P.ast,h);if(!T)return;if(T.kind==="default-expression"){let M=T.expression;if(!M||!B.isIdentifier(M))return;let U=uo(P.ast).getBinding(M.name);return U?await s({currentFile:g,binding:U,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}if(T.kind==="re-export"){if(!T.source||!T.name)return;let M=await mn(g,T.source,E);return M?m({...u,file:M,exportName:T.name}):void 0}let C=T.name;if(!C)return;let A=uo(P.ast).getBinding(C);return A?await s({currentFile:g,binding:A,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I})??void 0:void 0}finally{I.delete(R)}}}return{resolveExportValue:m,resolveComponentPropBinding:c,resolveBindingTarget:s}}import*as W from"@babel/types";function Jc(e,t){let n=e.scope.getBinding(t);if(!n)return null;let r=n.path.getFunctionParent();if(!r||!r.isArrowFunctionExpression()&&!r.isFunctionExpression())return null;let o=r.node.params[0],i=kt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!sC(s,r)?null:{callPath:s,basePath:i}}function sC(e,t){let n=e.node.callee;return!W.isMemberExpression(n)||!W.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Nm(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Pi(r,t)}function Cm(e,t){return e?W.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Rm(e,t,n,r,o){let i=W.isExpression(e.body)?e.body:e.body.body.find(a=>W.isReturnStatement(a))?.argument;if(!i||!W.isExpression(i))return;let s=Uc(i,t,n,r,o);return typeof s=="number"?s:void 0}function Uc(e,t,n,r,o){if(W.isNumericLiteral(e)||W.isStringLiteral(e)||W.isBooleanLiteral(e))return e.value;if(W.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(W.isMemberExpression(e)){let i=Yi(e,t);if(i)return qe(r,i);let s=Yi(e,n);return s?qe(o,s):void 0}if(W.isBinaryExpression(e)&&e.operator==="-"){let i=W.isExpression(e.left)?Uc(e.left,t,n,r,o):void 0,s=W.isExpression(e.right)?Uc(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function aC(e){if(W.isExpression(e.body))return e.body;for(let t of e.body.body)if(W.isReturnStatement(t)&&t.argument&&W.isExpression(t.argument))return t.argument;return null}function cC(e,t,n){let r=Dn(e,t,n);return typeof r=="boolean"?r:void 0}function Dn(e,t,n){if(W.isStringLiteral(e)||W.isNumericLiteral(e)||W.isBooleanLiteral(e))return e.value;if(W.isNullLiteral(e))return null;if(W.isIdentifier(e))return e.name===t?n:void 0;if(W.isMemberExpression(e)){let r=Yi(e,t);return r?qe(n,r):void 0}if(W.isUnaryExpression(e)&&e.operator==="!"){let r=Dn(e.argument,t,n);return r===void 0?void 0:!r}if(W.isLogicalExpression(e)){let r=Dn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Dn(e.right,t,n);if(e.operator==="||")return r||Dn(e.right,t,n)}if(W.isBinaryExpression(e)){let r=W.isExpression(e.left)?Dn(e.left,t,n):void 0,o=W.isExpression(e.right)?Dn(e.right,t,n):void 0;if(r===void 0||o===void 0)return;switch(e.operator){case"===":return r===o;case"!==":return r!==o;case"==":return r==o;case"!=":return r!=o;default:return}}}function wm(e){let t=[],n=e;for(;W.isMemberExpression(n)||W.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(W.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(W.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(W.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(W.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return W.isIdentifier(n)?{base:n.name,segments:t}:null}function Pm(e){return e.some(t=>t.kind==="dynamic")}function lC(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Am(e,t){if(!Array.isArray(e.value))return null;let n=e.collectionPathMap?.length?e.collectionPathMap:e.value.map((r,o)=>[...e.pathPrefix??[],{kind:"index",index:e.collectionIndexMap?.[o]??o}]);return n.length>0?n.map(r=>[...r,...t]):null}function uC(e,t){let n=[],r=[];for(let o of t){let i=qe(e,o);if(!Array.isArray(i))return null;for(let[s,a]of i.entries())n.push(a),r.push([...o,{kind:"index",index:s}])}return{value:n,collectionPathMap:r}}function Tm(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o}=e;async function i(u){let{currentFile:g,callPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u,R=h.node.callee;if(!W.isMemberExpression(R)||!W.isIdentifier(R.property)||R.property.name!=="map")return null;let P=h.get("callee");if(!P.isMemberExpression())return null;let T=P.get("object");if(Array.isArray(T)||!T.isExpression())return null;let C=await s({currentFile:g,expressionPath:T,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return!C||!Array.isArray(C.value)||C.value.length===0?null:C}async function s(u){let{currentFile:g,expressionPath:h,readFile:b,exists:E,fileCache:v,visited:I}=u;if(h.isIdentifier()){let R=h.scope.getBinding(h.node.name);if(!R)return null;let P=await t({currentFile:g,binding:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});return P?.kind==="static"?P:null}if(h.isCallExpression())return c({currentFile:g,callPath:h,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(h.isTSAsExpression()||h.isTSSatisfiesExpression()||h.isTSNonNullExpression()){let R=h.get("expression");if(!Array.isArray(R)&&R.isExpression())return s({...u,expressionPath:R})}if(h.isArrayExpression()){let R=qi(h.node);if(!R)return null;let P=await n(h.node,h.scope,g,b,E,v,I);return Array.isArray(P)?{kind:"static",file:g,root:{kind:"expression",sourceRange:R},value:P,sourceKind:"binding"}:null}if(h.isMemberExpression()){let R=await r({expression:h.node,scope:h.scope,currentFile:g,readFile:b,exists:E,fileCache:v,visited:I});if(!R)return null;let P=await o({currentFile:g,expressionPath:h,sourceInfo:R,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!P||P.kind==="external")return null;let T=await a({currentFile:g,expressionPath:h,provenance:P,readFile:b,exists:E,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:v,visited:I});if(!T||T.kind!=="static")return null;if(P.collectionPathMap?.length){let A=uC(T.value,P.collectionPathMap);if(A)return{kind:"static",file:P.file,root:P.root,value:A.value,sourceKind:P.sourceKind,collectionPathMap:A.collectionPathMap}}let C=qe(T.value,P.path);return Array.isArray(C)?{kind:"static",file:P.file,root:P.root,value:C,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function a(u){let{provenance:g}=u;if(g.root.kind==="binding"){let v=u.expressionPath.scope.getBinding(g.root.name);if(!v&&g.file!==u.currentFile){let I=await jt(g.file,u.readFile,u.fileCache);v=I.ast?uo(I.ast).getBinding(g.root.name):void 0}return v?await t({currentFile:g.file,binding:v,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited}):null}if(g.root.kind!=="expression")return null;let h=await jt(g.file,u.readFile,u.fileCache);if(!h.ast)return null;let b=vm(h.ast,g.root.sourceRange);if(!b)return null;let E=await n(b.node,b.scope,g.file,u.readFile,u.exists,u.fileCache,u.visited);return E===void 0?null:{kind:"static",file:g.file,root:g.root,value:E,sourceKind:g.sourceKind}}async function c(u){return await l(u)??await d(u)??await f(u)}async function l(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.isIdentifier(h.property)||h.property.name!=="filter")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!W.isArrowFunctionExpression(I)&&!W.isFunctionExpression(I))return null;let R=I.params[0];if(!W.isIdentifier(R))return null;let P=aC(I);if(!P)return null;let T=[],C=[],A=[];for(let[F,M]of v.value.entries()){let U=cC(P,R.name,M);if(typeof U!="boolean")return null;if(U){T.push(M),C.push(v.collectionIndexMap?.[F]??F);let q=v.collectionPathMap?.[F];q&&A.push(q)}}return{...v,value:T,pathPrefix:v.pathPrefix,collectionIndexMap:C,...A.length>0?{collectionPathMap:A}:{}}}async function d(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.isIdentifier(h.property)||h.property.name!=="slice")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I,R]=g.node.arguments,P=Cm(I,0),T=Cm(R,v.value.length);if(P===null||T===null)return null;let C=Math.max(0,P<0?v.value.length+P:P),A=Math.max(0,T<0?v.value.length+T:T),F=v.value.map((U,q)=>v.collectionIndexMap?.[q]??q).slice(C,A),M=v.collectionPathMap?.slice(C,A);return{...v,value:v.value.slice(C,A),pathPrefix:v.pathPrefix,collectionIndexMap:F,...M?{collectionPathMap:M}:{}}}async function f(u){let{callPath:g}=u,h=g.node.callee;if(!W.isMemberExpression(h)||!W.isIdentifier(h.property)||h.property.name!=="sort"&&h.property.name!=="toSorted")return null;let b=g.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let v=await s({currentFile:u.currentFile,expressionPath:E,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!v||!Array.isArray(v.value))return null;let[I]=g.node.arguments;if(!W.isArrowFunctionExpression(I)&&!W.isFunctionExpression(I))return null;let[R,P]=I.params;if(!W.isIdentifier(R)||!W.isIdentifier(P))return null;let T=v.value.map((A,F)=>({value:A,sourceIndex:v.collectionIndexMap?.[F]??F,originalIndex:F})),C=[...T];for(let A of T)for(let F of T)if(Rm(I,R.name,P.name,A.value,F.value)===void 0)return null;return C.sort((A,F)=>{let M=Rm(I,R.name,P.name,A.value,F.value)??0;return M===0?A.originalIndex-F.originalIndex:M}),{...v,value:C.map(A=>A.value),pathPrefix:v.pathPrefix,collectionIndexMap:C.map(A=>A.sourceIndex),...v.collectionPathMap?{collectionPathMap:C.map(A=>v.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function m(u){let g=null,h,b=[];for(let v of u.segments){if(v.kind!=="dynamic")continue;let I=await r({expression:v.expression,scope:u.expressionPath.scope,source:u.fileCache.get(u.currentFile)?.source,currentFile:u.currentFile,readFile:u.readFile,exists:u.exists,fileCache:u.fileCache,visited:u.visited});if(!I)return null;let R=Jc(u.expressionPath,I.base);if(!R)return null;let P=await i({currentFile:u.currentFile,callPath:R.callPath,readFile:u.readFile,exists:u.exists,graph:u.graph,externalSourceResolvers:u.externalSourceResolvers,externalAdapters:u.externalAdapters,functionCallContracts:u.functionCallContracts,fileCache:u.fileCache,visited:u.visited});if(!P||!Array.isArray(P.value))return null;let T=P.value.map((C,A)=>{let F=qe(P.value,[{kind:"index",index:A},...R.basePath,...I.path]);return lC(F)});if(T.some(C=>C===null)||g!==null&&g!==T.length)return null;g=T.length,h??=P.collectionIndexMap,b.push(T)}if(g===null||g===0)return null;let E=[];for(let v=0;v<g;v+=1){let I=[...u.rootPath],R=0;for(let P of u.segments){if(P.kind==="dynamic"){let T=b[R]?.[v];if(!T)return null;I.push(T),R+=1;continue}I.push({...P})}E.push(I)}return{...h?{collectionIndexMap:h}:{},collectionPathMap:E}}return{resolveRepeatCollectionTarget:i,resolveCollectionCallTarget:c,resolveDynamicMemberPathMap:m}}var{normalizeExpressionWithScope:dC,evaluateStaticExpression:es}=hm({resolveBindingTarget:e=>Yc(e)}),{resolveRepeatCollectionTarget:fC,resolveCollectionCallTarget:pC,resolveDynamicMemberPathMap:mC}=Tm({resolveBindingTarget:e=>Yc(e),evaluateStaticExpression:es,buildExpressionSourceInfo:Vt,resolveSourceInfoProvenance:bt}),{resolveExportValue:gC,resolveComponentPropBinding:hC,resolveBindingTarget:Yc}=Im({resolveExternalExpression:Qc,resolveCollectionCallTarget:pC,evaluateStaticExpression:es,resolveSourceInfoProvenance:bt,buildExpressionSourceInfo:Vt});function $m(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}function Fm(e,t,n){return{kind:"external",file:e,sourceType:"api-field",sourceId:t,displayPath:n,editMode:"readonly",diagnostics:[{code:"external-source-readonly",message:"Dynamic API data is read-only for content edits"}]}}async function jm(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Zi(s,t,n);if(!a)return null;let c=Qi(a,r.sourceRange);if(!c)return null;let l=await Vt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let m=await nl({currentFile:t,expressionPath:c,readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:new Set});return m?Wc(m,dr(c.node,n)):null}let d=new Set,f=await BC({currentFile:t,expressionPath:c,segment:{...r,source:l},readFile:o,exists:i,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:s,visited:d});return f?Wc(f,l.expression):null}async function pr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Zi(i,t,n);if(!s)return null;let a=e.sourceRange?Qi(s,e.sourceRange):e.expression!==void 0?lo(s,n,e.expression):null;if(!a)return null;let c=rl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,d=await Vt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),f=d?await bt({currentFile:t,expressionPath:c,sourceInfo:d,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await $C({currentFile:t,expressionPath:c,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l});return Wc(f,e.expression??dr(c.node,n))}async function Zc(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Zi(i,t,n);if(!s)return st("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?yC({file:t,source:n,ast:s,segment:e.target.segment,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:a}):xC({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Vt(e){if(Y.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!Y.isMemberExpression(e.expression))return null;let t=await dC(e.expression,e.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);return t?{kind:t.path.some(n=>n.kind==="index")?"index-expression":"member-expression",expression:dr(e.expression,e.source),base:t.base,path:t.path}:null}function Wc(e,t){if(!e||e.kind==="value"&&e.editMode==="readonly")return null;if(e.kind==="external")return{kind:"external-entry",file:e.file,sourceType:e.sourceType,sourceId:e.sourceId,adapterId:e.adapterId,displayExpression:e.displayPath};let n={kind:"value",root:e.root,path:e.path.length>0?e.path:[]};return{kind:"value-binding",file:e.file,locator:n,root:e.root,path:e.path,displayExpression:e.displayExpression??t,sourceKind:e.sourceKind,...e.collectionIndexMap?{collectionIndexMap:e.collectionIndexMap}:{},...e.collectionPathMap?{collectionPathMap:e.collectionPathMap}:{}}}async function yC(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Qi(r,o.sourceRange),d=l?await Vt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!d){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return _m(t,o.value);let m=await nl({currentFile:t,expressionPath:l,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});return m?m.kind==="external"?Bm(t,m):Gc(t,dr(l.node,n),m):bC({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return st("unsupported-expression","Unable to locate text expression for provenance resolution");let f=await bt({currentFile:t,expressionPath:l,sourceInfo:d,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!f){let m=Hc(l.node);if(m)return st(m.code,m.message);let u=l.scope.getBinding(d.base);if(u?.path.isVariableDeclarator()){let g=Hc(u.path.node.init);if(g)return st(g.code,g.message)}return u?.path.isVariableDeclarator()&&Y.isCallExpression(u.path.node.init)?SC("unsupported-expression",Xm(u.path.node.init,e.functionCallContracts)):st("unsupported-expression",`Unable to resolve provenance for expression "${d.expression}"`)}return f.kind==="external"?Bm(t,f):Gc(t,d.expression,f)}async function xC(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return st("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=lo(r,n,o.conditionExpression);if(!l)return st("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let d=await bt({currentFile:t,expressionPath:l,sourceInfo:o.conditionSource,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d)return st("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(d.kind==="external")return st("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let f=Gc(t,o.conditionExpression,d);return f.finalSource?{...f,finalSource:{...f.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...f.chain,{kind:"conditional-branch",file:d.file,displayName:o.conditionExpression,canEditHere:!0}]}:f}function _m(e,t){return{finalSource:{kind:"jsx-literal",file:e,locator:null,displayPath:t},chain:[{kind:"jsx-literal",file:e,displayName:t,canEditHere:!0}],confidence:"exact",editMode:"direct",diagnostics:[]}}async function bC(e){let t=await Km(e);if(t.length===0)return st("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(EC(e.expression))return Vm(t);if(Jm(e.expression))return st("unsupported-expression","i18n helpers require a static message id string");if(Y.isMemberExpression(e.expression)&&e.expression.computed&&!Y.isNumericLiteral(e.expression.property)&&!Y.isStringLiteral(e.expression.property))return st("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return st(n.code,n.message)}function st(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function SC(e,t){return Vm([{code:e,message:t}])}function Vm(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function EC(e){return Y.isCallExpression(e)||Y.isConditionalExpression(e)||Y.isLogicalExpression(e)||Y.isBinaryExpression(e)}function po(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.message}`;return t.has(r)?!1:(t.add(r),!0)})}async function Km(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Hc(t);if(l)return[l];if(Y.isCallExpression(t))return[{code:"unsupported-expression",message:Xm(t,c)}];if(Y.isMemberExpression(t)&&t.computed){let d=t.property;if(!Y.isNumericLiteral(d)&&!Y.isStringLiteral(d)){if(!Y.isExpression(d))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await es(d,n,r,o,i,s,a);if(typeof m!="string"&&!Number.isInteger(m))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return Y.isBinaryExpression(t)?po([...await Xc(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):Y.isLogicalExpression(t)?po([...await Xc(t.left,t.right,e),{code:"unsupported-expression",message:t.operator==="??"||t.operator==="||"?"Fallback expressions are recognized but remain readonly until a safer composition editing strategy is available":"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):Y.isConditionalExpression(t)?po([...await Xc(t.test,t.consequent,t.alternate,e),{code:"unsupported-expression",message:"Complex conditional expressions are recognized but remain readonly until a safer editing strategy is available"}]):[]}function Hc(e){return Jm(e)?Om("i18n helpers require a static message id string"):RC(e)?Om("CMS helpers require static entry id and field path string arguments"):null}async function Xc(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Km({...t,expression:o}));return r}function vC(e,t){let n=(t??[]).filter(r=>r.sourceType===e.sourceType&&(r.capabilities===void 0||r.capabilities.includes("write-text")));if(e.adapterId){let r=n.find(o=>o.adapterId===e.adapterId);if(r)return{adapterId:r.adapterId,editMode:"proxy",diagnostics:[]}}else if(n.length>0)return{adapterId:n[0]?.adapterId,editMode:"proxy",diagnostics:[]};return{adapterId:void 0,editMode:"readonly",diagnostics:[kC(e.sourceType)]}}async function Qc(e){for(let n of AC){if(!Mm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Lm(Dm(r),e.externalAdapters)}let t={currentFile:e.currentFile,expressionPath:e.expressionPath,readFile:e.readFile,exists:e.exists,graph:e.graph};for(let n of e.externalSourceResolvers??[]){if(!Mm(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Lm(Dm(r),e.externalAdapters)}return null}function kC(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function IC(e){return{code:"external-source-readonly",message:e}}function Om(e){return{code:"unsupported-expression",message:e}}function qc(e){return!e||!Y.isCallExpression(e)?null:Y.isIdentifier(e.callee)?e.callee.name:Y.isMemberExpression(e.callee)&&!e.callee.computed&&Y.isIdentifier(e.callee.object)&&Y.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Mm(e,t){if(!t||t.length===0)return!0;let n=qc(e.node);return n?t.includes(n):!1}function Dm(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:po(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Lm(e,t){let n=vC(e.match,t);return{kind:"external",file:e.match.file,sourceType:e.match.sourceType,sourceId:e.match.sourceId,adapterId:e.match.adapterId??n.adapterId,displayPath:e.match.displayPath,editMode:e.editMode==="readonly"?"readonly":n.editMode,diagnostics:po([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function CC(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!Y.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!Y.isStringLiteral(n)||!Y.isStringLiteral(r))return null;let o=n.value,i=r.value;return{sourceType:"cms-field",sourceId:`${o}:${i}`,file:`cms://${o}/${i.replace(/\./g,"/")}`,displayPath:`${o}.${i}`}}function RC(e){return!!e&&Y.isCallExpression(e)&&Y.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!Y.isStringLiteral(e.arguments[0])||!Y.isStringLiteral(e.arguments[1]))}function Um(e){if(!(!e||!Y.isCallExpression(e))){if(Y.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&Y.isStringLiteral(t)?t.value:null}if(Y.isMemberExpression(e.callee)&&!e.callee.computed&&Y.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&Y.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!Y.isObjectExpression(t))return null;for(let n of t.properties)if(Y.isObjectProperty(n)&&!n.computed&&(Y.isIdentifier(n.key)&&n.key.name==="id"||Y.isStringLiteral(n.key)&&n.key.value==="id")&&Y.isStringLiteral(n.value))return n.value.value;return null}}}function Jm(e){return Um(e)===null}async function NC(e,t,n){let r=new Set,o=fo.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=fo.posix.dirname(o);if(i===o){r.add(".");break}o=i}r.add("src"),r.add(".");for(let i of r){let s=i==="."?["locales","messages"]:[fo.posix.join(i,"locales"),fo.posix.join(i,"messages")];for(let a of s){let c=fo.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function wC(e){let t=Um(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await NC(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function PC(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!Y.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!Y.isExpression(n))return null;let o=await es(n,e.expressionPath.scope,e.currentFile,e.readFile,e.exists,e.fileCache,e.visited);if(typeof o!="string"||o.length===0)return null;let i={sourceType:"api-field",sourceId:o,file:`api://${o}`,displayPath:o};return r?{match:i,editMode:"readonly",diagnostics:[IC("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var AC=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>CC(e)},{helperNames:["apiField"],resolve:e=>PC(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>wC({currentFile:e,expressionPath:t,exists:n})}];function el(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Bm(e,t){return{finalSource:{kind:t.sourceType,file:t.file,locator:null,displayPath:t.displayPath,externalSource:{sourceType:t.sourceType,sourceId:t.sourceId,adapterId:t.adapterId}},chain:[...t.chainPrefix??[],{kind:t.sourceType,file:t.file,displayName:t.displayPath,canEditHere:t.editMode!=="readonly"}],confidence:"exact",editMode:t.editMode==="direct"?t.file===e?"direct":"proxy":t.editMode,diagnostics:t.diagnostics}}function Gc(e,t,n){let r={kind:"value",root:n.root,path:n.path.length>0?n.path:[]},o=n.path.some(l=>l.kind==="index"),i=LC(n),s;n.semanticKind?s=n.semanticKind:i?s="config-entry":n.sourceKind==="repeat-template"?s="repeat-template":n.path.length===0?s=n.sourceKind==="imported-binding"?"imported-binding":"binding":s=o?"array-item":"object-field";let a=n.displayExpression??t,c=[...n.chainPrefix??[]];return n.sourceKind==="binding"?c.push({kind:"binding",file:n.file,displayName:n.root.kind==="binding"?n.root.name:a,canEditHere:n.editMode!=="readonly"}):n.sourceKind==="imported-binding"?c.push({kind:"imported-binding",file:n.file,displayName:n.root.kind==="named-export"?n.root.name:"default",canEditHere:n.editMode!=="readonly"}):n.sourceKind==="repeat-template"&&c.push({kind:"repeat-template",file:n.file,displayName:t,canEditHere:n.editMode!=="readonly"}),n.path.length>0&&n.sourceKind!=="repeat-template"&&c.push({kind:o?"array-item":"object-field",file:n.file,displayName:a,canEditHere:n.editMode!=="readonly"}),i&&c.push({kind:"config-entry",file:n.file,displayName:i.displayPath,canEditHere:n.editMode!=="readonly"}),{finalSource:{kind:s,file:n.file,locator:r,root:n.root,path:n.path,displayPath:a,externalSource:i?{sourceType:"config-entry",sourceId:i.sourceId}:void 0},chain:n.editMode==="readonly"?c.map(l=>({...l,canEditHere:!1})):c,confidence:n.sourceKind==="repeat-template"?"safe-derived":"exact",editMode:n.editMode??(n.file===e?"direct":"proxy"),diagnostics:n.diagnostics??[]}}var TC=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function tl(e,t){let n=[...TC,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Xm(e,t){let n=e.callee;return Y.isIdentifier(n)&&tl(n.name,t)?.purity==="side-effect"?`Helper "${n.name}" is registered as side-effectful and remains readonly`:"Function calls remain readonly because purity does not establish an identity-preserving write target"}async function nl(e){let t=await Qc(e);if(t)return t;let n=await zm({...e,expressionPath:e.expressionPath});if(n)return n;if(e.expressionPath.isTemplateLiteral()){let r=e.expressionPath.node.expressions[0],o=e.expressionPath.get("expressions.0");if(e.expressionPath.node.expressions.length===1&&r&&o&&!Array.isArray(o)&&o.isExpression()){let i=await Vt({expression:o.node,scope:o.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(i){let s=await bt({...e,expressionPath:o,sourceInfo:i});if(s&&s.kind==="value")return{...s,displayExpression:i.expression,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]}}}}return await MC(e)}async function zm(e){let t=await Ct({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=rl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:el(t.provenance)}async function Ct(e){let t=rl(e.expressionPath),n=OC(e.currentFile,t.node);if(n&&e.visited.has(n))return null;n&&e.visited.add(n);try{if(t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral())return{kind:"none"};if(t.isIdentifier()){let r=await Vt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await bt({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isMemberExpression()){let r=await Vt({expression:t.node,scope:t.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(!r)return null;let o=await bt({currentFile:e.currentFile,expressionPath:t,sourceInfo:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!o||o.kind==="external"?null:{kind:"source",provenance:o}}if(t.isConditionalExpression()){let r=t.get("test"),o=t.get("consequent"),i=t.get("alternate");if(Array.isArray(r)||Array.isArray(o)||Array.isArray(i)||!r.isExpression()||!o.isExpression()||!i.isExpression())return null;let s=await Ct({...e,expressionPath:r,allowComposed:!0}),a=await Ct({...e,expressionPath:o,allowComposed:!1}),c=await Ct({...e,expressionPath:i,allowComposed:!1});return zc(s,a,c)}if(t.isCallExpression())return FC({...e,expressionPath:t});if(!e.allowComposed)return null;if(t.isBinaryExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Ct({...e,expressionPath:r,allowComposed:!0}),s=await Ct({...e,expressionPath:o,allowComposed:!0});return zc(i,s)}if(t.isLogicalExpression()){let r=t.get("left"),o=t.get("right");if(Array.isArray(r)||Array.isArray(o)||!r.isExpression()||!o.isExpression())return null;let i=await Ct({...e,expressionPath:r,allowComposed:!0}),s=await Ct({...e,expressionPath:o,allowComposed:!0});return zc(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Ct({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function rl(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function FC(e){let t=qc(e.expressionPath.node);if(t==="Math.round"||t==="Math.floor"||t==="Math.ceil"||t==="Math.trunc"||t==="useCountUp"){let r=e.expressionPath.get("arguments.0");return!r||Array.isArray(r)||!r.isExpression()?null:Ct({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(Y.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Ct({...e,expressionPath:o,allowComposed:!1})}}return null}function zc(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!_C(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function _C(e,t){return e.file===t.file&&e.sourceKind===t.sourceKind&&JSON.stringify(e.root)===JSON.stringify(t.root)&&JSON.stringify(e.path)===JSON.stringify(t.path)&&JSON.stringify(e.collectionIndexMap??null)===JSON.stringify(t.collectionIndexMap??null)&&JSON.stringify(e.collectionPathMap??null)===JSON.stringify(t.collectionPathMap??null)}function OC(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function MC(e){if(!e.expressionPath.isCallExpression())return null;let t=qc(e.expressionPath.node);if(!t)return null;let n=tl(t,e.functionCallContracts);if(!n||n.purity!=="pure")return null;let r=n.sourceArgIndex??0,o=e.expressionPath.get(`arguments.${r}`);if(!o||Array.isArray(o)||!o.isExpression())return null;let i=await Wm({currentFile:e.currentFile,argumentPath:o,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return i?el(i):null}async function Wm(e){let t=await Qc({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(t)return t;let n=await Vt({expression:e.argumentPath.node,scope:e.argumentPath.scope,source:e.fileCache.get(e.currentFile)?.source,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(n){let r=await bt({currentFile:e.currentFile,expressionPath:e.argumentPath,sourceInfo:n,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return!r||r.kind==="external"?r:{...r,displayExpression:n.expression}}return await nl({currentFile:e.currentFile,expressionPath:e.argumentPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited})}async function DC(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!Y.isCallExpression(t))return null;let n=t.callee;if(!Y.isIdentifier(n))return null;let r=tl(n.name,e.functionCallContracts);if(!r||r.purity!=="pure")return null;let o=r.sourceArgIndex??0,i=e.binding.path.get("init");if(!i||Array.isArray(i)||!i.isCallExpression())return null;let s=i.get(`arguments.${o}`);if(!s||Array.isArray(s)||!s.isExpression())return null;let a=await Wm({currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited,argumentPath:s});return a?el(a):null}function LC(e){if(e.sourceKind!=="imported-binding")return null;let t=e.root.kind==="binding"||e.root.kind==="named-export"?e.root.name:e.root.kind==="default-export"?"default":null;if(!t)return null;let n=/(^|[\/.-])(config|settings)([\/.-]|$)/i.test(e.file),r=/config|settings/i.test(t);if(!n&&!r)return null;let o=fr(t,e.path);return{sourceId:o,displayPath:o}}async function BC(e){let t=e.segment.source;return t?bt({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:t,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited}):null}async function bt(e){let t=e.sourceInfo,n=Jc(e.expressionPath,t.base);if(n){let l=await fC({currentFile:e.currentFile,callPath:n.callPath,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,fileCache:e.fileCache,visited:e.visited});if(!l){let h=Nm(n.callPath,[...n.basePath,...t.path]);return zr(h)?Fm(e.currentFile,h.sourceId,h.displayPath):null}let d=Am(l,[...n.basePath,...t.path]),f=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:f},...n.basePath,...t.path],u=[{kind:"index",index:0},...n.basePath,...t.path];return qe(l.value,u)===void 0?null:{kind:"value",file:l.file,root:l.root,path:d?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...d?{collectionPathMap:d}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],d=r.path.parentPath;if(!l||l.kind!=="property"||!d?.isImportDeclaration())return null;let f=await mn(e.currentFile,d.node.source.value,e.exists);if(!f)return null;let m=await gC({file:f,exportName:l.name,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!m||m.kind==="external")return null;let u=t.path.slice(1);return qe(m.value,u)===void 0?null:{kind:"value",file:m.file,root:m.root,path:u,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Tf(r);if(o){let l=o.expressionPath,d=await Vt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(d){let f=await bt({...e,expressionPath:l,sourceInfo:{...d,expression:fr(d.expression,t.path),path:[...d.path,...t.path]}});if(f)return f}if(t.path.length===0){let f=await zm({currentFile:e.currentFile,expressionPath:l,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(f)return f}}if(r.kind==="param")return hC({currentFile:e.currentFile,binding:r,sourceInfo:t,graph:e.graph,readFile:e.readFile,exists:e.exists,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});let i=await DC({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(i)return i;let s=Ni(r,t.path);if(zr(s))return Fm(e.currentFile,s.sourceId,s.displayPath);let a=await Yc({currentFile:e.currentFile,binding:r,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});return a?a.kind==="external"?t.path.length===0?a:null:qe(a.value,t.path)===void 0?null:{kind:"value",file:a.file,root:a.root,path:t.path,sourceKind:a.sourceKind,collectionIndexMap:a.collectionIndexMap}:null}async function $C(e){let t=wm(e.expressionPath.node);if(!t||!Pm(t.segments))return null;let n=await bt({currentFile:e.currentFile,expressionPath:e.expressionPath,sourceInfo:{kind:"identifier",expression:t.base,base:t.base,path:[]},readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache,visited:e.visited});if(!n||n.kind==="external")return n;let r=await mC({...e,rootPath:n.path,segments:t.segments});return r?{...n,path:r.collectionPathMap[0]??n.path,sourceKind:"repeat-template",displayExpression:dr(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:r.collectionPathMap}:null}async function Hm(e){let t=jC(e.propertyName);if(t.owner==="blocked")return ln(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return ln(t.owner,{code:"owner-delegated",message:`Property '${e.propertyName}' is owned by ${t.owner}`});let n=e.element.attributes?.filter(l=>l.name===e.propertyName)??[];if(n.length>1)return ln("generic",{code:"duplicate-property-source",message:`Property '${e.propertyName}' has multiple explicit sources`});let r=n[0],o=[];r&&o.push({kind:"attribute",order:r.order??e.element.attributes.indexOf(r),attribute:r});let i=e.element.attributeSpreads??[];for(let l of i)o.push({kind:"spread",order:l.order,spread:l,target:await KC(e,l)});o.sort((l,d)=>l.order-d.order);let s=o.at(-1);if(!s)return{status:"missing",owner:"generic"};if(o.filter(l=>l.kind==="spread"&&l.order>s.order).some(l=>!l.target))return ln("generic",{code:"ambiguous-property-source",message:`A spread may provide or override property '${e.propertyName}'`});if(s.kind==="spread")return s.target?{status:"binding",owner:"generic",target:s.target}:ln("generic",{code:"ambiguous-property-source",message:`The final spread source for '${e.propertyName}' is not provably writable`});let c=o.filter(l=>l.kind==="spread"&&l.order<s.order);return e.operation==="remove"&&c.length>0?ln("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):VC(e,s.attribute)}async function VC(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await pr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.value,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return r&&r.kind!=="external-entry"?{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:r}}:ln("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' has an unresolved value source`})}if(!t.source?.expression)return{status:"direct",owner:"generic",attribute:t,target:{kind:"jsx-attribute",file:e.file,sourceRange:t.sourceRange}};let n=await pr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:t.source.expression,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});return!n||n.kind==="external-entry"?ln("generic",{code:"unsupported-property-source",message:`Property '${e.propertyName}' does not have a local writable source`}):{status:"binding",owner:"generic",attribute:t,target:{kind:"value-binding",target:n}}}async function KC(e,t){let n=t.source?.expression;if(!n)return;let r=await pr({file:e.file,source:e.source,sourceRange:t.sourceRange,expression:n,sourceInfo:t.source,readFile:e.readFile,exists:e.exists,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:e.fileCache});if(!(!r||r.kind==="external-entry"))return{kind:"value-binding",target:UC(r,e.propertyName)}}function UC(e,t){let n=[...e.path??[],{kind:"property",name:t}];return{...e,path:n,locator:e.locator?{...e.locator,path:n}:{kind:"value",root:e.root??{kind:"binding",name:t},path:n}}}function ln(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Gm(e){let{key:t,element:n,graph:r,provenances:o}=e,i=XC(t,n,r),s=i?.tag??(Ln(n.tag)?n.tag:n.componentName),a=i?.identity.key??Ym(n,r)??t,c=HC(i),l=GC(t,n,r,o,i),d=JC(t,n,r,o,a);return{componentName:s,instanceKey:a,templateOwner:WC(i??n,s),...c.length>0?{variantKeys:c}:{},...l.length>0?{slotKeys:l}:{},editableStrategy:d,impactScope:YC(d),alternativeStrategies:ZC(d)}}function JC(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return ol(e,n)?"instance":!Ln(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Ym(e,t){if(Ln(e.tag))return e.identity.key;let n=[...t.elements.values()].filter(r=>r.importedFrom===e.sourceFile&&zC(r,e.componentName));return n.length!==1?null:n[0].identity.key}function XC(e,t,n){if(Ln(t.tag))return t;let r=ol(e,n);if(r)return r;let o=Ym(t,n);return o?n.elements.get(o)??null:null}function zC(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function WC(e,t){return Ln(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function HC(e){if(!e?.attributes)return[];let t=new Set(["variant","size","tone"]);return e.attributes.filter(n=>t.has(n.name)).map(n=>n.name)}function GC(e,t,n,r,o){let i=new Set,s=ol(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(d=>d.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Ln(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function ol(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Ln(r.tag))return r;n=r.parentKey}return null}function Ln(e){return/^[A-Z]/.test(e)}function YC(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function ZC(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function qm(e){let t=e.isRepeat??(e.graph?sR(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=iR(e.element.attributes??[]),i=[...r.values()].some(d=>d.ok),s=o.map(d=>QC({attribute:d,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(d.name),repeatTarget:r.get(d.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((d,f)=>d.order-f.order).map(d=>({raw:d.raw,sourceRange:aR(d.sourceRange,e.source),order:d.order,diagnostics:d.source?[]:[{code:"unsupported-spread-source",message:"The spread source cannot be resolved safely, so property ownership is conservative."}]})),l=t&&e.selectionRef?.instanceIndex!==void 0&&i;return{documentVersion:e.documentVersion,...e.selectionRef?{selectionRef:e.selectionRef}:{},items:s,spreads:c,creation:t?{selection:l?"materialize":"unsupported",template:"unsupported"}:{selection:a?"unsupported":"direct",template:a?"unsupported":"direct"}}}function QC(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=qC(t,n,e.isRepeat),s=["selection","template"].map(b=>({scope:b,result:Di({state:n,scope:b,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:b})=>b.ok)?.result,c=a?.ok?a.target:void 0,l=c?.kind==="value-binding"&&o&&(JSON.stringify(c.locator.root)!==JSON.stringify(o.selectedParentObjectLocator.root)||JSON.stringify(c.locator.path??[])!==JSON.stringify([...o.selectedParentObjectLocator.path??[],{kind:"property",name:t.name}]))?null:o,d=eR(t,n,l,e.isRepeat),f=c?rR(c,e.element,t.name):void 0,m=s.filter(({result:b})=>b.ok).map(({scope:b})=>b),u=m.length>0?nR(n,o,e.element):"unsupported",g=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=oR(t,n,r);if(m.length===0&&h.length===0){let b=s.find(({result:E})=>!E.ok)?.result;b&&!b.ok&&h.push({code:b.code,message:b.reason})}return{name:t.name,source:i,resolution:d,editMode:u,sourceScope:g,allowedWriteScopes:m,...f?{effectiveWriteTarget:f}:{},diagnostics:h}}function qC(e,t,n){let r;if(n&&t?.status==="binding"){let o=t.target;r=o?.kind==="value-binding"&&o.target.sourceKind==="repeat-template"?"repeat-template":"binding"}else e.syntaxKind==="boolean-shorthand"?r="boolean-shorthand":e.syntaxKind==="literal"||!e.source?r="literal":r="expression";return{kind:r,...e.raw!==void 0?{raw:e.raw}:{}}}function eR(e,t,n,r){return n?Zm(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:Zm(tR(e))}function tR(e){return e.resolution?e.resolution:e.syntaxKind==="boolean-shorthand"?{status:"resolved",value:!0}:e.resolvedValue!==void 0?{status:"resolved",value:e.resolvedValue}:e.source?{status:"unresolved"}:{status:"resolved",value:e.value}}function Zm(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function nR(e,t,n){if(t)return"direct";if(!e||e.status==="blocked")return"unsupported";if(e.status==="missing"||e.status==="direct")return"direct";let r=e.target;return r?.kind!=="value-binding"?"unsupported":r.target.file===n.sourceFile?"direct":"proxy"}function rR(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Qm({...e.target.selectedParentObjectLocator,path:[...e.target.selectedParentObjectLocator.path??[],{kind:"property",name:n}]})}:e.kind==="value-binding"?{kind:"value-path",file:e.file,isProxy:e.file!==t.sourceFile,displayPath:Qm(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function oR(e,t,n){let r=[];return t?.diagnostic&&r.push({code:t.diagnostic.code,message:t.diagnostic.message}),n&&!n.ok&&t?.status!=="missing"&&r.push({code:`repeat-${n.errorCode}`,message:n.reason}),e.resolution?.status==="unresolved"&&r.length===0&&r.push({code:"unsupported-property-source",message:`Property '${e.name}' has an unresolved value source`}),r}function iR(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function sR(e,t){let n=t.regions.filter(r=>r.kind==="repeat-region");for(let r of n){let o=e;for(;o;){if(r.childKeys.includes(o.identity.key))return!0;o=o.parentKey?t.elements.get(o.parentKey):void 0}}return!1}function Qm(e){return`${e.root.kind==="binding"?e.root.name:e.root.kind==="expression"?e.root.sourceRange?"expression":"value":e.root.kind}${(e.path??[]).map(n=>n.kind==="index"?`[${n.index}]`:`.${n.name}`).join("")}`}function aR(e,t){if(!t)return{start:e.startColumn,end:e.endColumn};let n=t.split(`
7
+ `),r=(o,i)=>n.slice(0,Math.max(0,o-1)).reduce((s,a)=>s+a.length+1,0)+i;return{start:r(e.startLine,e.startColumn),end:r(e.endLine,e.endColumn)}}function cR(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var lR=160;function eg(e,t,n,r={}){let o=Zn(e),i=[];for(let[s,a]of e.elements){let c=n.get(s),l={canUpdateText:r.canUpdateTextByKey?.get(s)??c?.canUpdateText??!1,canInsertChild:c?.canInsertChild??!1,canMove:c?.canMove??!1,canRemove:c?.canRemove??!1};i.push({key:s,tag:a.tag,label:a.tag===a.componentName?a.tag:`${a.tag} (${a.componentName})`,parentKey:a.parentKey,childKeys:[...a.childKeys],operationSummary:l,...r.dynamicDataSummaryByKey?.get(s)?{dynamicDataSummary:r.dynamicDataSummaryByKey.get(s)}:{}})}return{composition:o,routeId:e.routeId,version:e.version,rootKeys:[...e.rootKeys],entries:i}}function tg(e,t,n,r,o,i,s,a,c,l,d){let f=Zn(t),m=t.elements.get(e),u=n.nodes.get(e),g=r.get(e);if(!m||!u||!g)throw new Error(`Node not found: ${e}`);let h=sg(m.textSegments,s),b=ag(e,t,m,g,h),E=h?fR(h):void 0,v=pR(i,h),I=m.textSegments.map(C=>({index:C.index,value:C.value,editable:cg(C,g,s?.get(C.index)??null),source:o.get(C.index)??null})),R=og(m,t),P=m.childKeys.map(C=>{let A=t.elements.get(C);return A?{key:C,tag:A.tag,label:A.tag}:null}).filter(C=>C!==null),T=[];if(m.parentKey){let C=t.elements.get(m.parentKey);if(C)for(let A of C.childKeys){if(A===e)continue;let F=t.elements.get(A);F&&T.push({key:A,tag:F.tag,label:F.tag})}}return{composition:f,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:rg(m),label:m.tag,capabilities:b,writeTarget:i,effectiveWriteTarget:v,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...d?{dynamicData:d}:{},textSegments:I,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:R,children:P,siblings:T}}function ng(e,t,n,r,o,i,s,a){let c=Zn(t),l=t.elements.get(e),d=n.nodes.get(e),f=r.get(e);if(!l||!d||!f)throw new Error(`Node not found: ${e}`);let m=sg(l.textSegments,i);return{composition:c,key:e,tag:l.tag,componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:rg(l),label:l.tag,capabilities:ag(e,t,l,f,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(u=>({code:u.code,message:u.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(u=>{let g=o.get(u.index);return{index:u.index,editable:cg(u,f,i?.get(u.index)??null),source:g?{kind:g.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:og(l,t)}}function rg(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:uR(e.sourceRange),structuralPath:e.identity.structuralPath,...dR(e.textSegments)}}function og(e,t){let n=[],r=e.parentKey;for(;r;){let o=t.elements.get(r);if(!o)break;n.push({key:r,tag:o.tag,label:o.tag}),r=o.parentKey}return n.reverse(),n}function uR(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dR(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,lR)}:{}}function ig(e,t){let n=t.find(r=>r.editable&&r.source&&r.source.kind!=="literal");return n?.source?{kind:"value-binding",file:n.source.file,componentName:e.componentName,isProxy:n.source.file!==e.file}:{kind:"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function sg(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function ag(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(d=>d.kind==="repeat-region"&&d.childKeys.includes(e)),a=o?.diagnostics.find(d=>d.code==="missing-adapter"||d.code==="external-source-readonly")?.code,c=r.canUpdateText?{mode:o?.editMode??"direct",reasonCode:a??(o?.editMode==="upstream"?"component-prop":o?.finalSource?.kind==="repeat-template"?"repeat-item-data":void 0)}:{mode:"unsupported",reasonCode:"capability-denied"},l=r.canUpdateText&&lg(c.mode);return{...r,canUpdateText:l,editModes:{updateText:c,insertChild:r.canInsertChild?{mode:"direct",reasonCode:i||s?"repeat-template":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},move:r.canMove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"},remove:r.canRemove?{mode:s?"proxy":"direct",reasonCode:s?"repeat-collection":void 0}:{mode:"unsupported",reasonCode:"capability-denied"}}}}function cg(e,t,n){return!e.editable||!t.canUpdateText?!1:n?lg(n.editMode):!0}function lg(e){return e==="direct"||e==="proxy"||e==="upstream"}function fR(e){return{finalSource:e.finalSource?{kind:e.finalSource.kind,file:e.finalSource.file,displayPath:e.finalSource.displayPath,externalSource:e.finalSource.externalSource}:null,chain:e.chain.map(t=>({kind:t.kind,file:t.file,displayName:t.displayName,canEditHere:t.canEditHere})),confidence:e.confidence,editMode:e.editMode,diagnostics:e.diagnostics.map(t=>({code:t.code,message:t.message}))}}function pR(e,t){return t?.finalSource?t.finalSource.kind==="jsx-literal"?{kind:"jsx-node",file:e.file,isProxy:e.isProxy}:t.finalSource.kind==="config-entry"&&t.finalSource.locator?{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:cR(t.finalSource.kind)?{kind:"external-entry",file:t.finalSource.file,isProxy:!1,displayPath:t.finalSource.displayPath,sourceType:t.finalSource.externalSource?.sourceType,sourceId:t.finalSource.externalSource?.sourceId}:{kind:"value-path",file:t.finalSource.file,isProxy:t.finalSource.file!==e.file,displayPath:t.finalSource.displayPath}:{kind:e.kind==="route-export"?"route-export":"jsx-node",file:e.file,isProxy:e.isProxy}}var il=["set-class-name-source","apply-style-draft"];function ug(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:il,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element"}]};if(t.resolution&&t.resolution.status!=="resolved")return{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:t.source?.expression,diagnostics:[{code:"dynamic-binding",message:"Style binding is unresolved and cannot be edited"}]};if(t.source?.expression){let n=t.source.expression,r=typeof t.resolvedValue=="string"?t.resolvedValue:t.value!==n?t.value:void 0;return typeof r!="string"?{kind:"class-name-source",className:"",sourceKind:"dynamic-expression",editable:!1,operationBoundary:[],sourcePath:n,diagnostics:[{code:t.resolvedValue===void 0?"dynamic-binding":"non-string-binding",message:t.resolvedValue===void 0?"Style binding is dynamic and cannot be edited":"Style binding must resolve to a static string before it can be edited"}]}:{kind:"class-name-source",className:r,sourceKind:"static-expression",editable:!0,operationBoundary:il,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:il}}function dg(e){let t=new Map;for(let[n,r]of e.elements){let o=/^[A-Z]/.test(r.tag),i={file:r.sourceFile,componentName:r.componentName,isProxy:o},s=r.boundaryKind,a=[];r.isOpaque&&a.push({kind:"opaque-region",reason:`Component '${r.tag}' is opaque: internal structure not editable`}),o&&!r.isOpaque&&a.push({kind:"component-boundary",reason:`Component '${r.tag}' boundary: editing requires source file access`});let c={key:n,writeTarget:i,boundaryKind:s,parentKey:r.parentKey,childKeys:[...r.childKeys],constraints:a};t.set(n,c)}for(let n of e.regions){let r=n.kind==="repeat-region"?"repeat-region":n.kind==="conditional-region"?"conditional-region":n.kind==="opaque-region"?"opaque-region":"component-boundary",o=n.kind==="repeat-region"?"Node is inside a repeat region: operations affect the template, not individual instances":n.kind==="conditional-region"?"Node is inside a conditional region: visibility depends on runtime condition":`Node is inside a ${n.kind}`;for(let i of n.childKeys){let s=t.get(i);s&&s.constraints.push({kind:r,reason:o}),fg(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function fg(e,t,n,r,o){let i=o.elements.get(e);if(i)for(let s of i.childKeys){let a=r.get(s);a&&!a.constraints.some(c=>c.kind===t)&&(a.constraints.push({kind:t,reason:n}),fg(s,t,n,r,o))}}import pg from"node:path";function al(){let e=Promise.resolve();return{async runExclusive(t){let n,r=new Promise(i=>{n=i}),o=e;e=o.then(()=>r,()=>r),await o;try{return await t()}finally{n()}}}}async function gg(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=yR(i.path);if(!s.ok)return s;let a=s.path;if(o.has(a))return{ok:!1,code:"duplicate-target",path:a,reason:`Duplicate file target: ${a}`};if(o.add(a),i.kind==="create-only"){let c=t.has(a),l=n?await n(a):!1;if(c||l)return{ok:!1,code:"create-only-exists",path:a,reason:`Create-only file already exists: ${a}`}}r.push({...i,path:a})}return{ok:!0,plan:{operationId:e.operationId,intents:r}}}async function ts(e){let t=()=>mR(e);return e.mutex?e.mutex.runExclusive(t):t()}async function mR(e){let t=await gg(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=gR(e.overlay,t.plan),r;try{r=await e.buildCandidate({overlay:n,plan:t.plan})}catch(l){return{ok:!1,stage:"build",reason:"Candidate build failed.",error:l,recoveryRequired:!1}}let o,i;try{o=await e.prepareHistory?.({candidate:r,plan:t.plan}),await e.reverify?.({candidate:r,plan:t.plan,history:o}),i=await e.writeCandidate({candidate:r,plan:t.plan}),await e.markCandidateWritten?.({candidate:r,plan:t.plan,history:o,receipt:i})}catch(l){return sl({candidate:r,plan:t.plan,failedStage:"commit",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let s=r;try{let l=await e.validateCandidate({candidate:r,plan:t.plan,receipt:i});l!==void 0&&(s=l)}catch(l){return sl({candidate:r,plan:t.plan,failedStage:"validate",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let a;try{a=await e.publishCandidate({candidate:s,plan:t.plan,history:o,receipt:i})}catch(l){return sl({candidate:s,plan:t.plan,failedStage:"publish",error:l,history:o,receipt:i,rollbackCandidate:e.rollbackCandidate})}let c={candidate:s,plan:t.plan,history:o,receipt:i,published:a};try{await e.swapCandidate?.(c)}catch(l){return mg("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return mg("finalize",l,"Transaction finalization failed after live state swap.")}try{e.emitCommitted?.({candidate:s,plan:t.plan,published:a})}catch{}return{ok:!0,stage:"publish",published:a,plan:t.plan}}function gR(e,t){let n=new Map(e);for(let r of t.intents)r.kind==="delete"?n.delete(r.path):n.set(r.path,r.content);return n}function sl(e){return e.rollbackCandidate({candidate:e.candidate,plan:e.plan,failedStage:e.failedStage,error:e.error,...e.history===void 0?{}:{history:e.history},...e.receipt===void 0?{}:{receipt:e.receipt}}).then(()=>({ok:!1,stage:e.failedStage,reason:hR(e.failedStage),error:e.error,recoveryRequired:!1})).catch(t=>({ok:!1,stage:"rollback",reason:"Rollback failed after candidate commit/validation/publish failure.",error:t,recoveryRequired:!0,cause:e.error}))}function mg(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function hR(e){switch(e){case"commit":return"Candidate write or commit verification failed.";case"validate":return"Candidate validation failed.";case"publish":return"Candidate publish failed."}}function yR(e){if(e.length===0)return{ok:!1,code:"unsafe-path",path:e,reason:"File path must not be empty."};if(e.includes("\0")||e.includes("\\"))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};if(/^[a-zA-Z]:/.test(e)||pg.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=pg.posix.normalize(e);return t==="."||t===".."||t.startsWith("../")||t.includes("/../")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:t.startsWith("./")||t.includes("/./")?{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`}:{ok:!0,path:t}}var xR=50,bR=8*1024*1024;function bg(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??xR),s=Math.max(0,t.maxUndoBytes??bR);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:d,redo:f};async function a(C){let A=[...C.steps].sort((Z,fe)=>Z.order-fe.order),F=A.filter(Z=>Z.type!=="invoke-external-adapter");if(F.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let M=new Set(F.map(Z=>Z.file)),U=await v(M),q=new Map(U.map(Z=>[Z.file,Z.exists===!1?"":Z.content])),Ne;for(let Z of F){let fe=xg(Z,q.get(Z.file)??"");if(!fe.ok)return{ok:!1,errorCode:fe.errorCode,reason:fe.reason};q.set(Z.file,fe.source),Ne=fe.selectionRef??Ne}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...q].map(([Z,fe])=>({operation:"upsert",file:Z,content:fe,baseContentHash:U.find(Fe=>Fe.file===Z)?.sha256??null}))},...Ne?{selectionRef:Ne}:{}}}async function c(C){let A=[...C.steps].sort((Fe,Ht)=>Fe.order-Ht.order),F=A.filter(Fe=>Fe.type!=="invoke-external-adapter"),M=A.filter(Fe=>Fe.type==="invoke-external-adapter"),U=new Set(F.map(Fe=>Fe.file));if(F.length>0&&M.length>0)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(F.length===0)return b(C,M);let q=await v(U),Ne=new Map;for(let Fe of q)Ne.set(Fe.file,Fe.exists===!1?"":Fe.content);let Z;for(let Fe of F){let Ht=Ne.get(Fe.file)??"",Gt=xg(Fe,Ht);if(!Gt.ok)return{ok:!1,operationId:C.operationId,errorCode:Gt.errorCode,reason:Gt.reason,rolledBack:!1};Ne.set(Fe.file,Gt.source),Gt.selectionRef&&(Z=Gt.selectionRef)}let fe=await R([...Ne].map(([Fe,Ht])=>({file:Fe,content:Ht,exists:!0,version:0,sha256:ve(Ht)})),q);return fe.ok===!1?{ok:!1,operationId:C.operationId,errorCode:fe.rolledBack?"writeback-failed":"rollback-failed",reason:fe.reason,rolledBack:fe.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:q,postSnapshots:fe.snapshots,plan:C}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...fe.snapshots.map(Fe=>Fe.version)),affectedFiles:[...U],...Z?{selectionRef:Z}:{}})}async function l(C){let A=new Set(C.edits.map(fe=>fe.file)),F=await v(A),M=E(C,F);if(M)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:M.reason,affectedFiles:[M.file],rolledBack:!1};let U=new Map(F.map(fe=>[fe.file,fe])),q=C.edits.find(fe=>fe.operation==="create-only"&&U.get(fe.file)?.exists!==!1);if(q)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${q.file}`,affectedFiles:[q.file],rolledBack:!1};let Ne=C.edits.map(fe=>fe.operation==="delete"?{file:fe.file,content:"",exists:!1,version:0}:{file:fe.file,content:fe.content,exists:!0,version:0,sha256:ve(fe.content)}),Z=await R(Ne,F,new Set(C.edits.filter(fe=>fe.operation==="create-only").map(fe=>fe.file)));return Z.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:F,postSnapshots:Z.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:F}}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Z.snapshots.map(fe=>fe.version)),affectedFiles:[...A]})}async function d(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await R(C.preSnapshots,C.postSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(F=>F.version)),affectedFiles:C.preSnapshots.map(F=>F.file)})}async function f(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await R(C.postSnapshots,C.preSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(C),m(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(F=>F.version)),affectedFiles:C.postSnapshots.map(F=>F.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&u()>s;)n.shift()}function u(){return n.reduce((C,A)=>C+g(A),0)}function g(C){return h(C.preSnapshots)+h(C.postSnapshots)}function h(C){return C.reduce((A,F)=>A+F.file.length+F.content.length,0)}async function b(C,A){let F=[];for(let M of A){let U=M.capability??"write-text",q=o.find(Z=>Z.sourceType===M.sourceType&&(M.adapterId===void 0||Z.adapterId===M.adapterId)&&(Z.capabilities===void 0||Z.capabilities.includes(U)));if(!q)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${M.sourceType}`,rolledBack:!1};let Ne=await q.execute(M);if(!Ne.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:Ne.reason??`External adapter failed for ${M.sourceType}`,rolledBack:!1};F.push(M.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:F}}function E(C,A){if(C.conflictPolicy!=="compare-and-swap")return null;let F=new Map(A.map(M=>[M.file,M]));for(let M of C.edits){if(M.operation==="create-only")continue;if(M.baseContentHash===void 0)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};let U=F.get(M.file),q=M.baseContentHash;if(q===null){if(U?.exists!==!1)return{file:M.file,reason:`Source file ${M.file} was created or changed before save.`};continue}if(!q)return{file:M.file,reason:`Source file ${M.file} is missing baseContentHash. Reopen the file before saving.`};if(U?.exists===!1||U?.sha256!==q)return{file:M.file,reason:`Source file ${M.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function v(C){let A=[];for(let F of C)A.push(await I(F));return A}async function I(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(C)),M=await e.readFile(C);return{file:C,content:M,version:F,exists:!0,sha256:ve(M)}}async function R(C,A,F=new Set){let M=[];try{for(let U of C){if(F.has(U.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(U.file,U.content)}else await P(U);let q=e.bumpVersion(U.file);M.push(U.file),U.version=q}}catch(U){let q=await T(A.filter(Z=>M.includes(Z.file)));if(q.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${q.failedFiles.join(", ")}: ${yg(U)}`,rolledBack:!1,instanceConflict:hg(U)};let Ne=hg(U);return{ok:!1,reason:`${Ne?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${yg(U)}`,rolledBack:!0,instanceConflict:Ne}}return{ok:!0,snapshots:C.map(SR)}}async function P(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let A=[];for(let F of C)try{await P(F),e.bumpVersion(F.file)}catch{A.push(F.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function hg(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function SR(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function yg(e){return e instanceof Error?e.message:String(e)}function xg(e,t){switch(e.type){case"invoke-external-adapter":return{ok:!1,reason:"External adapter steps must be executed asynchronously",errorCode:"unsupported-operation"};case"add-import":return We(Gn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(Yn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Xn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return We(zn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(Ho({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(wr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(wr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ei({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(Yo({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ti({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(ni({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Wn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(Zo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,repeatExpression:e.repeatExpression,selectionContext:e.selectionContext}));case"set-class-name-source":return ER(e,t);case"set-property-changes":return We(Qo({source:t,locator:e.locator,changes:e.changes}));case"set-property-binding":return We(qo({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(oi({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function ER(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!sd(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ve(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:id({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function We(e){if(e.ok)return{ok:!0,source:e.source,...e.selectionRef?{selectionRef:e.selectionRef}:{}};switch(e.diagnostic.code){case"locator-miss":return{ok:!1,reason:e.diagnostic.message,errorCode:"locator-miss"};case"unsupported-syntax":case"binding-not-found":case"export-not-found":case"property-not-found":case"array-index-out-of-range":case"directive-conflict":case"metadata-shape-unsupported":return{ok:!1,reason:e.diagnostic.message,errorCode:"unsupported-operation"};case"invalid-parent-child-relation":case"self-closing-element":return{ok:!1,reason:e.diagnostic.message,errorCode:"invalid-target"};case"parse-failed":case"printer-failed":return{ok:!1,reason:e.diagnostic.message,errorCode:"ast-error"};default:return{ok:!1,reason:e.diagnostic.message,errorCode:"writeback-failed"}}}import{computeSiteEditCompositionKey as ns,SiteEditCompositionContextSchema as vR,SiteEditCompositionSelectorSchema as kR}from"@vcp-dev/contracts";var He=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Sg(e,t){throw new He("INVALID_COMPOSITION",e,{value:t})}function rs(e){let t=vR.safeParse(e);return t.success?t.data:Sg("Invalid SiteEditCompositionContext.",e)}function Eg(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let d=rs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=ns(d);if(n.has(f))throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d});let m=r.get(l.entryFile);if(m)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let u={context:d,entryFile:l.entryFile,key:f};t.push(u),n.set(f,u),r.set(l.entryFile,f)}if(t.length===0)throw new He("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let d=rs(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new He("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:d,version:l?.version});let f=ns(d);if(!n.has(f))throw new He("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:d,key:f});if(o.has(f))throw new He("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:d,key:f});o.set(f,l.version)}function i(l){let d=kR.safeParse(l);if(!d.success)return Sg("Invalid SiteEditCompositionSelector.",l);let f=t.filter(({context:m})=>m.routeId===d.data.routeId&&(d.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===d.data.templateId));if(f.length===1)return f[0];throw f.length>1?new He("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:d.data}):new He("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:d.data})}function s(l){let d=rs(l),f=ns(d),m=n.get(f);if(!m)throw new He("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:d,key:f});return m}function a(l){let d=rs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new He("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let f=ns(d),m=n.get(f);if(m){if(m.entryFile===l.entryFile)return m;throw new He("DUPLICATE_COMPOSITION",`Composition key ${f} is registered more than once.`,{key:f,context:d})}let u=[...n.values()].find(h=>h.entryFile===l.entryFile);if(u)throw new He("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:u.context});let g={context:d,entryFile:l.entryFile,key:f};return t.push(g),n.set(f,g),g}function c(l){let d=n.get(l);if(!d)return;n.delete(l);let f=t.findIndex(m=>m.key===l);return f>=0&&t.splice(f,1),o.delete(l),d}return{entries:t,byKey:n,initialVersions:o,register:a,unregister:c,resolveSelector:i,resolveContext:s,getByKey:l=>n.get(l),routeIds:()=>[...new Set(t.map(({context:l})=>l.routeId))]}}import{composeSiteEditRepeatInstanceKey as IR,stripSiteEditRepeatInstanceKeys as vg}from"@vcp-dev/contracts";function kg(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=vg(o.key)??o.key;if(i===o.key)continue;let s=n.get(i)??0;r.set(o.key,s),n.set(i,s+1)}return{entriesByKey:t,repeatOccurrenceIndexByKey:r}}function CR(e){let t=1;for(let n of e?.textTargets.values()??[])n?.kind==="value-binding"&&n.sourceKind==="repeat-template"&&(t=Math.max(t,n.collectionIndexMap?.length??0,n.collectionPathMap?.length??0));return t}function os(e){return e?.map(t=>({...t}))}function cl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=os(e.collectionPathMap?.[t])??os(e.locator?.path);if(r)for(let o=r.length-1;o>=0;o-=1){let i=r[o];if(i.kind==="index"){i.index=n;break}}return{...e,path:os(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>os(o)??[])}}function Ig(e,t,n){let r=new Set;for(let u of t.regions)if(u.kind==="repeat-region")for(let g of u.childKeys)r.add(g);if(r.size===0)return e;let o=new Map(e.entries.map(u=>[u.key,u])),i=[],s=new Map,a=(u,g)=>IR(u,g),c=(u,g,h)=>{let b=o.get(u);if(!b)return a(u,h);let E=a(u,h),v={...b,key:E,parentKey:g,childKeys:[]};return i.push(v),v.childKeys=b.childKeys.flatMap(I=>l(I,h,E)),E},l=(u,g,h)=>{if(!r.has(u))return[c(u,h,g)];let b=f(u,g),E=[];for(let v=0;v<b;v+=1)E.push(c(u,h,[...g,v]));return E},d=Array.from(new Set([...e.rootKeys,...e.entries.filter(u=>u.parentKey===null).map(u=>u.key)]));for(let u of d){if(!r.has(u)){c(u,null,[]);continue}let g=f(u,[]);for(let h=0;h<g;h+=1)c(u,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function f(u,g){let h=new Set;for(let b of m(u)){let E=n.get(b);if(E){for(let v of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(v?.kind!=="value-binding"||v.sourceKind!=="repeat-template"))for(let I of RR(v))I.length<=g.length||NR(I,g)&&h.add(I[g.length])}}return h.size>0?h.size:CR(n.get(u))}function m(u){let g=s.get(u);if(g)return g;let h=[u],b=o.get(u);for(let E of b?.childKeys??[])h.push(...m(E));return s.set(u,h),h}}function Cg(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Rg(e,t,n,r){let o=r?.repeatOccurrenceIndexByKey.get(t);if(o!==void 0)return o;if(!e)return null;let i=0;for(let s of e.entries)if((vg(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function RR(e){return e.collectionPathMap?.length?e.collectionPathMap.map(t=>t.filter(n=>n.kind==="index").map(n=>n.index)):e.collectionIndexMap?.length?e.collectionIndexMap.map(t=>[t]):[]}function NR(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Ng(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(d=>[d.key,d])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let d=o.get(a);if(!d)break;s.push({key:d.key,tag:d.tag,label:d.label}),a=d.parentKey}s.reverse();let c=i.childKeys.map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(d=>d!==i.key).map(d=>o.get(d)).filter(d=>d!==void 0).map(d=>({key:d.key,tag:d.tag,label:d.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function wg(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(c=>[c.key,c])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let c=o.get(a);if(!c)break;s.push({key:c.key,tag:c.tag,label:c.label}),a=c.parentKey}return s.reverse(),{...e,key:i.key,ancestors:s}}function Pg(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function wR(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var mo=class extends Error{constructor(t){let n=t.map(Pg);super(wR(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Ag(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof mo?{routeId:e,message:n,diagnostics:t.diagnostics.map(Pg)}:{routeId:e,message:n}}function ll(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function ul(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function mr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Tg(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function dl(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function Fg(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,d)=>l.preDigest===r[d]),i=t.files.every((l,d)=>l.postDigest===r[d]),s=t.historyTransition,a=n.digest===s.expectedIndexDigest,c=n.digest===s.publishedIndexDigest&&n.cursor===s.publishedCursor&&n.currentId===s.publishedCurrentId;return o&&a?"safely-uncommitted":i&&c?"durably-committed":"ambiguous"}var DR=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,LR=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],_g=32,Og=256;function BR(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Mg={maxEntries:50,maxBytes:8*1024*1024};function $R(){let e=new Map;return{async readFile(t){return(await import("node:fs/promises")).readFile(t,"utf-8")},async readFileBytes(t){return(await import("node:fs/promises")).readFile(t)},async getFileInfo(t){let n=await import("node:fs/promises");try{let r=await n.lstat(t);return!r.isFile()||r.isSymbolicLink()?null:{path:t,sizeBytes:r.size}}catch{return null}},async writeFile(t,n){await si(t,n)},async deleteFile(t){await(await import("node:fs/promises")).rm(t,{force:!0})},async exists(t){let n=await import("node:fs/promises");try{return await n.access(t),!0}catch{return!1}},getVersion(t){return e.get(t)??1},bumpVersion(t){let n=(e.get(t)??1)+1;return e.set(t,n),n}}}function jR(){let e=[],t=[];return{prepareAppend(r){return{kind:"append",entry:r}},prepareUndo(){let r=e.at(-1);return r?{kind:"undo",entry:r}:null},prepareRedo(){let r=t.at(-1);return r?{kind:"redo",entry:r}:null},publishPrepared(r){if(r.kind==="append"){e.push(r.entry),n(),t.length=0;return}if(r.kind==="undo"){if(e.at(-1)!==r.entry)throw new Error("undo history changed before publish");e.pop(),t.push(r.entry);return}if(t.at(-1)!==r.entry)throw new Error("redo history changed before publish");t.pop(),e.push(r.entry),n()},peekUndo(){return e.at(-1)??null},pushUndo(r){e.push(r),n(),t.length=0},popUndo(){return e.pop()??null},peekRedo(){return t.at(-1)??null},pushRedo(r){t.push(r)},popRedo(){return t.pop()??null},clearRedo(){t.length=0},getStatus(){return{canUndo:e.length>0,canRedo:t.length>0,undoDepth:e.length,redoDepth:t.length,recoveryRequired:!1}}};function n(){for(;e.length>Mg.maxEntries||VR(e)>Mg.maxBytes;)e.shift()}}function VR(e){return e.reduce((t,n)=>t+KR(n),0)}function KR(e){return Dg(e.preSnapshots)+Dg(e.postSnapshots)+UR(e.provenance)}function UR(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Dg(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Lg(e,t){return{key:AR(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageComposition:null,pageCompositionProjection:null,documentIndex:null,pagePlacementByKey:null,pagePlacementUnitByKey:null,pageUnitByKey:null,pagePlacementsByUnitKey:null,dependencyFiles:new Set([t]),detailProjections:null,fileVersions:new Map,styleContext:null}}var ss=class extends Error{constructor(t){super(t.reason),this.result=t}},Bn=class extends Error{constructor(t){super(ll(t)),this.failedRoutes=t}};function Bg(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=et(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(et(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function JR(e,t,n){if(!n)return;let r=et(n.key)??n.key;if(n.key!==e&&n.key!==t&&r!==t)throw new Error(`Selection reference '${n.key}' does not match selected key '${e}'`);if(n.instanceIndex!==void 0&&(!Number.isInteger(n.instanceIndex)||n.instanceIndex<0))throw new Error("Selection reference instanceIndex must be non-negative");if(n.instanceCount!==void 0&&(!Number.isInteger(n.instanceCount)||n.instanceCount<=0))throw new Error("Selection reference instanceCount must be positive");if(n.instanceIndex!==void 0&&n.instanceCount!==void 0&&n.instanceIndex>=n.instanceCount)throw new Error("Selection reference instanceIndex must be smaller than instanceCount");return{...n,key:t}}var XR=/\.(?:[cm]?[jt]sx?)$/i,zR=/\.json$/i,WR=/\.(?:css|scss|sass)$/i,HR=/\.mdx$/i,GR=/\.ya?ml$/i;function YR(e){if(!e||e.kind!=="value-binding")return null;let t="path"in e?e.path:void 0,n=e.root,r=n&&(n.kind==="binding"||n.kind==="named-export")?n.name:void 0;return{kind:e.sourceKind,file:e.file,expression:e.displayExpression,bindingName:r,path:t?.map(o=>o.kind==="property"?o.name:o.index)}}function ZR(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function QR(e,t){let n=new Map;for(let r of t)n.set(r.path,r.operation==="delete"?{exists:!1}:{exists:!0,content:r.content});return{async readFile(r){let o=n.get(r);if(o){if(!o.exists)throw new Error(`Source file not found: ${r}`);return o.content}return e.readFile(r)},async writeFile(){throw new Error("Source edit preflight overlay is read-only.")},async deleteFile(){throw new Error("Source edit preflight overlay is read-only.")},async exists(r){let o=n.get(r);return o?o.exists:e.exists(r)},async getFileInfo(r){let o=n.get(r);return o?o.exists?{path:r,sizeBytes:Buffer.byteLength(o.content,"utf8")}:null:e.getFileInfo?.(r)??null},async listFiles(r={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let o=Jg(await e.listFiles(r)),i=new Map(o.files.map(a=>[a.path,a]));for(let[a,c]of n)if(qR(a,r.roots??[])){if(!c.exists){i.delete(a);continue}i.set(a,{path:a,sizeBytes:Buffer.byteLength(c.content,"utf8")})}let s=[...i.values()].sort((a,c)=>a.path.localeCompare(c.path));return o.truncated?{files:s,truncated:o.truncated}:s},getVersion(r){return e.getVersion(r)},bumpVersion(r){return e.getVersion(r)}}}function qR(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Jg(e){return Array.isArray(e)?{files:e}:e}function eN(e){if(!FR(e.path))return{ok:!1,errorCode:"invalid-params",message:`Source file is read-only: ${e.path}`,details:{path:e.path}};if(e.operation==="upsert"&&e.content.includes("\0"))return{ok:!1,errorCode:"invalid-params",message:`Source file content must be valid text: ${e.path}`,details:{path:e.path}};if(e.operation==="delete"){if(e.capability!==OR||e.confirmDelete!==!0||e.confirmPath!==e.path)return{ok:!1,errorCode:"capability-denied",message:`Source file delete requires explicit confirmation: ${e.path}`,details:{path:e.path}};let t=TR(e.path);return t?{ok:!1,errorCode:"capability-denied",message:`Protected source file cannot be deleted: ${e.path}`,details:{path:e.path,protectionReason:t}}:{ok:!0}}if(XR.test(e.path)){let t=Pt({source:e.content,profile:hn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(zR.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ye(t)}`,details:{path:e.path}}}if(WR.test(e.path)){let t=$g({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(HR.test(e.path)){let t=$g({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(GR.test(e.path))try{MR(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ye(t)}`,details:{path:e.path}}}return{ok:!0}}function $g({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let f=0;f<e.length;f+=1){let m=e[f]??"",u=e[f+1]??"";if(n==="mdx"&&l&&e.startsWith("```",f)){c=!c;let g=e.indexOf(`
8
8
  `,f);if(g===-1){l=!0;break}f=g,l=!0;continue}if(c){l=m===`
9
9
  `||m==="\r";continue}if(s){m==="*"&&u==="/"&&(s=!1,f+=1),l=m===`
10
10
  `||m==="\r";continue}if(a){m===`
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
- `||m==="\r"))return fr(t,`Unterminated string literal in ${t}.`);l=m===`
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 fr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
14
- `||m==="\r"}if(s)return fr(t,`Unterminated block comment in ${t}.`);if(o)return fr(t,`Unterminated string literal in ${t}.`);if(c)return fr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?fr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function fr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function go(e){let t="idle",n=e.fileSystem??qC(),r=Ku(),o=rg({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?od(e.historyStore):eR()),d=tg(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=qc(),b=R();function E(p){return(es.isAbsolute(p)?es.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=es.posix.dirname(p),k=y.replace(/\.(?:tsx?|jsx?)$/i,""),N=es.posix.relative(x,k);return N.startsWith(".")?N:`./${N}`}function I(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function R(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),k=await Promise.all(y.files.map(async O=>await n.exists(O.path)?ve(await n.readFile(O.path)):null));if(mg({journal:y,index:x,observedFileDigests:k})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let O=await p.readStatus();O.recoveryRequired||(await p.cleanupTmp(),O=await p.readStatus()),g=O.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Ge(y)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=bg(p.context,p.entryFile);i.set(p.key,y),T(y,y.dependencyFiles)}function T(p,y){let x=new Set(y);C(p),p.dependencyFiles=x;for(let k of p.dependencyFiles){let N=s.get(k);N||(N=new Set,s.set(k,N)),N.add(p.key)}}function C(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function A(p){let y=new Set;for(let x of p)for(let k of s.get(x)??[])y.add(k);return y}function F(p){for(let y of p)if(!s.has(y))return!1;return!0}async function M(p,y,x,k,N){let O=new Map,D=Em(N.values()),z=new Map,L=typeof n.exists=="function"?V=>n.exists(V):async()=>!1;for(let[V,j]of p.elements){let ce=y.nodes.get(V);if(!ce)continue;let re=x.get(j.sourceFile)??k.get(j.sourceFile),be=new Map,Se=new Map,Ie=new Map,Ce=[];for(let Ee of j.textSegments){if(!re){be.set(Ee.index,null);continue}let mr=await vm({file:j.sourceFile,source:re,segment:Ee,readFile:tt=>n.readFile(tt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tt,adapterId:un,capabilities:bs})=>({sourceType:tt,adapterId:un,capabilities:bs})),functionCallContracts:e.functionCallContracts,fileCache:D}),We=await Kc({file:j.sourceFile,source:re,target:{kind:"text-segment",segment:Ee},readFile:tt=>n.readFile(tt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:tt,adapterId:un,capabilities:bs})=>({sourceType:tt,adapterId:un,capabilities:bs})),functionCallContracts:e.functionCallContracts,fileCache:D}),dt=uR(mr);be.set(Ee.index,dt),Se.set(Ee.index,mr),Ie.set(Ee.index,We),Ce.push({editable:Ee.editable,source:dt})}let _=new Map,U=new Map;if(re)for(let Ee of j.attributes??[]){let mr=await ur({file:j.sourceFile,source:re,sourceRange:Ee.sourceRange,expression:Ee.source?.expression??Ee.value,sourceInfo:Ee.source,readFile:dt=>n.readFile(dt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:tt,capabilities:un})=>({sourceType:dt,adapterId:tt,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:D}),We=await Am({element:j,file:j.sourceFile,source:re,propertyName:Ee.name,readFile:dt=>n.readFile(dt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:dt,adapterId:tt,capabilities:un})=>({sourceType:dt,adapterId:tt,capabilities:un})),functionCallContracts:e.functionCallContracts,fileCache:D});U.set(Ee.name,We),_.set(Ee.name,mr)}let te=Vm(dR(ce.writeTarget),Ce),ie=Tm({key:V,element:j,graph:p,provenances:Ie}),_e=zm(j),lt=re?await Cp({element:j,graph:p,file:j.sourceFile,source:re,readFile:Ee=>n.readFile(Ee),exists:L,fileCache:z}):void 0,ut=p.regions.find(Ee=>Ee.kind==="conditional-region"&&Ee.childKeys.includes(V)),pr,Je=ut?.sourceCandidates?.[0];if(re&&ut&&Je?.kind==="conditional-branch"){let Ee=await Kc({file:j.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Je},readFile:We=>n.readFile(We),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:We,adapterId:dt,capabilities:tt})=>({sourceType:We,adapterId:dt,capabilities:tt})),functionCallContracts:e.functionCallContracts,fileCache:D});pr={currentBranch:ut.childKeys.indexOf(V)<=0?"then":"else",availableBranches:ut.childKeys.length>1?["then","else"]:["then"],conditionExpression:Je.conditionExpression,provenance:{finalSource:Ee.finalSource?{kind:Ee.finalSource.kind,file:Ee.finalSource.file,displayPath:Ee.finalSource.displayPath}:null,chain:Ee.chain.map(We=>({kind:We.kind,file:We.file,displayName:We.displayName,canEditHere:We.canEditHere})),confidence:Ee.confidence,editMode:Ee.editMode,diagnostics:Ee.diagnostics.map(We=>({code:We.code,message:We.message}))}}}O.set(V,{textSources:be,textTargets:Se,elementPropertyTargets:_,propertyProvenances:U,isRepeat:AR(V,p),provenances:Ie,writeTarget:te,componentSemantic:ie,styleSource:_e,conditional:pr,dynamicData:lt})}return O}function K(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function q(p,y){let x=o.initialVersions.get(p.key)??0;for(let k of y.values())x=Math.max(x,k);return Math.max(x,p.graph?.version??0)}function Re(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Z(p){try{return Re(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,y,x={}){let k=i.get(p);if(!k)return null;let N=x.sourceCache??nl(f,[]),O=await Te(k.entryFile),{graph:D,allSources:z,diagnostics:L,parsedModules:V,entryModule:j}=await Qu(k.entryFile,y,Je=>n.readFile(Je),typeof n.exists=="function"?Je=>n.exists(Je):async()=>!1,{additionalEntries:O,version:k.graph?.version??1});if(L.length>0)throw new fo(L);let ce=new Map;for(let Je of z.keys())ce.set(Je,K(Je));let re=Math.max(q(k,ce),x.minimumVersion??0);x.changed&&re<=(k.graph?.version??0)&&(re=(k.graph?.version??0)+1),D.version=re;for(let[Je,Ee]of z)rl(N,Je,Ee,hg);let be=await zt(k.composition,k.entryFile,z,N);D.routeId=k.routeId,D.composition=k.composition;let Se=Hm(D),Ie=Bu(Se,D),Ce=await M(D,Se,z,N,V),_=Zg(D,Ie,Ce),U=Yg(Ce),te=sg(Dm(D,Se,Ie,{canUpdateTextByKey:_,dynamicDataSummaryByKey:U}),D,Ce),ie=Vd({route:k.routeId,composition:k.composition,entryFile:k.entryFile,version:re,source:y,ast:j?.ast}),_e=Ud(ie);ie.ok&&hR(te,D,ie.projection,V);let lt={...te,composition:k.composition,...be?{styleContext:be}:{},pageComposition:_e},ut=new Set([k.entryFile,...z.keys()]);if(be){ut.add(be.entryCss.path);for(let Je of be.stylesheets)ut.add(Je.path)}let pr={...k,dependencyFiles:ut,graph:D,topology:Se,capabilities:Ie,document:lt,pageComposition:_e,pageCompositionProjection:ie.projection,pagePlacementByKey:ie.ok?ie.projection.placementByKey:null,pagePlacementUnitByKey:ie.ok?ie.projection.placementUnitByKey:null,pageUnitByKey:ie.ok?ie.projection.unitByKey:null,pagePlacementsByUnitKey:ie.ok?ie.projection.placementsByUnitKey:null,documentIndex:ig(lt),detailProjections:Ce,fileVersions:ce,styleContext:be};if(x.publish===!1)return pr;dr(f,N);for(let Je of N.keys())m.delete(Je);return T(k,ut),Object.assign(k,pr),k}async function Te(p){let y=[];for(let x of IR(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function zt(p,y,x,k){let N=[];for(let[V,j]of x){if(ol(V)){N.push(V);continue}for(let ce of RR(j)){let re=Cg(V,ce);re&&N.push(re)}}if(!N.length){for(let V of CR(y))if(await Nl(V)){N.push(V);break}}let O=new Map,D=PR(N).slice(0,gg);for(;D.length>0&&O.size<gg;){let V=D.shift();if(O.has(V)||!ol(V))continue;let j=await Ht(V,k);if(j!==null){O.set(V,{path:V,content:j});for(let ce of wR(j)){let re=Cg(V,ce);re&&!O.has(re)&&!D.includes(re)&&D.push(re)}}}let z=[...O.values()].map(V=>({...V,hash:ve(V.content)})),L=z[0];return L?{composition:p,revision:ve(JSON.stringify(z.map(({path:V,hash:j})=>({path:V,hash:j})))),entryCss:L,stylesheets:z.slice(1)}:null}async function Ht(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await Nl(p))return null;let k=await n.readFile(p);return rl(y,p,k,hg),k}async function Nl(p){return typeof n.exists=="function"?n.exists(p):!1}function Yg(p){let y=new Map;for(let[x,k]of p)k.dynamicData?.bindings.length&&y.set(x,Dp(k.dynamicData.bindings));return y}function Zg(p,y,x){let k=new Map;for(let[N,O]of p.elements){if(!y.get(N)?.canUpdateText){k.set(N,!1);continue}let z=x.get(N),L=O.textSegments.some(V=>{if(!V.editable)return!1;let j=z?.provenances.get(V.index)??null;return!j||Qg(j)});k.set(N,L)}return k}function Qg(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Io(p,y={}){let x=[...new Set(p)],k=y.affectedCompositionKeys!==void 0,N=k?new Set(y.affectedCompositionKeys):A(x);if(!k&&(N.size===0||!F(x)))for(let L of i.values())Pl(L,x)&&N.add(L.key);let O=!k&&N.size===0&&x.some(Ig),D=y.publish===!1?nl(f,x):void 0,z={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:D}:{}};for(let L of i.values())if(!(y.excludedCompositionKeys?.has(L.key)||!(N.has(L.key)||O)))try{let j=!!L.graph,ce=await n.readFile(L.entryFile),re=await fe(L.key,ce,{...y,...D?{sourceCache:D}:{}});re?.graph&&(z.rebuiltRoutes.push({documentChanged:j,composition:L.composition,routeId:L.routeId,version:re.graph.version}),z.candidateRouteStates?.push({composition:L.composition,key:L.key,routeId:L.routeId,state:re}))}catch(j){z.failedRoutes.push({...fg(L.routeId,j),composition:L.composition})}return z}function Ln(p){let y=[...new Set(p)],x=A(y);if(x.size>0&&F(y))return[...x];for(let k of i.values())Pl(k,y)&&x.add(k.key);return[...x]}function qg(p){let y=new Set(Ln(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function eh(p){return[...new Set(Ln(p))].sort((x,k)=>x<k?-1:x>k?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function th(p,y){let x=new Set(Ln(y)),k=p.provenance?.affectedCompositions??[];if(k.length===0)return x;if([...new Set(k.map(O=>o.resolveContext(O).key))].some(O=>!x.has(O)))throw new Error("History provenance does not match the affected composition index.");return x}function nh(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let O=o.resolveContext(x);return{context:O.context,key:O.key}}let k=[...new Set(Ln(y))];if(k.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${k.length}).`);let N=o.getByKey(k[0]);if(!N)throw new Error("Legacy history entry references an unknown affected composition.");return{context:N.context,key:N.key}}function ps(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:k}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:k});for(let{composition:x,message:k}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:k})}function Pl(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Al(p){for(let y of p)a.add(y);c||P()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(P())return;await rh();let x=[...a];a.clear();let k=await Tl(x);if(k.length===0)continue;let N=Ln(k);for(let z of N){let L=i.get(z)?.composition;L&&r.emit({type:"graph-invalidated",composition:L})}let{rebuiltRoutes:O,failedRoutes:D}=await Io(k,{changed:!0});for(let{documentChanged:z,composition:L,version:V}of O)r.emit({type:"graph-ready",composition:L,version:V}),z&&r.emit({type:"document-changed",composition:L,version:V});for(let{composition:z,message:L}of D)y=!0,r.emit({type:"graph-error",composition:z,message:L})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Al([])}})())}async function rh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function Tl(p){let y=[];for(let x of new Set(p)){let k=f.get(x);if(k===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==k&&(m.delete(x),y.push(x))}catch(N){if(!gR(N))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function Fl(p){pg(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function _l(p){m.clear();for(let y of p)m.add(y)}async function Ol(p){let y=await Tl(p);if(y.length===0)return;let x=Ln(y);for(let O of x){let D=i.get(O)?.composition;D&&r.emit({type:"graph-invalidated",composition:D})}let{rebuiltRoutes:k,failedRoutes:N}=await Io(y,{changed:!0});for(let{documentChanged:O,composition:D,version:z}of k)r.emit({type:"graph-ready",composition:D,version:z}),O&&r.emit({type:"document-changed",composition:D,version:z});for(let{composition:O,message:D}of N)r.emit({type:"graph-error",composition:O,message:D})}async function oh(p,y){let x=jn(p,y);if(!x?.graph)return;let k=qe(p)??p,N=x.graph.elements.get(k);N&&await Ol([N.sourceFile])}async function Ml(p){let y=new Set;if(p.target.kind==="node"){let x=jn(p.target.key,p.composition),k=qe(p.target.key)??p.target.key,N=x?.graph?.elements.get(k);N&&y.add(N.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.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 k of x){let N=jn(k,p.composition),O=qe(k)??k,D=N?.graph?.elements.get(O);D&&y.add(D.sourceFile)}}await Ol(y)}async function ih(p){if(p.params.kind!=="source-edit")return ms(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=mR(y);if(!x.ok)return ms(p,x.errorCode,x.message,x.details)}u+=1;try{let y=await uh(p.params.edits);if(!y.ok)return ms(p,y.errorCode,y.message,y.details);await Ml(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(k=>k.operation==="delete"?{operation:"delete",file:k.path,baseContentHash:k.baseContentHash??null}:{operation:"upsert",file:k.path,baseContentHash:k.baseContentHash??null,content:k.content})};return await $n({request:p,filePlan:x})}catch(y){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:$.INTERNAL_ERROR,message:Ge(y)}}}finally{u-=1}}async function sh(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return le(p,$.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let y=await ia({files:[...p.params.artifact.components.flatMap(k=>k.materialization.files.map(N=>({path:N.pathTemplate,content:N.content}))),...p.params.artifact.pages.flatMap(k=>k.materialization.files.map(N=>({path:N.pathTemplate,content:N.content})))],exists:k=>n.exists(k),readFile:k=>n.readFile(k)});if(!y.ok)return le(p,$.MATERIALIZATION_REJECTED,y.message);let x=await da({artifact:p.params.artifact,exists:k=>n.exists(k)});return x.ok?await $n({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"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return le(p,$.INTERNAL_ERROR,Ge(y))}finally{u-=1}}async function ah(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return le(p,$.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return le(p,$.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let y=Rg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return le(p,$.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:D})=>/\.(?:tsx?|jsx?)$/.test(D)),k=Object.fromEntries(await Promise.all(x.map(async({path:D})=>[D,await n.readFile(D)]))),N=ff({expectedUrlPath:p.params.expectedUrlPath,files:k});if(!N.ok)return le(p,N.code==="HOME_PAGE_LOCKED"?$.HOME_PAGE_LOCKED:N.code==="ROUTE_NOT_FOUND"?$.ROUTE_NOT_FOUND:$.PLAN_FAILED,N.message);let O=await Promise.all(N.edits.map(async D=>({...D,baseContentHash:ve(await n.readFile(D.file))})));return $n({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:N.deletedFiles,updated_files:N.updatedFiles,preserved_shared_files:N.preservedSharedFiles,warnings:N.warnings},historyPolicy:"none"})}catch(y){return le(p,$.INTERNAL_ERROR,Ge(y))}finally{u-=1}}async function ch(p,y){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return le(p,$.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 le(p,$.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 le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return le(p,$.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let N=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!N)return le(p,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=p.params.kind==="insert-child"?p.params.position:null,D=await ia({files:N.files.map(L=>({path:L.pathTemplate,content:L.content})),exists:L=>n.exists(L),readFile:L=>n.readFile(L)});if(!D.ok)return le(p,$.MATERIALIZATION_REJECTED,D.message);let z=await Cd({manifest:N,generatedRoot:"components/site/generated",controlledFiles:N.files.map(L=>({pathTemplate:L.pathTemplate})),exists:L=>n.exists(L),commit:async L=>{let V=await n.readFile(y.entryFile),j=y.document,ce=y.pageCompositionProjection;if(!j||j.pageComposition?.status!=="supported"||j.version!==p.documentVersion||!ce||ce.status!=="supported"||ce.documentVersion!==j.version)return{ok:!0,data:le(p,$.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let re=L.entry.path,be=yh(L.instanceName),Se,Ie=[];if(p.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let te=xa({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:j.version,expectedDocumentVersion:p.documentVersion,source:V,projection:ce,placementKey:O.placementKey,component:{source:re,exportName:L.entry.export.kind==="default"?"default":L.entry.export.name,localName:be}});if(!te.ok)return{ok:!0,data:le(p,xs(te.error.code),te.error.message,{diagnostics:te.error.diagnostics})};let ie=te.plan.rewriteStep,_e;switch(ie.kind){case"insert-root-expression":_e=gi({source:V,locator:ie.locator,expectedSourceHash:ie.sourceHash,action:{kind:"insert",jsx:ie.node.jsx,placement:ie.placement,replaceOriginal:ie.replaceOriginal}});break;case"insert-child":_e=Kn({source:V,locator:ie.parentLocator,node:ie.node,placement:ie.placement,...ie.anchorLocator?{anchorLocator:ie.anchorLocator}:{}});break;default:_e={ok:!1,source:V,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(ie)}`}}}if(!_e.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,_e.diagnostic.message)};Se=_e.source}else{let te=ba({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:j.version,expectedDocumentVersion:p.documentVersion,source:V,projection:ce,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!te.ok)return{ok:!0,data:le(p,xs(te.error.code),te.error.message,{diagnostics:te.error.diagnostics})};let ie=te.plan.rewriteStep,_e;switch(ie.kind){case"replace-root-expression":_e=gi({source:V,locator:ie.locator,expectedSourceHash:ie.sourceHash,action:{kind:"replace",jsx:`<${be} />`}});break;case"replace-node":_e=Ko({source:V,locator:ie.locator,node:{jsx:`<${be} />`}});break;default:_e={ok:!1,source:V,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${ie.kind}`}}}if(!_e.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,_e.diagnostic.message)};let lt=await Dl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:V,mutatedSource:_e.source});Se=lt.source,Ie=await Promise.all(lt.files.map(async ut=>({operation:"delete",file:ut,baseContentHash:ve(await n.readFile(ut))})))}let Ce=zn({source:Se,moduleSpecifier:v(y.entryFile,re),imports:L.entry.export.kind==="default"?[{kind:"default",local:be}]:[{kind:"named",imported:L.entry.export.name,local:be}]});if(!Ce.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Ce.diagnostic.message)};let _=L.files.map(te=>({operation:"create-only",file:te.path,content:te.content})),U=[{operation:"upsert",file:y.entryFile,content:Ce.source,baseContentHash:ve(V)},..._,...Ie];u+=1;try{let te=await $n({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:U}});return!te.ok&&te.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:te.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:te}}finally{u-=1}}});return z.ok?z.data:le(p,$.VERSION_STALE,z.error.message,{materializationCode:z.error.code})}async function lh(p,y){if(p.kind!=="move-node"&&p.kind!=="remove-node")return le(p,$.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let N=await n.readFile(y.entryFile),O=ba({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:N,projection:k,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(!O.ok)return le(p,xs(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let D=O.plan.rewriteStep,z;switch(D.kind){case"move-node":z=Jn({source:N,locator:D.locator,targetParentLocator:D.targetParentLocator,placement:D.placement,...D.anchorLocator?{anchorLocator:D.anchorLocator}:{}});break;case"remove-node":z=Un({source:N,locator:D.locator});break;case"remove-root-expression":z=gi({source:N,locator:D.locator,expectedSourceHash:D.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:N,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${D.kind}`}}}if(!z.ok)return le(p,$.AST_PARSE_ERROR,z.diagnostic.message);let L=z.source,V=[];if(p.kind==="remove-node"){let ce=await Dl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:N,mutatedSource:L});L=ce.source,V=await Promise.all(ce.files.map(async re=>({operation:"delete",file:re,baseContentHash:ve(await n.readFile(re))})))}let j=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:ve(N)},...V];u+=1;try{return await $n({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:j}})}finally{u-=1}}async function Dl(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,k=p.routeState.pageCompositionProjection;if(!x||!k||k.status!=="supported"||!n.listFiles)return y;let O=k.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!O)return y;let D=[...x.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&I(_.sourceRange,O));if(!D?.importedFrom||!D.exportName)return y;let z=E(D.importedFrom),L="components/site/generated/";if(!z.startsWith(L))return y;let V=z.slice(L.length).split("/")[0];if(!V||!/-[0-9a-f]{8}$/i.test(V))return y;let j=`${L}${V}`;if([...x.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===z).length!==1)return y;let re=await n.listFiles({maxFiles:5e3,maxDepth:32}),be=Array.isArray(re)?re:re.files;if(!Array.isArray(re)&&re.truncated)return y;let Se=be.map(({path:_})=>_).filter(_=>_===j||_.startsWith(`${j}/`));if(Se.length===0||!Se.includes(z))return y;for(let{path:_}of be)if(!(_===p.routeState.entryFile||_===j||_.startsWith(`${j}/`)))try{if((await n.readFile(_)).includes(V))return y}catch{return y}let Ie=v(p.routeState.entryFile,z),Ce=Hn({source:p.mutatedSource,moduleSpecifier:Ie,imports:D.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:D.exportName}]});return Ce.ok?{source:Ce.source,files:Se.sort((_,U)=>_.localeCompare(U))}:y}async function uh(p){if(n.getFileInfo){for(let N of p)if(await n.exists(N.path)&&await n.getFileInfo(N.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${N.path}`,details:{path:N.path}}}for(let N of p){if(N.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(N.path))continue;let O=await n.exists(N.path)?await As(n,N.path):null;if(O?.ok){let D=KC(O.content,N.content);if(!D.ok)return{ok:!1,errorCode:"invalid-params",message:D.message,details:{path:N.path,code:D.code}}}}let y=dh(p);if(y.length===0)return{ok:!0};let x=fR(n,p),k=go({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(N=>({context:N.composition,entryFile:N.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let N of y){let O=i.get(N)?.composition;if(!O)continue;let D={routeId:O.routeId,...O.effectiveTemplateId!==void 0?{templateId:O.effectiveTemplateId}:{}};await k.initializeComposition(D),k.getDocument(D)}}catch(N){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ge(N)}`,details:{compositionKeys:y}}}finally{k.dispose()}return{ok:!0}}function dh(p){return p.map(x=>x.path).some(Ig)?[...i.keys()]:[]}function ms(p,y,x,k){let N=po(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:N,message:x,...k?{details:k}:{}}}}async function gs(p){let y=[];for(let x of new Set(p))y.push(await fh(x));return y}async function fh(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,K(p)),exists:!1};let x=await n.readFile(p);return{file:p,content:x,version:Math.max(1,K(p)),exists:!0,sha256:ve(x)}}async function Ll(p,y,x,k){if(!e.historyStore)return null;let N=new Map(y.map(z=>[z.file,z])),O=new Map(x.map(z=>[z.file,z])),D=[...new Set([...N.keys(),...O.keys()])].sort().map(z=>{let L=N.get(z),V=O.get(z);return{path:z,preDigest:L?.exists===!1||!L?null:ve(L.content),postDigest:V?.exists===!1||!V?null:ve(V.content)}});return{schemaVersion:2,transactionId:`${p}:${k.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:k,files:D}}async function Bl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Bn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function hs(p,y){let x=[];try{for(let k of p)await $l(k),typeof n.bumpVersion=="function"&&n.bumpVersion(k.file),x.push(k.file)}catch(k){let N=await ph(y.filter(O=>x.includes(O.file)));return N.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ge(k)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${N.failedFiles.join(", ")}: ${Ge(k)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(mh)}}async function $l(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function ph(p){let y=[];for(let x of p)try{await $l(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function mh(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:ve(p.content)}:{}}}async function $n(p){return h.runExclusive(()=>gh(p))}async function gh(p){let y=p.filePlan.edits.map(_=>_.file),x=o.resolveSelector(p.request.composition),k=x.context,N=p.historyPolicy==="none"?void 0:{initiatingComposition:k,affectedCompositions:eh(y)},O=await gs(y),D=new Map(O.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),z=Vl(),L=new Map(f),V=new Set(m),j=new Set([...i.values()].filter(_=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===_.entryFile)).map(_=>_.key)),ce=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:ve(_.content)}),re={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})},be=null,Se=!1,Ie=await Yi({overlay:D,exists:_=>n.exists(_),plan:re,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:O,postSnapshots:ce,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...N?{provenance:N}:{}}),U=_?.historyTransition?_.historyTransition:e.historyStore?QC(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return be=await Ll(p.request.id,O,ce,U),be=await Bl(be),{history:_,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new ts(_);return{postSnapshots:await gs(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:U})=>{let te=await Io(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:j});if(te.failedRoutes.length>0)throw new Mn(te.failedRoutes);let ie=Kl(z,te.candidateRouteStates??[]),_e=Ul(ie,x.key);return{..._,rebuild:te,routeSnapshots:ie,resultVersion:_e,...Sg(p.selectionRef,ie.map(lt=>lt.state.document))?{selectionRef:Sg(p.selectionRef,ie.map(lt=>lt.state.document))}:{}}},publishCandidate:async({candidate:_,history:U,receipt:te})=>{U?.history&&(await l.publishPrepared(U.history),Se=!0);let ie=_.resultVersion??te.internalResultVersion;return{composition:k,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ie,affectedFiles:te.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:U})=>{_.routeSnapshots&&Co(_.routeSnapshots),_.rebuild?.candidateSourceCache&&dr(f,_.rebuild.candidateSourceCache),Fl(U.postSnapshots)},finalizeCandidate:async()=>{await Bn(be);for(let _ of j)i.delete(_)},emitCommitted:({candidate:_,published:U})=>{ps(U,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:U})=>{if(Se)throw new Error("history was published before transaction finalization failed");if(U){let te=await hs(O,U.postSnapshots);if(!te.ok)throw new Error(te.reason)}Co(z),dr(f,L),_l(V),_?.history&&await l.discardPrepared?.(_.history),await Bn(be)}});if(Ie.ok)return Ie.published;if(Ie.stage==="precheck"||Ie.stage==="build")try{await Bn(be)}catch(_){let U=await Ro(Ge(_));return le(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(Ie.recoveryRequired){let _=await Ro(Ie.reason);return le(p.request,_===$.RECOVERY_PERSIST_FAILED?_:$.ROLLBACK_FAILED,Ie.reason)}let Ce=Ie.error;return Ce instanceof ts?{...le(p.request,po(Ce.result.errorCode),Ce.result.reason),...Ce.result.affectedFiles?{affectedFiles:Ce.result.affectedFiles}:{}}:Ce instanceof Mn?le(p.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${tl(Ce.failedRoutes)}`,{failedRoutes:Ce.failedRoutes}):le(p.request,Xl(Ie.stage),Ge(Ce))}async function jl(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?hh(p,y):{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:$.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function hh(p,y){let x=y.entry,k=p==="undo"?x.preSnapshots:x.postSnapshots,N=p==="undo"?x.postSnapshots:x.preSnapshots,O=k.map(U=>U.file),{context:D,key:z}=nh(x,O),L=await gs(O),V=new Map(L.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),j=Re(z),ce=Vl(),re=new Map(f),be=new Set(m),Se=null,Ie=!1,Ce,_=await Yi({overlay:V,plan:{operationId:`${p}:${x.operationId}`,intents:k.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Se=await Ll(`${p}:${x.operationId}`,L,k,y.historyTransition),Se=await Bl(Se),y),reverify:async()=>{},writeCandidate:async()=>{let U=await hs(k,N);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Ce=th(x,O);let te=await Io(O,{changed:!0,minimumVersion:j+1,publish:!1,affectedCompositionKeys:Ce});if(te.failedRoutes.length>0)throw new Mn(te.failedRoutes);let ie=Kl(ce,te.candidateRouteStates??[]),_e=Ul(ie,z);return{...U,rebuild:te,routeSnapshots:ie,resultVersion:_e}},publishCandidate:async({candidate:U,history:te})=>{if(!te)throw new Error("history cursor intent is missing");await l.publishPrepared(te),Ie=!0;let ie=U.resultVersion??j+1;return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:ie,affectedFiles:O,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:U,receipt:te})=>{U.routeSnapshots&&Co(U.routeSnapshots),U.rebuild?.candidateSourceCache&&dr(f,U.rebuild.candidateSourceCache),Fl(te.snapshots)},finalizeCandidate:async()=>{await Bn(Se)},emitCommitted:({candidate:U,published:te})=>ps(te,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:te})=>{if(Ie)throw new Error("history cursor was published before transaction finalization failed");if(te){let ie=await hs(N,te.snapshots);if(!ie.ok)throw new Error(ie.reason)}Co(ce),dr(f,re),_l(be),U&&await l.discardPrepared?.(U),await Bn(Se)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Bn(Se)}catch(U){let te=await Ro(Ge(U));return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,error:{code:te,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let U=await Ro(_.reason);return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:O,error:{code:U===$.RECOVERY_PERSIST_FAILED?U:$.ROLLBACK_FAILED,message:_.reason}}}return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:O,error:{code:_.error instanceof Mn?$.ROUTE_REBUILD_FAILED:Xl(_.stage),message:Ge(_.error),..._.error instanceof Mn?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function Vl(){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 Ul(p,y){return p.find(k=>k.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function Kl(p,y){let x=new Map(p.map(k=>[k.key,k]));for(let k of y)x.set(k.key,k);return[...x.values()]}function Co(p){for(let y of i.values())C(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),T(x,x.dependencyFiles)}}async function ys(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await fe(p,x)}function jn(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!Jl(x,p)?null:x}function Jl(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=qe(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function le(p,y,x,k){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:y,message:x,...k?{details:k}:{}}}}function Xl(p){return p==="validate"?$.ROUTE_REBUILD_FAILED:p==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function Ro(p){if(g=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function yh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function xs(p){return p==="VERSION_STALE"?$.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function zl(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await ys(x.key),x):le(p,$.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 ys(x.key),x):le(p,$.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return le(p,$.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await ys(y.key),Jl(y,p.target.key)?y:le(p,$.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):le(p,$.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,y){let x=o.register({context:p,entryFile:y}),k=i.get(x.key);if(k?.entryFile===y)return;k&&C(k);let N=bg(x.context,y);i.set(x.key,N),T(N,N.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(C(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let k=await n.readFile(x.entryFile);await fe(y.key,k),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(k){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Ge(k)}),k}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await b;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let k=jn(p,y),N=qe(p)??p;if(k?.graph&&k.topology&&k.capabilities&&k.detailProjections){let O=k.detailProjections.get(N);if(O){let D=k.graph.elements.get(N);if(!D)throw new Error(`Key not found: ${p}`);let z=oR(p,N,x),L=new Map;if(O.isRepeat&&z?.instanceIndex!==void 0)for(let ce of D.attributes??[])L.set(ce.name,Nc({file:D.sourceFile,source:f.get(D.sourceFile)??"",element:D,propertyName:ce.name,selectionRef:z,graph:k.graph,sources:f}));let V=Mm({element:D,graph:k.graph,source:f.get(D.sourceFile),documentVersion:k.graph.version,selectionRef:x,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:L}),j=Bm(N,k.graph,k.topology,k.capabilities,O.textSources,O.provenances,O.dynamicData,V);return p===N?j:ug(j,p,k.document??null,k.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=jn(p,y),k=qe(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let N=x.detailProjections.get(k);if(N){let O=Lm(k,x.graph,x.topology,x.capabilities,N.textSources,N.writeTarget,N.provenances,N.conditional,N.componentSemantic,N.styleSource,N.dynamicData);return p===k?O:lg(O,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=jn(p,y),k=qe(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let N=x.graph.elements.get(k);if(!N)throw new Error(`Key not found: ${p}`);let O=f.get(N.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${N.sourceFile}`);return Hs({key:k,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:O}})},refreshSourceForKey:oh,async execute(p){if(await b,g)return le(p,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return ih(p);if(p.kind==="insert-page-resource")return sh(p);if(p.kind==="delete-page-source")return ah(p);let y=await zl(p);if("ok"in y)return y;await Ml(p);let x=await zl(p);if("ok"in x)return x;let k=x;if(p.target.kind==="page-unit"){let j=p;return p.kind==="insert-child"||p.kind==="replace-node"?ch(j,k):p.kind==="move-node"||p.kind==="remove-node"?lh(j,k):le(p,$.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let O=p.params,D=p.target.kind==="node"?p.target.key:null;if(O.kind==="move-node"&&"kind"in O.target&&O.target.kind==="source-sibling"){let j=O.target,ce=D?k.document?.entries.find(U=>U.key===D):null,re=k.document?.entries.find(U=>U.key===j.anchorKey),be=ce?.pageCompositionActionScope,Se=be?.kind==="source-siblings"?be.siblingKeys:null,Ie=Se?.indexOf(ce?.key??"")??-1,Ce=Se?.indexOf(j.anchorKey)??-1,_=j.relation==="before"?Ie-1:Ie+1;if(!ce||!re||!Se||Ie<0||Ce!==_||re.pageCompositionActionScope?.kind!=="source-siblings"||re.pageCompositionActionScope.siblingKeys.length!==Se.length||re.pageCompositionActionScope.siblingKeys.some((U,te)=>U!==Se[te])||!ce.operationSummary.canMove)return le(p,$.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!k.graph||!k.topology||!k.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:p.target.kind==="route"?$.ROUTE_NOT_FOUND:$.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 z=vR(k,k.graph,k.capabilities,f,i),L=await new Di(z).plan(p);if(!L.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:po(L.errorCode),message:L.reason}};let V=L.plan;if(V.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:Z(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:$.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(V.steps.some(ce=>ce.type==="invoke-external-adapter")){let ce=await d.execute(V);if(!ce.ok)return le(p,po(ce.errorCode),ce.reason);let re={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Z(p),ce.resultVersion),affectedFiles:ce.affectedFiles,...ce.selectionRef?{selectionRef:ce.selectionRef}:{}};return ps(re,{rebuiltRoutes:[],failedRoutes:[]}),re}let j=await d.prepareRewritePlan(V);return j.ok?await $n({request:p,filePlan:j.filePlan,...j.selectionRef?{selectionRef:j.selectionRef}:{}}):le(p,po(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:Z(p),error:{code:$.INTERNAL_ERROR,message:Ge(j)}}}finally{u-=1}},async undo(p){if(await b,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:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await jl("undo")}finally{u-=1}},async redo(p){if(await b,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:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await jl("redo")}finally{u-=1}},notifyFileChanged(p){Al([p])},getAffectedCompositions(p){return qg(p)},subscribe(p){return r.subscribe(p)}}}function gR(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function hR(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&&mo(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=qe(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&&mo(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(v=>v.sourceRange!==null&&(mo(u.sourceRange,v.sourceRange)||ER(v.sourceRange,u.sourceRange))));if(b){f.pageCompositionUnitKey=b.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)}yR(e,t,n,r)}function yR(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&&mo(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 b=s.get(g.target)??0,E=Math.min(2,b+h);E!==b&&(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!==(qe(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 b=h.match.path,E=b.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Pe(E))){d(u)===1&&vg(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!vg(E))continue;let v=f.get(E.node)??[];v.push({entry:m,element:u,parentPath:E}),f.set(E.node,v)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let v of u.parentPath.node.children){if(xR(v))continue;if(!bR(v)){b=!1;break}let I=[...t.elements.values()].find(P=>P.sourceFile===u.element.sourceFile&&P.componentName===u.element.componentName&&mo(P.sourceRange,SR(v))),R=I?o.get(I.identity.key):null;if(!I||!R||R.parentKey||R.pageCompositionUnitKey!==g||d(I)!==1){b=!1;break}h.push(R)}if(!b||h.length!==m.length||m.some(({entry:v})=>!h.some(I=>I.key===v.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(v=>v.key);for(let v of h)v.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function vg(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function xR(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function bR(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function SR(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 mo(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ER(e,t){return kg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&kg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function kg(e,t,n,r){return e!==n?e-n:t-r}function vR(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 b=qe(h)??h,E=t.elements.get(b);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let b=t.elements.get(h);return b?l(h,b):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:Hs({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 el(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return el(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 b=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(b)return b;let E=g.attributes?.find(v=>v.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 Nc({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=HC(d);return f?{baseKey:f.baseKey,repeatIndex:cg(e.document??null,d,f.baseKey,e.documentIndex)??ag(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=qe(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 kR={"stale-version":$.VERSION_STALE,"capability-denied":$.CAPABILITY_REJECTED,"invalid-params":$.INVALID_PARAMS,"locator-miss":$.LOCATOR_FAILED,"route-not-found":$.ROUTE_NOT_FOUND,"unsupported-operation":$.UNSUPPORTED_OPERATION,"invalid-target":$.INVALID_TARGET,"ast-error":$.AST_PARSE_ERROR,"writeback-failed":$.WRITE_IO_ERROR,"rollback-failed":$.RECOVERY_REQUIRED,unknown:$.INTERNAL_ERROR};function po(e){return kR[e]}function Ge(e){return e instanceof Error&&e.message?e.message:String(e)}function Ig(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function IR(e){let t=Dn(e);if(!YC.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=>ZC.map(a=>`${s}/${a}`))}function CR(e){let n=Dn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function RR(e){return wg(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function wR(e){return wg(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function wg(e,t){let n=[];for(let r of e.matchAll(t)){let o=Ng(r[1]??"");o&&n.push(o)}return n}function Cg(e,t){let n=Ng(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Dn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Dn(`${NR(e)}/${n}`):n.startsWith("/")?Dn(n.slice(1)):ol(n)?Dn(n):null}function Ng(e){return e.split(/[?#]/,1)[0]?.trim()??""}function ol(e){return/\.css$/i.test(e)}function NR(e){let t=Dn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function PR(e){return Array.from(new Set(e))}function Dn(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 AR(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 ns=class{constructor(t){this.options=t,this.fileSystem=new hr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Po(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 Ao(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return _o(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Oo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Mo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=FR.safeParse(t);if(!n.success)return{result:No(t,n.error.issues.map(i=>i.message))};let r=new hr(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:hn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=_R.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>OR(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 go({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=To(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}:{}})}};function OR(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function MR(e){return new ns(e)}import{SiteEditOperationRequestSchema as BR}from"@vcp-dev/contracts";import Ct from"node:fs/promises";import Ye from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as DR,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as LR}from"@vcp-dev/contracts";var rs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=go({...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 _o(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Oo(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Mo(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 Ct.readFile(Ye.join(n,r),"utf8")},async readFileBytes(r){return Ct.readFile(Ye.join(n,r))},async getFileInfo(r){let o=Ye.join(n,...r.split("/"));try{let i=await Ct.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ei(Ye.join(n,r),o)},async createExclusive(r,o){let i=Ye.join(n,r);await Ct.mkdir(Ye.dirname(i),{recursive:!0});let s=await Ct.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Ct.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Ct.rm(Ye.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=Ye.join(n,i),a=Ye.dirname(Ye.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ye.sep}`);){try{await Ct.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ye.dirname(a);continue}break}a=Ye.dirname(a)}},async exists(r){try{return await Ct.access(Ye.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...LR,...DR],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=Ye.join(n,...f.split("/")),h;try{h=await Ct.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 b=await Ct.readdir(g,{withFileTypes:!0});for(let E of b)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 il(e){return new rs(e)}var os=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=il({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=To(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:Po(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:Ao(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=BR.safeParse(r);if(!o.success)return No(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:hn(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:hn(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:hn(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 $R(e){return new os(e)}import{createHash as jR,randomUUID as yl}from"node:crypto";import Ae from"node:fs/promises";import Fe from"node:path";var bt=1,al=1,VR=2,UR="index.json",KR="recovery.json",JR="transaction-journal.json",XR="document-version.json",ss={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},ee={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function Bg(e,t={}){let n=iw(e),r=cw(t.limits),o=sl(n),i=sw(n),s=await et(i),a=await et(o)||s;a||(await ZR(n),await QR(n)),a||await lw(n);let c=await st(n),l=new Set(a?(await ds(n)).map(f=>f.stageId):[]);a||await ho(n,c.entryIds);let d=async()=>{if(await et(o)||s)throw new oe(ee.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Dg(n)},async writeDocumentVersion(f){if(await d(),!Number.isInteger(f)||f<0)throw new oe(ee.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await Dg(n);await yo(Xg(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await d();let u=await Ag(f,r),g={schemaVersion:al,stageId:yl(),entryId:u.entryId,blobIds:u.blobs.map(h=>h.digest)};try{await Tg(n,u),await WR(n,g,m.durableManifest!==!1)}catch(h){try{await _g(n,g)}catch(b){throw new oe(ee.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await d(),dl(f);let m=await ll(n,f);m&&await _g(n,m)},async previewStagedAppend(f,m){return await d(),(await Pg(n,r,f,m)).transition},async previewCursor(f,m){await d();let u=await st(n);return fl(u,m),cl(f,u.entryIds.length),$g(u,u.entryIds,f)},async publishStagedAppend(f,m,u){if(await d(),as(f,"entryId"),u){dl(u);let h=await ll(n,u);if(!h||h.entryId!==f)throw new oe(ee.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Pg(n,r,f,m);return Mg({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{u?await cs(n,u):await YR(n,f),await ho(n,g.entryIds)}})},async append(f){await d();let m=await st(n),u=await Ag(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(u.entryId);try{await Tg(n,u);let h=await jg(n,g,r);return await bl(n,h.entryIds,h.cursor),await ho(n,h.entryIds),st(n)}catch(h){throw await ho(n,m.entryIds),h}},async readEntry(f){return as(f,"entryId"),bo(n,f)},async readBlob(f){as(f,"blobId");let m=await wl(n,f),u=await cn(m,ee.NOT_FOUND,"blob");return Sl(u,f,m),u},async readIndex(){return st(n)},async readStatus(){let f=await st(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await et(o)||await et(i)}},async readUndoRedoIds(){let f=await st(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await d();let u=await st(n);return fl(u,m),cl(f,u.entryIds.length),Mg({rootDir:n,previousDigest:u.digest,entryIds:u.entryIds,cursor:f})},async markRecoveryRequired(f){await et(o)||await yo(sl(n),{schemaVersion:bt,reason:aw(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Ae.rm(sl(n),{force:!0})},async readTransactionJournal(){return await et(i)?is(i):null},async writeTransactionJournal(f){await d(),zg(f);try{await yo(i,f)}catch(u){let g=await is(i).catch(()=>null);if(g&&Buffer.from(at(g)).equals(Buffer.from(at(f))))return;throw g?new oe(ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:u}):u}let m=await is(i);if(!Buffer.from(at(m)).equals(Buffer.from(at(f))))throw new oe(ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await et(i)?await is(i):null;if(m&&m.transactionId!==f)throw new oe(ee.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Ae.rm(i,{force:!0})}catch(u){if(!await et(i))return;throw u}if(await et(i))throw new oe(ee.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await d();for(let m of l)await cs(n,m),l.delete(m);await qR(n);let f=await st(n);await ho(n,f.entryIds)}}}async function Pg(e,t,n,r){as(n,"entryId");let o=await st(e);fl(o,r);let i=await bo(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await jg(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:$g(o,a.entryIds,a.cursor)}}function $g(e,t,n){return cl(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:zR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function zR(e,t){return ln(at({schemaVersion:bt,entryIds:e,cursor:t}))}function cl(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(ee.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function HR(e){if(!Rt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!ct(e.expectedIndexDigest)||!ct(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!ct(n)?!1:t===-1?n===null:ct(n)}async function Ag(e,t){if(!e.kind.trim())throw new oe(ee.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(ee.INVALID_JSON,"history blob name must not be empty");let l=ow(c.data),d=ln(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:bt,kind:e.kind,manifest:e.manifest,blobs:r},i=at({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(ee.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Tg(e,t){let n=kl(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Fg(Il(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Rl(e,a.digest))),Fg(n,at(r),{kind:"entry",digest:t.entryId},Cl(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Fg(e,t,n,r){let o=await gl(e)??(r?await gl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?ee.BLOB_CORRUPT:ee.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Kg(e,t)}async function jg(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await Ug(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(ee.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function WR(e,t,n){xl(t);let r=vl(e,t.stageId);if(n){await yo(r,t);return}await rw(r,t)}async function ll(e,t){let n=await gl(vl(e,t));if(n===null)return null;let r=So(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=xl(r);if(o.stageId!==t)throw new oe(ee.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function ds(e){let t=[];for(let n of await us(El(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);dl(r);let o=await ll(e,r);o&&t.push(o)}return t}async function _g(e,t){xl(t);let n=await st(e),r=(await ds(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await bo(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Og(kl(e,t.entryId),Cl(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Og(Il(e,s),Rl(e,s));await cs(e,t.stageId),await hl(Eo(e)),await hl(vo(e))}async function cs(e,t){await ul(vl(e,t)),await GR(e)}async function GR(e){try{await Ae.rmdir(El(e))}catch(t){if(ko(t)||Rt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function YR(e,t){for(let n of await ds(e))n.entryId===t&&await cs(e,n.stageId)}async function ul(e){if(await Ae.rm(e,{force:!0}),await et(e))throw new oe(ee.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Og(e,t){await ul(e),await ul(t)}function xl(e){if(!Rt(e)||e.schemaVersion!==al||typeof e.stageId!="string"||!Vg(e.stageId)||!ct(e.entryId))throw new oe(ee.INVALID_SCHEMA,"history stage schema is invalid");let t=Jg(e.blobIds,"history stage blobIds");return{schemaVersion:al,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function dl(e){if(!Vg(e))throw new oe(ee.INVALID_PATH,"history stageId must be a UUID")}function Vg(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function ho(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await bo(e,c);for(let d of l.blobs)r.add(d.digest)}for(let c of await ds(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=Eo(e),i=await us(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=Lg(c.slice(0,-5));l&&!n.has(l)&&await ls(Fe.join(o,c))}let s=vo(e),a=await us(s);for(let c of a){let l=Lg(c);l&&!r.has(l)&&await ls(Fe.join(s,c))}}async function st(e){let t=fs(e),n=await cn(t,ee.NOT_FOUND,"index"),r=So(Buffer.from(n).toString("utf8"),"index"),o=ew(r),i=[...o.entryIds],{totalBytes:s}=await Ug(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:bt,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function Ug(e,t){let n=0,r=new Set,o=fs(e),i=await cn(o,ee.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await bo(e,s),c=await Hg(e,s),l=await cn(c,ee.NOT_FOUND,"entry");n+=l.byteLength;for(let d of a.blobs){if(r.has(d.digest))continue;r.add(d.digest);let f=await wl(e,d.digest),m=await cn(f,ee.NOT_FOUND,"blob");Sl(m,d.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function bo(e,t){let n=await Hg(e,t),r=await cn(n,ee.NOT_FOUND,"entry"),o=So(Buffer.from(r).toString("utf8"),`entry ${t}`),i=tw(o);if(i.id!==t)throw new oe(ee.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(at({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new oe(ee.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await wl(e,a.digest),l=await cn(c,ee.NOT_FOUND,"blob");Sl(l,a.digest,c)}return i}async function bl(e,t,n){let r={schemaVersion:bt,digest:ln(at({schemaVersion:bt,entryIds:t,cursor:n})),entryIds:t,cursor:n};await yo(fs(e),r)}function fl(e,t){if(t!==void 0&&e.digest!==t)throw new oe(ee.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Mg(e){let t=ln(at({schemaVersion:bt,entryIds:e.entryIds,cursor:e.cursor}));try{return await bl(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await st(e.rootDir)}catch(n){let r=await st(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(ee.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function ZR(e){await Ae.mkdir(e,{recursive:!0}),await Ae.mkdir(Eo(e),{recursive:!0}),await Ae.mkdir(vo(e),{recursive:!0}),await Ae.mkdir(xo(e),{recursive:!0})}async function QR(e){await Ae.rm(xo(e),{recursive:!0,force:!0}),await Ae.mkdir(xo(e),{recursive:!0})}async function qR(e){let t=xo(e);await Ae.mkdir(t,{recursive:!0});for(let n of await us(t))n!=="stages"&&await Ae.rm(Fe.join(t,n),{recursive:!0,force:!0})}function ew(e){if(!Rt(e))throw new oe(ee.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==bt)throw new oe(ee.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Jg(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(ee.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!ct(o))throw new oe(ee.INDEX_CORRUPT,"index digest is invalid");let i=ln(at({schemaVersion:bt,entryIds:t,cursor:r}));if(o!==i)throw new oe(ee.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:bt,digest:o,entryIds:t,cursor:r}}function tw(e){if(!Rt(e))throw new oe(ee.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==bt)throw new oe(ee.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!ct(t))throw new oe(ee.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(ee.ENTRY_CORRUPT,"entry kind is invalid");let r=ml(e.manifest,"entry.manifest"),o=nw(e.blobs);return{id:t,schemaVersion:bt,kind:n,manifest:r,blobs:o}}function nw(e){if(!Array.isArray(e))throw new oe(ee.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Rt(t))throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!ct(o))throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function yo(e,t){await Kg(e,at(t))}async function rw(e,t){let n=Fe.dirname(e),r=Fe.basename(e),o=Fe.join(n,`.${r}.${process.pid}.${yl()}.tmp`);await Ae.mkdir(n,{recursive:!0});try{await Ae.writeFile(o,at(t),{flag:"wx"}),await Ae.rename(o,e)}finally{await ls(o)}}async function Kg(e,t){let n=Fe.dirname(e),r=Fe.basename(e),o=Fe.join(n,`.${r}.${process.pid}.${yl()}.tmp`);await Ae.mkdir(n,{recursive:!0});try{let i=await Ae.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Ae.rename(o,e),await hl(n)}finally{await ls(o)}}function at(e){return Buffer.from(JSON.stringify(pl(e)),"utf8")}function pl(e){if(Array.isArray(e))return e.map(t=>pl(t));if(Rt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=pl(e[n]);return t}return e}function So(e,t){try{return JSON.parse(e)}catch(n){throw new oe(ee.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ml(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>ml(n,t));if(Rt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ml(o,t);return n}break}throw new oe(ee.INVALID_JSON,`${t} must be JSON-serializable`)}function Jg(e,t){if(!Array.isArray(e))throw new oe(ee.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!ct(n))throw new oe(ee.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function as(e,t){if(!ct(e))throw new oe(ee.INVALID_PATH,`${t} must be a sha256 digest`)}function ct(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${jR("sha256").update(e).digest("hex")}`}function ow(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function cn(e,t,n){try{return await Ae.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function gl(e){try{return await Ae.readFile(e)}catch(t){if(ko(t))return null;throw t}}function Sl(e,t,n){if(ln(e)!==t)throw new oe(ee.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function et(e){try{return await Ae.access(e),!0}catch(t){if(ko(t))return!1;throw t}}async function ls(e){try{await Ae.rm(e,{force:!0,recursive:!0})}catch{}}async function hl(e){try{let t=await Ae.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function us(e){try{return await Ae.readdir(e)}catch(t){if(ko(t))return[];throw t}}function iw(e){if(typeof e!="string"||e.trim().length===0)throw new oe(ee.INVALID_ROOT,"history store rootDir must be a non-empty string");return Fe.resolve(e)}function fs(e){return Fe.join(e,UR)}function sl(e){return Fe.join(e,KR)}function sw(e){return Fe.join(e,JR)}function Xg(e){return Fe.join(e,XR)}async function Dg(e){try{let t=await Ae.readFile(Xg(e),"utf8"),n=So(t,"document version");if(!Rt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(ee.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(ko(t))return 0;throw t}}async function is(e){let t=await cn(e,ee.RECOVERY_PENDING,"transaction journal"),n=So(Buffer.from(t).toString("utf8"),"transaction journal");return zg(n),n}function zg(e){if(!Rt(e)||e.schemaVersion!==VR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!HR(e.historyTransition)||!Array.isArray(e.files))throw new oe(ee.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Rt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!ct(t.preDigest)||t.postDigest!==null&&!ct(t.postDigest))throw new oe(ee.INVALID_SCHEMA,"transaction journal file digest is invalid")}function aw(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Eo(e){return Fe.join(e,"entries")}function vo(e){return Fe.join(e,"blobs")}function xo(e){return Fe.join(e,"tmp")}function El(e){return Fe.join(xo(e),"stages")}function vl(e,t){return Fe.join(El(e),`${t}.json`)}function kl(e,t){return Fe.join(Eo(e),`${Gg(t)}.json`)}function Il(e,t){return Fe.join(vo(e),Gg(t))}function Cl(e,t){return Fe.join(Eo(e),`${t}.json`)}function Rl(e,t){return Fe.join(vo(e),t)}async function Hg(e,t){return Wg(kl(e,t),Cl(e,t))}async function wl(e,t){return Wg(Il(e,t),Rl(e,t))}async function Wg(e,t){return await et(e)?e:await et(t)?t:e}function Gg(e){return e.slice(7)}function Lg(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return ct(t)?t:null}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function cw(e){return{maxEntries:e?.maxEntries??ss.maxEntries,maxSessionBytes:e?.maxSessionBytes??ss.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ss.maxEntryBytes}}async function lw(e){let t=fs(e);await et(t)||await bl(e,[],-1)}export{oe as FileHistoryStoreError,Dr as PageTemplateManagedSourceError,os as PreviewFileSystemSiteEditEngineRuntime,ud as SITE_EDIT_RAW_COLOR_LITERAL_RE,ns as SnapshotSiteEditEngineRuntime,qd as computeManagedPageTemplatePaths,$R as createPreviewSiteEditEngineRuntime,MR as createSiteEditEngineRuntime,Yd as decodePageTemplateKey,Fa as encodePageTemplateId,ef as isManagedPageTemplateSourcePath,Bg as openFileHistoryStore,Ch as parseSourceModule,Rh as resolveImportBase,FE as resolveManagedPageTemplateComposition,xi as scanManagedPageTemplateCandidates,nf as scanSiteEditCompositionsFromFiles,Pr as scanSiteEditThemeStyleViolations};
12
+ `||m==="\r"))return gr(t,`Unterminated string literal in ${t}.`);l=m===`
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 gr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
14
+ `||m==="\r"}if(s)return gr(t,`Unterminated block comment in ${t}.`);if(o)return gr(t,`Unterminated string literal in ${t}.`);if(c)return gr(t,`Unterminated MDX code fence in ${t}.`);let d=r.at(-1);return d?gr(t,`Unclosed token "${d.char}" in ${t}.`):{ok:!0}}function gr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function yo(e){let t="idle",n=e.fileSystem??$R(),r=ad(),o=Eg({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?vd(e.historyStore):jR()),d=bg(n,{externalAdapters:e.externalAdapters}),f=new Map,m=new Set,u=0,g=e.historyStore?.recoveryRequired??!1,h=al(),b=R();function E(p){return(is.isAbsolute(p)?is.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,y){let x=is.posix.dirname(p),k=y.replace(/\.(?:tsx?|jsx?)$/i,""),w=is.posix.relative(x,k);return w.startsWith(".")?w:`./${w}`}function I(p,y){return p.startLine===y.startLine&&p.startColumn===y.startColumn&&p.endLine===y.endLine&&p.endColumn===y.endColumn}async function R(){let p=e.historyStore;if(p)try{let y=await p.readTransactionJournal();if(!y)return;let x=await p.readIndex(),k=await Promise.all(y.files.map(async O=>await n.exists(O.path)?ve(await n.readFile(O.path)):null));if(Fg({journal:y,index:x,observedFileDigests:k})!=="ambiguous"){await p.clearTransactionJournal(y.transactionId);let O=await p.readStatus();O.recoveryRequired||(await p.cleanupTmp(),O=await p.readStatus()),g=O.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${y.transactionId} at phase ${y.phase}`),g=!0}catch(y){g=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${Ye(y)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let y=Lg(p.context,p.entryFile);i.set(p.key,y),T(y,y.dependencyFiles)}function T(p,y){let x=new Set(y);C(p),p.dependencyFiles=x;for(let k of p.dependencyFiles){let w=s.get(k);w||(w=new Set,s.set(k,w)),w.add(p.key)}}function C(p){for(let y of p.dependencyFiles){let x=s.get(y);x&&(x.delete(p.key),x.size===0&&s.delete(y))}p.dependencyFiles.clear()}function A(p){let y=new Set;for(let x of p)for(let k of s.get(x)??[])y.add(k);return y}function F(p){for(let y of p)if(!s.has(y))return!1;return!0}async function M(p,y,x,k,w){let O=new Map,D=$m(w.values()),z=new Map,L=typeof n.exists=="function"?V=>n.exists(V):async()=>!1;for(let[V,j]of p.elements){let ce=y.nodes.get(V);if(!ce)continue;let re=x.get(j.sourceFile)??k.get(j.sourceFile),be=new Map,Se=new Map,Ce=new Map,Re=[];for(let Ee of j.textSegments){if(!re){be.set(Ee.index,null);continue}let yr=await jm({file:j.sourceFile,source:re,segment:Ee,readFile:nt=>n.readFile(nt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:nt,adapterId:fn,capabilities:Is})=>({sourceType:nt,adapterId:fn,capabilities:Is})),functionCallContracts:e.functionCallContracts,fileCache:D}),Ge=await Zc({file:j.sourceFile,source:re,target:{kind:"text-segment",segment:Ee},readFile:nt=>n.readFile(nt),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:nt,adapterId:fn,capabilities:Is})=>({sourceType:nt,adapterId:fn,capabilities:Is})),functionCallContracts:e.functionCallContracts,fileCache:D}),ft=YR(yr);be.set(Ee.index,ft),Se.set(Ee.index,yr),Ce.set(Ee.index,Ge),Re.push({editable:Ee.editable,source:ft})}let _=new Map,K=new Map;if(re)for(let Ee of j.attributes??[]){let yr=await pr({file:j.sourceFile,source:re,sourceRange:Ee.sourceRange,expression:Ee.source?.expression??Ee.value,sourceInfo:Ee.source,readFile:ft=>n.readFile(ft),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:nt,capabilities:fn})=>({sourceType:ft,adapterId:nt,capabilities:fn})),functionCallContracts:e.functionCallContracts,fileCache:D}),Ge=await Hm({element:j,file:j.sourceFile,source:re,propertyName:Ee.name,readFile:ft=>n.readFile(ft),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ft,adapterId:nt,capabilities:fn})=>({sourceType:ft,adapterId:nt,capabilities:fn})),functionCallContracts:e.functionCallContracts,fileCache:D});K.set(Ee.name,Ge),_.set(Ee.name,yr)}let te=ig(ZR(ce.writeTarget),Re),ie=Gm({key:V,element:j,graph:p,provenances:Ce}),Oe=ug(j),ut=re?await Up({element:j,graph:p,file:j.sourceFile,source:re,readFile:Ee=>n.readFile(Ee),exists:L,fileCache:z}):void 0,dt=p.regions.find(Ee=>Ee.kind==="conditional-region"&&Ee.childKeys.includes(V)),hr,Xe=dt?.sourceCandidates?.[0];if(re&&dt&&Xe?.kind==="conditional-branch"){let Ee=await Zc({file:j.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Xe},readFile:Ge=>n.readFile(Ge),exists:L,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Ge,adapterId:ft,capabilities:nt})=>({sourceType:Ge,adapterId:ft,capabilities:nt})),functionCallContracts:e.functionCallContracts,fileCache:D});hr={currentBranch:dt.childKeys.indexOf(V)<=0?"then":"else",availableBranches:dt.childKeys.length>1?["then","else"]:["then"],conditionExpression:Xe.conditionExpression,provenance:{finalSource:Ee.finalSource?{kind:Ee.finalSource.kind,file:Ee.finalSource.file,displayPath:Ee.finalSource.displayPath}:null,chain:Ee.chain.map(Ge=>({kind:Ge.kind,file:Ge.file,displayName:Ge.displayName,canEditHere:Ge.canEditHere})),confidence:Ee.confidence,editMode:Ee.editMode,diagnostics:Ee.diagnostics.map(Ge=>({code:Ge.code,message:Ge.message}))}}}O.set(V,{textSources:be,textTargets:Se,elementPropertyTargets:_,propertyProvenances:K,isRepeat:hN(V,p),provenances:Ce,writeTarget:te,componentSemantic:ie,styleSource:Oe,conditional:hr,dynamicData:ut})}return O}function U(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function q(p,y){let x=o.initialVersions.get(p.key)??0;for(let k of y.values())x=Math.max(x,k);return Math.max(x,p.graph?.version??0)}function Ne(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function Z(p){try{return Ne(o.resolveSelector(p.composition).key)}catch{return 0}}async function fe(p,y,x={}){let k=i.get(p);if(!k)return null;let w=x.sourceCache??ul(f,[]),O=await Fe(k.entryFile),{graph:D,allSources:z,diagnostics:L,parsedModules:V,entryModule:j}=await hd(k.entryFile,y,Xe=>n.readFile(Xe),typeof n.exists=="function"?Xe=>n.exists(Xe):async()=>!1,{additionalEntries:O,version:k.graph?.version??1});if(L.length>0)throw new mo(L);let ce=new Map;for(let Xe of z.keys())ce.set(Xe,U(Xe));let re=Math.max(q(k,ce),x.minimumVersion??0);x.changed&&re<=(k.graph?.version??0)&&(re=(k.graph?.version??0)+1),D.version=re;for(let[Xe,Ee]of z)dl(w,Xe,Ee,Og);let be=await Ht(k.composition,k.entryFile,z,w);D.routeId=k.routeId,D.composition=k.composition;let Se=dg(D),Ce=nd(Se,D),Re=await M(D,Se,z,w,V),_=gh(D,Ce,Re),K=mh(Re),te=Ig(eg(D,Se,Ce,{canUpdateTextByKey:_,dynamicDataSummaryByKey:K}),D,Re),ie=sf({route:k.routeId,composition:k.composition,entryFile:k.entryFile,version:re,source:y,ast:j?.ast}),Oe=af(ie);ie.ok&&nN(te,D,ie.projection,V);let ut={...te,composition:k.composition,...be?{styleContext:be}:{},pageComposition:Oe},dt=new Set([k.entryFile,...z.keys()]);if(be){dt.add(be.entryCss.path);for(let Xe of be.stylesheets)dt.add(Xe.path)}let hr={...k,dependencyFiles:dt,graph:D,topology:Se,capabilities:Ce,document:ut,pageComposition:Oe,pageCompositionProjection:ie.projection,pagePlacementByKey:ie.ok?ie.projection.placementByKey:null,pagePlacementUnitByKey:ie.ok?ie.projection.placementUnitByKey:null,pageUnitByKey:ie.ok?ie.projection.unitByKey:null,pagePlacementsByUnitKey:ie.ok?ie.projection.placementsByUnitKey:null,documentIndex:kg(ut),detailProjections:Re,fileVersions:ce,styleContext:be};if(x.publish===!1)return hr;mr(f,w);for(let Xe of w.keys())m.delete(Xe);return T(k,dt),Object.assign(k,hr),k}async function Fe(p){let y=[];for(let x of uN(p))typeof n.exists=="function"&&await n.exists(x)&&y.push({file:x,source:await n.readFile(x)});return y}async function Ht(p,y,x,k){let w=[];for(let[V,j]of x){if(fl(V)){w.push(V);continue}for(let ce of fN(j)){let re=Ug(V,ce);re&&w.push(re)}}if(!w.length){for(let V of dN(y))if(await Dl(V)){w.push(V);break}}let O=new Map,D=gN(w).slice(0,_g);for(;D.length>0&&O.size<_g;){let V=D.shift();if(O.has(V)||!fl(V))continue;let j=await Gt(V,k);if(j!==null){O.set(V,{path:V,content:j});for(let ce of pN(j)){let re=Ug(V,ce);re&&!O.has(re)&&!D.includes(re)&&D.push(re)}}}let z=[...O.values()].map(V=>({...V,hash:ve(V.content)})),L=z[0];return L?{composition:p,revision:ve(JSON.stringify(z.map(({path:V,hash:j})=>({path:V,hash:j})))),entryCss:L,stylesheets:z.slice(1)}:null}async function Gt(p,y){let x=y.get(p);if(x!==void 0)return x;if(!await Dl(p))return null;let k=await n.readFile(p);return dl(y,p,k,Og),k}async function Dl(p){return typeof n.exists=="function"?n.exists(p):!1}function mh(p){let y=new Map;for(let[x,k]of p)k.dynamicData?.bindings.length&&y.set(x,em(k.dynamicData.bindings));return y}function gh(p,y,x){let k=new Map;for(let[w,O]of p.elements){if(!y.get(w)?.canUpdateText){k.set(w,!1);continue}let z=x.get(w),L=O.textSegments.some(V=>{if(!V.editable)return!1;let j=z?.provenances.get(V.index)??null;return!j||hh(j)});k.set(w,L)}return k}function hh(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Ro(p,y={}){let x=[...new Set(p)],k=y.affectedCompositionKeys!==void 0,w=k?new Set(y.affectedCompositionKeys):A(x);if(!k&&(w.size===0||!F(x)))for(let L of i.values())Ll(L,x)&&w.add(L.key);let O=!k&&w.size===0&&x.some(Kg),D=y.publish===!1?ul(f,x):void 0,z={rebuiltRoutes:[],failedRoutes:[],...y.publish===!1?{candidateRouteStates:[],candidateSourceCache:D}:{}};for(let L of i.values())if(!(y.excludedCompositionKeys?.has(L.key)||!(w.has(L.key)||O)))try{let j=!!L.graph,ce=await n.readFile(L.entryFile),re=await fe(L.key,ce,{...y,...D?{sourceCache:D}:{}});re?.graph&&(z.rebuiltRoutes.push({documentChanged:j,composition:L.composition,routeId:L.routeId,version:re.graph.version}),z.candidateRouteStates?.push({composition:L.composition,key:L.key,routeId:L.routeId,state:re}))}catch(j){z.failedRoutes.push({...Ag(L.routeId,j),composition:L.composition})}return z}function jn(p){let y=[...new Set(p)],x=A(y);if(x.size>0&&F(y))return[...x];for(let k of i.values())Ll(k,y)&&x.add(k.key);return[...x]}function yh(p){let y=new Set(jn(p));return o.entries.filter(x=>y.has(x.key)).map(x=>x.context)}function xh(p){return[...new Set(jn(p))].sort((x,k)=>x<k?-1:x>k?1:0).map(x=>o.getByKey(x)?.context).filter(x=>x!==void 0)}function bh(p,y){let x=new Set(jn(y)),k=p.provenance?.affectedCompositions??[];if(k.length===0)return x;if([...new Set(k.map(O=>o.resolveContext(O).key))].some(O=>!x.has(O)))throw new Error("History provenance does not match the affected composition index.");return x}function Sh(p,y){let x=p.composition??p.provenance?.initiatingComposition;if(x){let O=o.resolveContext(x);return{context:O.context,key:O.key}}let k=[...new Set(jn(y))];if(k.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${k.length}).`);let w=o.getByKey(k[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function xs(p,y){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:x,version:k}of y.rebuiltRoutes)r.emit({type:"document-changed",composition:x,version:k});for(let{composition:x,message:k}of y.failedRoutes)r.emit({type:"graph-error",composition:x,message:k})}function Ll(p,y){return y.some(x=>p.dependencyFiles.has(x)||p.entryFile===x||p.graph?.fileIndex.has(x))}function Bl(p){for(let y of p)a.add(y);c||P()||(c=(async()=>{t="building";let y=!1;try{for(;a.size>0;){if(P())return;await Eh();let x=[...a];a.clear();let k=await $l(x);if(k.length===0)continue;let w=jn(k);for(let z of w){let L=i.get(z)?.composition;L&&r.emit({type:"graph-invalidated",composition:L})}let{rebuiltRoutes:O,failedRoutes:D}=await Ro(k,{changed:!0});for(let{documentChanged:z,composition:L,version:V}of O)r.emit({type:"graph-ready",composition:L,version:V}),z&&r.emit({type:"document-changed",composition:L,version:V});for(let{composition:z,message:L}of D)y=!0,r.emit({type:"graph-error",composition:z,message:L})}}finally{c=null,t!=="disposed"&&(t=!y&&[...i.values()].some(x=>x.graph)?"ready":"idle"),a.size>0&&Bl([])}})())}async function Eh(){for(;u>0;)await new Promise(p=>setTimeout(p,0))}async function $l(p){let y=[];for(let x of new Set(p)){let k=f.get(x);if(k===void 0){if(m.has(x)&&!await n.exists(x))continue;m.delete(x),y.push(x);continue}try{await n.readFile(x)!==k&&(m.delete(x),y.push(x))}catch(w){if(!tN(w))try{if(await n.exists(x))continue}catch{continue}m.add(x),y.push(x)}}return y}function jl(p){Tg(f,p);for(let y of p)y.exists===!1?m.add(y.file):m.delete(y.file)}function Vl(p){m.clear();for(let y of p)m.add(y)}async function Kl(p){let y=await $l(p);if(y.length===0)return;let x=jn(y);for(let O of x){let D=i.get(O)?.composition;D&&r.emit({type:"graph-invalidated",composition:D})}let{rebuiltRoutes:k,failedRoutes:w}=await Ro(y,{changed:!0});for(let{documentChanged:O,composition:D,version:z}of k)r.emit({type:"graph-ready",composition:D,version:z}),O&&r.emit({type:"document-changed",composition:D,version:z});for(let{composition:O,message:D}of w)r.emit({type:"graph-error",composition:O,message:D})}async function vh(p,y){let x=Un(p,y);if(!x?.graph)return;let k=et(p)??p,w=x.graph.elements.get(k);w&&await Kl([w.sourceFile])}async function Ul(p){let y=new Set;if(p.target.kind==="node"){let x=Un(p.target.key,p.composition),k=et(p.target.key)??p.target.key,w=x?.graph?.elements.get(k);w&&y.add(w.sourceFile)}else if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="page-unit"){let x=i.get(o.resolveSelector(p.target.composition).key);x&&y.add(x.entryFile)}else if(p.target.kind==="source-file")y.add(p.target.path);else if(p.target.kind==="source-batch")for(let x of p.target.paths)y.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 k of x){let w=Un(k,p.composition),O=et(k)??k,D=w?.graph?.elements.get(O);D&&y.add(D.sourceFile)}}await Kl(y)}async function kh(p){if(p.params.kind!=="source-edit")return bs(p,"invalid-params","source-edit requires source-edit params");for(let y of p.params.edits){let x=eN(y);if(!x.ok)return bs(p,x.errorCode,x.message,x.details)}u+=1;try{let y=await wh(p.params.edits);if(!y.ok)return bs(p,y.errorCode,y.message,y.details);await Ul(p);let x={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(k=>k.operation==="delete"?{operation:"delete",file:k.path,baseContentHash:k.baseContentHash??null}:{operation:"upsert",file:k.path,baseContentHash:k.baseContentHash??null,content:k.content})};return await Kn({request:p,filePlan:x})}catch(y){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:$.INTERNAL_ERROR,message:Ye(y)}}}finally{u-=1}}async function Ih(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return le(p,$.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");u+=1;try{let y=await pa({files:[...p.params.artifact.components.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...p.params.artifact.pages.flatMap(k=>k.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:k=>n.exists(k),readFile:k=>n.readFile(k)});if(!y.ok)return le(p,$.MATERIALIZATION_REJECTED,y.message);let x=await ba({artifact:p.params.artifact,exists:k=>n.exists(k)});return x.ok?await Kn({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"}):le(p,x.code==="MATERIALIZATION_CONFLICT"?$.MATERIALIZATION_CONFLICT:$.MATERIALIZATION_REJECTED,x.message,x.path?{path:x.path}:void 0)}catch(y){return le(p,$.INTERNAL_ERROR,Ye(y))}finally{u-=1}}async function Ch(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return le(p,$.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return le(p,$.PLAN_FAILED,"Complete project file listing is required for page deletion.");u+=1;try{let y=Jg(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(y.truncated)return le(p,$.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:y.truncated.reasons});let x=y.files.filter(({path:D})=>/\.(?:tsx?|jsx?)$/.test(D)),k=Object.fromEntries(await Promise.all(x.map(async({path:D})=>[D,await n.readFile(D)]))),w=Af({expectedUrlPath:p.params.expectedUrlPath,files:k});if(!w.ok)return le(p,w.code==="HOME_PAGE_LOCKED"?$.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?$.ROUTE_NOT_FOUND:$.PLAN_FAILED,w.message);let O=await Promise.all(w.edits.map(async D=>({...D,baseContentHash:ve(await n.readFile(D.file))})));return Kn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(y){return le(p,$.INTERNAL_ERROR,Ye(y))}finally{u-=1}}async function Rh(p,y){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return le(p,$.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 le(p,$.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 le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return le(p,$.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!w)return le(p,$.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=p.params.kind==="insert-child"?p.params.position:null,D=await pa({files:w.files.map(L=>({path:L.pathTemplate,content:L.content})),exists:L=>n.exists(L),readFile:L=>n.readFile(L)});if(!D.ok)return le(p,$.MATERIALIZATION_REJECTED,D.message);let z=await Ud({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(L=>({pathTemplate:L.pathTemplate})),exists:L=>n.exists(L),commit:async L=>{let V=await n.readFile(y.entryFile),j=y.document,ce=y.pageCompositionProjection;if(!j||j.pageComposition?.status!=="supported"||j.version!==p.documentVersion||!ce||ce.status!=="supported"||ce.documentVersion!==j.version)return{ok:!0,data:le(p,$.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let re=L.entry.path,be=Mh(L.instanceName),Se,Ce=[];if(p.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:le(p,$.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let te=Ra({routeId:y.routeId,entryFile:y.entryFile,currentDocumentVersion:j.version,expectedDocumentVersion:p.documentVersion,source:V,projection:ce,placementKey:O.placementKey,component:{source:re,exportName:L.entry.export.kind==="default"?"default":L.entry.export.name,localName:be}});if(!te.ok)return{ok:!0,data:le(p,ks(te.error.code),te.error.message,{diagnostics:te.error.diagnostics})};let ie=te.plan.rewriteStep,Oe;switch(ie.kind){case"insert-root-expression":Oe=Si({source:V,locator:ie.locator,expectedSourceHash:ie.sourceHash,action:{kind:"insert",jsx:ie.node.jsx,placement:ie.placement,replaceOriginal:ie.replaceOriginal}});break;case"insert-child":Oe=zn({source:V,locator:ie.parentLocator,node:ie.node,placement:ie.placement,...ie.anchorLocator?{anchorLocator:ie.anchorLocator}:{}});break;default:Oe={ok:!1,source:V,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(ie)}`}}}if(!Oe.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Oe.diagnostic.message)};Se=Oe.source}else{let te=Na({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:j.version,expectedDocumentVersion:p.documentVersion,source:V,projection:ce,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!te.ok)return{ok:!0,data:le(p,ks(te.error.code),te.error.message,{diagnostics:te.error.diagnostics})};let ie=te.plan.rewriteStep,Oe;switch(ie.kind){case"replace-root-expression":Oe=Si({source:V,locator:ie.locator,expectedSourceHash:ie.sourceHash,action:{kind:"replace",jsx:`<${be} />`}});break;case"replace-node":Oe=Go({source:V,locator:ie.locator,node:{jsx:`<${be} />`}});break;default:Oe={ok:!1,source:V,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${ie.kind}`}}}if(!Oe.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Oe.diagnostic.message)};let ut=await Jl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:V,mutatedSource:Oe.source});Se=ut.source,Ce=await Promise.all(ut.files.map(async dt=>({operation:"delete",file:dt,baseContentHash:ve(await n.readFile(dt))})))}let Re=Gn({source:Se,moduleSpecifier:v(y.entryFile,re),imports:L.entry.export.kind==="default"?[{kind:"default",local:be}]:[{kind:"named",imported:L.entry.export.name,local:be}]});if(!Re.ok)return{ok:!0,data:le(p,$.AST_PARSE_ERROR,Re.diagnostic.message)};let _=L.files.map(te=>({operation:"create-only",file:te.path,content:te.content})),K=[{operation:"upsert",file:y.entryFile,content:Re.source,baseContentHash:ve(V)},..._,...Ce];u+=1;try{let te=await Kn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:K}});return!te.ok&&te.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:te.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:te}}finally{u-=1}}});return z.ok?z.data:le(p,$.VERSION_STALE,z.error.message,{materializationCode:z.error.code})}async function Nh(p,y){if(p.kind!=="move-node"&&p.kind!=="remove-node")return le(p,$.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let x=y.document,k=y.pageCompositionProjection;if(!x||x.pageComposition?.status!=="supported"||!k||k.status!=="supported")return le(p,$.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==x.version||k.documentVersion!==x.version)return le(p,$.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${x.version}).`);let w=await n.readFile(y.entryFile),O=Na({routeId:y.routeId,composition:y.composition,entryFile:y.entryFile,currentDocumentVersion:x.version,expectedDocumentVersion:p.documentVersion,source:w,projection:k,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(!O.ok)return le(p,ks(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let D=O.plan.rewriteStep,z;switch(D.kind){case"move-node":z=Wn({source:w,locator:D.locator,targetParentLocator:D.targetParentLocator,placement:D.placement,...D.anchorLocator?{anchorLocator:D.anchorLocator}:{}});break;case"remove-node":z=Xn({source:w,locator:D.locator});break;case"remove-root-expression":z=Si({source:w,locator:D.locator,expectedSourceHash:D.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:w,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${D.kind}`}}}if(!z.ok)return le(p,$.AST_PARSE_ERROR,z.diagnostic.message);let L=z.source,V=[];if(p.kind==="remove-node"){let ce=await Jl({routeState:y,placementUnitKey:p.target.placementUnitKey,source:w,mutatedSource:L});L=ce.source,V=await Promise.all(ce.files.map(async re=>({operation:"delete",file:re,baseContentHash:ve(await n.readFile(re))})))}let j=[{operation:"upsert",file:y.entryFile,content:L,baseContentHash:ve(w)},...V];u+=1;try{return await Kn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:y.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:j}})}finally{u-=1}}async function Jl(p){let y={source:p.mutatedSource,files:[]},x=p.routeState.graph,k=p.routeState.pageCompositionProjection;if(!x||!k||k.status!=="supported"||!n.listFiles)return y;let O=k.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!O)return y;let D=[...x.elements.values()].find(_=>_.sourceFile===p.routeState.entryFile&&_.importedFrom&&I(_.sourceRange,O));if(!D?.importedFrom||!D.exportName)return y;let z=E(D.importedFrom),L="components/site/generated/";if(!z.startsWith(L))return y;let V=z.slice(L.length).split("/")[0];if(!V||!/-[0-9a-f]{8}$/i.test(V))return y;let j=`${L}${V}`;if([...x.elements.values()].filter(_=>_.sourceFile===p.routeState.entryFile&&E(_.importedFrom??"")===z).length!==1)return y;let re=await n.listFiles({maxFiles:5e3,maxDepth:32}),be=Array.isArray(re)?re:re.files;if(!Array.isArray(re)&&re.truncated)return y;let Se=be.map(({path:_})=>_).filter(_=>_===j||_.startsWith(`${j}/`));if(Se.length===0||!Se.includes(z))return y;for(let{path:_}of be)if(!(_===p.routeState.entryFile||_===j||_.startsWith(`${j}/`)))try{if((await n.readFile(_)).includes(V))return y}catch{return y}let Ce=v(p.routeState.entryFile,z),Re=Yn({source:p.mutatedSource,moduleSpecifier:Ce,imports:D.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:D.exportName}]});return Re.ok?{source:Re.source,files:Se.sort((_,K)=>_.localeCompare(K))}:y}async function wh(p){if(n.getFileInfo){for(let w of p)if(await n.exists(w.path)&&await n.getFileInfo(w.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${w.path}`,details:{path:w.path}}}for(let w of p){if(w.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(w.path))continue;let O=await n.exists(w.path)?await $s(n,w.path):null;if(O?.ok){let D=PR(O.content,w.content);if(!D.ok)return{ok:!1,errorCode:"invalid-params",message:D.message,details:{path:w.path,code:D.code}}}}let y=Ph(p);if(y.length===0)return{ok:!0};let x=QR(n,p),k=yo({projectRoot:e.projectRoot,fileSystem:x,compositions:[...i.values()].map(w=>({context:w.composition,entryFile:w.entryFile})),externalAdapters:e.externalAdapters,externalSourceResolvers:e.externalSourceResolvers,functionCallContracts:e.functionCallContracts,dev:e.dev});try{for(let w of y){let O=i.get(w)?.composition;if(!O)continue;let D={routeId:O.routeId,...O.effectiveTemplateId!==void 0?{templateId:O.effectiveTemplateId}:{}};await k.initializeComposition(D),k.getDocument(D)}}catch(w){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ye(w)}`,details:{compositionKeys:y}}}finally{k.dispose()}return{ok:!0}}function Ph(p){return p.map(x=>x.path).some(Kg)?[...i.keys()]:[]}function bs(p,y,x,k){let w=go(y);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:w,message:x,...k?{details:k}:{}}}}async function Ss(p){let y=[];for(let x of new Set(p))y.push(await Ah(x));return y}async function Ah(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:ve(x)}}async function Xl(p,y,x,k){if(!e.historyStore)return null;let w=new Map(y.map(z=>[z.file,z])),O=new Map(x.map(z=>[z.file,z])),D=[...new Set([...w.keys(),...O.keys()])].sort().map(z=>{let L=w.get(z),V=O.get(z);return{path:z,preDigest:L?.exists===!1||!L?null:ve(L.content),postDigest:V?.exists===!1||!V?null:ve(V.content)}});return{schemaVersion:2,transactionId:`${p}:${k.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:k,files:D}}async function zl(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Vn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Es(p,y){let x=[];try{for(let k of p)await Wl(k),typeof n.bumpVersion=="function"&&n.bumpVersion(k.file),x.push(k.file)}catch(k){let w=await Th(y.filter(O=>x.includes(O.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ye(k)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${Ye(k)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Fh)}}async function Wl(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function Th(p){let y=[];for(let x of p)try{await Wl(x),typeof n.bumpVersion=="function"&&n.bumpVersion(x.file)}catch{y.push(x.file)}return y.length===0?{ok:!0}:{ok:!1,failedFiles:y}}function Fh(p){let y=p.exists!==!1;return{file:p.file,content:y?p.content:"",version:p.version,exists:y,...y?{sha256:ve(p.content)}:{}}}async function Kn(p){return h.runExclusive(()=>_h(p))}async function _h(p){let y=p.filePlan.edits.map(_=>_.file),x=o.resolveSelector(p.request.composition),k=x.context,w=p.historyPolicy==="none"?void 0:{initiatingComposition:k,affectedCompositions:xh(y)},O=await Ss(y),D=new Map(O.filter(_=>_.exists!==!1).map(_=>[_.file,_.content])),z=Gl(),L=new Map(f),V=new Set(m),j=new Set([...i.values()].filter(_=>p.filePlan.edits.some(K=>K.operation==="delete"&&K.file===_.entryFile)).map(_=>_.key)),ce=p.filePlan.edits.map(_=>_.operation==="delete"?{file:_.file,content:"",version:0,exists:!1}:{file:_.file,content:_.content,version:0,exists:!0,sha256:ve(_.content)}),re={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})},be=null,Se=!1,Ce=await ts({overlay:D,exists:_=>n.exists(_),plan:re,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:O,postSnapshots:ce,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...w?{provenance:w}:{}}),K=_?.historyTransition?_.historyTransition:e.historyStore?BR(await e.historyStore.readIndex()):null;if(e.historyStore&&!K)throw new Error("Durable history did not provide an exact index transition.");return be=await Xl(p.request.id,O,ce,K),be=await zl(be),{history:_,historyTransition:K}},reverify:async()=>{},writeCandidate:async()=>{let _=await d.executeFilePlan(p.filePlan);if(!_.ok)throw new ss(_);return{postSnapshots:await Ss(_.affectedFiles),affectedFiles:_.affectedFiles,internalResultVersion:_.resultVersion}},validateCandidate:async({candidate:_,receipt:K})=>{let te=await Ro(K.affectedFiles,{changed:!0,minimumVersion:K.internalResultVersion,publish:!1,excludedCompositionKeys:j});if(te.failedRoutes.length>0)throw new Bn(te.failedRoutes);let ie=Zl(z,te.candidateRouteStates??[]),Oe=Yl(ie,x.key);return{..._,rebuild:te,routeSnapshots:ie,resultVersion:Oe,...Bg(p.selectionRef,ie.map(ut=>ut.state.document))?{selectionRef:Bg(p.selectionRef,ie.map(ut=>ut.state.document))}:{}}},publishCandidate:async({candidate:_,history:K,receipt:te})=>{K?.history&&(await l.publishPrepared(K.history),Se=!0);let ie=_.resultVersion??te.internalResultVersion;return{composition:k,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ie,affectedFiles:te.affectedFiles,...p.output?{output:p.output}:{},..._.selectionRef?{selectionRef:_.selectionRef}:{}}},swapCandidate:({candidate:_,receipt:K})=>{_.routeSnapshots&&No(_.routeSnapshots),_.rebuild?.candidateSourceCache&&mr(f,_.rebuild.candidateSourceCache),jl(K.postSnapshots)},finalizeCandidate:async()=>{await Vn(be);for(let _ of j)i.delete(_)},emitCommitted:({candidate:_,published:K})=>{xs(K,_.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:_,receipt:K})=>{if(Se)throw new Error("history was published before transaction finalization failed");if(K){let te=await Es(O,K.postSnapshots);if(!te.ok)throw new Error(te.reason)}No(z),mr(f,L),Vl(V),_?.history&&await l.discardPrepared?.(_.history),await Vn(be)}});if(Ce.ok)return Ce.published;if(Ce.stage==="precheck"||Ce.stage==="build")try{await Vn(be)}catch(_){let K=await wo(Ye(_));return le(p.request,K,"Unable to clear an uncommitted transaction journal.")}if(Ce.recoveryRequired){let _=await wo(Ce.reason);return le(p.request,_===$.RECOVERY_PERSIST_FAILED?_:$.ROLLBACK_FAILED,Ce.reason)}let Re=Ce.error;return Re instanceof ss?{...le(p.request,go(Re.result.errorCode),Re.result.reason),...Re.result.affectedFiles?{affectedFiles:Re.result.affectedFiles}:{}}:Re instanceof Bn?le(p.request,$.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${ll(Re.failedRoutes)}`,{failedRoutes:Re.failedRoutes}):le(p.request,ql(Ce.stage),Ye(Re))}async function Hl(p){return h.runExclusive(async()=>{let y=p==="undo"?await l.prepareUndo():await l.prepareRedo();return y?Oh(p,y):{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:$.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function Oh(p,y){let x=y.entry,k=p==="undo"?x.preSnapshots:x.postSnapshots,w=p==="undo"?x.postSnapshots:x.preSnapshots,O=k.map(K=>K.file),{context:D,key:z}=Sh(x,O),L=await Ss(O),V=new Map(L.filter(K=>K.exists!==!1).map(K=>[K.file,K.content])),j=Ne(z),ce=Gl(),re=new Map(f),be=new Set(m),Se=null,Ce=!1,Re,_=await ts({overlay:V,plan:{operationId:`${p}:${x.operationId}`,intents:k.map(K=>K.exists===!1?{kind:"delete",path:K.file}:{kind:"upsert",path:K.file,content:K.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(Se=await Xl(`${p}:${x.operationId}`,L,k,y.historyTransition),Se=await zl(Se),y),reverify:async()=>{},writeCandidate:async()=>{let K=await Es(k,w);if(!K.ok)throw new Error(K.reason);return{snapshots:K.snapshots}},validateCandidate:async({candidate:K})=>{Re=bh(x,O);let te=await Ro(O,{changed:!0,minimumVersion:j+1,publish:!1,affectedCompositionKeys:Re});if(te.failedRoutes.length>0)throw new Bn(te.failedRoutes);let ie=Zl(ce,te.candidateRouteStates??[]),Oe=Yl(ie,z);return{...K,rebuild:te,routeSnapshots:ie,resultVersion:Oe}},publishCandidate:async({candidate:K,history:te})=>{if(!te)throw new Error("history cursor intent is missing");await l.publishPrepared(te),Ce=!0;let ie=K.resultVersion??j+1;return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!0,resultVersion:ie,affectedFiles:O,...x.output?{output:x.output}:{}}},swapCandidate:({candidate:K,receipt:te})=>{K.routeSnapshots&&No(K.routeSnapshots),K.rebuild?.candidateSourceCache&&mr(f,K.rebuild.candidateSourceCache),jl(te.snapshots)},finalizeCandidate:async()=>{await Vn(Se)},emitCommitted:({candidate:K,published:te})=>xs(te,K.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:K,receipt:te})=>{if(Ce)throw new Error("history cursor was published before transaction finalization failed");if(te){let ie=await Es(w,te.snapshots);if(!ie.ok)throw new Error(ie.reason)}No(ce),mr(f,re),Vl(be),K&&await l.discardPrepared?.(K),await Vn(Se)}});if(_.ok)return _.published;if(_.stage==="precheck"||_.stage==="build")try{await Vn(Se)}catch(K){let te=await wo(Ye(K));return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,error:{code:te,message:"Unable to clear an uncommitted transaction journal."}}}if(_.recoveryRequired){let K=await wo(_.reason);return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:O,error:{code:K===$.RECOVERY_PERSIST_FAILED?K:$.ROLLBACK_FAILED,message:_.reason}}}return{composition:D,requestId:p,kind:x.kind,target:x.target,ok:!1,resultVersion:j,affectedFiles:O,error:{code:_.error instanceof Bn?$.ROUTE_REBUILD_FAILED:ql(_.stage),message:Ye(_.error),..._.error instanceof Bn?{details:{failedRoutes:_.error.failedRoutes}}:{}}}}function Gl(){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 Yl(p,y){return p.find(k=>k.key===y)?.state.graph?.version??o.initialVersions.get(y)??0}function Zl(p,y){let x=new Map(p.map(k=>[k.key,k]));for(let k of y)x.set(k.key,k);return[...x.values()]}function No(p){for(let y of i.values())C(y);for(let y of p){let x={...y.state,dependencyFiles:new Set(y.state.dependencyFiles),fileVersions:new Map(y.state.fileVersions)};i.set(y.key,x),T(x,x.dependencyFiles)}}async function vs(p){let y=i.get(p);if(!y)throw new Error(`Composition not found: ${p}`);if(y.graph)return;let x=await n.readFile(y.entryFile);await fe(p,x)}function Un(p,y){let x=i.get(o.resolveSelector(y).key)??null;return!x||!Ql(x,p)?null:x}function Ql(p,y){if(p.documentIndex?.entriesByKey.has(y)||p.graph?.elements.has(y))return!0;let x=et(y);return x&&x!==y?p.graph?.elements.has(x)===!0:!1}function le(p,y,x,k){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:y,message:x,...k?{details:k}:{}}}}function ql(p){return p==="validate"?$.ROUTE_REBUILD_FAILED:p==="publish"?$.HISTORY_COMMIT_FAILED:$.WRITE_IO_ERROR}async function wo(p){if(g=!0,!l.markRecoveryRequired)return $.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),$.RECOVERY_REQUIRED}catch{return $.RECOVERY_PERSIST_FAILED}}function Mh(p){let x=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return x?`Prefab${x}`:"GeneratedPrefab"}function ks(p){return p==="VERSION_STALE"?$.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?$.CROSS_PAGE_MOVE_UNSUPPORTED:$.UNSUPPORTED_OPERATION}async function eu(p){if(p.target.kind==="route"){let x=i.get(o.resolveSelector(p.target.composition).key)??null;return x?(x.graph||await vs(x.key),x):le(p,$.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 vs(x.key),x):le(p,$.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return le(p,$.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let y=i.get(o.resolveSelector(p.composition).key)??null;return y?(y.graph||await vs(y.key),Ql(y,p.target.key)?y:le(p,$.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):le(p,$.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,y){let x=o.register({context:p,entryFile:y}),k=i.get(x.key);if(k?.entryFile===y)return;k&&C(k);let w=Lg(x.context,y);i.set(x.key,w),T(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:x.context})},unregisterComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);x&&(C(x),i.delete(y.key),o.unregister(y.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:y.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(x.graph)t="ready";else{t="building";try{let k=await n.readFile(x.entryFile);await fe(y.key,k),t="ready",r.emit({type:"graph-ready",composition:y.context,version:i.get(y.key)?.graph?.version??0})}catch(k){throw t="idle",r.emit({type:"graph-error",composition:y.context,message:Ye(k)}),k}}},getDocument(p){let y=o.resolveSelector(p),x=i.get(y.key);if(!x)throw new Error(`Composition not registered: ${y.key}`);if(!x.document)throw new Error(`Composition not built: ${y.key}`);return x.document},async getHistoryStatus(){await b;let p=await l.getStatus?.();return p?{...p,recoveryRequired:g}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:g}},getObjectEditContext(p,y,x){let k=Un(p,y),w=et(p)??p;if(k?.graph&&k.topology&&k.capabilities&&k.detailProjections){let O=k.detailProjections.get(w);if(O){let D=k.graph.elements.get(w);if(!D)throw new Error(`Key not found: ${p}`);let z=JR(p,w,x),L=new Map;if(O.isRepeat&&z?.instanceIndex!==void 0)for(let ce of D.attributes??[])L.set(ce.name,Dc({file:D.sourceFile,source:f.get(D.sourceFile)??"",element:D,propertyName:ce.name,selectionRef:z,graph:k.graph,sources:f}));let V=qm({element:D,graph:k.graph,source:f.get(D.sourceFile),documentVersion:k.graph.version,selectionRef:x,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:L}),j=ng(w,k.graph,k.topology,k.capabilities,O.textSources,O.provenances,O.dynamicData,V);return p===w?j:wg(j,p,k.document??null,k.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,y){let x=Un(p,y),k=et(p)??p;if(x?.graph&&x.topology&&x.capabilities&&x.detailProjections){let w=x.detailProjections.get(k);if(w){let O=tg(k,x.graph,x.topology,x.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return p===k?O:Ng(O,p,x.document??null,x.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,y){let x=Un(p,y),k=et(p)??p;if(!x?.graph)throw new Error(`Key not found: ${p}`);let w=x.graph.elements.get(k);if(!w)throw new Error(`Key not found: ${p}`);let O=f.get(w.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return na({key:k,route:{composition:x.composition,routeId:x.routeId,graph:x.graph,source:O}})},refreshSourceForKey:vh,async execute(p){if(await b,g)return le(p,$.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return kh(p);if(p.kind==="insert-page-resource")return Ih(p);if(p.kind==="delete-page-source")return Ch(p);let y=await eu(p);if("ok"in y)return y;await Ul(p);let x=await eu(p);if("ok"in x)return x;let k=x;if(p.target.kind==="page-unit"){let j=p;return p.kind==="insert-child"||p.kind==="replace-node"?Rh(j,k):p.kind==="move-node"||p.kind==="remove-node"?Nh(j,k):le(p,$.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let O=p.params,D=p.target.kind==="node"?p.target.key:null;if(O.kind==="move-node"&&"kind"in O.target&&O.target.kind==="source-sibling"){let j=O.target,ce=D?k.document?.entries.find(K=>K.key===D):null,re=k.document?.entries.find(K=>K.key===j.anchorKey),be=ce?.pageCompositionActionScope,Se=be?.kind==="source-siblings"?be.siblingKeys:null,Ce=Se?.indexOf(ce?.key??"")??-1,Re=Se?.indexOf(j.anchorKey)??-1,_=j.relation==="before"?Ce-1:Ce+1;if(!ce||!re||!Se||Ce<0||Re!==_||re.pageCompositionActionScope?.kind!=="source-siblings"||re.pageCompositionActionScope.siblingKeys.length!==Se.length||re.pageCompositionActionScope.siblingKeys.some((K,te)=>K!==Se[te])||!ce.operationSummary.canMove)return le(p,$.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!k.graph||!k.topology||!k.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:p.target.kind==="route"?$.ROUTE_NOT_FOUND:$.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 z=cN(k,k.graph,k.capabilities,f,i),L=await new Vi(z).plan(p);if(!L.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:go(L.errorCode),message:L.reason}};let V=L.plan;if(V.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:Z(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:Z(p),error:{code:$.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};u+=1;try{if(V.steps.some(ce=>ce.type==="invoke-external-adapter")){let ce=await d.execute(V);if(!ce.ok)return le(p,go(ce.errorCode),ce.reason);let re={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(Z(p),ce.resultVersion),affectedFiles:ce.affectedFiles,...ce.selectionRef?{selectionRef:ce.selectionRef}:{}};return xs(re,{rebuiltRoutes:[],failedRoutes:[]}),re}let j=await d.prepareRewritePlan(V);return j.ok?await Kn({request:p,filePlan:j.filePlan,...j.selectionRef?{selectionRef:j.selectionRef}:{}}):le(p,go(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:Z(p),error:{code:$.INTERNAL_ERROR,message:Ye(j)}}}finally{u-=1}},async undo(p){if(await b,g)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Ne(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};u+=1;try{return await Hl("undo")}finally{u-=1}},async redo(p){if(await b,g)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:Ne(o.entries[0].key),error:{code:$.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};u+=1;try{return await Hl("redo")}finally{u-=1}},notifyFileChanged(p){Bl([p])},getAffectedCompositions(p){return yh(p)},subscribe(p){return r.subscribe(p)}}}function tN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function nN(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&&ho(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=et(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&&ho(u.sourceRange,n.container.sourceRange)&&d){f.pageCompositionUnitKey=d.placementUnitKey;continue}let b=n.placements.find(E=>E.members.some(v=>v.sourceRange!==null&&(ho(u.sourceRange,v.sourceRange)||aN(v.sourceRange,u.sourceRange))));if(b){f.pageCompositionUnitKey=b.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)}rN(e,t,n,r)}function rN(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&&ho(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 b=s.get(g.target)??0,E=Math.min(2,b+h);E!==b&&(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!==(et(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 b=h.match.path,E=b.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Ae(E))){d(u)===1&&jg(b)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!jg(E))continue;let v=f.get(E.node)??[];v.push({entry:m,element:u,parentPath:E}),f.set(E.node,v)}for(let m of f.values()){let u=m[0];if(!u)continue;let g=u.entry.pageCompositionUnitKey,h=[],b=!!(g&&d(u.element)===1);for(let v of u.parentPath.node.children){if(oN(v))continue;if(!iN(v)){b=!1;break}let I=[...t.elements.values()].find(P=>P.sourceFile===u.element.sourceFile&&P.componentName===u.element.componentName&&ho(P.sourceRange,sN(v))),R=I?o.get(I.identity.key):null;if(!I||!R||R.parentKey||R.pageCompositionUnitKey!==g||d(I)!==1){b=!1;break}h.push(R)}if(!b||h.length!==m.length||m.some(({entry:v})=>!h.some(I=>I.key===v.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(v=>v.key);for(let v of h)v.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function jg(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function oN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function iN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function sN(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 ho(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function aN(e,t){return Vg(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Vg(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Vg(e,t,n,r){return e!==n?e-n:t-r}function cN(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 b=et(h)??h,E=t.elements.get(b);return E?l(h,E):null}).filter(h=>h!==null);let g=t.elements.get(f.baseKey);return g?g.childKeys.map(h=>{let b=t.elements.get(h);return b?l(h,b):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:na({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 cl(e.detailProjections?.get(m.baseKey)?.textTargets.get(f)??null,m.repeatIndex)},async getElementPropertyWriteTarget(d,f){let m=c(d);return cl(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 b=e.detailProjections?.get(u.baseKey)?.propertyProvenances.get(f);if(b)return b;let E=g.attributes?.find(v=>v.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 Dc({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=_R(d);return f?{baseKey:f.baseKey,repeatIndex:Rg(e.document??null,d,f.baseKey,e.documentIndex)??Cg(f)}:{baseKey:d,repeatIndex:null}}function l(d,f){let m=et(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 lN={"stale-version":$.VERSION_STALE,"capability-denied":$.CAPABILITY_REJECTED,"invalid-params":$.INVALID_PARAMS,"locator-miss":$.LOCATOR_FAILED,"route-not-found":$.ROUTE_NOT_FOUND,"unsupported-operation":$.UNSUPPORTED_OPERATION,"invalid-target":$.INVALID_TARGET,"ast-error":$.AST_PARSE_ERROR,"writeback-failed":$.WRITE_IO_ERROR,"rollback-failed":$.RECOVERY_REQUIRED,unknown:$.INTERNAL_ERROR};function go(e){return lN[e]}function Ye(e){return e instanceof Error&&e.message?e.message:String(e)}function Kg(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function uN(e){let t=$n(e);if(!DR.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=>LR.map(a=>`${s}/${a}`))}function dN(e){let n=$n(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function fN(e){return Xg(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function pN(e){return Xg(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Xg(e,t){let n=[];for(let r of e.matchAll(t)){let o=zg(r[1]??"");o&&n.push(o)}return n}function Ug(e,t){let n=zg(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(`${mN(e)}/${n}`):n.startsWith("/")?$n(n.slice(1)):fl(n)?$n(n):null}function zg(e){return e.split(/[?#]/,1)[0]?.trim()??""}function fl(e){return/\.css$/i.test(e)}function mN(e){let t=$n(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function gN(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 hN(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 as=class{constructor(t){this.options=t,this.fileSystem=new br(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Mo(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 Do(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return $o(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 Vo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=xN.safeParse(t);if(!n.success)return{result:Oo(t,n.error.issues.map(i=>i.message))};let r=new br(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:Sn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=bN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>SN(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 yo({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Lo(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}:{}})}};function SN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function EN(e){return new as(e)}import{SiteEditOperationRequestSchema as IN}from"@vcp-dev/contracts";import Rt from"node:fs/promises";import Ze from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as vN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as kN}from"@vcp-dev/contracts";var cs=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=yo({...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 $o(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 Vo(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(Ze.join(n,r),"utf8")},async readFileBytes(r){return Rt.readFile(Ze.join(n,r))},async getFileInfo(r){let o=Ze.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 si(Ze.join(n,r),o)},async createExclusive(r,o){let i=Ze.join(n,r);await Rt.mkdir(Ze.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(Ze.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=Ze.join(n,i),a=Ze.dirname(Ze.join(n,o));for(;a!==s&&a.startsWith(`${s}${Ze.sep}`);){try{await Rt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Ze.dirname(a);continue}break}a=Ze.dirname(a)}},async exists(r){try{return await Rt.access(Ze.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...kN,...vN],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=Ze.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 b=await Rt.readdir(g,{withFileTypes:!0});for(let E of b)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 pl(e){return new cs(e)}var ls=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=pl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Lo(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:Mo(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:Do(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=IN.safeParse(r);if(!o.success)return Oo(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:Sn(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:Sn(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:Sn(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 CN(e){return new ls(e)}import{createHash as RN,randomUUID as Cl}from"node:crypto";import Te from"node:fs/promises";import _e from"node:path";var St=1,gl=1,NN=2,wN="index.json",PN="recovery.json",AN="transaction-journal.json",TN="document-version.json",ds={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},ee={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};async function nh(e,t={}){let n=XN(e),r=HN(t.limits),o=ml(n),i=zN(n),s=await tt(i),a=await tt(o)||s;a||(await LN(n),await BN(n)),a||await GN(n);let c=await at(n),l=new Set(a?(await hs(n)).map(f=>f.stageId):[]);a||await xo(n,c.entryIds);let d=async()=>{if(await tt(o)||s)throw new oe(ee.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")};return{rootDir:n,recoveryRequired:a,async readDocumentVersion(){return eh(n)},async writeDocumentVersion(f){if(await d(),!Number.isInteger(f)||f<0)throw new oe(ee.INVALID_SCHEMA,"document version must be a non-negative integer");let m=await eh(n);await bo(lh(n),{schemaVersion:1,version:Math.max(m,f)})},async stageAppend(f,m={}){await d();let u=await Hg(f,r),g={schemaVersion:gl,stageId:Cl(),entryId:u.entryId,blobIds:u.blobs.map(h=>h.digest)};try{await Gg(n,u),await ON(n,g,m.durableManifest!==!1)}catch(h){try{await Zg(n,g)}catch(b){throw new oe(ee.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:b})}throw h}return{stageId:g.stageId,entryId:g.entryId,blobIds:g.blobIds}},async discardStage(f){await d(),bl(f);let m=await yl(n,f);m&&await Zg(n,m)},async previewStagedAppend(f,m){return await d(),(await Wg(n,r,f,m)).transition},async previewCursor(f,m){await d();let u=await at(n);return Sl(u,m),hl(f,u.entryIds.length),rh(u,u.entryIds,f)},async publishStagedAppend(f,m,u){if(await d(),fs(f,"entryId"),u){bl(u);let h=await yl(n,u);if(!h||h.entryId!==f)throw new oe(ee.INVALID_SCHEMA,"history stage does not match the published entry")}let g=await Wg(n,r,f,m);return qg({rootDir:n,previousDigest:g.current.digest,entryIds:g.entryIds,cursor:g.cursor,afterWrite:async()=>{u?await ps(n,u):await DN(n,f),await xo(n,g.entryIds)}})},async append(f){await d();let m=await at(n),u=await Hg(f,r),g=[...m.entryIds];m.cursor<g.length-1&&g.splice(m.cursor+1),g.push(u.entryId);try{await Gg(n,u);let h=await oh(n,g,r);return await Nl(n,h.entryIds,h.cursor),await xo(n,h.entryIds),at(n)}catch(h){throw await xo(n,m.entryIds),h}},async readEntry(f){return fs(f,"entryId"),Eo(n,f)},async readBlob(f){fs(f,"blobId");let m=await Ml(n,f),u=await un(m,ee.NOT_FOUND,"blob");return wl(u,f,m),u},async readIndex(){return at(n)},async readStatus(){let f=await at(n);return{canUndo:f.undoIds.length>0,canRedo:f.redoIds.length>0,undoDepth:f.undoIds.length,redoDepth:f.redoIds.length,cursor:f.cursor,recoveryRequired:await tt(o)||await tt(i)}},async readUndoRedoIds(){let f=await at(n);return{undoIds:f.undoIds,redoIds:f.redoIds,currentId:f.currentId}},async setCursor(f,m){await d();let u=await at(n);return Sl(u,m),hl(f,u.entryIds.length),qg({rootDir:n,previousDigest:u.digest,entryIds:u.entryIds,cursor:f})},async markRecoveryRequired(f){await tt(o)||await bo(ml(n),{schemaVersion:St,reason:WN(f),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Te.rm(ml(n),{force:!0})},async readTransactionJournal(){return await tt(i)?us(i):null},async writeTransactionJournal(f){await d(),uh(f);try{await bo(i,f)}catch(u){let g=await us(i).catch(()=>null);if(g&&Buffer.from(ct(g)).equals(Buffer.from(ct(f))))return;throw g?new oe(ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:u}):u}let m=await us(i);if(!Buffer.from(ct(m)).equals(Buffer.from(ct(f))))throw new oe(ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(f){let m=await tt(i)?await us(i):null;if(m&&m.transactionId!==f)throw new oe(ee.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Te.rm(i,{force:!0})}catch(u){if(!await tt(i))return;throw u}if(await tt(i))throw new oe(ee.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await d();for(let m of l)await ps(n,m),l.delete(m);await $N(n);let f=await at(n);await xo(n,f.entryIds)}}}async function Wg(e,t,n,r){fs(n,"entryId");let o=await at(e);Sl(o,r);let i=await Eo(e,n),s=[...o.entryIds];o.cursor<s.length-1&&s.splice(o.cursor+1),s.push(i.id);let a=await oh(e,s,t);return{current:o,entryIds:a.entryIds,cursor:a.cursor,transition:rh(o,a.entryIds,a.cursor)}}function rh(e,t,n){return hl(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:FN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function FN(e,t){return dn(ct({schemaVersion:St,entryIds:e,cursor:t}))}function hl(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new oe(ee.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function _N(e){if(!Nt(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!lt(e.expectedIndexDigest)||!lt(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!lt(n)?!1:t===-1?n===null:lt(n)}async function Hg(e,t){if(!e.kind.trim())throw new oe(ee.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new oe(ee.INVALID_JSON,"history blob name must not be empty");let l=JN(c.data),d=dn(l);n.push({name:c.name,bytes:l,digest:d,sizeBytes:l.byteLength}),r.push({name:c.name,digest:d,sizeBytes:l.byteLength})}let o={schemaVersion:St,kind:e.kind,manifest:e.manifest,blobs:r},i=ct({...o}),s=dn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new oe(ee.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function Gg(e,t){let n=Tl(e,t.entryId),r={id:t.entryId,...t.entryBody},o=[...t.blobs.map(a=>Yg(Fl(e,a.digest),a.bytes,{kind:"blob",digest:a.digest},Ol(e,a.digest))),Yg(n,ct(r),{kind:"entry",digest:t.entryId},_l(e,t.entryId))],s=(await Promise.allSettled(o)).find(a=>a.status==="rejected");if(s)throw s.reason}async function Yg(e,t,n,r){let o=await kl(e)??(r?await kl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new oe(n.kind==="blob"?ee.BLOB_CORRUPT:ee.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await ah(e,t)}async function oh(e,t,n){let r=[...t],o=r.length-1;for(;;){if((await sh(e,r)).totalBytes<=n.maxSessionBytes&&r.length<=n.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new oe(ee.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");r.shift(),o-=1}}async function ON(e,t,n){Rl(t);let r=Al(e,t.stageId);if(n){await bo(r,t);return}await UN(r,t)}async function yl(e,t){let n=await kl(Al(e,t));if(n===null)return null;let r=vo(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Rl(r);if(o.stageId!==t)throw new oe(ee.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function hs(e){let t=[];for(let n of await gs(Pl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);bl(r);let o=await yl(e,r);o&&t.push(o)}return t}async function Zg(e,t){Rl(t);let n=await at(e),r=(await hs(e)).filter(s=>s.stageId!==t.stageId),o=new Set(n.entryIds),i=new Set;for(let s of n.entryIds){let a=await Eo(e,s);for(let c of a.blobs)i.add(c.digest)}for(let s of r){o.add(s.entryId);for(let a of s.blobIds)i.add(a)}o.has(t.entryId)||await Qg(Tl(e,t.entryId),_l(e,t.entryId));for(let s of t.blobIds)i.has(s)||await Qg(Fl(e,s),Ol(e,s));await ps(e,t.stageId),await Il(ko(e)),await Il(Io(e))}async function ps(e,t){await xl(Al(e,t)),await MN(e)}async function MN(e){try{await Te.rmdir(Pl(e))}catch(t){if(Co(t)||Nt(t)&&t.code==="ENOTEMPTY")return;throw t}}async function DN(e,t){for(let n of await hs(e))n.entryId===t&&await ps(e,n.stageId)}async function xl(e){if(await Te.rm(e,{force:!0}),await tt(e))throw new oe(ee.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Qg(e,t){await xl(e),await xl(t)}function Rl(e){if(!Nt(e)||e.schemaVersion!==gl||typeof e.stageId!="string"||!ih(e.stageId)||!lt(e.entryId))throw new oe(ee.INVALID_SCHEMA,"history stage schema is invalid");let t=ch(e.blobIds,"history stage blobIds");return{schemaVersion:gl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function bl(e){if(!ih(e))throw new oe(ee.INVALID_PATH,"history stageId must be a UUID")}function ih(e){return typeof e=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e)}async function xo(e,t){let n=new Set(t),r=new Set;for(let c of t){let l=await Eo(e,c);for(let d of l.blobs)r.add(d.digest)}for(let c of await hs(e)){n.add(c.entryId);for(let l of c.blobIds)r.add(l)}let o=ko(e),i=await gs(o);for(let c of i){if(!c.endsWith(".json"))continue;let l=th(c.slice(0,-5));l&&!n.has(l)&&await ms(_e.join(o,c))}let s=Io(e),a=await gs(s);for(let c of a){let l=th(c);l&&!r.has(l)&&await ms(_e.join(s,c))}}async function at(e){let t=ys(e),n=await un(t,ee.NOT_FOUND,"index"),r=vo(Buffer.from(n).toString("utf8"),"index"),o=jN(r),i=[...o.entryIds],{totalBytes:s}=await sh(e,i),a=i.slice(0,o.cursor+1).reverse(),c=i.slice(o.cursor+1);return{schemaVersion:St,digest:o.digest,entryIds:i,cursor:o.cursor,currentId:i[o.cursor]??null,undoIds:a,redoIds:c,totalBytes:s}}async function sh(e,t){let n=0,r=new Set,o=ys(e),i=await un(o,ee.NOT_FOUND,"index");n+=i.byteLength;for(let s of t){let a=await Eo(e,s),c=await dh(e,s),l=await un(c,ee.NOT_FOUND,"entry");n+=l.byteLength;for(let d of a.blobs){if(r.has(d.digest))continue;r.add(d.digest);let f=await Ml(e,d.digest),m=await un(f,ee.NOT_FOUND,"blob");wl(m,d.digest,f),n+=m.byteLength}}return{totalBytes:n}}async function Eo(e,t){let n=await dh(e,t),r=await un(n,ee.NOT_FOUND,"entry"),o=vo(Buffer.from(r).toString("utf8"),`entry ${t}`),i=VN(o);if(i.id!==t)throw new oe(ee.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(dn(ct({schemaVersion:i.schemaVersion,kind:i.kind,manifest:i.manifest,blobs:i.blobs}))!==t)throw new oe(ee.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);for(let a of i.blobs){let c=await Ml(e,a.digest),l=await un(c,ee.NOT_FOUND,"blob");wl(l,a.digest,c)}return i}async function Nl(e,t,n){let r={schemaVersion:St,digest:dn(ct({schemaVersion:St,entryIds:t,cursor:n})),entryIds:t,cursor:n};await bo(ys(e),r)}function Sl(e,t){if(t!==void 0&&e.digest!==t)throw new oe(ee.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function qg(e){let t=dn(ct({schemaVersion:St,entryIds:e.entryIds,cursor:e.cursor}));try{return await Nl(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.(),await at(e.rootDir)}catch(n){let r=await at(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new oe(ee.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function LN(e){await Te.mkdir(e,{recursive:!0}),await Te.mkdir(ko(e),{recursive:!0}),await Te.mkdir(Io(e),{recursive:!0}),await Te.mkdir(So(e),{recursive:!0})}async function BN(e){await Te.rm(So(e),{recursive:!0,force:!0}),await Te.mkdir(So(e),{recursive:!0})}async function $N(e){let t=So(e);await Te.mkdir(t,{recursive:!0});for(let n of await gs(t))n!=="stages"&&await Te.rm(_e.join(t,n),{recursive:!0,force:!0})}function jN(e){if(!Nt(e))throw new oe(ee.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==St)throw new oe(ee.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=ch(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new oe(ee.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!lt(o))throw new oe(ee.INDEX_CORRUPT,"index digest is invalid");let i=dn(ct({schemaVersion:St,entryIds:t,cursor:r}));if(o!==i)throw new oe(ee.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:St,digest:o,entryIds:t,cursor:r}}function VN(e){if(!Nt(e))throw new oe(ee.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==St)throw new oe(ee.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!lt(t))throw new oe(ee.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new oe(ee.ENTRY_CORRUPT,"entry kind is invalid");let r=vl(e.manifest,"entry.manifest"),o=KN(e.blobs);return{id:t,schemaVersion:St,kind:n,manifest:r,blobs:o}}function KN(e){if(!Array.isArray(e))throw new oe(ee.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Nt(t))throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!lt(o))throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new oe(ee.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function bo(e,t){await ah(e,ct(t))}async function UN(e,t){let n=_e.dirname(e),r=_e.basename(e),o=_e.join(n,`.${r}.${process.pid}.${Cl()}.tmp`);await Te.mkdir(n,{recursive:!0});try{await Te.writeFile(o,ct(t),{flag:"wx"}),await Te.rename(o,e)}finally{await ms(o)}}async function ah(e,t){let n=_e.dirname(e),r=_e.basename(e),o=_e.join(n,`.${r}.${process.pid}.${Cl()}.tmp`);await Te.mkdir(n,{recursive:!0});try{let i=await Te.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Te.rename(o,e),await Il(n)}finally{await ms(o)}}function ct(e){return Buffer.from(JSON.stringify(El(e)),"utf8")}function El(e){if(Array.isArray(e))return e.map(t=>El(t));if(Nt(e)){let t={};for(let n of Object.keys(e).sort())t[n]=El(e[n]);return t}return e}function vo(e,t){try{return JSON.parse(e)}catch(n){throw new oe(ee.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function vl(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>vl(n,t));if(Nt(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=vl(o,t);return n}break}throw new oe(ee.INVALID_JSON,`${t} must be JSON-serializable`)}function ch(e,t){if(!Array.isArray(e))throw new oe(ee.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!lt(n))throw new oe(ee.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function fs(e,t){if(!lt(e))throw new oe(ee.INVALID_PATH,`${t} must be a sha256 digest`)}function lt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function dn(e){return`sha256:${RN("sha256").update(e).digest("hex")}`}function JN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function un(e,t,n){try{return await Te.readFile(e)}catch(r){throw new oe(t,`${n} not found: ${e}`,{cause:r})}}async function kl(e){try{return await Te.readFile(e)}catch(t){if(Co(t))return null;throw t}}function wl(e,t,n){if(dn(e)!==t)throw new oe(ee.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function tt(e){try{return await Te.access(e),!0}catch(t){if(Co(t))return!1;throw t}}async function ms(e){try{await Te.rm(e,{force:!0,recursive:!0})}catch{}}async function Il(e){try{let t=await Te.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function gs(e){try{return await Te.readdir(e)}catch(t){if(Co(t))return[];throw t}}function XN(e){if(typeof e!="string"||e.trim().length===0)throw new oe(ee.INVALID_ROOT,"history store rootDir must be a non-empty string");return _e.resolve(e)}function ys(e){return _e.join(e,wN)}function ml(e){return _e.join(e,PN)}function zN(e){return _e.join(e,AN)}function lh(e){return _e.join(e,TN)}async function eh(e){try{let t=await Te.readFile(lh(e),"utf8"),n=vo(t,"document version");if(!Nt(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new oe(ee.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Co(t))return 0;throw t}}async function us(e){let t=await un(e,ee.RECOVERY_PENDING,"transaction journal"),n=vo(Buffer.from(t).toString("utf8"),"transaction journal");return uh(n),n}function uh(e){if(!Nt(e)||e.schemaVersion!==NN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!_N(e.historyTransition)||!Array.isArray(e.files))throw new oe(ee.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Nt(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!lt(t.preDigest)||t.postDigest!==null&&!lt(t.postDigest))throw new oe(ee.INVALID_SCHEMA,"transaction journal file digest is invalid")}function WN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function ko(e){return _e.join(e,"entries")}function Io(e){return _e.join(e,"blobs")}function So(e){return _e.join(e,"tmp")}function Pl(e){return _e.join(So(e),"stages")}function Al(e,t){return _e.join(Pl(e),`${t}.json`)}function Tl(e,t){return _e.join(ko(e),`${ph(t)}.json`)}function Fl(e,t){return _e.join(Io(e),ph(t))}function _l(e,t){return _e.join(ko(e),`${t}.json`)}function Ol(e,t){return _e.join(Io(e),t)}async function dh(e,t){return fh(Tl(e,t),_l(e,t))}async function Ml(e,t){return fh(Fl(e,t),Ol(e,t))}async function fh(e,t){return await tt(e)?e:await tt(t)?t:e}function ph(e){return e.slice(7)}function th(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return lt(t)?t:null}function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Co(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function HN(e){return{maxEntries:e?.maxEntries??ds.maxEntries,maxSessionBytes:e?.maxSessionBytes??ds.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??ds.maxEntryBytes}}async function GN(e){let t=ys(e);await tt(t)||await Nl(e,[],-1)}export{oe as FileHistoryStoreError,Br as PageTemplateManagedSourceError,ls as PreviewFileSystemSiteEditEngineRuntime,wd as SITE_EDIT_RAW_COLOR_LITERAL_RE,as as SnapshotSiteEditEngineRuntime,xf as computeManagedPageTemplatePaths,CN as createPreviewSiteEditEngineRuntime,EN as createSiteEditEngineRuntime,gf as decodePageTemplateKey,ja as encodePageTemplateId,Qh as instrumentSiteEditRuntimeAttributes,bf as isManagedPageTemplateSourcePath,nh as openFileHistoryStore,Uh as parseSourceModule,Jh as resolveImportBase,xv as resolveManagedPageTemplateComposition,ki as scanManagedPageTemplateCandidates,Ef as scanSiteEditCompositionsFromFiles,Tr as scanSiteEditThemeStyleViolations};