@vcp-dev/site-edit-engine 0.10.69 → 0.10.71
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 +10 -10
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as Sy from"@babel/parser";import*as He from"@babel/types";import*as tn from"node:path";var Vs=[".tsx",".ts",".jsx",".js"],Ey=Vs.map(e=>`/index${e}`),vy=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 uu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&vy.has(n[1].toLowerCase())}function du(e){let t=[];for(let n of e.program.body)He.isImportDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),He.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),He.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value);return He.traverseFast(e.program,n=>{let r=He.isImportExpression(n)?n.source:He.isCallExpression(n)&&He.isImport(n.callee)?n.arguments[0]:null;He.isStringLiteral(r)&&kt(r.value)&&t.push(r.value)}),t}function kt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function bn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function ky(e,t){if(Vs.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Vs){let r=`${e}${n}`;if(await t(r))return r}for(let n of Ey){let r=`${e}${n}`;if(await t(r))return r}return null}async function Sn(e,t,n){let r=await Lo(e,t,n);return r.ok?r.path:null}async function Lo(e,t,n){let r=bn(e,t);try{if(!Iy(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 ky(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 Iy(e,t,n){if(!kt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.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!tn.posix.isAbsolute(e)}import{createHash as Ry}from"node:crypto";import*as fu from"@babel/parser";function En(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:En(t,n,r,o)}}function Ks(e,t,n,r,o){return{ok:!1,source:e,diagnostic:En(t,n,r,o)}}var Cy={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Ft(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:fu.parse(t,{sourceType:"module",plugins:Cy[n]})}}catch(r){return{ok:!1,source:t,diagnostic:En("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Us(e,t){return Ft({source:e,profile:pu(t.kind)})}function Cr(e,t){return Ft({source:e,profile:pu(t)})}function pu(e){return"next-app-entry"}function vn(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 Xt=(e,t)=>{let n=Ft({source:t,profile:vn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Ry("sha256").update(t).digest("hex")}`,ast:n.ast,imports:du(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function wy(e,t){return Xt(e,t)}function Ny(e,t){return bn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Py,parseComponentI18nResourcesJson as Ay,resolveSiteTextDirection as Ty,SiteLocaleSchema as Fy}from"@vcp-dev/contracts";var _y=["i18next","react-i18next"],My="components/ui/site-locale-provider.tsx",Oy="components/ui/component-i18n-provider.tsx",mu="app/layout.tsx";async function Do(e){let t=e.files.filter(m=>m.path.endsWith(Py));if(t.length===0)return{ok:!0};for(let m of["package.json",mu,My,Oy])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=gu(n)&&gu(n.dependencies)?n.dependencies:{},o=_y.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(mu),s=Js(i,"html","lang"),a=Js(i,"html","dir"),c=Js(i,"SiteLocaleProvider","locale"),l=Fy.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Ty(l.data))return nn("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 nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return nn("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let m of t){let g=Ay(m.content);if(!g.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return nn(`Component i18n resource ${m.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Js(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 gu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import zs from"@babel/generator";import*as Eu from"@babel/parser";import Ws from"@babel/traverse";import*as we from"@babel/types";import{computeSiteEditSourceIdentityKey as Dy}from"@vcp-dev/contracts";var hu="data-vcp-ui-component",Bo="components/ui";function zt(e){if(!e)return!1;let t=Xs(e);return t===Bo||t.startsWith(`${Bo}/`)||t.includes(`/${Bo}/`)||t.endsWith(`/${Bo}`)}function kn(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?zt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?zt(Xs(`${Ly(t)}/${e}`)):zt(e):!1}function Xs(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 Ly(e){let t=Xs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as lP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as dP,isSiteEditRuntimeTextTag as fP}from"@vcp-dev/contracts/site-edit-runtime-capability";var yu={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 By=typeof zs=="function"?zs:zs.default,jy=typeof Ws=="function"?Ws:Ws.default,$y=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Vy="suppressHydrationWarning",Ky=new Set(["SiteEditBootstrap"]);function Uy(e){let t=zy(e.file,e.projectRoot);if(!Xy(e.source)||zt(t))return{code:e.source,elements:[]};let n=e.attributes??yu,r=Eu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Hy(r,t);return jy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!Yy(c)||vu(a,n.key))return;let l=Qy(s)??"default",u=ex(s),d=Dy(t,l,u),m=$o(c)??"unknown",g=Wy(c)?"jsx":"component-call";if(g==="component-call"&&!qy(s.node.children)&&Ky.has(m))return;let f=g==="component-call"&&Gy(m,i);Zy(a,n.key,d),f&&xu(a,hu),Jy(s)&&xu(a,Vy),o.push({key:d,tag:m,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:By(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Jy(e){return!e.findParent(t=>t.isJSXElement())}function Xy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function zy(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 Wy(e){return we.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function $o(e){return we.isJSXIdentifier(e)?e.name:we.isJSXMemberExpression(e)?Iu(e):null}function Hy(e,t){let n=new Set;for(let r of e.program.body)if(!(!we.isImportDeclaration(r)||!kn(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function Gy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function Yy(e){let t=$o(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!$y.has(t)}function vu(e,t){return e.attributes.some(n=>we.isJSXAttribute(n)&&we.isJSXIdentifier(n.name,{name:t}))}function Zy(e,t,n){ku(e,we.jsxAttribute(we.jsxIdentifier(t),we.stringLiteral(n)))}function xu(e,t){vu(e,t)||ku(e,we.jsxAttribute(we.jsxIdentifier(t),null))}function ku(e,t){let n=e.attributes.findIndex(r=>we.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Iu(e){return`${we.isJSXIdentifier(e.object)?e.object.name:Iu(e.object)}.${e.property.name}`}function Qy(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&we.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 qy(e){return e.some(t=>we.isJSXElement(t)||we.isJSXFragment(t))}var bu=new WeakMap,jo=new WeakMap,Hs=new WeakMap;function ex(e){let t=bu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=tx(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return bu.set(e.node,o),o}function tx(e){let t=$o(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${Su(e,t)}`:`${t}#${Su(e,t)}`}function Su(e,t){let n=Cu(e)??e.getFunctionParent();if(!n)return 0;let r=Hs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Hs.get(n.node);o||(o=new Map,Hs.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()?Vo(n):nx(n);for(let c of a)if($o(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 nx(e){let t=jo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Cu(r)&&n.push(r)}}),jo.set(e.node,n),n}function Cu(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 Vo(e){let t=jo.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(...Vo(o));continue}o.isJSXExpressionContainer()&&n.push(...In(o.get("expression")))}return jo.set(e.node,n),n}function In(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Vo(e);if(e.isParenthesizedExpression())return In(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return In(e.get("right"));if(e.isConditionalExpression())return[...In(e.get("consequent")),...In(e.get("alternate"))];if(e.isCallExpression()&&ox(e.node)){let t=e.get("arguments")[0];return rx(t)}return[]}function rx(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Vo(t);if(t.isParenthesizedExpression())return In(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?In(r):[]}return[]}function ox(e){return we.isMemberExpression(e.callee)&&we.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as jN,SiteEditPatchPlanSchema as $N}from"@vcp-dev/contracts";function Cn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Ko(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 Uo(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 Jo(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:ix(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 Xo(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:Cn(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 ix(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 Gw,computeSiteEditCompositionKey as Yw,getSiteEditSourceDeleteProtectionReason as Zw,isSiteEditTextSourcePath as Qw,parseSiteEditRepeatInstanceKey as qw,SITE_EDIT_SOURCE_DELETE_CAPABILITY as eN,stripSiteEditRepeatInstanceKeys as it}from"@vcp-dev/contracts";import ws from"node:path";import{parse as tN}from"yaml";import qs from"node:path";import{TextDecoder as ax}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as wu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Nu,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Pu,SiteEditCompositionContextSchema as cx,SiteEditSourceFileResponseSchema as Gs,SiteEditSourceLocationSchema as lx,SiteEditSourcePathSchema as zo,SiteEditSourceTreeResponseSchema as ux,isSiteEditTextSourcePath as dx}from"@vcp-dev/contracts";import{createHash as sx}from"node:crypto";var Rr=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 Ce(e){return`sha256:${sx("sha256").update(e).digest("hex")}`}var fx=[...Pu,...wu,...Nu];function ea(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return cx.parse(e.composition)}var Ys=2e3,Zs=12,Qs=24*1024*1024,Ru=512*1024,px=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),mx={".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"},gx={".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"},hx=new ax("utf-8",{fatal:!0});async function Wo(e,t={}){let n=ea(t),{files:r,truncated:o}=await kx(e,t),i=Rx(r.map(s=>s.metadata));return ux.parse({composition:n,nodes:i,defaultPath:wx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Ho(e,t,n={}){let r=ea(n),o=zo.parse(t.path),i=await xx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(na(o)){let a=Fu(o),c=await Sx(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Gs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await ta(e,o);return s.ok?Gs.parse({composition:r,path:o,kind:"text",language:_u(o),sizeBytes:s.sizeBytes,contentHash:Ce(s.content),readonly:!1,content:s.content}):Gs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function ta(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=yx(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 yx(e){if(e.includes(0))return null;try{return hx.decode(e)}catch{return null}}async function xx(e,t,n){if(!Ex(t,n))return null;let r=await bx(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function bx(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Au(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(na(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Sx(e,t){if(!px.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>Ru)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>Ru?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Ex(e,t){return Pu.some(n=>n===e)||wu.some(n=>n===e)||Nu.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=zo.safeParse(n);return r.success&&r.data===e})}function Go(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return lx.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 Au(e){return Array.isArray(e)?{files:e}:e}function vx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function kx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Au(await e.listFiles({roots:Ix(t),maxFiles:Ys+1,maxDepth:Zs,maxTotalBytes:Qs+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=zo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Zs){o.add("max-depth");continue}if(r.size>=Ys){o.add("max-files");break}if(i+a.sizeBytes>Qs){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Cx(l,a.sizeBytes,ea(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:vx([...o]),maxFiles:Ys,maxDepth:Zs,maxTotalBytes:Qs}}:{}}}function Ix(e){let t=new Set(fx);for(let n of e.routeEntryFiles??[]){let r=zo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Cx(e,t,n){return na(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Fu(e),readonly:!0}:{composition:n,path:e,kind:"text",language:_u(e),sizeBytes:t,readonly:!1}}function Rx(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(u=>u.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 Tu(t)}function Tu(e){return e.map(t=>t.kind==="directory"?{...t,children:Tu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function wx(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 na(e){return!dx(e)}function Fu(e){let t=qs.posix.extname(e).toLowerCase();return!t&&qs.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":mx[t]??"application/octet-stream"}function _u(e){let t=qs.posix.extname(e).toLowerCase();return gx[t]??"plaintext"}import*as wn from"@babel/types";import ra from"@babel/traverse";import*as _t from"@babel/types";function Me(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(_t.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(_t.isIdentifier(s)&&s.name==="Fragment"||_t.isStringLiteral(s)&&s.value==="Fragment")&&Mu(i.parentPath)}if(!_t.isJSXMemberExpression(t)||!_t.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!_t.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())&&Mu(r.parentPath)}function Mu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof ra=="function"?ra:ra.default,Yo=new WeakMap,Zo=new WeakMap;function Mt(e,t){let n=Us(e,t);if(!n.ok)return Ks(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ce(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}}:Ks(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ce(e,t){return t.kind==="jsx-node"?Bu(e,t):t.kind==="jsx-attribute"?_x(e,t):t.kind==="value"?Mx(e,t):t.kind==="expression"?Ox(e,t):t.kind==="directive"?Lx(e,t):t.kind==="export"?Dx(e,t):{ok:!1,diagnostic:En("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Bu(e,t){return t.strategy==="source-range"?Nx(e,t):Px(e,t)}function Nx(e,t){let n=null;if(rn(e,{JSXElement(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Rn(o.node,t.sourceRange))return;let i=De("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Be("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!Gx(r.path,t.expectedIdentity)?Be("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Px(e,t){if(t.structuralPath===""){let r=Tx(e,t.component);if(r){let o=Fx(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(Nr(r)!==t.component||ia(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Nr(r)!==t.component||ia(r)!==t.structuralPath)return;let i=De("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Ax(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Be("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Ax(e,t,n){let r=null;return rn(e,{JSXElement(o){if(Nr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Nr(o)!==t||!Rn(o.node,n))return;let i=De("jsx-node",o);i&&(r=i,o.stop())}}),r}function Tx(e,t){let n=null;return rn(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 Fx(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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Be("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 Be("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function _x(e,t){let n=Bu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>Yx(c,t.name));if(!s||!s.isJSXAttribute())return Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=De("jsx-attribute",s);return a?{ok:!0,match:a}:Be("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Mx(e,t){let n=Bx(e,t);if(!n.ok)return n;let r=jx(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ht(r.match.path.node.loc,t.expectedRange)?Be("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Ox(e,t){let n=null;return rn(e,{Identifier(r){if(!Xx(r))return;let o=Lu(r);if(!o||!Du(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Ht(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Lu(r);if(!o||!Du(o,t))return;let i=De("expression",r);i&&(t.expectedRange&&!Ht(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("expression","locator-miss","Expression not found")}function Lx(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ht(i.node.loc,t.expectedRange))return;let s=De("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Be("directive","locator-miss",`Directive '${t.value}' not found`)}function Dx(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=De("export",c);if(!m||t.expectedRange&&!Ht(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=sa(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=De("export",u);if(!d||t.expectedRange&&!Ht(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=sa(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ht(s.node.loc,t.expectedRange))return;let a=De("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=De("export",o);i&&(t.expectedRange&&!Ht(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Be("export","export-not-found",`Export '${Hx(t)}' not found`)}function Bx(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Rn(r.node,t.root.sourceRange))return;let o=De("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 g=r.get("init");if(!g.node)return;let f=De("value",g);if(!f)return;n=f,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(g=>g?.type==="Identifier"&&g.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 u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let m=De("value",d);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=sa(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=De("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=De("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Be("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 jx(e,t){let n=oa(e);for(let o of t){if(n=oa(n),o.kind==="property"){if(!n.isObjectExpression())return Be("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Be("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>Zx(l,o.name));if(!c||!c.isObjectProperty())return Be("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Be("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Be("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Be("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=oa(n);let r=De("value",n);return r?{ok:!0,match:r}:Be("value","locator-miss","Resolved value has no source range")}function oa(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function De(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 Rn(e,t){return Ht(e.loc,t)}function Ht(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 ia(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Me(n)){let o=$u(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ou(n,o)}`):t.unshift(`${o}#${Ou(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Ux(n.parentPath)&&!Jx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Ou(e,t){let n=ju(e)??e.getFunctionParent();if(!n)return 0;let r=Yo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Yo.get(n.node)?.get(t);if(!i){let a=Yo.get(n.node);a||(a=new Map,Yo.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?wr(n):$x(n);for(let a of s)if($u(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function $x(e){let t=Zo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!ju(r)&&n.push(r)}}),Zo.set(e.node,n),n}function ju(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function wr(e){let t=Zo.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(Me(o)){n.push(...wr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wr(o));continue}o.isJSXExpressionContainer()&&n.push(...Wt(o.get("expression")))}return Zo.set(e.node,n),n}function Wt(e){if(e.isJSXElement())return Me(e)?wr(e):[e];if(e.isJSXFragment())return wr(e);if(e.isParenthesizedExpression())return Wt(e.get("expression"));if(e.isLogicalExpression()&&Vx(e.node.operator))return Wt(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(...Wt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Wt(a));break}}return i}else if(o.node&&o.isExpression())return Wt(o)}}}}return e.isConditionalExpression()?[...Wt(e.get("consequent")),...Wt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Wt(t)):[]}function Vx(e){return e==="&&"||e==="||"||e==="??"}function $u(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Kx(e.name):null}function Kx(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 Nr(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 Ux(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Jx(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 Xx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Lu(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 Du(e,t){return e.base===t.base&&zx(e.path,t.path??[])}function zx(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 Wx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Hx(e){return e.exportKind==="named"?e.name:e.exportKind}function Be(e,t,n,r){return{ok:!1,diagnostic:En(t,n,e,r)}}function Gx(e,t){return Nr(e)!==t.component?!1:ia(e)===t.structuralPath}function Yx(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function sa(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function Zx(e,t){return e.isObjectProperty()?Wx(e.node)===t:!1}import*as Ku from"@babel/parser";import{arrayExpression as nb,booleanLiteral as rb,identifier as ob,jsxAttribute as ib,jsxExpressionContainer as sb,jsxIdentifier as ab,nullLiteral as cb,numericLiteral as lb,objectExpression as ub,objectProperty as db,stringLiteral as ca}from"@babel/types";import aa from"@babel/generator";var Qx=typeof aa=="function"?aa:aa.default;function qx(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
|
|
3
|
-
`).map(r=>
|
|
4
|
-
`)}function Qo(e){let{ast:t,source:n}=e;try{let r=qx(n),i=Qx(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=tb(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Vu(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 Pr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Vu(e),afterSourceHash:Vu(t),inverse:n.inverse}}}function xe(e,t,n){let r=Qo({ast:e,source:t});return r.ok?Pr(t,r.source,n):r}function Ne(e,t){let n=Cr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function qo(e,t){return Qo({ast:e,source:t})}function fb(e,t,n){let r=ce(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Gn(e,t,n){let r=fb(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 on(e){return typeof e=="string"?ca(e):typeof e=="number"?lb(e):typeof e=="boolean"?rb(e):e===null?cb():Array.isArray(e)?nb(e.map(t=>on(t))):ub(Object.entries(e).map(([t,n])=>{let r=db(la(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function pb(e){return typeof e=="string"?ca(e):sb(on(e))}function Ar(e,t){return ib(ab(e),pb(t))}function ei(e,t){try{let r=Ku.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 la(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?ob(e):ca(e)}function ti(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Ne(t,"jsx-node");if(!i.ok)return i.result;let s=ce(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=mb(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",m=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[wn.jsxText(d)]:[],wn.jsxExpressionContainer(wn.stringLiteral("")),...m?[wn.jsxText(m)]:[]]);break}let u=gb(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};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.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return xe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function mb(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=hb(r.get("expression"));o.length>0&&t.push(...o)}}return t}function gb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function hb(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||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as ua}from"@babel/types";function Yn(e){let{source:t,locator:n}=e,r=Ne(t,"jsx-node");if(!r.ok)return r.result;let o=ce(r.ast,n);return o.ok?(yb(o.match.path),xe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function yb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ua());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ua());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ua());return}e.remove()}import{cloneNode as xb}from"@babel/types";function ni(e){let t=Ne(e.source,"jsx-node");if(!t.ok)return t.result;let n=ce(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ei(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(xb(r.node,!0)),xe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as Pb}from"@babel/types";import da from"@babel/traverse";import*as ne from"@babel/types";function Tr(e,t,n){return`${e}::${t}::${n}`}var V={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 bb=typeof da=="function"?da:da.default;function ht(e,t,n,r){if(!e.ok)return e;let o=gt(n,t);if(!o)return e;let i=Sb(t,o,r);return i?{...e,selectionRef:i}:e}function Sb(e,t,n){let r=Eb(e,t);if(!r)return;let o=n.sourceLocator?Uu(n.sourceLocator):void 0,i=n.targetParentLocator?Uu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??kb(r)??i?.component??o?.component;if(!(!s||!a))return{key:Tr(s,a,Ib(r))}}function Uu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Eb(e,t){let n=Gu(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Gu(e,t){let n=null;return bb(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function gt(e,t){if(!e)return null;if(ne.isJSXElement(e))return Nb(t,e)?Ju(e.children,t):e;if(ne.isJSXFragment(e))return Ju(e.children,t);if(ne.isJSXExpressionContainer(e)||ne.isParenthesizedExpression(e)||ne.isTSAsExpression(e)||ne.isTSSatisfiesExpression(e)||ne.isTSTypeAssertion(e)||ne.isTSNonNullExpression(e))return gt(e.expression,t);if(ne.isLogicalExpression(e))return gt(e.right,t);if(ne.isConditionalExpression(e))return gt(e.consequent,t)??gt(e.alternate,t);if(ne.isCallExpression(e)||ne.isOptionalCallExpression(e))return Yu(e)?vb(e.arguments[0],t):null;if(ne.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=gt(n,t);if(r)return r}return null}function Ju(e,t){for(let n of e){let r=gt(n,t);if(r)return r}return null}function vb(e,t){return!e||!ne.isArrowFunctionExpression(e)&&!ne.isFunctionExpression(e)?null:ne.isBlockStatement(e.body)?Fr(e.body.body,t):gt(e.body,t)}function Fr(e,t){for(let n of e){if(ne.isReturnStatement(n)){let r=gt(n.argument,t);if(r)return r;continue}if(ne.isBlockStatement(n)){let r=Fr(n.body,t);if(r)return r;continue}if(ne.isIfStatement(n)){let r=Xu(n.consequent,t);if(r)return r;let o=n.alternate?Xu(n.alternate,t):null;if(o)return o;continue}if(ne.isSwitchStatement(n))for(let r of n.cases){let o=Fr(r.consequent,t);if(o)return o}}return null}function Xu(e,t){return ne.isBlockStatement(e)?Fr(e.body,t):Fr([e],t)}function kb(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(ne.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&ne.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 zu=new WeakMap,Wu=new WeakMap,fa=new WeakMap;function Ib(e){let t=zu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Cb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return zu.set(e.node,o),o}function Cb(e){let t=Zu(e.node.openingElement.name);return!t||Me(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Hu(e,t)}`:`${t}#${Hu(e,t)}`}function Hu(e,t){let n=Rb(e);if(!n)return 0;let r=fa.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=fa.get(n.node);o||(o=new Map,fa.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Nn(n))if(Zu(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 Rb(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Me(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Nn(e){let t=Wu.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(Me(o)){n.push(...Nn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Nn(o));continue}o.isJSXExpressionContainer()&&n.push(...Ot(o.get("expression")))}return Wu.set(e.node,n),n}function Ot(e){if(e.isJSXElement())return Me(e)?Nn(e):[e];if(e.isJSXFragment())return Nn(e);if(e.isParenthesizedExpression())return Ot(e.get("expression"));if(e.isLogicalExpression())return Ot(e.get("right"));if(e.isConditionalExpression())return[...Ot(e.get("consequent")),...Ot(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Ot(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Yu(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?wb(n):[]}return[]}function wb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Me(t)?Nn(t):[t];if(t.isJSXFragment())return Nn(t);if(t.isParenthesizedExpression())return Ot(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Ot(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(...Ot(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Ot(o)),n}return n}function Yu(e){let t=e.callee;return(ne.isMemberExpression(t)||ne.isOptionalMemberExpression(t))&&ne.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Nb(e,t){let n=Gu(e,t);return n?Me(n):!1}function Zu(e){return ne.isJSXIdentifier(e)?e.name:ne.isJSXMemberExpression(e)?Qu(e):ne.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Qu(e){return`${ne.isJSXIdentifier(e.object)?e.object.name:Qu(e.object)}.${e.property.name}`}function sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&pa(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!pa(n))return null;let r=n;for(;r&&r!==e;){if(!pa(r)||!Me(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function pa(e){return e.isJSXElement()||e.isJSXFragment()}function Zn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=ce(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 v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ei(t,r.jsx);if(!u.ok)return u.result;let d=Pb(u.node,!0),m=l.node.children,g={...s,targetParentLocator:n},f=v=>s?ht(v,a.ast,d,g):v;if(o==="append")return m.push(d),f(xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(d),f(xe(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=ce(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=sn(c.match.path,h.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let E=l.node.children,x=E.findIndex(v=>v===h.match.path.node);return x===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?x:x+1,0,d),f(xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as qu from"@babel/parser";import{cloneNode as Ab}from"@babel/types";function ri(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=Tb(t,r);if(!c.ok)return c.result;let l=ce(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 u=l.match.path,d=null;if(i){let E=ce(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let x=sn(l.match.path,E.match.path);if(!x)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=x,d=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ab(c.node,!0),g=u.node.children,f={...s,targetParentLocator:n},h=E=>s?ht(E,a.ast,m,f):E;if(o==="append")return g.push(m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(E=>E===d);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Tb(e,t){try{let r=qu.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 Fb,nullLiteral as ma}from"@babel/types";import*as an from"@babel/types";import*as ed from"@babel/types";function _r(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!ed.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function Qn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ce(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 u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let v=ce(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let R=v.match.path.isJSXElement()?_r(v.match.path,l.match.path):v.match.path,N=sn(l.match.path,R);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,d=R}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=d&&typeof d.key=="number"?d.key:-1;if(d&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?_r(c.match.path,l.match.path):c.match.path,f=Fb(g.node,!0);if(!an.isJSXElement(f)&&!an.isJSXExpressionContainer(f)&&!an.isJSXFragment(f)&&!an.isJSXText(f))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");_b(g);let y=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(f),ht(qo(a.ast,t),a.ast,f,E);if(o==="prepend")return y.unshift(f),ht(qo(a.ast,t),a.ast,f,E);let x=m-(h!==-1&&h<m?1:0);return y.splice(o==="before"?x:x+1,0,f),ht(qo(a.ast,t),a.ast,f,E)}function _b(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ma());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ma());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ma());return}e.remove()}import*as td from"@babel/parser";import{cloneNode as Mb,nullLiteral as ga}from"@babel/types";function oi(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Ne(t,"jsx-node");if(!c.ok)return c.result;let l=Ob(t,s);if(!l.ok)return l.result;let u=ce(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ce(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let v=d.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=d.match.path,g=null;if(i){let v=ce(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let R=sn(d.match.path,v.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,g=v.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let f=m.node,h=Mb(l.node,!0);Lb(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},E=f.children;if(o==="append")return E.push(h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return E.unshift(h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let x=E.findIndex(v=>v===g);return x===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?x:x+1,0,h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function Ob(e,t){try{let r=td.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 Lb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ga());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ga());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ga());return}e.remove()}import{SiteEditSetPropsParamsSchema as Db,classifySiteEditPropertyName as Bb}from"@vcp-dev/contracts";import*as qn from"@babel/types";function ii(e){let t=Db.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=Ne(e.source,"jsx-node");if(!n.ok)return n.result;let r=Gn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Bb(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(qn.isJSXAttribute),s=new Map;for(let a of i){let c=jb(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(u=>u!==c));continue}let l=Ar(a.name,a.value).value;c?c.value=l:o.attributes.push(Ar(a.name,a.value))}return xe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function jb(e){return qn.isJSXIdentifier(e.name)?e.name.name:qn.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as $b}from"@vcp-dev/contracts";import*as H from"@babel/types";var nd=["prefetch","replace","scroll","locale","onNavigate"],Vb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function Kb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>H.isJSXAttribute(n)&&H.isJSXIdentifier(n.name)&&Vb.test(n.name.name)))return!0;t=t.parentPath}return!1}function si(e){let t=Ne(e.source,"jsx-node");if(!t.ok)return t.result;let n=Gn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=$b.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Gt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=Gb(s.name);if(!a)return Gt(e.source,"Unsupported JSX link tag");if(s.attributes.some(H.isJSXSpreadAttribute))return Gt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let f of s.attributes){if(!H.isJSXAttribute(f))continue;let h=ya(f);if(!h)return Gt(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(f),c.set(h,y)}if([...c.values()].some(f=>f.length>1))return Gt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Hb(l))return Gt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:Xb(o,s.name);if(!u&&!d)return Gt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&Kb(o))return Gt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let m=null;if(e.link.kind==="internal-route")if(d)m=a;else{let f=zb(t.ast,o);if(!f.ok)return Gt(e.source,f.reason);m=f.localName}if(d&&e.link.kind!=="internal-route"){let f=H.jsxIdentifier("a");s.name=f,i.closingElement&&(i.closingElement.name=H.jsxIdentifier("a")),Wb(t.ast,d,o)}else m&&u&&(s.name=H.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=H.jsxIdentifier(m)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),nd.forEach(f=>g.add(f))):(g.add("href"),e.link.kind==="native-link"&&nd.forEach(f=>g.add(f))),s.attributes=s.attributes.filter(f=>{if(!H.isJSXAttribute(f))return!0;let h=ya(f);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(H.jsxAttribute(H.jsxIdentifier("href"),H.stringLiteral(e.link.href))),Ub(s,e.changes),xe(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Ub(e,t){for(let n of t){let r=e.attributes.find(s=>H.isJSXAttribute(s)&&ya(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?H.stringLiteral(n.value):H.jsxExpressionContainer(ha(n.value)),i=H.jsxAttribute(H.jsxIdentifier(n.name),o);r&&H.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ha(e){return e===null?H.nullLiteral():typeof e=="string"?H.stringLiteral(e):typeof e=="number"?H.numericLiteral(e):typeof e=="boolean"?H.booleanLiteral(e):Array.isArray(e)?H.arrayExpression(e.map(t=>ha(t))):typeof e=="object"?H.objectExpression(Object.entries(e).map(([t,n])=>H.objectProperty(H.isValidIdentifier(t)?H.identifier(t):H.stringLiteral(t),ha(n)))):H.nullLiteral()}function Jb(e){return H.isImportDefaultSpecifier(e)||H.isImportSpecifier(e)&&e.importKind!=="type"&&(H.isIdentifier(e.imported,{name:"default"})||H.isStringLiteral(e.imported,{value:"default"}))}function rd(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(H.isIdentifier(e.node.imported,{name:"default"})||H.isStringLiteral(e.node.imported,{value:"default"}))}function Xb(e,t){if(!H.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!rd(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function zb(e,t){let n=e.program.body.filter(c=>H.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(Jb);if(o)return t.scope.getBinding(o.local.name)?.path.node!==o?{ok:!1,reason:"The next/link import is shadowed at the selected element"}:{ok:!0,localName:o.local.name};let i=t.scope.getProgramParent(),s=["Link","NextLink",...Array.from({length:20},(c,l)=>`NextLink${l+2}`)].find(c=>!i.hasBinding(c)&&!t.scope.hasBinding(c));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=H.importDefaultSpecifier(H.identifier(s));if(r)r.specifiers.unshift(a);else{let c=H.importDeclaration([a],H.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&H.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function Wb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!rd(o.path)||o.referenced)return;let i=o.path.parentPath;if(!(!i?.isImportDeclaration()||i.node.source.value!=="next/link")&&(i.node.specifiers=i.node.specifiers.filter(s=>s!==o.path.node),i.node.specifiers.length===0)){let s=e.program.body.indexOf(i.node);s>=0&&e.program.body.splice(s,1)}}function Hb(e){return!e.value||H.isStringLiteral(e.value)}function Gb(e){return H.isJSXIdentifier(e)?e.name:null}function ya(e){return H.isJSXIdentifier(e.name)?e.name.name:null}function Gt(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as od}from"@vcp-dev/contracts";function ai(e){let t=od(e.name),n=od(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(!id(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=Ne(e.source,"jsx-node");if(!r.ok)return r.result;let o=Gn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ke.isJSXAttribute(l)&&Zb(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=Yb(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Ar(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return xe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function Yb(e,t){return id(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function id(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function Zb(e){return Ke.isJSXIdentifier(e.name)?e.name.name:Ke.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as qb,identifier as Mr,importDeclaration as eS,importDefaultSpecifier as tS,importNamespaceSpecifier as nS,importSpecifier as rS,isImportDefaultSpecifier as sd,isImportNamespaceSpecifier as ad,isImportSpecifier as cd,stringLiteral as oS}from"@babel/types";function er(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!pS(y));if(o!==-1){let y=r[o],E=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=uS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=Ne(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(E=>{let x=mS(y,E);return x?[x]:[]}))),d=i.imports.filter(y=>!u.has(md(y)));if(d.length===0)return Pr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=dS(c.body),g=d.find(y=>m.has(xa(y)));if(g)return J(t,"unsupported-syntax",`Import local binding already exists: ${xa(g)}`);let f=lS(d);if(f.reduce((y,E)=>y+E.length,0)!==d.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of f){if(!fd(ud(y)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(x=>iS(x,y));if(E)sS(E,y);else{let x=eS(ld(y),oS(n));fS(c.body,x),l.push(x)}}return xe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function iS(e,t){return e.importKind==="type"?!1:fd(cS(aS(e),ud(t)))}function sS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>ba(o)));for(let o of ld(t)){let i=ba(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return pd(e.specifiers),{changed:n}}function ld(e){let t=e.map(n=>{switch(n.kind){case"named":return rS(n.local?Mr(n.local):Mr(n.imported),Mr(n.imported));case"default":return tS(Mr(n.local));case"namespace":return nS(Mr(n.local));default:return n}});return pd(t),t}function ud(e){let t=dd();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 aS(e){let t=dd();for(let n of e.specifiers)sd(n)?t.defaultLocals.add(n.local.name):ad(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function dd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function cS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function fd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function pd(e){let t=[...e.filter(n=>sd(n)),...e.filter(n=>ad(n)),...e.filter(n=>cd(n))];e.splice(0,e.length,...t)}function lS(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 uS(e){let t=new Map,n=new Map;for(let r of e){let o=md(r);if(t.has(o))continue;let i=xa(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 dS(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(qb(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 fS(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 pS(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 md(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 xa(e){return e.kind==="named"?e.local??e.imported:e.local}function mS(e,t){return e.importKind==="type"||cd(t)&&t.importKind==="type"?null:ba(t)}function ba(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 tr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!hS(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Ne(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return Pr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>gS(u,d))),l.specifiers.length===0&&a.body.splice(c,1),xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function gS(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 hS(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 Or(e){let{source:t,locator:n,next:r}=e,o=di(t,n);return o.ok?(o.path.replaceWith(on(r)),xe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ci(e){let{source:t,locator:n,index:r,value:o}=e,i=di(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,on(o)),xe(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 li(e){let{source:t,locator:n,index:r}=e,o=di(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),xe(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 ui(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=di(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),xe(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function di(e,t){let n=Ne(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ce(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 Xe from"@babel/types";function fi(e){let t=Ne(e.source,"value");if(!t.ok)return t.result;let n=ce(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=>Xe.isSpreadElement(a)||Xe.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=>Xe.isObjectProperty(a)&&yS(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"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(la(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return xe(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function yS(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as xS,isSiteEditRuntimeVoidElementTag as bS}from"@vcp-dev/contracts/site-edit-runtime-capability";function nr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function SS(e,t,n){let r=nr(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",u=i.tag.toLowerCase(),d=i.tag!==u,m=!d&&bS(u),g=d||xS(u),f=d&&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&&!g&&!s.some(R=>R.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&g&&(!a||f);return{composition:r,key:e,canUpdateText:y,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function gd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,SS(r,e,t));return n}function Sa(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:Ce(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=ES(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:Ce(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:yd(r),version:{documentVersion:e.route.graph.version,contentHash:Ce(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:hd(e.route.source,o),valueRaw:s?hd(e.route.source,s):null,attrRange:yd(o),diagnostics:[]}}function xd(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 ES(e,t){let n=Ft({source:e,profile:vn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ce(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:vS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function bd(e){let t=Ft({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 hd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function yd(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 vS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Sd(){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 kS}from"node:crypto";import pi from"node:fs/promises";import Ea from"node:path";import{setTimeout as IS}from"node:timers/promises";var CS={async mkdir(e,t){await pi.mkdir(e,t)},async writeFile(e,t,n){await pi.writeFile(e,t,n)},async rename(e,t){await pi.rename(e,t)},async rm(e,t){await pi.rm(e,t)}},RS=new Set(["EACCES","EBUSY","EPERM"]),wS=[10,20,40,80,160];async function NS(e,t,n){for(let r of wS)try{await e.rename(t,n);return}catch(o){if(!PS(o))throw o;await IS(r)}await e.rename(t,n)}function PS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&RS.has(e.code)}async function mi(e,t,n=CS){let r=Ea.dirname(e),o=Ea.basename(e),i=Ea.join(r,`.${o}.${process.pid}.${kS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await NS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import va from"@babel/traverse";import*as k from"@babel/types";import*as de from"@babel/types";function Lt(e,t={}){if(de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSNonNullExpression(e)||de.isTypeCastExpression(e)||de.isParenthesizedExpression(e))return Lt(e.expression,t);if(de.isStringLiteral(e))return{status:"resolved",value:e.value};if(de.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(de.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(de.isNullLiteral(e))return{status:"resolved",value:null};if(de.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(de.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(de.isUnaryExpression(e)&&e.operator==="void"&&de.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(de.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||de.isSpreadElement(r))return{status:"unresolved"};let o=Lt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(de.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!de.isObjectProperty(r)||r.computed||!de.isExpression(r.value))return{status:"unresolved"};let o=AS(r.key);if(o===null)return{status:"unresolved"};let i=Lt(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 de.isMemberExpression(e)||de.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function AS(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:de.isNumericLiteral(e)?String(e.value):null}var TS=typeof va=="function"?va:va.default;function Ge(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 FS(e){return/^[A-Z]/.test(e)}function wa(e){let t=e.openingElement;return k.isJSXIdentifier(t.name)?t.name.name==="Fragment":k.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function or(e){return k.isJSXFragment(e)}function vd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?kd(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function kd(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${kd(e.object)}.${e.property.name}`:e.property.name}function _S(e){return e.split(".")[0]??e}function MS(e){let t=e;for(;t;){let n=t.node;if(k.isFunctionDeclaration(n)&&n.id||k.isVariableDeclarator(n)&&k.isIdentifier(n.id))return n.id.name;if(k.isExportDefaultDeclaration(n)){let r=n.declaration;if(k.isFunctionDeclaration(r)&&r.id)return r.id.name;if(k.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function OS(){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 LS(e){let t=new Map;for(let n of e.program.body){if(!k.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(k.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(k.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(k.isImportSpecifier(o)){let i=k.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Yt(e,t=[]){if(k.isIdentifier(e))return t.push(e.name),t;if(k.isObjectPattern(e)){for(let n of e.properties)k.isObjectProperty(n)?Yt(n.value,t):k.isRestElement(n)&&Yt(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?Yt(n.argument,t):Yt(n,t));return t}return k.isAssignmentPattern(e)?(Yt(e.left,t),t):(k.isRestElement(e)&&Yt(e.argument,t),t)}function It(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Lr(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 DS(e,t,n){e.set(t,{resolved:!0,value:n})}function Na(e,t){e.set(t,{resolved:!1})}function Id(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 $e(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return $e(e.expression,t,n);if(k.isLogicalExpression(e))return gi([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return gi([k.isExpression(e.left)?$e(e.left,t,n):null,k.isExpression(e.right)?$e(e.right,t,n):null]);if(k.isConditionalExpression(e))return gi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return gi(e.expressions.filter(k.isExpression).map(i=>$e(i,t,n)));if(k.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!k.isMemberExpression(e)&&!k.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;k.isMemberExpression(o)||k.isOptionalMemberExpression(o);){if(o.computed)if(k.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(k.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&k.isExpression(o.property)){let i=cn(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(!k.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return k.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:It(e,t),base:o.name,path:r}:null}function gi(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 cn(e,t){if(k.isStringLiteral(e)||k.isNumericLiteral(e)||k.isBooleanLiteral(e))return e.value;if(k.isNullLiteral(e))return null;if(k.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(k.isIdentifier(e)){let n=Lr(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(k.isObjectExpression(e)){let n={};for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isExpression(r.value))return;let o=null;if(k.isIdentifier(r.key)?o=r.key.name:k.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!k.isIdentifier(r.value))return;let s=Lr(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Lr(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Id(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return Rd(e,t)??void 0}function Cd(e,t,n){let r=$e(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:It(e,n),source:null}:null;let o=Lr(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Id(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 ka(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:OS(),parentStack:[],valueScopes:i,importMap:o}}function Ca(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Yt(o.id))Na(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&DS(n,o.id.name,i)}}function BS(e){let t=[];for(let n of e){if(k.isVariableDeclaration(n)){t.push(n);continue}k.isExportNamedDeclaration(n)&&n.declaration&&k.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function jS(e,t,n){let r=[],o=0;for(let i of e)if(k.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(k.isJSXExpressionContainer(i)&&k.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:Ge(i),editable:!0,source:null}):r.push({index:o++,value:It(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=Cd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function $S(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=KS(i.name);if(!s)continue;let a=It(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ge(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:Ge(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(k.isJSXExpressionContainer(i.value)&&k.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?Rd(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Ge(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=Cd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:GS(c),sourceRange:Ge(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=US(i.value.expression,t),d=$e(i.value.expression,n,t),m=l?.value??It(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function VS(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:It(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function KS(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function US(e,t){return Lt(e,{resolveIdentifier(n){let r=Lr(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=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Rd(e,t){let n=rr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function rr(e,t){if(k.isStringLiteral(e))return[e.value];if(k.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(k.isNullLiteral(e))return[];if(k.isBooleanLiteral(e))return e.value?null:[];if(k.isIdentifier(e)||k.isMemberExpression(e)){if(k.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=rr(e.consequent,t),r=rr(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:rr(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=rr(r,t);if(!o)return null;n.push(...o)}return n}if(k.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!k.isObjectProperty(r))return null;let o=XS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=JS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!k.isExpression(o))return null;let i=rr(o,t);if(!i)return null;r.push(...i)}return r}return null}function JS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function XS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function zS(e,t){let n=e.attributes.find(r=>k.isJSXAttribute(r)&&k.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!k.isJSXAttribute(n)||!k.isJSXExpressionContainer(n.value)?null:n.value.expression}function WS(e,t){for(let n of t){let r=zS(e,n);if(r)return r}return null}function HS(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function GS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function YS(e){if(!k.isCallExpression(e)&&!k.isOptionalCallExpression(e))return null;let t=e.callee;return!k.isMemberExpression(t)&&!k.isOptionalMemberExpression(t)||!k.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!k.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Ia(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function ZS(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function QS(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Ed(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:It(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];k.isIdentifier(i)&&(o.itemParamName=i.name),k.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Zt(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(wa(e))return Si(e.children,t,n);let r=xi(e,t,n);return r?[r]:[]}return or(e)?bi(e,t,n):k.isParenthesizedExpression(e)?Zt(e.expression,t,n):k.isExpression(e)?Ei(e,t,n):[]}function hi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Yt(o))Na(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return Zt(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return wd(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function wd(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Ca([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...Zt(s.init,t,n))}continue}r.push(...Ra(o,t,n))}return r}function Ra(e,t,n){if(k.isReturnStatement(e))return e.argument?Zt(e.argument,t,n):[];if(k.isBlockStatement(e))return Pn(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Pn(e.consequent.body,t,n):Ra(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Pn(e.alternate.body,t,n):Ra(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Pn(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Pn(e.block.body,t,n);return e.handler&&r.push(...Pn(e.handler.body.body,t,n)),e.finalizer&&r.push(...Pn(e.finalizer.body,t,n)),r}return[]}function Pn(e,t,n){let r=new Map;t.valueScopes.push(r);try{return wd(e,t,n)}finally{t.valueScopes.pop()}}function yi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function qS(e,t,n,r){let o=WS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:vd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=HS(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(ZS(a)&&Ia(c)){let l=hi(c,n,r),u=Ed(o,c,r,n);yi(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(QS(a)){let l=Ia(c)?hi(c,n,r):Zt(c,n,r);yi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!Ia(s.expression))continue;let a=hi(s.expression,n,r),c=Ed(o,s.expression,r,n);yi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function xi(e,t,n){let r=vd(e.openingElement);if(r==="Fragment"||wa(e))return Si(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=FS(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,u=Tr(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,g=jS(e.children,t,n),f=$S(e.openingElement,t,n),h=VS(e.openingElement,t,n),y,E,x=!1;if(s){let R=t.importMap.get(r)??t.importMap.get(_S(r));R&&(y=R.specifier,E=R.exportName,x=kn(R.specifier,t.file))}let v={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:g,attributes:f.length>0?f:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...x?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:E};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),qS(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),eE(e.children,t,n),t.parentStack.pop()),u}function bi(e,t,n){return Si(e.children,t,n)}function Si(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(wa(o))r.push(...Si(o.children,t,n));else{let i=xi(o,t,n);i&&r.push(i)}else or(o)?r.push(...bi(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...Ei(o.expression,t,n));return r}function eE(e,t,n){for(let r of e)k.isJSXElement(r)?xi(r,t,n):or(r)?bi(r,t,n):k.isJSXExpressionContainer(r)&&Ei(r.expression,t,n)}function tE(e){return e==="&&"||e==="||"||e==="??"}function Ei(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=YS(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:It(r.collection,n),collectionSource:$e(r.collection,n,t)};if(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];k.isIdentifier(u)&&(c.itemParamName=u.name),k.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ge(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...hi(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:It(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(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(k.isLogicalExpression(e)&&tE(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:It(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Zt(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return Ei(e.expression,t,n);if(k.isJSXElement(e)){let o=xi(e,t,n);return o?[o]:[]}return or(e)?bi(e,t,n):[]}function nE(e){let t=e.argument;return t&&(k.isExpression(t)||or(t))?t:null}function Dr(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=nE(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(k.isIfStatement(r)){let o=k.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Dr(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Dr(i,r.test))}continue}if(k.isSwitchStatement(r))for(let o of r.cases){let i=o.test?k.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Dr(o.consequent,i))}}return n}function vi(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Nd(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(m=>m.specifier);if(!k.traverseFast(r,m=>{if(k.isJSXElement(m)||k.isJSXFragment(m))return k.traverseFast.stop}))return{graph:vi(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=LS(r);TS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(m){let g=MS(m);if(!g)return;let f=m.node,h=[];if(k.isArrowFunctionExpression(f))k.isExpression(f.body)||or(f.body)?h=[{argument:f.body,statement:k.returnStatement(k.isExpression(f.body)?f.body:null)}]:k.isBlockStatement(f.body)&&(h=Dr(f.body.body));else{let N=f.body;k.isBlockStatement(N)&&(h=Dr(N.body))}if(h.length===0){m.skip();return}let y=new Map;Ca(BS(r.program.body),ka(t,g,s,a,u,[y]),y);let E=new Map;for(let N of f.params)for(let T of Yt(N))Na(E,T);let x=k.isBlockStatement(f.body)?f.body.body:[],v=h[0]?.statement??null;for(let N of x){if(v&&N===v)break;k.isVariableDeclaration(N)&&Ca([N],ka(t,g,s,a,u,[y,E]),E)}let R=ka(t,g,s,a,u,[y,E]);for(let N of h){let T=Zt(N.argument,R,n);for(let I of T)c.includes(I)||c.push(I);if(N.condition){let I={kind:"conditional-branch",conditionExpression:It(N.condition,n),conditionSource:$e(N.condition,n,R)};yi(R,"conditional-region","",N.statement,T,[I])}}m.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function Pa(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function ki(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Pd(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Ad(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Xt,c=new Map,l=new Map,u=new Map,d=[],m=new Set,g=E=>{let x=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(x)||(m.add(x),d.push(E))},f=[{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(;f.length>0;){let E=f.shift(),{file:x,source:v,depth:R,diagnosticEntryFile:N,importStack:T}=E;if(h.has(x))continue;h.add(x),c.set(x,v);let I=o.validationOnly&&R<i?o.validatedImports?.(x,v):void 0,P,F;if(I)P=vi(x),F=I;else{let j=a(x,v);if(!j.ok){g(ki(j.diagnostic,N,T));continue}u.set(x,j.module);let G=o.validationOnly&&R<i?{graph:vi(x),localImports:j.module.imports.map(pe=>pe.specifier)}:Nd(j.module);P=G.graph,F=G.localImports}let L=[...new Set([...P.elements.values()].map(j=>j.importedFrom).filter(j=>typeof j=="string"&&kt(j)))],W=L.length?await Pd(L,j=>Lo(x,j,r)):[],z=new Map(L.map((j,G)=>[j,W[G]]));for(let j of P.elements.values())if(j.importedFrom&&kt(j.importedFrom)){let G=j.importedFrom,pe=z.get(G);pe.ok?(j.importedFrom=pe.path,zt(pe.path)&&(j.isPublicUiComponent=!0)):kn(G,x)||g(ki(pe.diagnostic,N,Pa(T,x,G,pe.diagnostic.path)))}if(l.set(x,P),R>=i)continue;let he=await Pd(F,async j=>{if(uu(j))return null;let G=z.get(j)??await Lo(x,j,r);if(!G.ok)return kn(j,x)?null:{diagnostic:ki(G.diagnostic,N,Pa(T,x,j,G.diagnostic.path))};let pe=G.path;if(h.has(pe)||zt(pe))return null;let st=Pa(T,x,j,pe);try{let tt=await n(pe);return{entry:{file:pe,source:tt,depth:R+1,diagnosticEntryFile:N,importStack:st}}}catch(tt){return{diagnostic:ki({path:pe,code:"import-read-failed",message:`Failed to read imported file: ${pe}`,details:{fromFile:x,specifier:j,reason:tt instanceof Error?tt.message:String(tt)}},N,st)}}});for(let j of he)j&&"entry"in j?f.push(j.entry):j&&g(j.diagnostic)}let y=rE(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function rE(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...d])}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}}function Td(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as FE}from"@vcp-dev/contracts";import{createHash as oE,randomUUID as ja}from"node:crypto";import Oe from"node:fs/promises";import Le from"node:path";var Vd=new WeakMap;function ir(e){return Vd.get(e)?.()??e.readIndex()}var yt=1,Ta=1,iE=2,sE="index.json",aE="recovery.json",cE="transaction-journal.json",lE="document-version.json",Ri={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},oe={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"},se=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Qt(){return{entries:new Map,blobSizes:new Map}}function Ii(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Kd(n,r,t);return n}function Kd(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Ud(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Jd(e,t={}){let n=RE(e),r=AE(t.limits),o=Aa(n),i=wE(n),s=await nt(i),a=await nt(o)||s;a||(await xE(n),await bE(n)),a||await TE(n);let c=Qt(),l=await Ni(n,c),u=new Set(a?(await _i(n)).map(x=>x.stageId):[]);a||await Ld(n,l.entryIds,c);let d=l.digest,m=Ii(l.entryIds,c),g=async x=>{let{index:v,sizeBytes:R}=await Kr(n);if(Zd(v,x),v.digest!==d){let N=Qt();await Hd(n,v.entryIds,N,R),m=Ii(v.entryIds,N),d=v.digest}return{...Mi(v),totalBytes:m.objectBytes+R}},f=async x=>{$a(x),await g(),await Md(n,m,[x.entryId],x.blobIds,x.stageId),await wi(n,x.stageId)},h=async(x,v)=>{let R=await g(v);zd(x,R.entryIds.length);let N=Qt();for(let T of R.entryIds.slice(Math.min(R.cursor,x)+1,Math.max(R.cursor,x)+1))await jr(n,T,N);return R},y=async()=>{if(await nt(o)||s)throw new se(oe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return jd(n)},async writeDocumentVersion(x){if(await y(),!Number.isInteger(x)||x<0)throw new se(oe.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await jd(n);x<=v||await Br(tf(n),{schemaVersion:1,version:Math.max(v,x)})},async stageAppend(x,v={}){await y();let R=await fE(x,r),N={schemaVersion:Ta,stageId:ja(),entryId:R.entryId,blobIds:R.blobs.map(T=>T.digest)};try{await pE(n,R),await gE(n,N,v.durableManifest!==!1)}catch(T){try{await f(N)}catch(I){throw new se(oe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw T}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(x){await y(),Ma(x);let v=await Fa(n,x);v&&await f(v)},async previewStagedAppend(x,v){await y();let R=await g(v);return(await Fd(n,r,x,R,m)).transition},async previewCursor(x,v){await y();let R=await h(x,v);return Xd(R,R.entryIds,x)},async publishStagedAppend(x,v,R){if(await y(),Ai(x,"entryId"),R){Ma(R);let F=await Fa(n,R);if(!F||F.entryId!==x)throw new se(oe.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await g(v),T=m,I=await Fd(n,r,x,N,T),P=await Bd({rootDir:n,previousDigest:I.current.digest,entryIds:I.entryIds,cursor:I.cursor,readback:async()=>Dd(n,I.usage),afterWrite:async()=>{R?await wi(n,R):await yE(n,x),await Md(n,I.usage,[...T.entries.keys()].filter(F=>!I.usage.entries.has(F)),[...T.blobs.keys()].filter(F=>!I.usage.blobs.has(F)))}});return m=I.usage,d=P.digest,P},async append(x){await y();let v=await g(),R=await E.stageAppend(x);try{return await E.publishStagedAppend(R.entryId,v.digest,R.stageId)}catch(N){throw await E.discardStage(R.stageId),N}},async readEntry(x){return Ai(x,"entryId"),jr(n,x)},async readBlob(x){Ai(x,"blobId");let v=await rf(n,x),R=await $r(v,oe.NOT_FOUND,"blob");return ef(R,x,v),R},async readIndex(){let x=Qt(),v=await Ni(n,x);return m=Ii(v.entryIds,x),d=v.digest,v},async readStatus(){let x=await Pi(n);return{canUndo:x.undoIds.length>0,canRedo:x.redoIds.length>0,undoDepth:x.undoIds.length,redoDepth:x.redoIds.length,cursor:x.cursor,recoveryRequired:await nt(o)||await nt(i)}},async readUndoRedoIds(){let x=await Pi(n);return{undoIds:x.undoIds,redoIds:x.redoIds,currentId:x.currentId}},async setCursor(x,v){await y();let R=await h(x,v),N=await Bd({rootDir:n,previousDigest:R.digest,entryIds:R.entryIds,cursor:x,readback:async()=>Dd(n,m)});return d=N.digest,N},async markRecoveryRequired(x){await nt(o)||await Br(Aa(n),{schemaVersion:yt,reason:NE(x),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Oe.rm(Aa(n),{force:!0})},async readTransactionJournal(){return await nt(i)?Ci(i):null},async writeTransactionJournal(x){await y(),nf(x);try{await Br(i,x)}catch(R){let N=await Ci(i).catch(()=>null);if(N&&Buffer.from(rt(N)).equals(Buffer.from(rt(x))))return;throw N?new se(oe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:R}):R}let v=await Ci(i);if(!Buffer.from(rt(v)).equals(Buffer.from(rt(x))))throw new se(oe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(x){let v=await nt(i)?await Ci(i):null;if(v&&v.transactionId!==x)throw new se(oe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Oe.rm(i,{force:!0})}catch(R){if(!await nt(i))return;throw R}if(await nt(i))throw new se(oe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let R of u)await wi(n,R),u.delete(R);await SE(n);let x=Qt(),v=await Ni(n,x);await Ld(n,v.entryIds,x),m=Ii(v.entryIds,x),d=v.digest}};return Vd.set(E,()=>Pi(n)),E}async function Fd(e,t,n,r,o){Ai(n,"entryId");let i=Qt(),s=await jr(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))Ud(a,u);Kd(a,s.id,i),c.push(s.id);let l=mE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Xd(r,l.entryIds,l.cursor)}}function Xd(e,t,n){return zd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:uE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function uE(e,t){return ln(rt({schemaVersion:yt,entryIds:e,cursor:t}))}function zd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new se(oe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function dE(e){if(!Ct(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 fE(e,t){if(!e.kind.trim())throw new se(oe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new se(oe.INVALID_JSON,"history blob name must not be empty");let l=CE(c.data),u=ln(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:yt,kind:e.kind,manifest:e.manifest,blobs:r},i=rt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new se(oe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function pE(e,t){let n=Ja(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>_d(Xa(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Wa(e,c.digest))),_d(n,rt(r),{kind:"entry",digest:t.entryId},za(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function _d(e,t,n,r){let o=await Da(e)??(r?await Da(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new se(n.kind==="blob"?oe.BLOB_CORRUPT:oe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Qd(e,t)}function mE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+rt(Yd(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new se(oe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Ud(n,r.shift()),o-=1}}async function gE(e,t,n){$a(t);let r=Ua(e,t.stageId);if(n){await Br(r,t);return}await IE(r,t)}async function Fa(e,t){let n=await Da(Ua(e,t));if(n===null)return null;let r=Ur(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=$a(r);if(o.stageId!==t)throw new se(oe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function _i(e){let t=[];for(let n of await Fi(Ka(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Ma(r);let o=await Fa(e,r);o&&t.push(o)}return t}async function Md(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await _i(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await Od(Ja(e,a),za(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Od(Xa(e,a),Wa(e,a));await Ba(Jr(e)),await Ba(Xr(e))}async function wi(e,t){await _a(Ua(e,t)),await hE(e)}async function hE(e){try{await Oe.rmdir(Ka(e))}catch(t){if(zr(t)||Ct(t)&&t.code==="ENOTEMPTY")return;throw t}}async function yE(e,t){for(let n of await _i(e))n.entryId===t&&await wi(e,n.stageId)}async function _a(e){if(await Oe.rm(e,{force:!0}),await nt(e))throw new se(oe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Od(e,t){await _a(e),await _a(t)}function $a(e){if(!Ct(e)||e.schemaVersion!==Ta||typeof e.stageId!="string"||!Wd(e.stageId)||!lt(e.entryId))throw new se(oe.INVALID_SCHEMA,"history stage schema is invalid");let t=qd(e.blobIds,"history stage blobIds");return{schemaVersion:Ta,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Ma(e){if(!Wd(e))throw new se(oe.INVALID_PATH,"history stageId must be a UUID")}function Wd(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 Ld(e,t,n=Qt()){let r=new Set(t),o=new Set;for(let l of t){let u=await jr(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await _i(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Jr(e),s=await Fi(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=$d(l.slice(0,-5));u&&!r.has(u)&&await Ti(Le.join(i,l))}let a=Xr(e),c=await Fi(a);for(let l of c){let u=$d(l);u&&!o.has(u)&&await Ti(Le.join(a,l))}}async function Ni(e,t=Qt()){let{index:n,sizeBytes:r}=await Kr(e),{totalBytes:o}=await Hd(e,n.entryIds,t,r);return{...Mi(n),totalBytes:o}}async function Dd(e,t){let{index:n,sizeBytes:r}=await Kr(e);return{...Mi(n),totalBytes:t.objectBytes+r}}async function Kr(e){let t=Va(e),n=await $r(t,oe.NOT_FOUND,"index"),r=Ur(Buffer.from(n).toString("utf8"),"index");return{index:EE(r),sizeBytes:n.byteLength}}async function Pi(e){return Mi((await Kr(e)).index)}function Mi(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:yt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Hd(e,t,n,r){let o=0,i=new Set;o+=r??(await Kr(e)).sizeBytes;for(let s of new Set(t)){let a=await jr(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function jr(e,t,n=Qt()){let r=n.entries.get(t);if(r)return r.entry;let o=await PE(e,t),i=await $r(o,oe.NOT_FOUND,"entry"),s=Ur(Buffer.from(i).toString("utf8"),`entry ${t}`),a=vE(s);if(a.id!==t)throw new se(oe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(rt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new se(oe.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let m=await rf(e,d),g=await $r(m,oe.NOT_FOUND,"blob");return ef(g,d,m),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),m=[],g=0,f=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&m.length===0;){let E=g++;try{d[E]=await u(l[E])}catch(x){m.push({index:E,error:x})}}}),h=await Promise.allSettled(f),y=m.sort((E,x)=>E.index-x.index)[0];if(y)throw y.error;for(let E of h)if(E.status==="rejected")throw E.reason;for(let E=0;E<l.length;E++)n.blobSizes.set(l[E],d[E])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Gd(e,t,n){await Br(Va(e),Yd(t,n))}function Yd(e,t){return{schemaVersion:yt,digest:ln(rt({schemaVersion:yt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Zd(e,t){if(t!==void 0&&e.digest!==t)throw new se(oe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Bd(e){Zd(await Pi(e.rootDir),e.previousDigest);let t=ln(rt({schemaVersion:yt,entryIds:e.entryIds,cursor:e.cursor}));try{await Gd(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new se(oe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ni(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new se(oe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function xE(e){await Oe.mkdir(e,{recursive:!0}),await Oe.mkdir(Jr(e),{recursive:!0}),await Oe.mkdir(Xr(e),{recursive:!0}),await Oe.mkdir(Vr(e),{recursive:!0})}async function bE(e){await Oe.rm(Vr(e),{recursive:!0,force:!0}),await Oe.mkdir(Vr(e),{recursive:!0})}async function SE(e){let t=Vr(e);await Oe.mkdir(t,{recursive:!0});for(let n of await Fi(t))n!=="stages"&&await Oe.rm(Le.join(t,n),{recursive:!0,force:!0})}function EE(e){if(!Ct(e))throw new se(oe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==yt)throw new se(oe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=qd(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new se(oe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!lt(o))throw new se(oe.INDEX_CORRUPT,"index digest is invalid");let i=ln(rt({schemaVersion:yt,entryIds:t,cursor:r}));if(o!==i)throw new se(oe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:yt,digest:o,entryIds:t,cursor:r}}function vE(e){if(!Ct(e))throw new se(oe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==yt)throw new se(oe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!lt(t))throw new se(oe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new se(oe.ENTRY_CORRUPT,"entry kind is invalid");let r=La(e.manifest,"entry.manifest"),o=kE(e.blobs);return{id:t,schemaVersion:yt,kind:n,manifest:r,blobs:o}}function kE(e){if(!Array.isArray(e))throw new se(oe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ct(t))throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!lt(o))throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Br(e,t){await Qd(e,rt(t))}async function IE(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${ja()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{await Oe.writeFile(o,rt(t),{flag:"wx"}),await Oe.rename(o,e)}finally{await Ti(o)}}async function Qd(e,t){let n=Le.dirname(e),r=Le.basename(e),o=Le.join(n,`.${r}.${process.pid}.${ja()}.tmp`);await Oe.mkdir(n,{recursive:!0});try{let i=await Oe.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Oe.rename(o,e),await Ba(n)}finally{await Ti(o)}}function rt(e){return Buffer.from(JSON.stringify(Oa(e)),"utf8")}function Oa(e){if(Array.isArray(e))return e.map(t=>Oa(t));if(Ct(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Oa(e[n]);return t}return e}function Ur(e,t){try{return JSON.parse(e)}catch(n){throw new se(oe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function La(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=>La(n,t));if(Ct(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=La(o,t);return n}break}throw new se(oe.INVALID_JSON,`${t} must be JSON-serializable`)}function qd(e,t){if(!Array.isArray(e))throw new se(oe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!lt(n))throw new se(oe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ai(e,t){if(!lt(e))throw new se(oe.INVALID_PATH,`${t} must be a sha256 digest`)}function lt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${oE("sha256").update(e).digest("hex")}`}function CE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function $r(e,t,n){try{return await Oe.readFile(e)}catch(r){throw new se(t,`${n} not found: ${e}`,{cause:r})}}async function Da(e){try{return await Oe.readFile(e)}catch(t){if(zr(t))return null;throw t}}function ef(e,t,n){if(ln(e)!==t)throw new se(oe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function nt(e){try{return await Oe.access(e),!0}catch(t){if(zr(t))return!1;throw t}}async function Ti(e){try{await Oe.rm(e,{force:!0,recursive:!0})}catch{}}async function Ba(e){try{let t=await Oe.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Fi(e){try{return await Oe.readdir(e)}catch(t){if(zr(t))return[];throw t}}function RE(e){if(typeof e!="string"||e.trim().length===0)throw new se(oe.INVALID_ROOT,"history store rootDir must be a non-empty string");return Le.resolve(e)}function Va(e){return Le.join(e,sE)}function Aa(e){return Le.join(e,aE)}function wE(e){return Le.join(e,cE)}function tf(e){return Le.join(e,lE)}async function jd(e){try{let t=await Oe.readFile(tf(e),"utf8"),n=Ur(t,"document version");if(!Ct(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new se(oe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(zr(t))return 0;throw t}}async function Ci(e){let t=await $r(e,oe.RECOVERY_PENDING,"transaction journal"),n=Ur(Buffer.from(t).toString("utf8"),"transaction journal");return nf(n),n}function nf(e){if(!Ct(e)||e.schemaVersion!==iE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!dE(e.historyTransition)||!Array.isArray(e.files))throw new se(oe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ct(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!lt(t.preDigest)||t.postDigest!==null&&!lt(t.postDigest))throw new se(oe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function NE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Jr(e){return Le.join(e,"entries")}function Xr(e){return Le.join(e,"blobs")}function Vr(e){return Le.join(e,"tmp")}function Ka(e){return Le.join(Vr(e),"stages")}function Ua(e,t){return Le.join(Ka(e),`${t}.json`)}function Ja(e,t){return Le.join(Jr(e),`${sf(t)}.json`)}function Xa(e,t){return Le.join(Xr(e),sf(t))}function za(e,t){return Le.join(Jr(e),`${t}.json`)}function Wa(e,t){return Le.join(Xr(e),t)}async function PE(e,t){return of(Ja(e,t),za(e,t))}async function rf(e,t){return of(Xa(e,t),Wa(e,t))}async function of(e,t){return await nt(e)?e:await nt(t)?t:e}function sf(e){return e.slice(7)}function $d(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return lt(t)?t:null}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function AE(e){return{maxEntries:e?.maxEntries??Ri.maxEntries,maxSessionBytes:e?.maxSessionBytes??Ri.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Ri.maxEntryBytes}}async function TE(e){let t=Va(e);await nt(t)||await Gd(e,[],-1)}var _E={affectedCompositions:[]};function df(e){let t=null,n=new WeakMap;async function r(){return t??=ME(e),t}async function o(i){if(!i)return null;let s=Ha(i);return s?OE(e,s):i}return{async prepareAppend(i){let s=await ir(e),a=await e.stageAppend(lf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await ir(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await ir(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);af(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,sr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Ha(c.at(-1))!==Ha(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);af(l,i.historyTransition),Object.assign(a,sr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await ir(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,sr(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(lf(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,sr(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,sr(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function af(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")}function Ha(e){return typeof e=="string"?e:e?.historyId}async function ME(e){let t=await ir(e);return sr(t)}function sr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function OE(e,t){let n=await e.readEntry(t),r=LE(n),o=r.provenance??_E;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 cf(e,n,r.preSnapshots),postSnapshots:await cf(e,n,r.postSnapshots)}}async function cf(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(jE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function lf(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 u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=DE(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 LE(e){if(!pf(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:ff(t.provenance)}:{},preSnapshots:uf(t.preSnapshots,"preSnapshots"),postSnapshots:uf(t.postSnapshots,"postSnapshots")}}function DE(e){if(e.provenance!==void 0)return ff(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function ff(e){let t=FE.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 uf(e,t){return e.map((n,r)=>{if(!pf(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&&!BE(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 BE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function jE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function pf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as ev}from"node:crypto";import Li from"node:path";import{parse as kf}from"@babel/parser";import tv from"@babel/traverse";import*as If from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Ya,PageResourceArtifactSchema as nv,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as rv,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as ov,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as iv,parseComponentI18nResourcesJson as sv}from"@vcp-dev/contracts";var gf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,hf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,$E=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,VE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,KE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,UE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,JE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,XE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,zE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,WE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,HE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,GE=/\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,YE=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,ZE=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Wr(e,t){let n=Oi([...xt(e,$E),...xt(e,VE),...xt(e,KE),...xt(e,t.includeRgbBackgroundImage?UE:JE),...t.includeExtendedColorFunctions?[...xt(e,XE),...xt(e,zE)]:[]]),r=Oi([...xt(e,WE),...xt(e,HE)]).filter(o=>t.colorMixPolicy==="always"||gf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...xt(e,GE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...xt(e,ZE).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Oi(xt(e,hf)),hardCodedSurfaceOccurrences:qE(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Oi(xt(e,YE)):[]}}function xt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var mf=160,QE=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function qE(e){let t=new RegExp(hf.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),u=
|
|
6
|
-
`,i.index),g=e.slice(n[d]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>mf?`${g.slice(0,mf-1)}\u2026`:g})}return o}function Oi(e){return[...new Set(e)]}var Za="{{$INSTANCE}}",av=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,cv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Qa="components/site/generated",lv=/\.(?:tsx?|json)$/,uv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,dv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],fv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ga=tv,pv=typeof Ga=="function"?Ga:Ga.default;async function qa(e){let t=nv.safeParse(e.artifact);if(!t.success)return Fe("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>ev(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=vv(r());if(!i)return Fe("Random instance suffix must be 8 lowercase hex chars.");let s=`${kv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let R=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${R}/page.tsx`})}let u=[],d=new Set,m=new Set,g=new Map,f=new Map,h=[],y=new Set(n.pages.flatMap(v=>v.components.map(R=>R.component_id)));for(let v of n.components){if(!y.has(v.component_id))continue;let R=yf({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!R.ok)return R;for(let N of R.files){let T=bf(N,d,u);if(T)return T}m.add(R.entry),f.set(R.entry,R.entryExport),g.set(v.component_id,R.entry)}for(let[v,R]of n.pages.entries()){let N=l[v],T=yf({materialization:R.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!T.ok)return T;for(let I of T.files){let P=bf(I,d,u);if(P)return P}m.add(T.entry),f.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(R.components.map(I=>I.component_id))})}let E=gv(u,m,s,g,h,f);if(!E.ok)return E;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?qa({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let x=hv(u);return x||(u.sort((v,R)=>v.file.localeCompare(R.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function yf(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:xf(o.pathTemplate,e.packageInstanceId);if(!s)return Fe("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=mv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?xv(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??xf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Fe("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function mv(e,t,n,r){let o,i=e.replace(av,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Fe(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(cv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Fe(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Za,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Fe("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function xf(e,t){let n=`${Qa}/${t}`;if(e.split(Za).length>2)return null;let o=e.replace(Za,t),i=`${Qa}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Li.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!lv.test(a)||uv.test(a)?null:a}function bf(e,t,n){return t.has(e.file)?Fe(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function gv(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${Qa}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return Fe("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Ya)&&!sv(g.content).success)return Fe("Materialization component i18n resources are invalid.",g.file);continue}try{let h=kf(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let x=E.source.value,v=Sv(g.file,x,s,a);if(!v.allowed)return Fe(`Materialization import is outside the controlled package: ${x}`,g.file);v.internalPath&&c.get(g.file).add(v.internalPath)}let y;if(pv(h,{Identifier(E){E.isReferencedIdentifier()&&fv.has(E.node.name)&&(y??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(y??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(y??="style element",E.stop())}}),y)return Fe(`Materialization source uses forbidden capability: ${y}`,g.file)}catch{return Fe("Materialization source must parse as TS/TSX.",g.file)}let f=Wr(g.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(f.hardCodedSurfaceHits.length>0||f.rawColorHits.length>0||f.privateTokenHits.length>0)return Fe("Materialization source violates the public theme token policy.",g.file)}if([...t].some(g=>!s.has(g)))return Fe("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Fe("Materialization JSON files cannot be package entries.");for(let[g,f]of i){let h=l.get(g);if(!h||!yv(h,f))return Fe("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,f])=>[f,g]));for(let g of o){let f=vf(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!f.has(y))return Fe(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of f){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return Fe(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let f of vf(g,c))d.add(f);if(d.size!==e.length)return Fe("Every materialization file must be reachable from a package entry.");let m=Ev(e,l,c);return m||{ok:!0}}function hv(e){if(e.length>rv)return Fe("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>ov)return Fe("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>iv?Fe("Page resource exceeds the aggregate content byte limit."):null}function yv(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 xv(e,t,n){let r;try{r=kf(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Fe("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=Sf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&bv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Sf(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"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function Sf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&If.isExpression(t)?t:null}function bv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function Sv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Ef(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:dv.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Li.posix.normalize(Li.posix.join(Li.posix.dirname(e),t)),i=Ef(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Ef(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 Ev(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Ya))continue;let i=o.file.slice(0,-Ya.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Fe("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return Fe("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function vf(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 vv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function kv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Fe(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as Iv}from"node:crypto";import qt from"node:path";import{parse as Cv}from"@babel/parser";import Rv from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Di,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Cf,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as wv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Nv,SiteEditMaterializationSchema as Pv,parseComponentI18nResourcesJson as Av}from"@vcp-dev/contracts";var nc="components/site/generated",Rf="{{$INSTANCE}}",Bi=5,Tv=/^[a-z][a-z0-9-]{0,48}$/,Fv=/^[a-f0-9]{8}$/,wf=/\.tsx?$/,_v=/\.json$/,Mv=/\.(?:tsx?|json)$/,Ov=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Lv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Dv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],ec=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),tc=Rv,Bv=typeof tc=="function"?tc:tc.default;function jv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Cf)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=Yv(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=Pv.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Wv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${nc}.`,path:e.generatedRoot}};if(!_f(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=Af(r.data.files),s=Af(e.controlledFiles);if(!Zv(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Cf)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 u=Buffer.byteLength(l.content,"utf8");if(u>wv)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+=u}return a>Nv?{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 $v(e){let t=jv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!Ov.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Dv,...i],a=t.data.generatedRoot,c=_f(e.manifest.instanceBaseName),l=Math.max(1,Math.min(Bi,e.maxAttempts??Bi));for(let u=0;u<l;u+=1){let d=Hv(e.instanceNameGenerator?.()??Iv(4).toString("hex"));if(!d)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let m=`${c}-${d}`,g=Of(a,m),f=Vv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:g,allowedExternalImports:s});if(!f.ok)return f;if(!await Kv(e.exists,g,f.data.files))return{ok:!0,data:f.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Ff(e){let t=Math.max(1,Math.min(Bi,e.maxAttempts??Bi));for(let n=0;n<t;n+=1){let r=await $v({...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 Vv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Nf({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=Nf({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=Uv(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 Kv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Nf(e){if(e.pathTemplate.split(Rf).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(Rf,e.instanceName),n=Gv(t);return n?Of(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||!Mv.test(n)||Lv.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 Uv(e,t,n,r,o){let i=new Set(e.map(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(_v.test(d.path)){if(d.path.endsWith(Di)){let f=Av(d.content);if(!f.success)return An("MATERIALIZATION_DATA_UNSUPPORTED",f.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return An("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let m;try{m=Cv(d.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:d.path}}}let g=Wr(d.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{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:d.path}};s.set(d.path,m)}for(let d of e){if(!wf.test(d.path))continue;let m=s.get(d.path),g=null;if(Bv(m,{ImportDeclaration(f){let h=Pf({importer:d.path,source:f.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},f.stop();else if(h.internalPath&&(a.get(d.path).add(h.internalPath),h.internalPath.endsWith(Di))){let y=Jv({importer:d.path,imported:h.internalPath,source:f.node.source.value,ast:m});y.ok?c.get(h.internalPath).add(d.path):(g??=y.error,f.stop())}},ExportAllDeclaration(f){g??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},f.stop()},ExportNamedDeclaration(f){if(f.node.source){let h=Pf({importer:d.path,source:f.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},f.stop()):a.get(d.path).add(h.internalPath)}},CallExpression(f){if(f.node.callee.type==="Import"){g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},f.stop();return}f.node.callee.type==="Identifier"&&f.node.callee.name==="require"&&(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},f.stop())},NewExpression(f){f.node.callee.type==="Identifier"&&f.node.callee.name==="Function"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},f.stop())},MetaProperty(f){f.node.meta.type==="Identifier"&&f.node.meta.name==="import"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},f.stop())},MemberExpression(f){let h=Tf(f.node);h&&ec.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},f.stop())},OptionalMemberExpression(f){let h=Tf(f.node);h&&ec.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},f.stop())},Identifier(f){f.isReferencedIdentifier()&&ec.has(f.node.name)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${f.node.name}.`,file:d.path},f.stop())},JSXAttribute(f){f.node.name.type==="JSXIdentifier"&&f.node.name.name==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},f.stop())},JSXOpeningElement(f){f.node.name.type==="JSXIdentifier"&&f.node.name.name.toLowerCase()==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},f.stop())}}),g)return{ok:!1,error:g}}if(!wf.test(n))return An("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return An("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!Xv(l,r))return An("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,m]of c)if(m.size!==1)return An("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return zv(n,a).size!==e.length?An("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:nc,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Pf(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=qt.posix.normalize(qt.posix.join(qt.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 Jv(e){let t=qt.posix.dirname(e.importer),n=qt.posix.dirname(e.imported),r=qt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=qt.posix.basename(e.imported).slice(0,-Di.length),i=`./${r}${Di}`;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 Xv(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 zv(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 An(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function Wv(e){let t=Mf(e);return t===nc?t:null}function Hv(e){let t=e.trim().toLowerCase();return Fv.test(t)?t:null}function _f(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 Tv.test(t)?t:null}function Mf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=qt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function Gv(e){let t=Mf(e);return!t||t!==e?null:t}function Of(...e){return qt.posix.join(...e)}function Af(e){return new Set(e.map(t=>t.pathTemplate))}function Yv(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 Zv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Tf(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 yc}from"node:crypto";import uc from"@babel/traverse";function rc(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(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.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(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as Qv}from"node:crypto";import Lf from"node:path";import*as Vf from"@babel/parser";import oc from"@babel/generator";import*as Ue from"@babel/types";var Df=typeof oc=="function"?oc:oc.default;function sc(e){let t=Uf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=lc(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=tk(n,o),s={jsx:`<${e.component.localName} />`},a=qv(e);if(i){let g=ic(e);return g.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:g.locator,sourceHash:g.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(cc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Hr("Route page composition does not expose a verifiable container boundary.");let u=Yr(c),d=jf(e.source,u,l,"Route page composition container");if(!d.ok)return d.result;let m=o.anchorSourceRange?Yr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Hr("Route page composition placement does not expose a verifiable anchor boundary.");let g=jf(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.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:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function qv(e){let t=ik(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 ji(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Tn(e.source,"Root expression rewrite requires an exact expression locator.");let t=Cr(e.source,"value");if(!t.ok)return Tn(e.source,t.diagnostic.message);let n=ce(t.ast,e.locator);if(!n.ok)return Tn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Tn(e.source,"Resolved value locator does not point to an expression.");let o=ar(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Tn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:Df(t.ast,{}).code};let i;try{i=Vf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Tn(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?Tn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(ek(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Df(t.ast,{}).code})}function ek(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function Tn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function ac(e){let t=Uf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Jf(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(nk(n,o)){let h=ic(e);return h.ok?e.operation==="remove-node"&&!Bf(n,o.placementUnitKey)?Hr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Hr("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=Yr(o.sourceRange),a=Mt(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?[]:[Gr(a.diagnostic)]}};if(ar(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=ic(e);return h.ok?Bf(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}}}:Hr("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||!ok(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=lc(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 u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.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 d=u.containerSourceRange;if(!d||!u.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=Yr(d),g=Mt(e.source,m);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[Gr(g.diagnostic)]}};if(ar(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return $f("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,y=u.anchorSourceHash;if(!h||!y)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=Yr(h),x=Mt(e.source,E);return!x.ok||!x.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:x.ok===!1?x.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:x.ok?[]:[Gr(x.diagnostic)]}}:ar(e.source,x.match.node.start??null,x.match.node.end??null)!==y?$f("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:u.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:u.relation}}}}function Bf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function tk(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&cc(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 nk(e,t){return e.container.kind!=="jsx-container"&&cc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ic(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Mt(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?[]:[Gr(r.diagnostic)]}}}:ar(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Kf("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function jf(e,t,n,r){let o=Mt(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?[]:[Gr(o.diagnostic)]}}}:ar(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Kf(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Kf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Hr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function $f(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Gr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Uf(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&&!rk(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 rk(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function ok(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function ik(e,t){let n=Lf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Lf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Yr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function ar(e,t,n){return t==null||n==null?null:`sha256:${Qv("sha256").update(e.slice(t,n)).digest("hex")}`}function cc(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 sk=typeof uc=="function"?uc:uc.default;function Hf(e){if(!e.ast)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=mk(e.ast);if(!t)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=hk(t);if(!n.ok)return Rt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=xk(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Sk(r,t))return Rt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return fc(e,t,"virtual-route-root",r);if(bk(r)){let o=Ik({input:e,source:e.source,expression:r});return dc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Me(r)&&!un(r)){let o=gc(r),i=Wf({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return dc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=vk(r);if(!o.ok)return Rt(e,[o.diagnostic]);let i=cr(o.path);if(i.unsupported)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Ek(e.source,r,i.members))return fc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Me(r);if(i.members.length===0&&s)return fc(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=Wf({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return dc(e,t,l,{kind:a,sourceKind:c},r)}return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function lc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Jf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Gf(e){return e.ok?ak(e.projection):ck(e.projection)}function ak(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,u]of t){let d=u.members.flatMap((h,y)=>Yf(e,u,h,y,e.container.placementKey)),m=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>uk(l,h,u.independent)),g=d.length>0?d:[{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,g.map(({sourceMember:h})=>h)),o.set(l,m);let f=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:f,businessMemberKeys:m.map(h=>h.key),isMultiMember:u.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:lk(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function ck(e){let t=e.diagnostics.map(dk);return{status:"unsupported",version:e.version,composition:e.composition,reason:fk(e.diagnostics),diagnostics:t}}function lk(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 Yf(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)=>Yf(e,t,a,c,i))]}function uk(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function dk(e){return{code:pk(e),message:e.message}}function fk(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 pk(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 mk(e){let t=null;return sk(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=gk(o.path);i&&(t=i,n.stop())}}),t}function gk(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 hk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Qr(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ve("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:Ve("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ve("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(!yk(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Zf(s)||Qf(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Qr(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ve("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function yk(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(Zf(o)||Qf(o))return null;return r}function Zf(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Qf(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function xk(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=Qr(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 bk(e){return e.isConditionalExpression()?Xf(Qr(e.get("consequent")))&&Xf(Qr(e.get("alternate"))):!1}function Xf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Qr(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 Sk(e,t){if(e.isIdentifier())return zf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return zf(n.node.name,t)}return!1}function zf(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 Ek(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&mc(t)}function mc(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(!mc(t))return!1;continue}if(t.isJSXElement()&&!mc(t))return!1}return!0}function vk(e){let t=e;if(e.isJSXFragment()||Me(e)){let r=Zr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=Zr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(Zr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function Zr(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(...Zr(n));continue}n.isJSXElement()&&(Me(n)?t.push(...Zr(n)):t.push(n))}return t}function cr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:hc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:bt(r.node.loc),businessMemberCount:0,parentSourceRange:bt(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=cr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?cr(o):null;n||=i?.unsupported??!1,t.push({...gc(o,i?.members),sourceRange:bt(r.node.loc),parentSourceRange:bt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:hc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:bt(r.node.loc),businessMemberCount:1,parentSourceRange:bt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Me(r)){let o=cr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?cr(r):null;n||=o?.unsupported??!1,t.push({...gc(r,o?.members),parentSourceRange:bt(e.node.loc)})}}return{members:t,unsupported:n}}function gc(e,t){let n=e.isJSXElement()&&un(e)?t??cr(e).members:[],r=e.isJSXElement()&&!un(e)&&!Me(e);return{memberKey:hc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:bt(e.node.loc),businessMemberCount:r?1:qf(n),parentSourceRange:bt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:kk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function kk(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 qf(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function $i(e){return e.length===0?0:Math.max(1,qf(e))}function Wf(e){let t=bt(e.containerPath.node.loc),n=xc(e.source,e.containerPath.node.start,e.containerPath.node.end),r=St(e.input,e.containerKind,e.sourceKind,t),o=St(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:$i(e.members)<=1,memberCount:$i(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Ik(e){let t=bt(e.expression.node.loc),n=xc(e.source,e.expression.node.start,e.expression.node.end),r=St(e.input,"virtual-route-root","atomic-expression",t),o=St(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:St(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 ep(e,t){let n=bt(t.node.loc),r=xc(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function dc(e,t,n,r,o){let i=ep(e,o);if(!i)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=Ck(e,n,s),c=rc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:np(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 Ck(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,m,g,f,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:$i(f)<=1,memberCount:$i(f),sourceRange:m,sourceHash:m?pc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?pc(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?pc(e.source,g):null,members:f}),i=t.placementKey,s=t.members.map(l=>St(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",St(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=St(e,i,"placement-unit",l.sourceRange);r.push(o("before",St(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",St(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function fc(e,t,n,r){let o=ep(e,r);if(!o)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=St(e,n,"empty-container",void 0),s=St(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=rc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:np(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 Rt(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 Ve(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function St(e,t,n,r){return tp([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function hc(e,t,n){return tp(["member",e,String(t??-1),String(n??-1)])}function tp(e){return`pc_${yc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function xc(e,t,n){return t==null||n==null?null:`sha256:${yc("sha256").update(e.slice(t,n)).digest("hex")}`}function pc(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:${yc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function bt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function np(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 Dk}from"@vcp-dev/contracts";import p_ from"node:fs";import g_ from"node:path";var wk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function qr(e){let t=e.map(r=>Lk(r.path)),n=Nk(t);return n?t.filter(r=>Ak(n,r)).map(r=>({routeId:Tk(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function bc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=Ok(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Nk(e){return e.some(r=>r.startsWith("app/")&&!Pk(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function Pk(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Ak(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return wk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Tk(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(_k).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Fk(e){return e.startsWith("(")&&e.endsWith(")")}function _k(e){return!e||e.startsWith("@")||e.startsWith("_")||Fk(e)?null:Mk(e)}function Mk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function Ok(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function Lk(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var eo=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function ot(e,t={}){throw new eo("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Sc(e){return Dk.safeParse(e).success||ot("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function rp(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||ot("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return ot("invalid-template-key",{path:e})}return Sc(t)!==e&&ot("noncanonical-template-key",{path:e}),t}function Bk(e){let t=bc(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("(")||jk(r)&&!op(r)))&&ot("invalid-public-route",{routeId:e}),t}function jk(e){return e.includes("[")||e.includes("]")}function op(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function ip(e){return e.some(op)}function sp(e,t,n="app"){n!=="app"&&n!=="src/app"&&ot("invalid-app-root");let r=Bk(e),o=Sc(t),i=ip(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))&&ot("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function ap(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function cp(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===".")&&ot("invalid-file-path",{path:i}),n.has(i)&&ot("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ki(e){let t=cp(e.files),n=qr([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new eo("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(!ap(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||ot("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=ip(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,m=rp(u),g=d.length?`/${d.join("/")}`:"/";sp(g,m,a).templateEntryFile!==i&&ot("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&ot("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Vi(i.routeId,s.routeId)||Vi(i.templateId,s.templateId))}function lp(e){let t=cp(e.files),n=Ki({files:t}),r=qr([...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 $k(e){let t=bc(e.selector.routeId),n=lp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&ot("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||ot("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 qk}from"@vcp-dev/contracts";import{parse as hM}from"@babel/parser";import{parse as I_}from"@babel/parser";import{FormBlockIdSchema as R_,FormSpecV1Schema as w_}from"@vcp-dev/contracts";var to="components/site/generated/forms",N_=`${to}/vcp-form-runtime.tsx`,Ui="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",P_=new RegExp(`^${to}/form-(${Ui})\\.spec\\.ts$`),A_=new RegExp(`^${to}/form-(${Ui})\\.tsx$`),T_=new RegExp(`^@/${to}/form-(${Ui})$`),F_=new RegExp(`(?:^|/)${to}/form-(${Ui})(?:\\.tsx?)?$`);var __=Symbol("invalid-literal");import{createHash as L_}from"node:crypto";import{posix as B_}from"node:path";import{parse as $_}from"@babel/parser";import{FormSpecV1Schema as K_}from"@vcp-dev/contracts";var U_=Symbol("dynamic");import{parse as Vk}from"@babel/parser";function Ji(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var Kk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function up(e){let t=Kk.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 Uk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function dp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Jk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Ec(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(Ec);if(t?.type==="ObjectExpression"){let n={};for(let r of Ji(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=dp(r.key);if(!o)throw new Error("unsupported object key");n[o]=Ec(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function vc(e,t){let n=[],r=up(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Vk(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 Ji(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Ji(u.declarations)){let m=d.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=Jk(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 Ji(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=dp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=Uk(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Ec(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}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 Xk}from"@babel/parser";var fp=["page","anchor","external","email","phone","group","file"],zk=["link","cta"],mp=["description","badge","iconKey"],kc=["label","targetType","href","role","openInNewTab","nofollow","children",...mp],Wk=new Set(kc);function ro(e){return Array.isArray(e)?e:[]}function no(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Hk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function pp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Ic(e){let t=[],n;try{n=Xk(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 ro(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of ro(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 ro(r.elements).forEach((i,s)=>{let a=gp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function gp(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 ro(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Hk(l.key);u&&(r[u]=l.value)}let o=no(r.label),i=no(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!fp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${fp.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 mp){if(r[l]===void 0)continue;let u=no(r[l]);u!==void 0?s[l]=u: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))Wk.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 ${kc.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=[];ro(r.children.elements).forEach((u,d)=>{let m=gp(u,`${t}.children[${d}]`,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=no(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=no(r.role);if(c!==void 0&&(zk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=pp(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=pp(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 Gk}from"@babel/parser";function oo(e){return Array.isArray(e)?e:[]}function hp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Yk(e){let t;try{t=Gk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of oo(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of oo(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=hp(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 Cc(e,t){let n=yp(t);if(!n)return{status:"unsupported",source:e};let r=Yk(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Ic(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=oo(l.elements);for(let[d,m]of u.entries()){if(Qk(m,n)){let f=u[d+1],h=u[d-1],y=m.start,E=m.end;if(typeof y!="number"||typeof E!="number")continue;if(f&&typeof f.start=="number")s.push({start:y,end:f.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let x=/^\s*,/.exec(e.slice(E));s.push({start:y,end:x?E+x[0].length:E})}continue}let g=Zk(m);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function Zk(e){if(e.type==="ObjectExpression")for(let t of oo(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return hp(t.value)}}function yp(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Qk(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of oo(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"&&yp(n??"")===t}import{estimateNavLabelWidth as q_}from"@vcp-dev/contracts";import{parse as nM}from"@babel/parser";var eI="components/site/generated/",io=[".tsx",".ts",".jsx",".js"];function xp(e){if(e.expectedUrlPath===qk)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(qr(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let x=vc(y,E);return x.found&&x.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 y of h)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=tI(e.files);if(!i.ok)return i.error;let s=i.graph,a=iI(o,s),c=sI(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,y)=>h.localeCompare(y)),u=[...o,...[...c].sort((h,y)=>h.localeCompare(y))],d=new Set(u),m=u.map(h=>({operation:"delete",file:h})),g=[],f=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let E=Cc(y,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),g.push(h)):E.status==="unsupported"&&f.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&f.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:f}}function tI(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")||!nI(r))continue;let s=Xt(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(rI(c))continue;let l=bn(r,c),u=oI(l,t);if(!u)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(u)}n.set(r,a)}return{ok:!0,graph:n}}function nI(e){let t=e.toLowerCase();return io.some(n=>t.endsWith(n))}function rI(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!io.some(n=>e.endsWith(n)))}function oI(e,t){let n=e.replace(/\\/g,"/");return(io.some(o=>n.endsWith(o))?[n]:[...io.map(o=>`${n}${o}`),...io.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function iI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(eI)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function sI(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 bm from"@babel/parser";import*as fe from"@babel/types";import*as as from"node:path";import*as ve from"@babel/types";function bp(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 Dt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Fn(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ve.isObjectPattern(n)||ve.isArrayPattern(n))return Fn(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(cI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Fn(e,t,n=!1){return ve.isIdentifier(e)?e.name===t&&n:ve.isObjectPattern(e)?e.properties.some(r=>ve.isObjectProperty(r)?Fn(r.value,t,n):Fn(r.argument,t,n)):ve.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ve.isRestElement(r)?r.argument:r;return Fn(o,t,n)}):ve.isAssignmentPattern(e)?Fn(e.left,t,!0):ve.isRestElement(e)?Fn(e.argument,t,n):!1}function lr(e,t){if(e.path.isObjectPattern()){if(t){let r=wt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Dt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Dt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Sp(r),i=!1,s=o?o.initBinding&&Rc(o.initBinding)?(i=Dt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=lr(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=wt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Dt(e)}}}}let n=dI(e);if(n){let r=aI(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||Dt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=lI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Dt(e)}}let i=so(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Dt(e)}:null}if(Rc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Dt(e)}}return null}function aI(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=Sp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Rc(i)?(a=Dt(i),[...s]):(()=>{let u=lr(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=wt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Dt(t)}:null}function Sp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=fI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Rc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function cI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function lI(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=wt(i.node,t);if(a)return a}return null}function Ep(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Xi(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=so(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=uI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=so(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 Xi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=so(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&wt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Xi(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=Xi(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=Xi(r,t);if(o)return o}}return null}function wt(e,t,n=[]){if(ve.isIdentifier(e))return e.name===t?n:null;if(ve.isObjectPattern(e)){for(let r of e.properties)if(ve.isObjectProperty(r)){let o=so(r);if(!o)continue;let i=wt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ve.isRestElement(r)){let o=wt(r.argument,t,n);if(o)return o}}if(ve.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ve.isRestElement(o)?o.argument:o,s=wt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ve.isAssignmentPattern(e)?wt(e.left,t,n):null}function uI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function dI(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 so(e){return e.computed?null:ve.isIdentifier(e.key)?e.key.name:ve.isStringLiteral(e.key)?e.key.value:null}function fI(e){let t=[],n=e;for(;ve.isMemberExpression(n);){if(n.computed)if(ve.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ve.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ve.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ve.isIdentifier(n)?{base:n.name,path:t}:null}import*as wp from"@babel/parser";import Pc from"@babel/traverse";import*as ur from"@babel/types";import*as le from"@babel/types";var vp=new WeakMap;function Hi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?zi(n,t):null}if(e.isMemberExpression()){let n=xI(e.node),r=pI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?zi(o,[...r,...t]):null}return e.isAwaitExpression()||Nc(e.node)?dn(SI(e.node),t,"awaited or fetched expression"):null}function pI(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?t:null}function zi(e,t=[],n){let r=mI(e,t);if(r)return r;let o=gI(e,t,n);if(o)return o;let i=hI(e,t,n);return i||null}function co(e){return e?.kind==="api-source"}function mI(e,t){if(e.path.isVariableDeclarator()&&le.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&wc(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&le.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>le.isObjectProperty(c)&&Cp(c)==="data"&&ao(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&wc(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=yI(e);if(!n||Cp(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()||!wc(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function gI(e,t,n){if(e.path.isVariableDeclarator()&&le.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Ip(c.node))return null;let[l,u]=e.path.node.id.elements;return!le.isIdentifier(l)||l.name!==e.identifier.name||!le.isIdentifier(u)?null:kp(e,u.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!Ip(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return le.isIdentifier(a)&&kp(e,a.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function hI(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?dn(e.identifier.name,t,"awaited binding result"):Nc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function yI(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 ao(e,t){return le.isIdentifier(e)?e.name===t:le.isAssignmentPattern(e)?ao(e.left,t):le.isObjectPattern(e)?e.properties.some(n=>le.isObjectProperty(n)?ao(n.value,t):ao(n.argument,t)):le.isArrayPattern(e)?e.elements.some(n=>!!n&&ao(le.isRestElement(n)?n.argument:n,t)):!1}function kp(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=vp.get(n);c||(c=new WeakMap,vp.set(n,c)),s=c.get(i.node),s||(s=new Map,c.set(i.node,s));let l=s.get(t);if(l!==void 0)return l}i.traverse({CallExpression(c){Nc(c.node)&&(r=!0),(bI(c.node.callee,t)||c.node.arguments.some(l=>le.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function wc(e){let t=Gi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Ip(e){return Gi(e.callee)==="useState"}function Nc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Wi(e,o=>le.isCallExpression(o)&&Gi(o.callee)==="fetch");return t?.set(e,r),r}function xI(e){let t=e;for(;le.isMemberExpression(t);)t=t.object;return le.isIdentifier(t)?t.name:null}function Cp(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function Gi(e){return le.isIdentifier(e)?e.name:le.isMemberExpression(e)&&le.isIdentifier(e.property)?e.property.name:null}function bI(e,t){return Wi(e,n=>le.isIdentifier(n)&&n.name===t)}function Wi(e,t){if(t(e))return!0;let n=le.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(le.isNode(i)&&Wi(i,t))return!0;continue}if(le.isNode(o)&&Wi(o,t))return!0}return!1}function SI(e){return le.isIdentifier(e)?e.name:le.isCallExpression(e)?Gi(e.callee)??"api":le.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:EI(e,t),reason:n}}function EI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Np=typeof Pc=="function"?Pc:Pc.default;function Pp(e,t){let n=Tp(e);if(!n)return{allowed:!0};let r=!1;return Np(n,{CallExpression(o){if(!Fp(o.node,t.sourceRange)||!vI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||co(Hi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Ap(e,t){let n=Tp(e);if(!n)return{allowed:!0};let r=!1;return Np(n,{JSXExpressionContainer(o){Fp(o.node,t.sourceRange)&&(ur.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 Tp(e){try{return wp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function vI(e){let t=e.callee;return ur.isMemberExpression(t)&&ur.isIdentifier(t.property)&&t.property.name==="map"}function Fp(e,t){let n=e.loc;return n?Rp({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Rp({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Rp(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 _p from"@babel/parser";import Ac from"@babel/traverse";import*as _e from"@babel/types";import*as dr from"node:path";var Nt=typeof Ac=="function"?Ac:Ac.default;function Je(e){try{return _p.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Tc(e){return e.computed?_e.isStringLiteral(e.key)||_e.isNumericLiteral(e.key)?String(e.key.value):null:kI(e.key)}function kI(e){return _e.isIdentifier(e)?e.name:_e.isStringLiteral(e)||_e.isNumericLiteral(e)?String(e.value):null}function _n(e){return _e.isParenthesizedExpression(e)||_e.isTSAsExpression(e)||_e.isTSSatisfiesExpression(e)||_e.isTSNonNullExpression(e)||_e.isTSTypeAssertion(e)?_n(e.expression):_e.isExpression(e)?e:null}function Fc(e){if(_e.isIdentifier(e))return[e.name];if((_e.isMemberExpression(e)||_e.isOptionalMemberExpression(e))&&!e.computed&&_e.isIdentifier(e.property)){let t=_n(e.object),n=t?Fc(t):null;return n?[...n,e.property.name]:null}return null}function Mn(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?dr.normalize(dr.join(dr.dirname(e),t)).replace(/\\/g,"/"):t}function ut(e,t){return Yi(e)===Yi(t)}function Yi(e){let t=fr(e);return t.endsWith("/index")?t.slice(0,-6):t}function fr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Lp(e,t,n){let r=$p(e,t);if(Vp(e,r),Kp(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 Nt(e,{JSXElement(s){zp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Zi(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 Dp(e,t){let n=new Map,r=i=>{let s=pr(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 II(i,n))o=r(s)||o}return[...n.values()]}function II(e,t){let n=[],r=CI(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=lo(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=Mn(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let u of t.values())ut(u.file,i)&&n.push({file:e.file,namespace:_c(l,u.namespace),exportName:u.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ut(l.file,i)&&On(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let u of c){let d=lo(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(pr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=lo(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Mn(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ut(c.file,i)&&n.push({file:e.file,namespace:_c(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ut(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function _c(e,t){return t?`${e}.${t}`:e}function On(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function lo(e,t,n){return!On(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function CI(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=Mn(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(pr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>ut(u.file,s)&&On(u.namespace,"default"));for(let u of l){let d=lo(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(d=>ut(d.file,s)&&On(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(pr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ut(c.file,s)&&r(a.local.name,{...c,namespace:_c(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=_n(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)??[],u=new Set(l.map(pr));for(let d of c){let m=lo(d.namespace,a.name,s.id.name),g=m?{...d,namespace:m}:d,f=pr(g);u.has(f)||(r(s.id.name,g),u.add(f),o=!0)}}}return n}function pr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Yi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function Bp(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 Oc(e){let t=RI(e),n=[],r=Kp(e.ast,t);return Nt(e.ast,{JSXElement(o){ut(e.file,e.sourceFile)&&Zi(o)===e.sourceComponent||zp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function jp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function $p(e,t){let n=jp();return Nt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function RI(e){let t=jp();return ut(e.file,e.sourceFile)&&wI(t,$p(e.ast,e.sourceComponent)),Nt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Mn(e.file,o),s=e.componentIdentities.filter(a=>ut(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(u=>On(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let m=Op(d,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>On(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let m of u){let g=Op(m,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),Vp(e.ast,t),t}function wI(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 Vp(e,t){Nt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=_n(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=Ln(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Mc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=Ln(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Xp(n.node.id,o.namespaceMembers,t,n)}}}})}function Kp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Nt(e,{ReferencedIdentifier(r){if(n){r.stop();return}NI(r)||!r.isIdentifier()||!Up(r,t)||PI(r,t)||AI(r)||(n=!0,r.stop())}}),n}function NI(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 Up(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)&&Ln(r.node,t,r)?r:null}function PI(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Mp(e,r))return!1;let o=Up(e,t);if(!o)return!1;if(_n(r.node)===o.node)return!!Ln(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Mp(e,a)&&!!Ln(a.node,t,a)}function AI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Mp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Ln(e,t,n){let r=_n(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 TI(r,t,n);let o=Fc(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?Jp(s,o.slice(1).join(".")):null}function TI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Tc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=Ln(i.value,t,n)!==null);continue}let a=Ln(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 Jp(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 Mc(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 Xp(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&&Mc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Tc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Jp(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&&Mc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){Xp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Op(e,t){if(!On(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 zp(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=Wp(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 Wp(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=Wp(e.object);return t?[...t,e.property.name]:null}return null}function Zi(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 Hp(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Oc({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 Se(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 be(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Bt(e,t){let n=be(e);return!!(n&&dt(t,n))}function dt(e,t){return t.start>=e.start&&t.end<=e.end}function Et(e,t){let n=ce(e,Se(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Qi(e,t)}function mr(e,t){let n=be(t);return n?e.slice(n.start,n.end):""}function Gp(e,t){return e.start===t.start&&e.end===t.end}function Qi(e,t){let n=null;return Nt(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 qi(e,t){return Lc(e,t).length>0}function es(e,t){let n=be(e.node),r=be(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()&&!FI(o,n,r)))return!0;o=o.parentPath}return!1}function FI(e,t,n){let r=be(e.node.consequent);if(r&&dt(r,t)&&!dt(r,n))return!1;let o=e.node.alternate?be(e.node.alternate):null;return!(o&&dt(o,t)&&!dt(o,n))}function Lc(e,t){let n=be(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=be(o.node.consequent),a=be(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()&&Dc(o.node.operator)){let s=be(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 Dc(e){return e==="&&"||e==="||"||e==="??"}function Yp(e,t){let n=be(e.consequent);if(n&&dt(n,t))return n;let r=be(e.alternate);return r&&dt(r,t)?r:null}function Zp(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=>fr(a.file)));if(!t.has(fr(e.sourceFile))||!t.has(fr(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(fr(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=Bp(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=Je(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=Dp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Oc({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!ut(s.file,e.targetFile)||Zi(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 BI}from"@vcp-dev/contracts";function ts(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 uo();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return uo();let u=_I(a,l,o?.instanceCount);if(!u)return uo();c=u}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"?uo():{ok:!0,target:{kind:"jsx-attribute"}}}function uo(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function _I(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 jt from"@babel/types";import{SiteEditSetPropsParamsSchema as MI}from"@vcp-dev/contracts";function Qp(e){let t=e.changes??(e.change?[e.change]:[]);if(!MI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return fo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return fo("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=Ne(e.source,"value");if(!o.ok)return fo("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=ce(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return fo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?OI(r):LI(c.match.path.node,r.name);if(!l)return fo("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 OI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function LI(e,t){let n=e.properties.filter(i=>jt.isObjectProperty(i)&&DI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!jt.isExpression(r.value))return null;let o=Lt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function DI(e){return jt.isIdentifier(e)?e.name:jt.isStringLiteral(e)?e.value:jt.isNumericLiteral(e)?String(e.value):null}function fo(e,t){return{ok:!1,errorCode:e,reason:t}}function qp(e){if(e.change.name!=="className"&&e.change.name!=="class")return po("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return po("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return po("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return po("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 po("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 po(e,t){return{ok:!1,errorCode:e,reason:t}}async function tm(e){let t=BI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return pn("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await jI(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);em(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(KI(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=ts({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"){Bc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Qp({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);em(n,l.steps);continue}Bc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:$I(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),VI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function jI(e,t){return t.name!=="className"&&t.name!=="class"?null:qp({node:e.node,change:t,classNameSource:e.classNameSource})}function $I(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 VI(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 em(e,t){for(let n of t)Bc(e,{...n,order:e.length})}function Bc(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 KI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?jc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function jc(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)=>jc(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=>jc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as hr from"@babel/types";import*as Q from"@babel/types";function $c(e,t,n){let r=Et(t,n);return r?$t(e,r):null}function $t(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(!Q.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=mr(e,u.node),m=r.node.params.map(h=>mr(e,h)),g=be(i.node),f=be(r.node);return!d||m.some(h=>h.length===0)||!g||!f?null:{callStart:g.start,callEnd:g.end,callbackStart:f.start,callbackEnd:f.end,collectionExpression:d,callbackParams:m,mapOperator:Q.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ns(u.node),callbackPath:r,collectionPath:u}}function mo(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function UI(e,t){let n=be(e.node);return n?JI(t).some(r=>{let o=be(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function JI(e){let t=e.callbackPath.node.body;return Q.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(Q.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(Q.isBlockStatement(n)){t.push(...mn(n.body));continue}if(Q.isIfStatement(n)){let r=Q.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=Q.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(Q.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}Q.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return Q.isJSXElement(e)?XI(e)?nm(e.children):[e]:Q.isJSXFragment(e)?nm(e.children):Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSNonNullExpression(e)||Q.isTSTypeAssertion(e)?gn(e.expression):Q.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:Q.isLogicalExpression(e)&&Dc(e.operator)?gn(e.right):[]}function nm(e){return e.flatMap(t=>Q.isJSXElement(t)||Q.isJSXFragment(t)?gn(t):Q.isJSXExpressionContainer(t)&&(Q.isJSXElement(t.expression)||Q.isJSXFragment(t.expression)||Q.isConditionalExpression(t.expression)||Q.isLogicalExpression(t.expression))?gn(t.expression):[])}function XI(e){let t=e.openingElement.name;return Q.isJSXIdentifier(t)?t.name==="Fragment":Q.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function rm(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ns(e){return!(Q.isIdentifier(e)||Q.isThisExpression(e)||Q.isMemberExpression(e)||Q.isOptionalMemberExpression(e)||Q.isCallExpression(e)||Q.isOptionalCallExpression(e))}function om(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(Q.isMemberExpression(n)||Q.isOptionalMemberExpression(n))&&Q.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function gr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=ce(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Qi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=$t(e,o);return i?UI(o,i):t.isRepeatItemRoot===!0}function im(e,t){let n=Je(e);if(!n)return!1;let r=ce(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Qi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(Q.isMemberExpression(s)||Q.isOptionalMemberExpression(s))&&Q.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Re from"@babel/types";function Vc(e){if(Re.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Re.isJSXMemberExpression(e)){let t=e;for(;Re.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function zI(e,t){let n=be(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Bt(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Vc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Kc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=ce(r,Se(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ce(r,Se(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=_r(o.match.path,i.match.path);if(qi(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=zI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function am(e){let t=e;for(;Re.isTSQualifiedName(t);)t=t.left;return Re.isIdentifier(t)?t.name:null}function go(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function rs(e){let t=[],n=r=>{if(r){if(Re.isIdentifier(r)){t.push(r.name);return}if(Re.isObjectPattern(r)){for(let o of r.properties){if(Re.isRestElement(o)){n(o.argument);continue}Re.isObjectProperty(o)&&n(o.value)}return}if(Re.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Re.isAssignmentPattern(r)){n(r.left);return}if(Re.isRestElement(r)){n(r.argument);return}Re.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Uc(e,t){let n=be(e.node),r=be(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=sm(e),i=sm(t);if(!o||!i||!Gp(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=Yp(s.node,n);if(a&&!dt(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=be(s.node.right);if(a&&dt(a,n)&&!dt(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())&&om(s)){let a=be(s.node.body)??be(s.node);if(a&&!dt(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 sm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?be(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Re.isJSXElement(t.node.body)||Re.isJSXFragment(t.node.body)||Re.isConditionalExpression(t.node.body)||Re.isLogicalExpression(t.node.body)))return be(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Jc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&qi(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=be(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>rs(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||Bt(u.path.node,o)||i.has(u.path.node)||hn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Vc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Xc(e,t,n){let r=be(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>rs(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return go(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Bt(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function cm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>rs(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)||hn(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(hr.isIdentifier(l))o(l.name,c);else{let u=am(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function zc(e,t){let n=be(e.node),r=new Set;return go(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Bt(i.path.node,n)||hn(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 lm(e){let t=[];for(let n of e.callbackPath.node.params){if(hr.isIdentifier(n)){t.push(n.name);continue}if(hr.isRestElement(n)&&hr.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 um(e,t){return{...e,callbackParams:t}}function Wc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ho(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 dm(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 Dn(e){return{file:e.file,component:e.component}}function WI(e){return e.target.kind==="node"?e.target.key:null}function HI(e){return"kind"in e}function os(e){return!HI(e)}function Qc(e,t){let n=as.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=as.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Hc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Mt(n,Se(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function el(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 GI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function YI(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 ZI(e){let t=Lp(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Uc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=QI({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Sm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ns(o):!0}}}function QI(e){let t=be(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||Bt(a.path.node,t))return;let c=tC(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=rC(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=qI(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=zc(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}hn(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:oC(e.source,t,[...n.values()])}}function qI(e,t){if(t.length===0)return e;let n=Sm(e);if(!n)return null;let r=ns(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=eC(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function eC(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function tC(e,t,n){let r=nC(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=lr(t,o);if(!i)return null;let s=r?.range??be(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function nC(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Bt(n.node,t)||n.node.computed||!fe.isIdentifier(n.node.property))return null;let r=be(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function rC(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()&&fe.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=mr(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 oC(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 Sm(e){try{let n=bm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=fe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&fe.isExpression(r)?r:null}catch{return null}}function iC(e){let t=be(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||Bt(s.path.node,t))return;let a=fm(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=fm(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!sC(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return go(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 sC(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 fm(e,t,n){let r=aC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Mn(t,i),a=i.startsWith(".")?Qc(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=fe.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 aC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function pm(e,t,n,r){let o=Lc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=mr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=cC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${uC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function cC(e,t){return lC(e.node)?t:`(${t})`}function lC(e){return fe.isIdentifier(e)||fe.isThisExpression(e)||fe.isSuper(e)||fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)||fe.isCallExpression(e)||fe.isOptionalCallExpression(e)||fe.isBooleanLiteral(e)||fe.isNumericLiteral(e)||fe.isStringLiteral(e)||fe.isNullLiteral(e)||fe.isUnaryExpression(e)}function uC(e){return e.trim().startsWith("<")?e:`(${e})`}var dC={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 is(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=dC[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 fC(e,t){for(let n of e.program.body){if(!fe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>fe.isImportDefaultSpecifier(o));if(r&&fe.isImportDefaultSpecifier(r))return r.local.name}return null}function pC(e,t,n){for(let r of e.program.body){if(!fe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>fe.isImportSpecifier(i)&&(fe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&fe.isImportSpecifier(o))return o.local.name}return null}function mm(e){let t=new Set;return Nt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function gm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function mC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=el(e),o=Je(t);if(n.exportName!=="default"){let a=o?pC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?gm(r,mm(o)):r;return{localName:c,importStep:Yc(e,c)}}if(!o)return{localName:r,importStep:Yc(e,r)};let i=fC(o,n.source);if(i)return{localName:i};let s=gm(r,mm(o));return{localName:s,importStep:Yc(e,s)}}function gC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??el(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 hC(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?yC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function yC(e){return Object.fromEntries(Object.entries(e).filter(t=>qc(t[1])))}function qc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(qc):typeof e=="object"?Object.values(e).every(qc):!1}function Yc(e,t=el(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 hm(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 xC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function yr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function tl(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function yo(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:tl(e,t.slice(0,n)),index:r.index}}return null}function Zc(e,t){return e.locator?e.collectionPathMap?.[t]?tl(e.locator,e.collectionPathMap[t]):yo(e.locator)?SC(e.locator,EC(t,e.collectionIndexMap)):null:null}function bC(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:Em(o,t)}function Em(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Em(r,t);return o===void 0?void 0:{[n.name]:o}}function SC(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},tl(e,i)}return null}function EC(e,t){return t?.[e]??e}function ym(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 vC(e,t){return kC(e.root,t.root)&&CC(e.path??[],t.path??[])}function kC(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&&IC(e.sourceRange,t.sourceRange)}}function IC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function CC(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 ss=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:yr(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:yr(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:yr(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:yr(t.kind,t.params.kind)};let r=t;if(!os(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=hm(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:yr(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"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:yr(t.kind,t.params.kind)};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.planSetLinkTarget(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=WI(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):xm(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return xm(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:Se(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}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?tm({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 u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let f=Zc(u,i.instanceIndex);if(!f)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=f}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,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:Se(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=Zc(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:Se(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Je(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ce(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!GI(a.match.path))return{ok:!0,value:r};let c=YI(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=Zc(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=Je(this.graph.getFileContent(t));if(!o)return!1;let i=ce(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 d=i;if(d?.kind==="value-binding"&&d.locator){let m=yo(d.locator);if(m)return this.buildPlan(t,n,[{order:0,file:d.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=ho(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:Se(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||Hp(n,t)>1)return null;let r=Qc(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(!os(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=ho(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 u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let g=Pp(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let f=is(r,n.params.node);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let h=[],y=0,E=n.params.node.kind==="component-call"?mC(n.params.node,this.graph.getFileContent(r.file)):void 0,x=E?.importStep;return x&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:x.moduleSpecifier,imports:x.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Se(r),node:{jsx:gC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?Se(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!os(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:hC(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(!os(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(d=>d.isRepeatItemRoot&&d.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=yo(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=bC(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 u=n.params.position.relation==="prepend"?ym(0,a.collectionIndexMap):ym(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:u,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=ho(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 gr(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:")||im(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&&gr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let m=$t(c,u),g=$t(c,d);if(!mo(m,g))return null;if(a&&(s==="before"||s==="after")){let h=Et(l,a),y=h?$t(c,h):null;if(!mo(m,y))return null}if(es(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let f=Kc(c,r,o);return f.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Dn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:f.reason??`Cannot move node because it depends on bindings outside the target scope: ${f.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&gr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let m=$t(c,u);if(!m)return null;let g=$t(c,d);if(mo(m,g))return null;if(g&&!rm(g,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 v=$c(c,l,a);if(g&&!mo(g,v)||!g&&v)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 v=is(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let f=Hc(this.graph,r);if(!f)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(es(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=pm(c,u,d,f);for(let v of h.conditionPaths){let R=Xc(v,d,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 y=Jc(u,d,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let E=cm(m,d);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 x=m;if(r.component!==o.component){let v=ZI({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:d});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};x=v.context}else{let v=zc(m.collectionPath,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,repeatExpression:Wc(x,h.sourceJsx),selectionContext:Dn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&gr(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),u=Je(c),d=Je(l);if(!u||!d)return null;let m=Zp({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,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 g=Et(u,r),f=Et(d,o);if(!g||!f)return null;let h=Uc(m.callSitePath,f);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=$t(c,g);if(!y)return null;if($t(l,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&$c(l,d,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=is(o,{kind:"native-tag",tag:r.tag});if(F)return{ok:!1,errorCode:"unsupported-operation",reason:F}}let x=Hc(this.graph,r);if(!x)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(es(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=pm(c,g,f,x);for(let F of v.conditionPaths){let L=Xc(F,f,y);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let R=Jc(g,f,y,{preserveConditionalBoundary:v.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 N=iC({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:f});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let T=lm(y);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let I=um(y,T.callbackParams),P=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}];for(let F of N.imports)P.push({order:P.length,file:o.file,type:"add-import",moduleSpecifier:F.moduleSpecifier,imports:F.imports});return P.push({order:P.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Se(o),expression:Wc(I,v.sourceJsx),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Dn(o)}),this.buildPlan(t,n,P,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 v=n.params.target,R=this.graph.getNode(v.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 N=this.graph.getFileVersion(r.file);if(n.documentVersion!==N)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${N})`};let T=this.graph.getFileContent(r.file),I=Je(T),P=I?Et(I,r):null,F=I?Et(I,R):null,L=P?.parentPath,W=F?.parentPath;if(!P||!F||!L||!W||L.node!==W.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Me(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let z=L.node.loc;return z?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:z.start.line,startColumn:z.start.column,endLine:z.end.line,endColumn:z.end.column}},placement:v.relation,anchorLocator:Se(R),selectionContext:Dn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=hm(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(xC(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 v=n.params.target.relation,R=i.anchorNode&&(v==="before"||v==="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:v,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,u=n.params.target.relation,d=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,g=ho(r,c,m);if(g&&!Gc(g)&&!dm(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,R=await this.graph.getTextWriteTarget(d.key,0);if(v?.kind==="value-binding"&&R?.kind==="value-binding"&&v.locator&&R.locator){let N=yo(v.locator),T=yo(R.locator);if(N&&T&&v.file===R.file&&vC(N.locator,T.locator)){let I=N.index,P=T.index,F=u==="before"?P-(I<P?1:0):P+(I<P?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:N.locator,fromIndex:I,toIndex:F}],o)}}}if(r.isRepeatItemRoot&&gr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let f=this.getRepeatBackedTemplateStructureReason(r),h=Gc(g)?g:f;if(h&&Gc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(v)return v;let R=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(R)return R;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=is(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let E=Kc(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 x=[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(s),placement:u,anchorLocator:d?Se(d):void 0,selectionContext:Dn(s)}];return this.buildPlan(t,n,x,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Hc(this.graph,r)??`<${r.component} />`,m=Ap(u,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:Se(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let f=r.tag??r.component,y={moduleSpecifier:Qc(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:f}]:[{kind:"named",imported:r.exportName,local:f===r.exportName?void 0:f}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:d},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Dn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:d},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Dn(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,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:Ce(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 xm(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 sl from"@babel/generator";import{parse as $C}from"@babel/parser";import*as w from"@babel/types";import*as Kt from"@babel/types";import nl from"@babel/generator";import*as ke from"@babel/types";var RC=typeof nl=="function"?nl:nl.default,wC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,NC=/^((?:https?:)?\/\/)[^/@\s]+@/i,PC=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function km(e,t){let n=Vt(e.callee);if(!n)return null;if(n==="fetch")return rl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(vm(r))return rl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(vm(r))return rl(e.arguments[0],r,t,["ky client contract"])}return null}function rl(e,t,n,r){if(!e||ke.isSpreadElement(e)||ke.isJSXNamespacedName(e))return _C(t,n,r,"missing url argument");let o=xo(e);return{sourceKind:FC(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 xo(e){if(ke.isStringLiteral(e))return cs(e.value);if(ke.isTemplateLiteral(e))return cs(AC(e));if(ke.isBinaryExpression(e)&&e.operator==="+"){let t=xo(e.left),n=xo(e.right);return!t&&!n?void 0:cs(`${t??ol(e.left)}${n??ol(e.right)}`)}if(ke.isMemberExpression(e)){let t=Im(e);if(t)return`env:${t}`}if(!(ke.isCallExpression(e)&&Vt(e.callee)==="new URL")){if(ke.isNewExpression(e)&&ke.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ke.isSpreadElement(t)?xo(t):void 0,o=n&&!ke.isSpreadElement(n)?xo(n):void 0;return o&&r?cs(`${o} + ${r}`):r??o}if(ke.isIdentifier(e))return`:${e.name}`}}function AC(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+=ol(r))}return t}function ol(e){if(ke.isIdentifier(e))return`:${e.name}`;if(ke.isMemberExpression(e)){let t=Im(e);if(t)return`env:${t}`}return`:${TC(e)}`}function TC(e){return RC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function cs(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(NC,"$1<redacted>@").replace(PC,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?wC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function FC(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 _C(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function vm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Im(e){return!ke.isMemberExpression(e.object)||!ke.isIdentifier(e.object.object,{name:"process"})||!MC(e.object.property,"env")?null:ke.isIdentifier(e.property)?e.property.name:ke.isStringLiteral(e.property)?e.property.value:null}function MC(e,t){return ke.isIdentifier(e)&&e.name===t}function Vt(e){if(ke.isIdentifier(e))return e.name;if(ke.isMemberExpression(e)){let t=Vt(e.object),n=ke.isIdentifier(e.property)?e.property.name:ke.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var OC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),LC=new Set(["getConfig","submit"]);function Cm(e,t){let n=DC(Vt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!OC.has(i))return null;let s=il(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(!LC.has(i))return null;let s=il(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=il(e,0)??BC(e,0,"path")??"/cms/:path",s=jC(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 DC(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 Rm(e,t){let n=Vt(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 wm(e){let t=Vt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function il(e,t){let n=e.arguments[t];return Kt.isStringLiteral(n)?n.value:null}function BC(e,t,n){let r=e.arguments[t];if(!Kt.isObjectExpression(r))return null;for(let o of r.properties)if(Kt.isObjectProperty(o)&&!o.computed&&(Kt.isIdentifier(o.key)&&o.key.name===n||Kt.isStringLiteral(o.key)&&o.key.value===n)&&Kt.isStringLiteral(o.value))return o.value.value;return null}function jC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Nm(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let m={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,f=g.get(a)??new Map,h=f.get(c)??new Map;return h.set(l,m),f.set(c,h),g.set(a,f),t.set(s,g),n.add(m),d.catch(()=>{r(m)}),d}}}var tL=typeof sl=="function"?sl:sl.default,Dm=new WeakMap;function Bm(e){let t=new Map;return Dm.set(t,new Map([...e].map(n=>[n.file,n]))),t}var VC={maxFunctionDepth:8,maxImportDepth:6},KC=new Set(["src","href","alt","poster","content","title","aria-label"]),Pm=new WeakMap;function UC(e,t,n){let r=Pm.get(t.fileCache);r||(r=new WeakMap,Pm.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let m={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(m);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let f=g.get(d.tag)??[];f.push(m),g.set(d.tag,f)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function jm(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&Tm(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=ul(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...VC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:eg(n,e.element.componentName)};await $m(e.element.componentName,e.graph,r);let o=[];o.push(...await WC(e.element,e.graph,r),...await HC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await GC(s,e.element,e.graph,r);a&&o.push(ds(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Tm(s,e.element);if(!a)continue;let c=await Jm(s.source,e.element,e.graph,r);c&&o.push(ds(c,a,s.name))}let i=uR(o).sort(Qm);return{hasDynamicData:i.length>0,bindings:i}}async function $m(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 UC(t,n,e)){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 JC(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 u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await Um(l.sourceFile,n);if(!d)continue;let m=ps(d,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=eg(d,l.componentName),await $m(l.componentName,t,m);let g=await XC(l,m);for(let[f,h]of g){if(!h)continue;let y=a.get(f)??[];y.push(h),a.set(f,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Ym(u);d.length===1&&c.set(l,d[0])}zC(o,c,n)}var Am=new WeakMap;function JC(e,t,n,r){let o=Am.get(r.fileCache);return o||(o=Nm(),Am.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Vm(e,t,n,r))}async function Vm(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 Um(e,r))?.imports.get(t);if(!s||!kt(s.source))return!1;let a=await rg(e,s.source,r.exists);return a?a===n?!0:Vm(a,s.importedName,n,r,o):!1}async function XC(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(Km(e.sourceRange));if(r)for(let i of r.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);let o=new Map;for(let[i,s]of n){let a=await je(s,t);a&&o.set(i,a)}return o}function Km(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function Um(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 ul(e,r,t.fileCache)}function zC(e,t,n){if(w.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,ll(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,ze(o))}}function Tm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":KC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function WC(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 fs(i.collectionSource,n);s&&r.push(ds(Bn(s),"repeat-region",i.collectionExpression))}return r}async function HC(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 fs(i.conditionSource,n);s&&r.push(ds(Bn(s),"conditional-region",i.conditionExpression))}return r}async function GC(e,t,n,r){return Jm(e.source,t,n,r)}async function Jm(e,t,n,r){let o=await YC(e,t,n,r);return o||fs(e,r)}async function YC(e,t,n,r){if(!e)return null;let o=ZC(e.base,t,n);if(!o)return null;let i=await fs(o.collectionSource,r);return i?vo(i,e.path,!0):null}function ZC(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 fs(e,t){if(!e)return null;let n=await Xm(e.base,t);return n?vo(n,e.path,!1):null}async function Xm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return dR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await QC(e,t);if(r)return t.variableCache.set(e,ze(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await je(o,t);return t.variableCache.set(e,s?ze(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await tg(i,t);if(s){let a=ps(s,t,{importDepth:t.importDepth+1}),c=ng(i,s);if(c){let d=(await jn(c,[],a)).returnSource;return t.variableCache.set(e,d?ze(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await je(l,a);return t.variableCache.set(e,u?ze(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function QC(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await je(o,t);if(i)return i}return null}async function je(e,t){if(w.isIdentifier(e))return Xm(e.name,t);if(w.isMemberExpression(e)||w.isOptionalMemberExpression(e)){let n=w.isMemberExpression(e)?Rm(e,{file:t.file}):null;if(n)return Gm(n);let r=await qC(e,t);if(!r)return null;let o=cR(e);return vo(r,o,!1)}if(w.isAwaitExpression(e))return w.isExpression(e.argument)?je(e.argument,t):null;if(w.isCallExpression(e))return zm(e,t);if(w.isObjectExpression(e)){let n=await Wm(e,t);return Object.keys(n).length>0?ll(n,t.file):null}if(w.isConditionalExpression(e)){let n=await je(e.consequent,t),r=await je(e.alternate,t);return Eo(_m(n,r))}if(w.isLogicalExpression(e)){let n=await je(e.left,t),r=await je(e.right,t);return Eo(_m(n,r))}return w.isTSAsExpression(e)||w.isTSSatisfiesExpression(e)||w.isTSNonNullExpression(e)||w.isTypeCastExpression(e)||w.isParenthesizedExpression(e)?je(e.expression,t):null}async function qC(e,t){let n=e;for(;w.isMemberExpression(n)||w.isOptionalMemberExpression(n);)n=n.object;return w.isExpression(n)?je(n,t):null}async function zm(e,t){let n=Cm(e,{file:t.file,imports:t.analysis.imports});if(n)return Gm(n);if(wm(e)){let d=e.arguments[0];if(d&&w.isExpression(d))return Eo(await je(d,t))}let r=await eR(e,t);if(r)return r;let o=km(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 rR(e,t);if(i)return i;let s=await oR(e,t);if(s)return s;let a=await iR(e,t);if(a)return a;let c=await sR(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(w.isExpression(d)){let m=await je(d,t);m&&l.push(m)}let u=Ym(l);return u.length===1?Eo(u[0]):null}async function eR(e,t){let n=Vt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=nR(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(w.isIdentifier(s)){let a=await So(s.name,t);if(a)return(await jn(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!w.isObjectExpression(r))return ls(t.file,`${n} without static options`);let o=tR(r,"queryFn");if(!o)return ls(t.file,`${n} without queryFn`);if(w.isIdentifier(o)){let i=await So(o.name,t);return i?(await jn(i.node,[],i.context)).returnSource:ls(t.file,`${n} queryFn unresolved`)}return w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)?(await jn(o,[],t)).returnSource:w.isCallExpression(o)?zm(o,t):null}function tR(e,t){for(let n of e.properties){if(!w.isObjectProperty(n)||!w.isExpression(n.value))continue;if(Hm(n)===t)return n.value}return null}function nR(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 rR(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 je(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Bn(r);let o=e.arguments[0];if(w.isIdentifier(o)){let i=await So(o.name,t);if(!i)return Bn(r);let s=await jn(i.node,[r],i.context);return{...Bn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(w.isArrowFunctionExpression(o)||w.isFunctionExpression(o)){let i=await jn(o,[r],t);return{...Bn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Bn(r)}async function oR(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"json"})||!w.isExpression(e.callee.object)?null:je(e.callee.object,t)}async function iR(e,t){return!w.isMemberExpression(e.callee)||!w.isIdentifier(e.callee.property,{name:"then"})||!w.isExpression(e.callee.object)?null:Eo(await je(e.callee.object,t))}async function sR(e,t){if(!w.isIdentifier(e.callee))return null;let n=await So(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!w.isExpression(i)){r.push(ls(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await je(i,t);r.push(s)}return(await jn(n.node,r,n.context)).returnSource}async function So(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 tg(r,t);if(!o)return null;let i=ps(o,t,{importDepth:t.importDepth+1}),s=ng(r,o);return s?{node:s,context:i}:So(r.importedName,i)}async function jn(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=ps(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&al(c,lR(u),r)});let o=aR(e),i=null,s,a=!1;for(let c of o){if(w.isObjectExpression(c)){s={...s??{},...await Wm(c,r)},i=i??ll(s,n.file);continue}let l=await je(c,r);if(l){if(!i){i=l;continue}let u=cl(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function al(e,t,n){if(w.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(w.isAssignmentPattern(e)){al(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=vo(t,[{kind:"property",name:r.key.name}],!0),i=w.isAssignmentPattern(r.value)?r.value.left:r.value;al(i,o,n)}}function aR(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 Wm(e,t){let n={};for(let r of e.properties){if(!w.isObjectProperty(r))continue;let o=Hm(r);if(!o||!w.isExpression(r.value))continue;let i=await je(r.value,t);i&&(n[o]=i)}return n}function Hm(e){return w.isIdentifier(e.key)&&!e.computed?e.key.name:w.isStringLiteral(e.key)?e.key.value:null}function cR(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 vo(e,t,n){if(t.length===0)return ze(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return vo(e.fieldMap[r.name],t.slice(1),n);let o=ze(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=bo(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=bo(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=bo(o.fieldPath,i.join(".")),o):(o.valuePath=bo(o.valuePath,Fm(t)),o)}return o.valuePath=bo(o.valuePath,Fm(t)),o}function Fm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function bo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function Gm(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 Bn(e){let t=ze(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function lR(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function Eo(e){return e?{...ze(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function _m(e,t){return e?t?cl(e,t):ze(e):t?ze(t):null}function cl(e,t){if(us(e)!==us(t))return null;let n=qm(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Ym(e){let t=new Map;for(let n of e){let r=us(n),o=t.get(r);t.set(r,o?cl(o,n):ze(n))}return[...t.values()]}function us(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,us(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 ll(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 ls(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ds(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 Zm(e){let t=[...e].sort(Qm),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 uR(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 Qm(e,t){return Mm(e.targetKind)-Mm(t.targetKind)||qm(e.confidence,t.confidence)||Om(e.sourceKind)-Om(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Mm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Om(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function qm(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function ul(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Dm.get(n)?.get(e),i=o?.source===t?o.ast:$C(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap},a=[],c=[];w.traverse(i,{enter(d){switch(w.isFunction(d)&&a.push(d),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let m=d.loc;if(!m)return;let g=Km({startLine:m.start.line,startColumn:m.start.column,endLine:m.end.line,endColumn:m.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let m=d.source.value;for(let g of d.specifiers)w.isImportSpecifier(g)&&w.isIdentifier(g.local)?s.imports.set(g.local.name,{source:m,importedName:w.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):w.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:m,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let m=a.at(-1),g=m&&(w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))?m:null,f=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,f);for(let h of xr(d.id))f.set(h,w.isExpression(d.init)?d.init:null);if(w.isArrayPattern(d.id)&&w.isCallExpression(d.init)&&Vt(d.init.callee)==="useState"){let[h,y]=d.id.elements;w.isIdentifier(h)&&w.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}w.isIdentifier(d.id)&&Lm(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let m=d.declaration,g=d.source?.value;if(g)for(let f of d.specifiers){if(!w.isExportSpecifier(f))continue;let h=w.isIdentifier(f.exported)?f.exported.name:f.exported.value,y=f.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(w.isFunctionDeclaration(m)&&m.id?.name&&s.functions.set(m.id.name,m),w.isVariableDeclaration(m))for(let f of m.declarations)w.isIdentifier(f.id)&&Lm(f.init)&&s.functions.set(f.id.name,f.init);break}case"ExportDefaultDeclaration":{let m=d.declaration;if((w.isFunctionDeclaration(m)||w.isFunctionExpression(m)||w.isArrowFunctionExpression(m))&&s.functions.set("default",m),w.isIdentifier(m)){let g=s.functions.get(m.name);g&&s.functions.set("default",g)}break}}},exit(d){w.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,m)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(m),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let m=w.isIdentifier(d.callee)?d.callee.name:null;m&&l.has(m)&&w.isExpression(d.arguments[0])&&u(m,d.arguments[0]);let g=new Set;for(let f of d.arguments)w.isIdentifier(f)&&f.name!==m&&l.has(f.name)&&g.add(f.name);for(let f of g)u(f,d)}return n.set(e,s),s}function xr(e){return!e||w.isVoidPattern(e)?[]:w.isIdentifier(e)?[e.name]:w.isObjectPattern(e)?e.properties.flatMap(t=>w.isObjectProperty(t)?xr(t.value):xr(t.argument)):w.isArrayPattern(e)?e.elements.flatMap(t=>t?xr(w.isRestElement(t)?t.argument:t):[]):w.isAssignmentPattern(e)?xr(e.left):w.isRestElement(e)?xr(e.argument):[]}function Lm(e){return w.isFunctionExpression(e)||w.isArrowFunctionExpression(e)}function eg(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function tg(e,t){let n=await rg(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return ul(n,r,t.fileCache)}function ng(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function rg(e,t,n){return kt(t)?Sn(e,t,n):null}function ps(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 dR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as fl from"@babel/parser";import dl from"@babel/traverse";import*as q from"@babel/types";import{classifySiteEditPropertyName as fR}from"@vcp-dev/contracts";var pl=typeof dl=="function"?dl:dl.default;function ml(e){let t=fR(e.propertyName);if(t.owner!=="generic")return ft("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ft("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ft("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ft("missing-instance-index","A repeat property target requires an instance index");let r;try{r=fl.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return ft("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=pR(r,e.element.sourceRange);if(!o)return ft("repeat-not-found","The selected element is not inside a supported map repeat");if(!q.isIdentifier(o.callback.params[0]))return ft("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=mR(r,o.collection,e.file,e.sources);if(!i)return ft("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,E]of s.elements.entries()){if(!E||!q.isObjectExpression(E)||!lg(E))return ft("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let x=[{kind:"index",index:y}];l.push(x),u.push({kind:"value",root:a.root,path:x})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return ft("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let m=n.instanceIndex;if(m>=d)return ft("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let g=s.elements[m];if(!g||!q.isObjectExpression(g))return ft("unsafe-collection","Selected repeat item is not an object");let f=SR(e.element,e.propertyName),h=xR(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:d},(y,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:bR(g,e.propertyName),...f?{property:f}:{},selectionRef:n}:ft("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function pR(e,t){let n=[];return pl(e,{CallExpression(r){let o=og(r.node);o&&sg(o.callback,t)&&n.push({...o,span:ig(r.node)})},OptionalCallExpression(r){let o=og(r.node);o&&sg(o.callback,t)&&n.push({...o,span:ig(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function og(e){let t=e.callee;if(!q.isMemberExpression(t)&&!q.isOptionalMemberExpression(t)||t.computed||!q.isIdentifier(t.property)||t.property.name!=="map"||!q.isExpression(t.object))return null;let n=e.arguments[0];return!n||!q.isExpression(n)||!q.isArrowFunctionExpression(n)&&!q.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function mR(e,t,n,r){let o=ko(t);if(o&&q.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:dg(o)}},sourceFile:n};if(!q.isIdentifier(t))return null;let i=[];if(pl(e,{VariableDeclarator(s){q.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ko(i[0].init);return!s||!q.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return gR(e,t.name,n,r)}function gR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!q.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!q.isStringLiteral(o.source)||!q.isImportSpecifier(i))continue;let s=yR(n,o.source.value,r);if(!s)return null;let a=q.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=fl.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=hR(l,a),d=u?ko(u):null;return!d||!q.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function hR(e,t){let n=null;return pl(e,{VariableDeclarator(r){n||!q.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!q.isExpression(r.node.init)||(n=r.node.init)}}),n}function yR(e,t,n){let r=bn(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 ko(e){return q.isParenthesizedExpression(e)?ko(e.expression):q.isTSAsExpression(e)?cg(e.typeAnnotation)?ko(e.expression):null:q.isTSSatisfiesExpression(e)?null:e}function cg(e){return q.isTSTypeReference(e)&&q.isIdentifier(e.typeName)&&e.typeName.name==="const"}function lg(e){return e.properties.every(t=>!q.isObjectProperty(t)||t.computed||!q.isExpression(t.value)?!1:ms(t.value))}function ms(e){if(q.isTSAsExpression(e)&&cg(e.typeAnnotation))return ms(e.expression);if(q.isTSSatisfiesExpression(e))return!1;if(q.isArrayExpression(e))return e.elements.every(n=>!n||q.isSpreadElement(n)||!q.isExpression(n)?!1:ms(n));if(q.isObjectExpression(e))return lg(e);let t=Lt(e);return t.status==="resolved"||t.status==="undefined"}function xR(e,t){let n=e.properties.filter(o=>q.isObjectProperty(o)&&ug(o.key)===t);if(n.length>1)return null;let r=n[0];return r?q.isExpression(r.value)?ms(r.value)?"static":q.isIdentifier(r.value)||q.isMemberExpression(r.value)?"binding":null:null:"missing"}function bR(e,t){let n=e.properties.filter(o=>q.isObjectProperty(o)&&ug(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!q.isExpression(r.value)?{status:"undefined"}:Lt(r.value)}function SR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function ug(e){return q.isIdentifier(e)?e.name:q.isStringLiteral(e)?e.value:q.isNumericLiteral(e)?String(e.value):null}function dg(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 ig(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function sg(e,t){let n=dg(e);return ag(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&ag(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function ag(e,t,n,r){return e===n?t-r:e-n}function ft(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as ow}from"@vcp-dev/contracts";import*as te from"@babel/types";import No from"node:path";import*as B from"@babel/types";import*as yg from"@babel/parser";import gl from"@babel/traverse";import*as ie from"@babel/types";function hs(e,t){let n=[],r=e;for(;ie.isMemberExpression(r);){if(r.computed)if(ie.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ie.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ie.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ie.isIdentifier(r)||r.name!==t?null:n}function fg(e){if(ie.isIdentifier(e))return{base:e.name,path:[]};if(!ie.isMemberExpression(e))return null;let t=[],n=e;for(;ie.isMemberExpression(n);){if(n.computed)if(ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ie.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ie.isIdentifier(n)?{base:n.name,path:t}:null}function Ye(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}var Ut=Symbol("not-closed-literal");function gs(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:Ut;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return gs(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ie.isSpreadElement(n))return Ut;let r=gs(n);if(r===Ut)return Ut;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ie.isObjectProperty(n)||n.computed||n.shorthand||!ie.isExpression(n.value))return Ut;let r=ie.isIdentifier(n.key)?n.key.name:ie.isStringLiteral(n.key)?n.key.value:null;if(!r)return Ut;let o=gs(n.value);if(o===Ut)return Ut;t[r]=o}return t}default:return Ut}}function pg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let m=gs(i);if(m!==Ut)return m;if(!ie.isTemplateLiteral(i)){if(ie.isTSAsExpression(i)||ie.isTSSatisfiesExpression(i)||ie.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ie.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let f=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return f?.kind==="static"?f.value:void 0}if(ie.isArrayExpression(i)){let g=[];for(let f of i.elements){if(!f||ie.isSpreadElement(f))return;let h=await r(f,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(ie.isObjectExpression(i)){let g={};for(let f of i.properties){if(!ie.isObjectProperty(f)||f.computed)return;let h=null;if(ie.isIdentifier(f.key)?h=f.key.name:ie.isStringLiteral(f.key)&&(h=f.key.value),!h)return;if(f.shorthand){if(!ie.isIdentifier(f.value))return;let E=await r(f.value,s,a,c,l,u,d);if(E===void 0)return;g[h]=E;continue}if(!ie.isExpression(f.value))return;let y=await r(f.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(ie.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let f=s.getBinding(g.base);if(!f)return;let h=await t({currentFile:a,binding:f,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:Ye(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ie.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ie.isIdentifier(i))return{base:i.name,path:[]};if(!ie.isMemberExpression(i))return null;let m=[],g=i;for(;ie.isMemberExpression(g);){if(g.computed){let f=g.property;if(ie.isNumericLiteral(f))m.unshift({kind:"index",index:f.value});else if(ie.isStringLiteral(f))m.unshift({kind:"property",name:f.value});else{let h=ie.isExpression(f)?await n(f,s,a,c,l,u,d):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(!ie.isIdentifier(g.property))return null;m.unshift({kind:"property",name:g.property.name})}g=g.object}return ie.isIdentifier(g)?{base:g.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var xg=typeof gl=="function"?gl:gl.default,mg=new WeakMap;function bg(e){try{return yg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ys(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=bg(n);return e.set(t,{source:n,ast:o}),o}function xs(e,t){return hl(Io(e).expressionRanges,t,!1)}function Sg(e,t){return Io(e).exactExpressions.get(Eg(t))??null}function bs(e,t){return hl(Io(e).jsxRanges,t,!0)}function Io(e){let t=mg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return xg(e,{Expression(r){let o=r;n.expressions.push(o);let i=gg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=Eg(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=gg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(hg),n.jsxRanges.sort(hg),mg.set(e,n),n}function gg(e,t){let n=Co(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Eg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function hg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function hl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Co(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 br(e,t){if(t)return yl(e,t);let n=fg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function yl(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ro(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Io(e).expressions){if(yl(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function vg(e,t,n,r){return hl(Io(e).expressionRanges,r,!0,o=>yl(o.node,t)===n)}function Sr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function wo(e){let t=null;if(xg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Pt(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=bg(o),s={source:o,ast:i};return n.set(e,s),s}function ER(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 vR(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,u=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(u)||!B.isMemberExpression(u.callee)||!B.isIdentifier(u.callee.object,{name:"Reflect"})||!B.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!B.isIdentifier(u.arguments[0],{name:n.name})||!B.isIdentifier(u.arguments[1],{name:r.name})||!B.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function kR(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 kg(e,t){let n=kR(e.path);if(!n)return null;let r=lr(e,t);return r?{...n,...r}:null}function Ig(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function xl(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 bl(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 Cg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:R}=f,N=`${h}::${y.kind}::${y.identifier.name}`;if(R.has(N))return null;R.add(N);try{let T=await a({currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:R});if(T)return T;if(y.path.isImportSpecifier()||y.path.isImportDefaultSpecifier())return await m({currentFile:h,binding:y,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,fileCache:v,visited:R});if(y.kind==="param")return null;if(y.path.isVariableDeclarator()){let I=y.path.node.init;if(!I||!B.isExpression(I))return null;let P=vR(I);if(P&&!y.path.scope.getBinding("Proxy")&&!y.path.scope.getBinding("Reflect")){let W=y.path.scope.getBinding(P),z=W?await s({...f,binding:W}):null;if(z?.kind==="static"&&z.value!==null&&!Array.isArray(z.value)&&typeof z.value=="object")return z}let F=y.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let W=await t({currentFile:h,expressionPath:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});if(W)return W;if(F.isCallExpression()){let z=await n({currentFile:h,callPath:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});if(z)return z}}let L=await r(I,y.path.scope,h,E,x,v,R);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:L,sourceKind:"binding"}}if(y.path.isIdentifier()&&y.path.parentPath?.isExportDefaultDeclaration()){let I=y.path.parentPath.node.declaration;if(!B.isExpression(I))return null;let P=await r(I,y.path.scope,h,E,x,v,R);return P===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:P,sourceKind:"binding"}}return null}finally{R.delete(N)}}async function a(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:R}=f;if(!y.path.isVariableDeclarator()||!y.path.get("id").isArrayPattern())return null;let N=y.path,T=N.node.init;if(!T||!B.isCallExpression(T))return null;let I=ER(T);if(!I||!B.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(z=>B.isIdentifier(z)&&z.name===y.identifier.name)!==0)return null;let F=I==="useReducer"?1:0,L=T.arguments[F];if(!L||!B.isExpression(L))return null;let W=await r(L,N.scope,h,E,x,v,R);return W===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:y.identifier.name,hook:I},value:W,sourceKind:"binding"}}async function c(f){let h=f.expressionPath.scope.getBinding(f.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!f.graph)return null;let y=kg(h,f.sourceInfo);if(!y)return null;let E=[...f.graph.elements.values()].filter(v=>Ig(v,f.currentFile,y.componentName,y.exportName));if(!E.length)return null;let x=[];for(let v of E){if(v.sourceFile!==E[0].sourceFile||v.componentName!==E[0].componentName||v.attributeSpreads?.length)return null;let R=await Pt(v.sourceFile,f.readFile,f.fileCache),N=R.ast?bs(R.ast,v.sourceRange):null;if(!N)return null;let T=N.parentPath;for(;T&&!T.isFunction();){if(T.isJSXElement()){let he=T.node.openingElement.name;if(!B.isJSXIdentifier(he)||!/^[a-z]/.test(he.name))return null}else if(!T.isJSXFragment()&&!T.isReturnStatement()&&!T.isBlockStatement())return null;T=T.parentPath}if(!T)return null;let I=N.get("openingElement").get("attributes").filter(he=>he.isJSXAttribute()&&B.isJSXIdentifier(he.node.name,{name:y.propName}));if(I.length!==1)return null;let P=I[0];if(!P?.isJSXAttribute())return null;let F=P.get("value"),L=F.isJSXExpressionContainer()?F.get("expression"):F;if(!L.isExpression())return null;let W=await r(L.node,L.scope,v.sourceFile,f.readFile,f.exists,f.fileCache,f.visited),z=W===void 0?void 0:Ye(W,y.remainingPath);if(z===void 0)return null;x.push(z)}return x}async function l(f){let h=kg(f.binding,f.sourceInfo);if(!h||!f.graph)return null;let y=[...f.graph.elements.values()].filter(I=>Ig(I,f.currentFile,h.componentName,h.exportName));if(y.length!==1)return null;let E=y[0],x=E.attributes?.find(I=>I.name===h.propName);if(x&&!x.source){let I=await u({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,fileCache:f.fileCache});if(I)return xl(I,{componentName:h.componentName,propName:h.propName,file:E.sourceFile})}if(!x?.source){let I=await d({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(I)return xl(I,{componentName:h.componentName,propName:h.propName,file:E.sourceFile});let P=Ep(f.binding,h.componentName,h.propName);if(!P||P.propName!==h.propName)return null;let F=await r(P.expressionPath.node,P.expressionPath.scope,f.currentFile,f.readFile,f.exists,f.fileCache,f.visited);if(F===void 0)return null;let L=h.remainingPath;return L.length>0&&Ye(F,L)===void 0?null:{kind:"value",file:f.currentFile,root:{kind:"binding",name:h.propName},path:L,sourceKind:"binding",semanticKind:"component-prop",displayExpression:P.displayPath,chainPrefix:[{kind:"component-prop",file:f.currentFile,displayName:P.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await Pt(E.sourceFile,f.readFile,f.fileCache);if(!v.ast)return null;let R=vg(v.ast,v.source,x.source.expression,x.sourceRange)??Ro(v.ast,v.source,x.source.expression);if(!R)return null;let N={...x.source,expression:Sr(x.source.expression,h.remainingPath),path:[...x.source.path,...h.remainingPath]},T=await o({currentFile:E.sourceFile,expressionPath:R,sourceInfo:N,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});return T?xl(T.kind==="external"?T:{...T,displayExpression:N.expression},{componentName:h.componentName,propName:h.propName,file:E.sourceFile}):null}async function u(f){let h=await Pt(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=bs(h.ast,f.caller.sourceRange);if(!y)return null;let E=y.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===f.propName);if(!E?.isJSXAttribute())return null;let x=E.get("value"),v=x.isStringLiteral()?x:x.isJSXExpressionContainer()?x.get("expression"):null;if(!v?.isExpression())return null;let R=Co(v.node);return R?{kind:"value",file:f.caller.sourceFile,root:{kind:"expression",sourceRange:R},path:f.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:f.propName,editMode:"upstream",diagnostics:[]}:null}async function d(f){let h=await Pt(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=bs(h.ast,f.caller.sourceRange);if(!y)return null;let E=y.get("openingElement");for(let x of E.get("attributes")){if(!x.isJSXSpreadAttribute())continue;let v=x.get("argument");if(!v.isExpression())continue;let R=await i({expression:v.node,scope:v.scope,source:h.source,currentFile:f.caller.sourceFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!R)continue;let N=[{kind:"property",name:f.propName},...f.remainingPath],T={...R,expression:Sr(R.expression,N),path:[...R.path,...N]},I=await o({currentFile:f.caller.sourceFile,expressionPath:v,sourceInfo:T,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(I)return I.kind==="external"?I:{...I,displayExpression:T.expression}}return null}async function m(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:R}=f,N=y.path.parentPath;if(!N||!N.isImportDeclaration())return null;let T=N.node.source.value;if(typeof T!="string")return null;let I=await Sn(h,T,x);if(!I)return null;if(y.path.isImportDefaultSpecifier()){let he=await Pt(I,E,v),j=he.ast?bl(he.ast,"default"):null,G=await g({file:I,exportName:"default",readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});return!G||G.kind!=="static"?null:{kind:"static",file:j?.kind==="default-expression"?G.file:I,root:j?.kind==="default-expression"?G.root:{kind:"default-export"},value:G.value,sourceKind:"imported-binding"}}if(!y.path.isImportSpecifier())return null;let P=y.path.node.imported,F=B.isIdentifier(P)?P.name:P.value,L=await Pt(I,E,v),W=L.ast?bl(L.ast,F):null,z=await g({file:I,exportName:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});return z?z.kind==="external"?z:{kind:"static",file:W?.kind==="re-export"?z.file:I,root:W?.kind==="re-export"||z.root.kind==="binding"&&z.root.name!==W?.name?z.root:{kind:"named-export",name:F},value:z.value,sourceKind:"imported-binding"}:null}async function g(f){let{file:h,exportName:y,readFile:E,exists:x,fileCache:v,visited:R}=f,N=`export::${h}::${y}`;if(!R.has(N)){R.add(N);try{let T=await Pt(h,E,v);if(!T.ast)return;let I=bl(T.ast,y);if(!I)return;if(I.kind==="default-expression"){let W=I.expression;if(!W||!B.isIdentifier(W))return;let z=wo(T.ast).getBinding(W.name);return z?await s({currentFile:h,binding:z,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R})??void 0:void 0}if(I.kind==="re-export"){if(!I.source||!I.name)return;let W=await Sn(h,I.source,x);return W?g({...f,file:W,exportName:I.name}):void 0}let P=I.name;if(!P)return;let F=wo(T.ast).getBinding(P);return F?await s({currentFile:h,binding:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R})??void 0:void 0}finally{R.delete(N)}}}return{resolveExportValue:g,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as Z from"@babel/types";function El(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=wt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!IR(s,r)?null:{callPath:s,basePath:i}}function IR(e,t){let n=e.node.callee;return!Z.isMemberExpression(n)||!Z.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Pg(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Hi(r,t)}function Rg(e,t){return e?Z.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function wg(e,t,n,r,o){let i=Z.isExpression(e.body)?e.body:e.body.body.find(a=>Z.isReturnStatement(a))?.argument;if(!i||!Z.isExpression(i))return;let s=Sl(i,t,n,r,o);return typeof s=="number"?s:void 0}function Sl(e,t,n,r,o){if(Z.isNumericLiteral(e)||Z.isStringLiteral(e)||Z.isBooleanLiteral(e))return e.value;if(Z.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(Z.isMemberExpression(e)){let i=hs(e,t);if(i)return Ye(r,i);let s=hs(e,n);return s?Ye(o,s):void 0}if(Z.isBinaryExpression(e)&&e.operator==="-"){let i=Z.isExpression(e.left)?Sl(e.left,t,n,r,o):void 0,s=Z.isExpression(e.right)?Sl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function CR(e){if(Z.isExpression(e.body))return e.body;for(let t of e.body.body)if(Z.isReturnStatement(t)&&t.argument&&Z.isExpression(t.argument))return t.argument;return null}function RR(e,t,n){let r=$n(e,t,n);return typeof r=="boolean"?r:void 0}function $n(e,t,n){if(Z.isStringLiteral(e)||Z.isNumericLiteral(e)||Z.isBooleanLiteral(e))return e.value;if(Z.isNullLiteral(e))return null;if(Z.isIdentifier(e))return e.name===t?n:void 0;if(Z.isMemberExpression(e)){let r=hs(e,t);return r?Ye(n,r):void 0}if(Z.isUnaryExpression(e)&&e.operator==="!"){let r=$n(e.argument,t,n);return r===void 0?void 0:!r}if(Z.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(Z.isBinaryExpression(e)){let r=Z.isExpression(e.left)?$n(e.left,t,n):void 0,o=Z.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 Ag(e){let t=[],n=e;for(;Z.isMemberExpression(n)||Z.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(Z.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(Z.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(Z.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(Z.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return Z.isIdentifier(n)?{base:n.name,segments:t}:null}function Tg(e){return e.some(t=>t.kind==="dynamic")}function Ng(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Fg(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 wR(e,t){let n=[],r=[];for(let o of t){let i=Ye(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 _g(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(f){let{currentFile:h,callPath:y,readFile:E,exists:x,fileCache:v,visited:R}=f,N=y.node.callee;if(!Z.isMemberExpression(N)||!Z.isIdentifier(N.property)||N.property.name!=="map")return null;let T=y.get("callee");if(!T.isMemberExpression())return null;let I=T.get("object");if(Array.isArray(I)||!I.isExpression())return null;let P=await a({currentFile:h,expressionPath:I,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});return!P||!Array.isArray(P.value)||P.value.length===0?null:P}async function a(f){let{currentFile:h,expressionPath:y,readFile:E,exists:x,fileCache:v,visited:R}=f;if(y.isIdentifier()){let N=y.scope.getBinding(y.node.name);if(!N)return null;let T=await t({currentFile:h,binding:N,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});return T?.kind==="static"?T:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let N=y.get("expression");if(!Array.isArray(N)&&N.isExpression())return a({...f,expressionPath:N})}if(y.isArrayExpression()){let N=Co(y.node);if(!N)return null;let T=await n(y.node,y.scope,h,E,x,v,R);return Array.isArray(T)?{kind:"static",file:h,root:{kind:"expression",sourceRange:N},value:T,sourceKind:"binding"}:null}if(y.isMemberExpression()){let N=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:E,exists:x,fileCache:v,visited:R});if(!N)return null;let T=await o({currentFile:h,expressionPath:y,sourceInfo:N,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});if(!T||T.kind==="external")return null;let I=await c({currentFile:h,expressionPath:y,provenance:T,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:R});if(!I||I.kind!=="static")return null;if(T.collectionPathMap?.length){let F=wR(I.value,T.collectionPathMap);if(F)return{kind:"static",file:T.file,root:T.root,value:F.value,sourceKind:T.sourceKind,collectionPathMap:F.collectionPathMap}}let P=Ye(I.value,T.path);return Array.isArray(P)?{kind:"static",file:T.file,root:T.root,value:P,sourceKind:T.sourceKind,pathPrefix:T.path,collectionIndexMap:T.collectionIndexMap,collectionPathMap:T.collectionPathMap}:null}return null}async function c(f){let{provenance:h}=f;if(h.root.kind==="binding"){let v=f.expressionPath.scope.getBinding(h.root.name);if(!v&&h.file!==f.currentFile){let R=await Pt(h.file,f.readFile,f.fileCache);v=R.ast?wo(R.ast).getBinding(h.root.name):void 0}return v?await t({currentFile:h.file,binding:v,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited}):null}if(h.root.kind!=="expression")return null;let y=await Pt(h.file,f.readFile,f.fileCache);if(!y.ast)return null;let E=Sg(y.ast,h.root.sourceRange);if(!E)return null;let x=await n(E.node,E.scope,h.file,f.readFile,f.exists,f.fileCache,f.visited);return x===void 0?null:{kind:"static",file:h.file,root:h.root,value:x,sourceKind:h.sourceKind}}async function l(f){return await u(f)??await d(f)??await m(f)}async function u(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="filter")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[R]=h.node.arguments;if(!Z.isArrowFunctionExpression(R)&&!Z.isFunctionExpression(R))return null;let N=R.params[0];if(!Z.isIdentifier(N))return null;let T=CR(R);if(!T)return null;let I=[],P=[],F=[];for(let[L,W]of v.value.entries()){let z=RR(T,N.name,W);if(typeof z!="boolean")return null;if(z){I.push(W),P.push(v.collectionIndexMap?.[L]??L);let he=v.collectionPathMap?.[L];he&&F.push(he)}}return{...v,value:I,pathPrefix:v.pathPrefix,collectionIndexMap:P,...F.length>0?{collectionPathMap:F}:{}}}async function d(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="slice")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[R,N]=h.node.arguments,T=Rg(R,0),I=Rg(N,v.value.length);if(T===null||I===null)return null;let P=Math.max(0,T<0?v.value.length+T:T),F=Math.max(0,I<0?v.value.length+I:I),L=v.value.map((z,he)=>v.collectionIndexMap?.[he]??he).slice(P,F),W=v.collectionPathMap?.slice(P,F);return{...v,value:v.value.slice(P,F),pathPrefix:v.pathPrefix,collectionIndexMap:L,...W?{collectionPathMap:W}:{}}}async function m(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[R]=h.node.arguments;if(!Z.isArrowFunctionExpression(R)&&!Z.isFunctionExpression(R))return null;let[N,T]=R.params;if(!Z.isIdentifier(N)||!Z.isIdentifier(T))return null;let I=v.value.map((F,L)=>({value:F,sourceIndex:v.collectionIndexMap?.[L]??L,originalIndex:L})),P=[...I];for(let F of I)for(let L of I)if(wg(R,N.name,T.name,F.value,L.value)===void 0)return null;return P.sort((F,L)=>{let W=wg(R,N.name,T.name,F.value,L.value)??0;return W===0?F.originalIndex-L.originalIndex:W}),{...v,value:P.map(F=>F.value),pathPrefix:v.pathPrefix,collectionIndexMap:P.map(F=>F.sourceIndex),...v.collectionPathMap?{collectionPathMap:P.map(F=>v.collectionPathMap?.[F.originalIndex]).filter(F=>!!F)}:{}}}async function g(f){let h=null,y=!1,E,x=[];for(let R of f.segments){if(R.kind!=="dynamic")continue;let N=await r({expression:R.expression,scope:f.expressionPath.scope,source:f.fileCache.get(f.currentFile)?.source,currentFile:f.currentFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!N)return null;let T=El(f.expressionPath,N.base),I;if(T){y=!0;let P=await s({currentFile:f.currentFile,callPath:T.callPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!P||!Array.isArray(P.value))return null;I=P.value.map((F,L)=>{let W=Ye(P.value,[{kind:"index",index:L},...T.basePath,...N.path]);return Ng(W)}),E??=P.collectionIndexMap}else{let P=await i({...f,sourceInfo:N});if(!P)return null;I=P.map(Ng)}if(I.some(P=>P===null)||h!==null&&h!==I.length)return null;h=I.length,x.push(I)}if(h===null||h===0)return null;let v=[];for(let R=0;R<h;R+=1){let N=[...f.rootPath],T=0;for(let I of f.segments){if(I.kind==="dynamic"){let P=x[T]?.[R];if(!P)return null;N.push(P),T+=1;continue}N.push({...I})}v.push(N)}return{sourceKind:y||h>1?"repeat-template":"binding",...E?{collectionIndexMap:E}:{},collectionPathMap:v}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:NR,evaluateStaticExpression:Ss}=pg({resolveBindingTarget:e=>Es(e)}),{resolveRepeatCollectionTarget:PR,resolveCollectionCallTarget:AR,resolveDynamicMemberPathMap:TR}=_g({resolveBindingTarget:e=>Es(e),evaluateStaticExpression:Ss,buildExpressionSourceInfo:Jt,resolveSourceInfoProvenance:vt,resolveComponentPropValues:e=>MR(e)}),{resolveExportValue:FR,resolveComponentPropBinding:_R,resolveComponentPropValues:MR,resolveBindingTarget:Es}=Cg({resolveExternalExpression:Nl,resolveCollectionCallTarget:AR,evaluateStaticExpression:Ss,resolveSourceInfoProvenance:vt,buildExpressionSourceInfo:Jt});function Kg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Mg=new WeakMap;function OR(e){let t=Mg.get(e);return t||(t=new WeakMap,Mg.set(e,t)),t}function Og(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 Ug(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=ys(s,t,n);if(!a)return null;let c=xs(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 Fl({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?Il(m,br(c.node,n)):null}let u=new Set,d=await rw({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:u});return d?Il(d,l.expression):null}async function Er(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ys(i,t,n);if(!s)return null;let a=e.sourceRange?xs(s,e.sourceRange):e.expression!==void 0?Ro(s,n,e.expression):null;if(!a)return null;let c=vs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Jt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await vt({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await Zg({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 Il(d,e.expression??br(c.node,n))}async function wl(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=ys(i,t,n);if(!s)return pt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?LR({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}):DR({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(te.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!te.isMemberExpression(e.expression))return null;let t=await NR(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:br(e.expression,e.source),base:t.base,path:t.path}:null}function Il(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 LR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=xs(r,o.sourceRange),u=l?await Jt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return Lg(t,o.value);let m=await Fl({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"?Vg(t,m):Rl(t,br(l.node,n),m):BR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return pt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await vt({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let m=Cl(l.node);if(m)return pt(m.code,m.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let f=Cl(g.path.node.init);if(f)return pt(f.code,f.message)}return g?.path.isVariableDeclarator()&&te.isCallExpression(g.path.node.init)?jR("unsupported-expression",Hg(g.path.node.init,e.functionCallContracts)):pt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Vg(t,d):Rl(t,u.expression,d)}async function DR(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ro(r,n,o.conditionExpression);if(!l)return pt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await vt({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(!u)return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Rl(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function Lg(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 BR(e){let t=await Xg(e);if(t.length===0)return pt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if($R(e.expression))return Jg(t);if(Wg(e.expression))return pt("unsupported-expression","i18n helpers require a static message id string");if(te.isMemberExpression(e.expression)&&e.expression.computed&&!te.isNumericLiteral(e.expression.property)&&!te.isStringLiteral(e.expression.property))return pt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return pt(n.code,n.message)}function pt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function jR(e,t){return Jg([{code:e,message:t}])}function Jg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function $R(e){return te.isCallExpression(e)||te.isConditionalExpression(e)||te.isLogicalExpression(e)||te.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 Xg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Cl(t);if(l)return[l];if(te.isCallExpression(t))return[{code:"unsupported-expression",message:Hg(t,c)}];if(te.isMemberExpression(t)&&t.computed){let u=t.property;if(!te.isNumericLiteral(u)&&!te.isStringLiteral(u)){if(!te.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await Ss(u,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 te.isBinaryExpression(t)?Po([...await vl(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):te.isLogicalExpression(t)?Po([...await vl(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"}]):te.isConditionalExpression(t)?Po([...await vl(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 Cl(e){return Wg(e)?Dg("i18n helpers require a static message id string"):XR(e)?Dg("CMS helpers require static entry id and field path string arguments"):null}async function vl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Xg({...t,expression:o}));return r}function VR(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:[KR(e.sourceType)]}}async function Nl(e){for(let n of GR){if(!Bg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return $g(jg(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(!Bg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return $g(jg(r),e.externalAdapters)}return null}function KR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function UR(e){return{code:"external-source-readonly",message:e}}function Dg(e){return{code:"unsupported-expression",message:e}}function Pl(e){return!e||!te.isCallExpression(e)?null:te.isIdentifier(e.callee)?e.callee.name:te.isMemberExpression(e.callee)&&!e.callee.computed&&te.isIdentifier(e.callee.object)&&te.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Bg(e,t){if(!t||t.length===0)return!0;let n=Pl(e.node);return n?t.includes(n):!1}function jg(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Po(e.diagnostics??[])}:{match:e,diagnostics:[]}}function $g(e,t){let n=VR(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 JR(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!te.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!te.isStringLiteral(n)||!te.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 XR(e){return!!e&&te.isCallExpression(e)&&te.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!te.isStringLiteral(e.arguments[0])||!te.isStringLiteral(e.arguments[1]))}function zg(e){if(!(!e||!te.isCallExpression(e))){if(te.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&te.isStringLiteral(t)?t.value:null}if(te.isMemberExpression(e.callee)&&!e.callee.computed&&te.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&te.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!te.isObjectExpression(t))return null;for(let n of t.properties)if(te.isObjectProperty(n)&&!n.computed&&(te.isIdentifier(n.key)&&n.key.name==="id"||te.isStringLiteral(n.key)&&n.key.value==="id")&&te.isStringLiteral(n.value))return n.value.value;return null}}}function Wg(e){return zg(e)===null}async function zR(e,t,n){let r=new Set,o=No.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=No.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"]:[No.posix.join(i,"locales"),No.posix.join(i,"messages")];for(let a of s){let c=No.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function WR(e){let t=zg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await zR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function HR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!te.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!te.isExpression(n))return null;let o=await Ss(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:[UR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var GR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>JR(e)},{helperNames:["apiField"],resolve:e=>HR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>WR({currentFile:e,expressionPath:t,exists:n})}];function Al(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Vg(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 Rl(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=nw(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 YR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Tl(e,t){let n=[...YR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Hg(e,t){let n=e.callee;return te.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 Fl(e){let t=await Nl(e);if(t)return t;let n=await Gg({...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 vt({...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 ew(e)}async function Gg(e){let t=await At({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=vs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Al(t.provenance)}async function At(e){let t=vs(e.expressionPath),n=qR(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 vt({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 vt({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 At({...e,expressionPath:r,allowComposed:!0}),a=await At({...e,expressionPath:o,allowComposed:!1}),c=await At({...e,expressionPath:i,allowComposed:!1});return kl(s,a,c)}if(t.isCallExpression())return ZR({...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 At({...e,expressionPath:r,allowComposed:!0}),s=await At({...e,expressionPath:o,allowComposed:!0});return kl(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 At({...e,expressionPath:r,allowComposed:!0}),s=await At({...e,expressionPath:o,allowComposed:!0});return kl(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:At({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function vs(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 ZR(e){let t=Pl(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:At({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(te.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:At({...e,expressionPath:o,allowComposed:!1})}}return null}function kl(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!QR(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function QR(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 qR(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function ew(e){if(!e.expressionPath.isCallExpression())return null;let t=Pl(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 Yg({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?Al(i):null}async function Yg(e){let t=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});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 vt({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 Fl({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 tw(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!te.isCallExpression(t))return null;let n=t.callee;if(!te.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 Yg({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?Al(a):null}function nw(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=Sr(t,e.path);return{sourceId:o,displayPath:o}}async function rw(e){let t=e.segment.source;return t?vt({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 vt(e){let t=e.sourceInfo,n=El(e.expressionPath,t.base);if(n){let l=await PR({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=Pg(n.callPath,[...n.basePath,...t.path]);return co(h)?Og(e.currentFile,h.sourceId,h.displayPath):null}let u=Fg(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Ye(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await Sn(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let m=await FR({file:d,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 g=t.path.slice(1);return Ye(m.value,g)===void 0?null:{kind:"value",file:m.file,root:m.root,path:g,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=bp(r);if(o){let l=o.expressionPath,u=await Jt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await vt({...e,expressionPath:l,sourceInfo:{...u,expression:Sr(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let m=await Zg({...e,expressionPath:vs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await Gg({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(d)return d}}if(r.kind==="param")return _R({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 tw({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=zi(r,t.path,OR(e.fileCache));if(co(s))return Og(e.currentFile,s.sourceId,s.displayPath);let a=await Es({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:Ye(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 Zg(e){let t=Ag(e.expressionPath.node);if(!t||!Tg(t.segments))return null;let n=await vt({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 TR({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await Es({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Ye(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:br(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Qg(e){let t=ow(e.propertyName);if(t.owner==="blocked")return yn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return yn(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 yn("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 sw(e,l)});o.sort((l,u)=>l.order-u.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 yn("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}:yn("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?yn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):iw(e,s.attribute)}async function iw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Er({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}}:yn("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 Er({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"?yn("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 sw(e,t){let n=t.source?.expression;if(!n)return;let r=await Er({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:aw(r,e.propertyName)}}function aw(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 yn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function qg(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(Vn(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>dw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>cw({...r,graph:e},n)}function cw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=uw(n,r,o,t),a=s?.tag??(Vn(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=pw(s),u=mw(n,r,o,i,s),d=lw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:fw(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:gw(d),alternativeStrategies:hw(d)}}function lw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return _l(e,n)?"instance":!Vn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function uw(e,t,n,r){if(Vn(t.tag))return t;let o=_l(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function dw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function fw(e,t){return Vn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function pw(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 mw(e,t,n,r,o){let i=new Set,s=_l(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Vn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function _l(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Vn(r.tag))return r;n=r.parentKey}return null}function Vn(e){return/^[A-Z]/.test(e)}function gw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function hw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function nh(e){let t=e.isRepeat??(e.graph?Cw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=Iw(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>yw({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:Rw(u.sourceRange,e.source),order:u.order,diagnostics:u.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 yw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=xw(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:ts({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.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,u=bw(t,n,l,e.isRepeat),d=c?vw(c,e.element,t.name):void 0,m=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=m.length>0?Ew(n,o,e.element):"unsupported",f=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=kw(t,n,r);if(m.length===0&&h.length===0){let y=s.find(({result:E})=>!E.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:f,allowedWriteScopes:m,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function xw(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 bw(e,t,n,r){return n?eh(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:eh(Sw(e))}function Sw(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 eh(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function Ew(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 vw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:th({...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:th(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function kw(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 Iw(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Cw(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 th(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 Rw(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 ww(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Nw=160;function rh(e,t,n,r={}){let o=nr(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 oh(e,t,n,r,o,i,s,a,c,l,u){let d=nr(t),m=t.elements.get(e),g=n.nodes.get(e),f=r.get(e);if(!m||!g||!f)throw new Error(`Node not found: ${e}`);let h=lh(m.textSegments,s),y=uh(e,t,m,f,h),E=h?Fw(h):void 0,x=_w(i,h),v=m.textSegments.map(I=>({index:I.index,value:I.value,editable:dh(I,f,s?.get(I.index)??null),source:o.get(I.index)??null})),R=ah(m,t),N=m.childKeys.map(I=>{let P=t.elements.get(I);return P?{key:I,tag:P.tag,label:P.tag}:null}).filter(I=>I!==null),T=[];if(m.parentKey){let I=t.elements.get(m.parentKey);if(I)for(let P of I.childKeys){if(P===e)continue;let F=t.elements.get(P);F&&T.push({key:P,tag:F.tag,label:F.tag})}}return{composition:d,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:sh(m),label:m.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:x,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:R,children:N,siblings:T}}function ih(e,t,n,r,o,i,s,a){let c=nr(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let m=lh(l.textSegments,i),g=Pw(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:sh(l),label:l.tag,capabilities:uh(e,t,l,d,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(f=>({code:f.code,message:f.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(f=>{let h=o.get(f.index);return{index:f.index,editable:dh(f,d,i?.get(f.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:ah(l,t)}}function Pw(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function sh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:Aw(e.sourceRange),structuralPath:e.identity.structuralPath,...Tw(e.textSegments)}}function ah(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 Aw(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Tw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Nw)}:{}}function ch(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 lh(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function uh(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.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&&fh(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 dh(e,t,n){return!e.editable||!t.canUpdateText?!1:n?fh(n.editMode):!0}function fh(e){return e==="direct"||e==="proxy"||e==="upstream"}function Fw(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 _w(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}:ww(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 Ml=["set-class-name-source","apply-style-draft"];function ph(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Ml,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:Ml,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Ml}}function mh(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}),gh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function gh(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}),gh(s,t,n,r,o))}}import hh from"node:path";function Ll(){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 xh(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=Dw(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 ks(e){let t=()=>Mw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Mw(e){let t=await xh(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Ow(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 Ol({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 Ol({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 Ol({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 yh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return yh("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 Ow(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 Ol(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:Lw(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 yh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function Lw(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 Dw(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)||hh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=hh.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 Bw=50,jw=8*1024*1024;function vh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Bw),s=Math.max(0,t.maxUndoBytes??jw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(I){let P=[...I.steps].sort((j,G)=>j.order-G.order),F=P.filter(j=>j.type!=="invoke-external-adapter");if(F.length!==P.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(F.map(j=>j.file)),W=await x(L),z=new Map(W.map(j=>[j.file,j.exists===!1?"":j.content])),he;for(let j of F){let G=Eh(j,z.get(j.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};z.set(j.file,G.source),he=G.selectionRef??he}return{ok:!0,filePlan:{operationId:I.operationId,kind:"source-edit",target:I.target,documentVersion:I.documentVersion,conflictPolicy:"compare-and-swap",edits:[...z].map(([j,G])=>({operation:"upsert",file:j,content:G,baseContentHash:W.find(pe=>pe.file===j)?.sha256??null}))},...he?{selectionRef:he}:{}}}async function c(I){let P=[...I.steps].sort((pe,st)=>pe.order-st.order),F=P.filter(pe=>pe.type!=="invoke-external-adapter"),L=P.filter(pe=>pe.type==="invoke-external-adapter"),W=new Set(F.map(pe=>pe.file));if(F.length>0&&L.length>0)return{ok:!1,operationId:I.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 y(I,L);let z=await x(W),he=new Map;for(let pe of z)he.set(pe.file,pe.exists===!1?"":pe.content);let j;for(let pe of F){let st=he.get(pe.file)??"",tt=Eh(pe,st);if(!tt.ok)return{ok:!1,operationId:I.operationId,errorCode:tt.errorCode,reason:tt.reason,rolledBack:!1};he.set(pe.file,tt.source),tt.selectionRef&&(j=tt.selectionRef)}let G=await R([...he].map(([pe,st])=>({file:pe,content:st,exists:!0,version:0,sha256:Ce(st)})),z);return G.ok===!1?{ok:!1,operationId:I.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:z,postSnapshots:G.snapshots,plan:I}),m(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...G.snapshots.map(pe=>pe.version)),affectedFiles:[...W],...j?{selectionRef:j}:{}})}async function l(I){let P=new Set(I.edits.map(G=>G.file)),F=await x(P),L=E(I,F);if(L)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let W=new Map(F.map(G=>[G.file,G])),z=I.edits.find(G=>G.operation==="create-only"&&W.get(G.file)?.exists!==!1);if(z)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${z.file}`,affectedFiles:[z.file],rolledBack:!1};let he=I.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:Ce(G.content)}),j=await R(he,F,new Set(I.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return j.ok===!1?{ok:!1,operationId:I.operationId,errorCode:j.rolledBack?"writeback-failed":"rollback-failed",reason:j.reason,rolledBack:j.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:F,postSnapshots:j.snapshots,plan:{operationId:I.operationId,kind:I.kind,target:I.target,documentVersion:I.documentVersion,steps:[],preSnapshots:F}}),m(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...j.snapshots.map(G=>G.version)),affectedFiles:[...P]})}async function u(){let I=n.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let P=await R(I.preSnapshots,I.postSnapshots);return P.ok===!1?{ok:!1,operationId:I.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(n.pop(),r.push(I),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...P.snapshots.map(F=>F.version)),affectedFiles:I.preSnapshots.map(F=>F.file)})}async function d(){let I=r.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let P=await R(I.postSnapshots,I.preSnapshots);return P.ok===!1?{ok:!1,operationId:I.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(r.pop(),n.push(I),m(),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...P.snapshots.map(F=>F.version)),affectedFiles:I.postSnapshots.map(F=>F.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((I,P)=>I+f(P),0)}function f(I){return h(I.preSnapshots)+h(I.postSnapshots)}function h(I){return I.reduce((P,F)=>P+F.file.length+F.content.length,0)}async function y(I,P){let F=[];for(let L of P){let W=L.capability??"write-text",z=o.find(j=>j.sourceType===L.sourceType&&(L.adapterId===void 0||j.adapterId===L.adapterId)&&(j.capabilities===void 0||j.capabilities.includes(W)));if(!z)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let he=await z.execute(L);if(!he.ok)return{ok:!1,operationId:I.operationId,errorCode:"writeback-failed",reason:he.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};F.push(L.file)}return{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:0,affectedFiles:F}}function E(I,P){if(I.conflictPolicy!=="compare-and-swap")return null;let F=new Map(P.map(L=>[L.file,L]));for(let L of I.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let W=F.get(L.file),z=L.baseContentHash;if(z===null){if(W?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!z)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(W?.exists===!1||W?.sha256!==z)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function x(I){let P=[];for(let F of I)P.push(await v(F));return P}async function v(I){if(!await e.exists(I))return{file:I,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(I)),L=await e.readFile(I);return{file:I,content:L,version:F,exists:!0,sha256:Ce(L)}}async function R(I,P,F=new Set){let L=[];try{for(let W of I){if(F.has(W.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(W.file,W.content)}else await N(W);let z=e.bumpVersion(W.file);L.push(W.file),W.version=z}}catch(W){let z=await T(P.filter(j=>L.includes(j.file)));if(z.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${z.failedFiles.join(", ")}: ${Sh(W)}`,rolledBack:!1,instanceConflict:bh(W)};let he=bh(W);return{ok:!1,reason:`${he?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Sh(W)}`,rolledBack:!0,instanceConflict:he}}return{ok:!0,snapshots:I.map($w)}}async function N(I){if(I.exists===!1){await e.deleteFile(I.file);return}await e.writeFile(I.file,I.content)}async function T(I){let P=[];for(let F of I)try{await N(F),e.bumpVersion(F.file)}catch{P.push(F.file)}return P.length===0?{ok:!0}:{ok:!1,failedFiles:P}}}function bh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function $w(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ce(e.content)}:{}}}function Sh(e){return e instanceof Error?e.message:String(e)}function Eh(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(er({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(tr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Yn({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(ti({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(Or({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(Or({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(ci({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(ri({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(li({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(ui({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(Qn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(oi({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 Vw(e,t);case"set-property-changes":return We(ii({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(si({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(ai({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(fi({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Vw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!bd(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!==Ce(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:xd({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 Is,SiteEditCompositionContextSchema as Kw,SiteEditCompositionSelectorSchema as Uw}from"@vcp-dev/contracts";var Ze=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function kh(e,t){throw new Ze("INVALID_COMPOSITION",e,{value:t})}function Cs(e){let t=Kw.safeParse(e);return t.success?t.data:kh("Invalid SiteEditCompositionContext.",e)}function Ih(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Cs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Is(u);if(n.has(d))throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let m=r.get(l.entryFile);if(m)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new Ze("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Cs(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ze("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Is(u);if(!n.has(d))throw new Ze("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Ze("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=Uw.safeParse(l);if(!u.success)return kh("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Ze("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ze("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Cs(l),d=Is(u),m=n.get(d);if(!m)throw new Ze("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return m}function a(l){let u=Cs(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Is(u),m=n.get(d);if(m){if(m.entryFile===l.entryFile)return m;throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(h=>h.entryFile===l.entryFile);if(g)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let f={context:u,entryFile:l.entryFile,key:d};return t.push(f),n.set(d,f),f}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(m=>m.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}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))]}}function Dl(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function Ch(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as Jw,stripSiteEditRepeatInstanceKeys as Rh}from"@vcp-dev/contracts";function wh(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Rh(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 Xw(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 Rs(e){return e?.map(t=>({...t}))}function Bl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Rs(e.collectionPathMap?.[t])??Rs(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:Rs(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Rs(o)??[])}}function Nh(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let f of g.childKeys)r.add(f);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,f)=>Jw(g,f),c=(g,f,h)=>{let y=o.get(g);if(!y)return a(g,h);let E=a(g,h),x={...y,key:E,parentKey:f,childKeys:[]};return i.push(x),x.childKeys=y.childKeys.flatMap(v=>l(v,h,E)),E},l=(g,f,h)=>{if(!r.has(g))return[c(g,h,f)];let y=d(g,f),E=[];for(let x=0;x<y;x+=1)E.push(c(g,h,[...f,x]));return E},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let f=d(g,[]);for(let h=0;h<f;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,f){let h=new Set;for(let y of m(g)){let E=n.get(y);if(E){for(let x of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(x?.kind!=="value-binding"||x.sourceKind!=="repeat-template"))for(let v of zw(x))v.length<=f.length||Ww(v,f)&&h.add(v[f.length])}}return h.size>0?h.size:Xw(n.get(g))}function m(g){let f=s.get(g);if(f)return f;let h=[g],y=o.get(g);for(let E of y?.childKeys??[])h.push(...m(E));return s.set(g,h),h}}function Ph(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Ah(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((Rh(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function zw(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 Ww(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 Th(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Fh(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 _h(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Hw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var Ao=class extends Error{constructor(t){let n=t.map(_h);super(Hw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Mh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof Ao?{routeId:e,message:n,diagnostics:t.diagnostics.map(_h)}:{routeId:e,message:n}}function jl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function $l(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function vr(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Oh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Vl(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 Lh(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),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 nN=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,rN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Dh=32,Kl=256;function oN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Bh={maxEntries:50,maxBytes:8*1024*1024};function iN(){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 mi(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}}}async function sN(e,t){if(t.length===0)return[];let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return[]}if(!n||typeof n!="object")return[];let r=n.dependencies;return!r||typeof r!="object"||Array.isArray(r)?[]:t.filter(o=>{if(!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];return typeof i=="string"&&i.trim().length>0})}function aN(){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>Bh.maxEntries||cN(e)>Bh.maxBytes;)e.shift()}}function cN(e){return e.reduce((t,n)=>t+lN(n),0)}function lN(e){return jh(e.preSnapshots)+jh(e.postSnapshots)+uN(e.provenance)}function uN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function jh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function $h(e,t){return{key:Yw(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 Ns=class extends Error{constructor(t){super(t.reason),this.result=t}},Kn=class extends Error{constructor(t){super(jl(t)),this.failedRoutes=t}};function Vh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=it(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(it(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function dN(e,t,n){if(!n)return;let r=it(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 fN=/\.(?:[cm]?[jt]sx?)$/i,pN=/\.json$/i,mN=/\.(?:css|scss|sass)$/i,gN=/\.mdx$/i,hN=/\.ya?ml$/i;function yN(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 xN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function bN(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},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(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=Wh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(SN(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function SN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Wh(e){return Array.isArray(e)?{files:e}:e}function EN(e){if(!Qw(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!==eN||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=Zw(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(fN.test(e.path)){let t=Ft({source:e.content,profile:vn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(pN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${qe(t)}`,details:{path:e.path}}}if(mN.test(e.path)){let t=Kh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(gN.test(e.path)){let t=Kh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(hN.test(e.path))try{tN(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function Kh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let m=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let f=e.indexOf(`
|
|
1
|
+
import*as Iy from"@babel/parser";import*as He from"@babel/types";import*as tn from"node:path";var Js=[".tsx",".ts",".jsx",".js"],Cy=Js.map(e=>`/index${e}`),Ry=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 yu(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Ry.has(n[1].toLowerCase())}function xu(e){let t=[];for(let n of e.program.body)He.isImportDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),He.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value),He.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&kt(n.source.value)&&t.push(n.source.value);return He.traverseFast(e.program,n=>{let r=He.isImportExpression(n)?n.source:He.isCallExpression(n)&&He.isImport(n.callee)?n.arguments[0]:null;He.isStringLiteral(r)&&kt(r.value)&&t.push(r.value)}),t}function kt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Sn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=tn.dirname(e);return tn.join(n,t).replace(/\\/g,"/")}async function wy(e,t){if(Js.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Js){let r=`${e}${n}`;if(await t(r))return r}for(let n of Cy){let r=`${e}${n}`;if(await t(r))return r}return null}async function En(e,t,n){let r=await Do(e,t,n);return r.ok?r.path:null}async function Do(e,t,n){let r=Sn(e,t);try{if(!Ny(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 wy(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 Ny(e,t,n){if(!kt(t)||t.includes("\0")||t.includes("\\")||tn.posix.isAbsolute(n))return!1;let r=tn.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!tn.posix.isAbsolute(e)}import{createHash as Ay}from"node:crypto";import*as bu from"@babel/parser";function vn(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:vn(t,n,r,o)}}function Xs(e,t,n,r,o){return{ok:!1,source:e,diagnostic:vn(t,n,r,o)}}var Py={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function _t(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:bu.parse(t,{sourceType:"module",plugins:Py[n]})}}catch(r){return{ok:!1,source:t,diagnostic:vn("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function zs(e,t){return _t({source:e,profile:Su(t.kind)})}function wr(e,t){return _t({source:e,profile:Su(t)})}function Su(e){return"next-app-entry"}function kn(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 Xt=(e,t)=>{let n=_t({source:t,profile:kn({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Ay("sha256").update(t).digest("hex")}`,ast:n.ast,imports:xu(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function Ty(e,t){return Xt(e,t)}function Fy(e,t){return Sn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as _y,parseComponentI18nResourcesJson as My,resolveSiteTextDirection as Oy,SiteLocaleSchema as Ly}from"@vcp-dev/contracts";var Dy=["i18next","react-i18next"],By="components/ui/site-locale-provider.tsx",jy="components/ui/component-i18n-provider.tsx",Eu="app/layout.tsx";async function Bo(e){let t=e.files.filter(m=>m.path.endsWith(_y));if(t.length===0)return{ok:!0};for(let m of["package.json",Eu,By,jy])if(!await e.exists(m))return nn(`Target snapshot is missing required i18n host file: ${m}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return nn("Target snapshot package.json is invalid.")}let r=vu(n)&&vu(n.dependencies)?n.dependencies:{},o=Dy.filter(m=>typeof r[m]!="string"||r[m].trim().length===0);if(o.length>0)return nn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(Eu),s=Ws(i,"html","lang"),a=Ws(i,"html","dir"),c=Ws(i,"SiteLocaleProvider","locale"),l=Ly.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Oy(l.data))return nn("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 nn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return nn("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let m of t){let g=My(m.content);if(!g.success)return nn(`Component i18n resource is invalid: ${m.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return nn(`Component i18n resource ${m.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Ws(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 vu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nn(e){return{ok:!1,message:e}}import Gs from"@babel/generator";import*as Nu from"@babel/parser";import Ys from"@babel/traverse";import*as we from"@babel/types";import{computeSiteEditSourceIdentityKey as Vy}from"@vcp-dev/contracts";var ku="data-vcp-ui-component",jo="components/ui";function zt(e){if(!e)return!1;let t=Hs(e);return t===jo||t.startsWith(`${jo}/`)||t.includes(`/${jo}/`)||t.endsWith(`/${jo}`)}function In(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?zt(e.slice(2)):e.startsWith("./")||e.startsWith("../")?zt(Hs(`${$y(t)}/${e}`)):zt(e):!1}function Hs(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 $y(e){let t=Hs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as fP}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as mP,isSiteEditRuntimeTextTag as gP}from"@vcp-dev/contracts/site-edit-runtime-capability";var Iu={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 Ky=typeof Gs=="function"?Gs:Gs.default,Uy=typeof Ys=="function"?Ys:Ys.default,Jy=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Xy="suppressHydrationWarning",zy=new Set(["SiteEditBootstrap"]);function Wy(e){let t=Yy(e.file,e.projectRoot);if(!Gy(e.source)||zt(t))return{code:e.source,elements:[]};let n=e.attributes??Iu,r=Nu.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Qy(r,t);return Uy(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!ex(c)||Pu(a,n.key))return;let l=nx(s)??"default",u=ox(s),d=Vy(t,l,u),m=Vo(c)??"unknown",g=Zy(c)?"jsx":"component-call";if(g==="component-call"&&!rx(s.node.children)&&zy.has(m))return;let f=g==="component-call"&&qy(m,i);tx(a,n.key,d),f&&Cu(a,ku),Hy(s)&&Cu(a,Xy),o.push({key:d,tag:m,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Ky(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Hy(e){return!e.findParent(t=>t.isJSXElement())}function Gy(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function Yy(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 Zy(e){return we.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Vo(e){return we.isJSXIdentifier(e)?e.name:we.isJSXMemberExpression(e)?Tu(e):null}function Qy(e,t){let n=new Set;for(let r of e.program.body)if(!(!we.isImportDeclaration(r)||!In(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function qy(e,t){let n=e.split(".")[0]??e;return t.has(n)}function ex(e){let t=Vo(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Jy.has(t)}function Pu(e,t){return e.attributes.some(n=>we.isJSXAttribute(n)&&we.isJSXIdentifier(n.name,{name:t}))}function tx(e,t,n){Au(e,we.jsxAttribute(we.jsxIdentifier(t),we.stringLiteral(n)))}function Cu(e,t){Pu(e,t)||Au(e,we.jsxAttribute(we.jsxIdentifier(t),null))}function Au(e,t){let n=e.attributes.findIndex(r=>we.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Tu(e){return`${we.isJSXIdentifier(e.object)?e.object.name:Tu(e.object)}.${e.property.name}`}function nx(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&we.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 rx(e){return e.some(t=>we.isJSXElement(t)||we.isJSXFragment(t))}var Ru=new WeakMap,$o=new WeakMap,Zs=new WeakMap;function ox(e){let t=Ru.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=ix(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Ru.set(e.node,o),o}function ix(e){let t=Vo(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${wu(e,t)}`:`${t}#${wu(e,t)}`}function wu(e,t){let n=Fu(e)??e.getFunctionParent();if(!n)return 0;let r=Zs.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Zs.get(n.node);o||(o=new Map,Zs.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()?Ko(n):sx(n);for(let c of a)if(Vo(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 sx(e){let t=$o.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Fu(r)&&n.push(r)}}),$o.set(e.node,n),n}function Fu(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 Ko(e){let t=$o.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(...Ko(o));continue}o.isJSXExpressionContainer()&&n.push(...Cn(o.get("expression")))}return $o.set(e.node,n),n}function Cn(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Ko(e);if(e.isParenthesizedExpression())return Cn(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Cn(e.get("right"));if(e.isConditionalExpression())return[...Cn(e.get("consequent")),...Cn(e.get("alternate"))];if(e.isCallExpression()&&cx(e.node)){let t=e.get("arguments")[0];return ax(t)}return[]}function ax(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Ko(t);if(t.isParenthesizedExpression())return Cn(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?Cn(r):[]}return[]}function cx(e){return we.isMemberExpression(e.callee)&&we.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as KN,SiteEditPatchPlanSchema as UN}from"@vcp-dev/contracts";function Rn(e){return{requestId:e.requestId,kind:e.kind,composition:e.composition,target:e.target,resultVersion:e.resultVersion,affectedFiles:e.affectedFiles,...e.fileChanges?{fileChanges:e.fileChanges}:{},...e.output?{output:e.output}:{},...e.selectionRef?{selectionRef:e.selectionRef}:{}}}function Uo(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 Jo(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 Xo(e){return{composition:e.composition,key:e.key,tag:e.tag,...e.linkSourceKind?{linkSourceKind:e.linkSourceKind}:{},label:e.label,sourceLocator:e.sourceLocator,isOpaque:e.isOpaque,ancestors:e.ancestors,componentName:e.componentName,sourceFile:e.sourceFile,capabilities:lx(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 zo(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:Rn(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 lx(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 Qw,computeSiteEditCompositionKey as qw,getSiteEditSourceDeleteProtectionReason as eN,isSiteEditTextSourcePath as tN,parseSiteEditRepeatInstanceKey as nN,SITE_EDIT_SOURCE_DELETE_CAPABILITY as rN,stripSiteEditRepeatInstanceKeys as it}from"@vcp-dev/contracts";import As from"node:path";import{parse as oN}from"yaml";import na from"node:path";import{TextDecoder as dx}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Mu,SITE_EDIT_SOURCE_ALLOWED_DIRS as Ou,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Lu,SiteEditCompositionContextSchema as fx,SiteEditSourceFileResponseSchema as Qs,SiteEditSourceLocationSchema as px,SiteEditSourcePathSchema as Wo,SiteEditSourceTreeResponseSchema as mx,isSiteEditTextSourcePath as gx}from"@vcp-dev/contracts";import{createHash as ux}from"node:crypto";var Nr=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 Ce(e){return`sha256:${ux("sha256").update(e).digest("hex")}`}var hx=[...Lu,...Mu,...Ou];function ra(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return fx.parse(e.composition)}var qs=2e3,ea=12,ta=24*1024*1024,_u=512*1024,yx=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),xx={".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"},bx={".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"},Sx=new dx("utf-8",{fatal:!0});async function Ho(e,t={}){let n=ra(t),{files:r,truncated:o}=await wx(e,t),i=Ax(r.map(s=>s.metadata));return mx.parse({composition:n,nodes:i,defaultPath:Tx(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Go(e,t,n={}){let r=ra(n),o=Wo.parse(t.path),i=await vx(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(ia(o)){let a=ju(o),c=await Ix(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Qs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await oa(e,o);return s.ok?Qs.parse({composition:r,path:o,kind:"text",language:$u(o),sizeBytes:s.sizeBytes,contentHash:Ce(s.content),readonly:!1,content:s.content}):Qs.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function oa(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Ex(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 Ex(e){if(e.includes(0))return null;try{return Sx.decode(e)}catch{return null}}async function vx(e,t,n){if(!Cx(t,n))return null;let r=await kx(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function kx(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Du(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(ia(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Ix(e,t){if(!yx.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>_u)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>_u?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Cx(e,t){return Lu.some(n=>n===e)||Mu.some(n=>n===e)||Ou.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Wo.safeParse(n);return r.success&&r.data===e})}function Yo(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return px.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 Du(e){return Array.isArray(e)?{files:e}:e}function Rx(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function wx(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Du(await e.listFiles({roots:Nx(t),maxFiles:qs+1,maxDepth:ea,maxTotalBytes:ta+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=Wo.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>ea){o.add("max-depth");continue}if(r.size>=qs){o.add("max-files");break}if(i+a.sizeBytes>ta){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Px(l,a.sizeBytes,ra(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Rx([...o]),maxFiles:qs,maxDepth:ea,maxTotalBytes:ta}}:{}}}function Nx(e){let t=new Set(hx);for(let n of e.routeEntryFiles??[]){let r=Wo.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Px(e,t,n){return ia(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:ju(e),readonly:!0}:{composition:n,path:e,kind:"text",language:$u(e),sizeBytes:t,readonly:!1}}function Ax(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(u=>u.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 Bu(t)}function Bu(e){return e.map(t=>t.kind==="directory"?{...t,children:Bu(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Tx(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 ia(e){return!gx(e)}function ju(e){let t=na.posix.extname(e).toLowerCase();return!t&&na.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":xx[t]??"application/octet-stream"}function $u(e){let t=na.posix.extname(e).toLowerCase();return bx[t]??"plaintext"}import*as Nn from"@babel/types";import sa from"@babel/traverse";import*as Mt from"@babel/types";function Oe(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Mt.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(Mt.isIdentifier(s)&&s.name==="Fragment"||Mt.isStringLiteral(s)&&s.value==="Fragment")&&Vu(i.parentPath)}if(!Mt.isJSXMemberExpression(t)||!Mt.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Mt.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())&&Vu(r.parentPath)}function Vu(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var rn=typeof sa=="function"?sa:sa.default,Zo=new WeakMap,Qo=new WeakMap;function Ot(e,t){let n=zs(e,t);if(!n.ok)return Xs(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=ce(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}}:Xs(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function ce(e,t){return t.kind==="jsx-node"?Xu(e,t):t.kind==="jsx-attribute"?Dx(e,t):t.kind==="value"?Bx(e,t):t.kind==="expression"?jx(e,t):t.kind==="directive"?$x(e,t):t.kind==="export"?Vx(e,t):{ok:!1,diagnostic:vn("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Xu(e,t){return t.strategy==="source-range"?Fx(e,t):_x(e,t)}function Fx(e,t){let n=null;if(rn(e,{JSXElement(o){if(!wn(o.node,t.sourceRange))return;let i=Be("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!wn(o.node,t.sourceRange))return;let i=Be("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!wn(o.node,t.sourceRange))return;let i=Be("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!wn(o.node,t.sourceRange))return;let i=Be("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return je("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!qx(r.path,t.expectedIdentity)?je("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function _x(e,t){if(t.structuralPath===""){let r=Ox(e,t.component);if(r){let o=Lx(r);if(o)return o}}let n=null;return rn(e,{JSXElement(r){if(Ar(r)!==t.component||ca(r)!==t.structuralPath)return;let i=Be("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Ar(r)!==t.component||ca(r)!==t.structuralPath)return;let i=Be("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Mx(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:je("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Mx(e,t,n){let r=null;return rn(e,{JSXElement(o){if(Ar(o)!==t||!wn(o.node,n))return;let i=Be("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Ar(o)!==t||!wn(o.node,n))return;let i=Be("jsx-node",o);i&&(r=i,o.stop())}}),r}function Ox(e,t){let n=null;return rn(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 Lx(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 je("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?je("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 je("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Dx(e,t){let n=Xu(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>eb(c,t.name));if(!s||!s.isJSXAttribute())return je("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Be("jsx-attribute",s);return a?{ok:!0,match:a}:je("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Bx(e,t){let n=Kx(e,t);if(!n.ok)return n;let r=Ux(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ht(r.match.path.node.loc,t.expectedRange)?je("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function jx(e,t){let n=null;return rn(e,{Identifier(r){if(!Gx(r))return;let o=Uu(r);if(!o||!Ju(o,t))return;let i=Be("expression",r);i&&(t.expectedRange&&!Ht(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Uu(r);if(!o||!Ju(o,t))return;let i=Be("expression",r);i&&(t.expectedRange&&!Ht(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:je("expression","locator-miss","Expression not found")}function $x(e,t){let n=null;return rn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ht(i.node.loc,t.expectedRange))return;let s=Be("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:je("directive","locator-miss",`Directive '${t.value}' not found`)}function Vx(e,t){let n=null;return rn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let m=Be("export",c);if(!m||t.expectedRange&&!Ht(c.node.loc,t.expectedRange))return;n=m,r.stop();return}if(!c.isVariableDeclaration())return;let l=la(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Be("export",u);if(!d||t.expectedRange&&!Ht(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=la(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ht(s.node.loc,t.expectedRange))return;let a=Be("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Be("export",o);i&&(t.expectedRange&&!Ht(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:je("export","export-not-found",`Export '${Qx(t)}' not found`)}function Kx(e,t){let n=null;return rn(e,{Expression(r){if(n||t.root.kind!=="expression"||!wn(r.node,t.root.sourceRange))return;let o=Be("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 g=r.get("init");if(!g.node)return;let f=Be("value",g);if(!f)return;n=f,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(g=>g?.type==="Identifier"&&g.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 u=o.hook==="useReducer"?1:0,d=r.get(`init.arguments.${u}`);if(!d||Array.isArray(d)||!d.node)return;let m=Be("value",d);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=la(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Be("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Be("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:je("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 Ux(e,t){let n=aa(e);for(let o of t){if(n=aa(n),o.kind==="property"){if(!n.isObjectExpression())return je("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return je("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>tb(l,o.name));if(!c||!c.isObjectProperty())return je("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return je("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return je("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return je("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=aa(n);let r=Be("value",n);return r?{ok:!0,match:r}:je("value","locator-miss","Resolved value has no source range")}function aa(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Be(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 wn(e,t){return Ht(e.loc,t)}function Ht(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 ca(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Oe(n)){let o=Wu(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Ku(n,o)}`):t.unshift(`${o}#${Ku(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Wx(n.parentPath)&&!Hx(n.parentPath))break;n=n.parentPath}return t.join("/")}function Ku(e,t){let n=zu(e)??e.getFunctionParent();if(!n)return 0;let r=Zo.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Zo.get(n.node)?.get(t);if(!i){let a=Zo.get(n.node);a||(a=new Map,Zo.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Pr(n):Jx(n);for(let a of s)if(Wu(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Jx(e){let t=Qo.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!zu(r)&&n.push(r)}}),Qo.set(e.node,n),n}function zu(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Pr(e){let t=Qo.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(Oe(o)){n.push(...Pr(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Pr(o));continue}o.isJSXExpressionContainer()&&n.push(...Wt(o.get("expression")))}return Qo.set(e.node,n),n}function Wt(e){if(e.isJSXElement())return Oe(e)?Pr(e):[e];if(e.isJSXFragment())return Pr(e);if(e.isParenthesizedExpression())return Wt(e.get("expression"));if(e.isLogicalExpression()&&Xx(e.node.operator))return Wt(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(...Wt(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Wt(a));break}}return i}else if(o.node&&o.isExpression())return Wt(o)}}}}return e.isConditionalExpression()?[...Wt(e.get("consequent")),...Wt(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Wt(t)):[]}function Xx(e){return e==="&&"||e==="||"||e==="??"}function Wu(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?zx(e.name):null}function zx(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 Ar(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 Wx(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Hx(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 Gx(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Uu(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 Ju(e,t){return e.base===t.base&&Yx(e.path,t.path??[])}function Yx(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 Zx(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Qx(e){return e.exportKind==="named"?e.name:e.exportKind}function je(e,t,n,r){return{ok:!1,diagnostic:vn(t,n,e,r)}}function qx(e,t){return Ar(e)!==t.component?!1:ca(e)===t.structuralPath}function eb(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function la(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function tb(e,t){return e.isObjectProperty()?Zx(e.node)===t:!1}import*as Gu from"@babel/parser";import{arrayExpression as sb,booleanLiteral as ab,identifier as cb,jsxAttribute as lb,jsxExpressionContainer as ub,jsxIdentifier as db,nullLiteral as fb,numericLiteral as pb,objectExpression as mb,objectProperty as gb,stringLiteral as da}from"@babel/types";import ua from"@babel/generator";var nb=typeof ua=="function"?ua:ua.default;function rb(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 ob(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 ib(e,t){return e.split(`
|
|
3
|
+
`).map(r=>ob(r,t)).join(`
|
|
4
|
+
`)}function qo(e){let{ast:t,source:n}=e;try{let r=rb(n),i=nb(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=ib(i,r)),{ok:!0,source:i}}catch(r){return J(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Hu(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 Tr(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Hu(e),afterSourceHash:Hu(t),inverse:n.inverse}}}function xe(e,t,n){let r=qo({ast:e,source:t});return r.ok?Tr(t,r.source,n):r}function Ne(e,t){let n=wr(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ei(e,t){return qo({ast:e,source:t})}function hb(e,t,n){let r=ce(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Yn(e,t,n){let r=hb(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 on(e){return typeof e=="string"?da(e):typeof e=="number"?pb(e):typeof e=="boolean"?ab(e):e===null?fb():Array.isArray(e)?sb(e.map(t=>on(t))):mb(Object.entries(e).map(([t,n])=>{let r=gb(fa(t),on(n));return t==="__proto__"&&(r.computed=!0),r}))}function yb(e){return typeof e=="string"?da(e):ub(on(e))}function Fr(e,t){return lb(db(e),yb(t))}function ti(e,t){try{let r=Gu.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 fa(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?cb(e):da(e)}function ni(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=Ne(t,"jsx-node");if(!i.ok)return i.result;let s=ce(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=xb(s.match.path)[r];if(!c)return J(t,"locator-miss",`Text segment ${r} not found`,"jsx-node");switch(c.kind){case"jsx-text":{let l=c.path.node.value;if(o.trim().length===0){let d=l.match(/^\s*/)?.[0]??"",m=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Nn.jsxText(d)]:[],Nn.jsxExpressionContainer(Nn.stringLiteral("")),...m?[Nn.jsxText(m)]:[]]);break}let u=bb(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/{/g,"{").replace(/}/g,"}")};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.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${").replace(/\r/g,"\\r"),c.path.node.quasis[l].value.cooked=o;break}}return xe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function xb(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=Sb(r.get("expression"));o.length>0&&t.push(...o)}}return t}function bb(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function Sb(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||n.length===1&&e.node.expressions.length===0)&&t.push({kind:"template-literal",path:e,quasiIndex:r});if(t.length>0)return t}return e.isCallExpression()?[]:[]}import{nullLiteral as pa}from"@babel/types";function Zn(e){let{source:t,locator:n}=e,r=Ne(t,"jsx-node");if(!r.ok)return r.result;let o=ce(r.ast,n);return o.ok?(Eb(o.match.path),xe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function Eb(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(pa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(pa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(pa());return}e.remove()}import{cloneNode as vb}from"@babel/types";function ri(e){let t=Ne(e.source,"jsx-node");if(!t.ok)return t.result;let n=ce(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ti(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(vb(r.node,!0)),xe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as _b}from"@babel/types";import ma from"@babel/traverse";import*as ne from"@babel/types";function _r(e,t,n){return`${e}::${t}::${n}`}var V={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 kb=typeof ma=="function"?ma:ma.default;function ht(e,t,n,r){if(!e.ok)return e;let o=gt(n,t);if(!o)return e;let i=Ib(t,o,r);return i?{...e,selectionRef:i}:e}function Ib(e,t,n){let r=Cb(e,t);if(!r)return;let o=n.sourceLocator?Yu(n.sourceLocator):void 0,i=n.targetParentLocator?Yu(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??wb(r)??i?.component??o?.component;if(!(!s||!a))return{key:_r(s,a,Nb(r))}}function Yu(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function Cb(e,t){let n=nd(e,t);return!n||n.node.type!=="JSXElement"?null:n}function nd(e,t){let n=null;return kb(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function gt(e,t){if(!e)return null;if(ne.isJSXElement(e))return Fb(t,e)?Zu(e.children,t):e;if(ne.isJSXFragment(e))return Zu(e.children,t);if(ne.isJSXExpressionContainer(e)||ne.isParenthesizedExpression(e)||ne.isTSAsExpression(e)||ne.isTSSatisfiesExpression(e)||ne.isTSTypeAssertion(e)||ne.isTSNonNullExpression(e))return gt(e.expression,t);if(ne.isLogicalExpression(e))return gt(e.right,t);if(ne.isConditionalExpression(e))return gt(e.consequent,t)??gt(e.alternate,t);if(ne.isCallExpression(e)||ne.isOptionalCallExpression(e))return rd(e)?Rb(e.arguments[0],t):null;if(ne.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=gt(n,t);if(r)return r}return null}function Zu(e,t){for(let n of e){let r=gt(n,t);if(r)return r}return null}function Rb(e,t){return!e||!ne.isArrowFunctionExpression(e)&&!ne.isFunctionExpression(e)?null:ne.isBlockStatement(e.body)?Mr(e.body.body,t):gt(e.body,t)}function Mr(e,t){for(let n of e){if(ne.isReturnStatement(n)){let r=gt(n.argument,t);if(r)return r;continue}if(ne.isBlockStatement(n)){let r=Mr(n.body,t);if(r)return r;continue}if(ne.isIfStatement(n)){let r=Qu(n.consequent,t);if(r)return r;let o=n.alternate?Qu(n.alternate,t):null;if(o)return o;continue}if(ne.isSwitchStatement(n))for(let r of n.cases){let o=Mr(r.consequent,t);if(o)return o}}return null}function Qu(e,t){return ne.isBlockStatement(e)?Mr(e.body,t):Mr([e],t)}function wb(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(ne.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&ne.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 qu=new WeakMap,ed=new WeakMap,ga=new WeakMap;function Nb(e){let t=qu.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=Pb(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return qu.set(e.node,o),o}function Pb(e){let t=od(e.node.openingElement.name);return!t||Oe(e)?null:/^[A-Z]/.test(t)?`component:${t}#${td(e,t)}`:`${t}#${td(e,t)}`}function td(e,t){let n=Ab(e);if(!n)return 0;let r=ga.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ga.get(n.node);o||(o=new Map,ga.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Pn(n))if(od(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 Ab(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Oe(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Pn(e){let t=ed.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(Oe(o)){n.push(...Pn(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Pn(o));continue}o.isJSXExpressionContainer()&&n.push(...Lt(o.get("expression")))}return ed.set(e.node,n),n}function Lt(e){if(e.isJSXElement())return Oe(e)?Pn(e):[e];if(e.isJSXFragment())return Pn(e);if(e.isParenthesizedExpression())return Lt(e.get("expression"));if(e.isLogicalExpression())return Lt(e.get("right"));if(e.isConditionalExpression())return[...Lt(e.get("consequent")),...Lt(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Lt(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&rd(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?Tb(n):[]}return[]}function Tb(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Oe(t)?Pn(t):[t];if(t.isJSXFragment())return Pn(t);if(t.isParenthesizedExpression())return Lt(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Lt(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(...Lt(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Lt(o)),n}return n}function rd(e){let t=e.callee;return(ne.isMemberExpression(t)||ne.isOptionalMemberExpression(t))&&ne.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function Fb(e,t){let n=nd(e,t);return n?Oe(n):!1}function od(e){return ne.isJSXIdentifier(e)?e.name:ne.isJSXMemberExpression(e)?id(e):ne.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function id(e){return`${ne.isJSXIdentifier(e.object)?e.object.name:id(e.object)}.${e.property.name}`}function sn(e,t){if(t.parentPath===e&&t.listKey==="children"&&ha(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ha(n))return null;let r=n;for(;r&&r!==e;){if(!ha(r)||!Oe(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ha(e){return e.isJSXElement()||e.isJSXFragment()}function Qn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=ce(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 v=c.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ti(t,r.jsx);if(!u.ok)return u.result;let d=_b(u.node,!0),m=l.node.children,g={...s,targetParentLocator:n},f=v=>s?ht(v,a.ast,d,g):v;if(o==="append")return m.push(d),f(xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return m.unshift(d),f(xe(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=ce(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=sn(c.match.path,h.match.path);if(!y)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let E=l.node.children,x=E.findIndex(v=>v===h.match.path.node);return x===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?x:x+1,0,d),f(xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as sd from"@babel/parser";import{cloneNode as Mb}from"@babel/types";function oi(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=Ob(t,r);if(!c.ok)return c.result;let l=ce(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 u=l.match.path,d=null;if(i){let E=ce(a.ast,i);if(!E.ok)return{ok:!1,source:t,diagnostic:E.diagnostic};let x=sn(l.match.path,E.match.path);if(!x)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=x,d=E.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Mb(c.node,!0),g=u.node.children,f={...s,targetParentLocator:n},h=E=>s?ht(E,a.ast,m,f):E;if(o==="append")return g.push(m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(E=>E===d);return y===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,m),h(xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function Ob(e,t){try{let r=sd.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 Lb,nullLiteral as ya}from"@babel/types";import*as an from"@babel/types";import*as ad from"@babel/types";function Or(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!ad.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function qn(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=Ne(t,"jsx-node");if(!a.ok)return a.result;let c=ce(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=ce(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 u=l.match.path;if(l.match.path.isJSXElement()){let v=l.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let v=ce(a.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let w=v.match.path.isJSXElement()?Or(v.match.path,l.match.path):v.match.path,N=sn(l.match.path,w);if(!N)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=N,d=w}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=d&&typeof d.key=="number"?d.key:-1;if(d&&m===-1)return J(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?Or(c.match.path,l.match.path):c.match.path,f=Lb(g.node,!0);if(!an.isJSXElement(f)&&!an.isJSXExpressionContainer(f)&&!an.isJSXFragment(f)&&!an.isJSXText(f))return J(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let h=g.parentPath?.node===u.node&&typeof g.key=="number"?g.key:-1;if(d&&g.parentPath?.node===d.parentPath?.node&&g.key===d.key)return J(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");Db(g);let y=u.node.children,E={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(f),ht(ei(a.ast,t),a.ast,f,E);if(o==="prepend")return y.unshift(f),ht(ei(a.ast,t),a.ast,f,E);let x=m-(h!==-1&&h<m?1:0);return y.splice(o==="before"?x:x+1,0,f),ht(ei(a.ast,t),a.ast,f,E)}function Db(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ya());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ya());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ya());return}e.remove()}import*as cd from"@babel/parser";import{cloneNode as Bb,nullLiteral as xa}from"@babel/types";function ii(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=Ne(t,"jsx-node");if(!c.ok)return c.result;let l=jb(t,s);if(!l.ok)return l.result;let u=ce(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=ce(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return J(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let v=d.match.path.node;if(!v.closingElement||v.openingElement.selfClosing)return J(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let m=d.match.path,g=null;if(i){let v=ce(c.ast,i);if(!v.ok)return{ok:!1,source:t,diagnostic:v.diagnostic};let w=sn(d.match.path,v.match.path);if(!w)return J(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");m=w,g=v.match.path.node}else if(o==="before"||o==="after")return J(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return J(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let f=m.node,h=Bb(l.node,!0);$b(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},E=f.children;if(o==="append")return E.push(h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return E.unshift(h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let x=E.findIndex(v=>v===g);return x===-1?J(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(E.splice(o==="before"?x:x+1,0,h),ht(xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function jb(e,t){try{let r=cd.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 $b(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(xa());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(xa());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(xa());return}e.remove()}import{SiteEditSetPropsParamsSchema as Vb,classifySiteEditPropertyName as Kb}from"@vcp-dev/contracts";import*as er from"@babel/types";function si(e){let t=Vb.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=Ne(e.source,"jsx-node");if(!n.ok)return n.result;let r=Yn(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=Kb(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(er.isJSXAttribute),s=new Map;for(let a of i){let c=Ub(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(u=>u!==c));continue}let l=Fr(a.name,a.value).value;c?c.value=l:o.attributes.push(Fr(a.name,a.value))}return xe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function Ub(e){return er.isJSXIdentifier(e.name)?e.name.name:er.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as Jb}from"@vcp-dev/contracts";import*as H from"@babel/types";var ld=["prefetch","replace","scroll","locale","onNavigate"],Xb=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function zb(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>H.isJSXAttribute(n)&&H.isJSXIdentifier(n.name)&&Xb.test(n.name.name)))return!0;t=t.parentPath}return!1}function ai(e){let t=Ne(e.source,"jsx-node");if(!t.ok)return t.result;let n=Yn(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=Jb.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Gt(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=qb(s.name);if(!a)return Gt(e.source,"Unsupported JSX link tag");if(s.attributes.some(H.isJSXSpreadAttribute))return Gt(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let f of s.attributes){if(!H.isJSXAttribute(f))continue;let h=Sa(f);if(!h)return Gt(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(f),c.set(h,y)}if([...c.values()].some(f=>f.length>1))return Gt(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!Qb(l))return Gt(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:Gb(o,s.name);if(!u&&!d)return Gt(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&zb(o))return Gt(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let m=null;if(e.link.kind==="internal-route")if(d)m=a;else{let f=Yb(t.ast,o);if(!f.ok)return Gt(e.source,f.reason);m=f.localName}if(d&&e.link.kind!=="internal-route"){let f=H.jsxIdentifier("a");s.name=f,i.closingElement&&(i.closingElement.name=H.jsxIdentifier("a")),Zb(t.ast,d,o)}else m&&u&&(s.name=H.jsxIdentifier(m),i.closingElement&&(i.closingElement.name=H.jsxIdentifier(m)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),ld.forEach(f=>g.add(f))):(g.add("href"),e.link.kind==="native-link"&&ld.forEach(f=>g.add(f))),s.attributes=s.attributes.filter(f=>{if(!H.isJSXAttribute(f))return!0;let h=Sa(f);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(H.jsxAttribute(H.jsxIdentifier("href"),H.stringLiteral(e.link.href))),Wb(s,e.changes),xe(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function Wb(e,t){for(let n of t){let r=e.attributes.find(s=>H.isJSXAttribute(s)&&Sa(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?H.stringLiteral(n.value):H.jsxExpressionContainer(ba(n.value)),i=H.jsxAttribute(H.jsxIdentifier(n.name),o);r&&H.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function ba(e){return e===null?H.nullLiteral():typeof e=="string"?H.stringLiteral(e):typeof e=="number"?H.numericLiteral(e):typeof e=="boolean"?H.booleanLiteral(e):Array.isArray(e)?H.arrayExpression(e.map(t=>ba(t))):typeof e=="object"?H.objectExpression(Object.entries(e).map(([t,n])=>H.objectProperty(H.isValidIdentifier(t)?H.identifier(t):H.stringLiteral(t),ba(n)))):H.nullLiteral()}function Hb(e){return H.isImportDefaultSpecifier(e)||H.isImportSpecifier(e)&&e.importKind!=="type"&&(H.isIdentifier(e.imported,{name:"default"})||H.isStringLiteral(e.imported,{value:"default"}))}function ud(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(H.isIdentifier(e.node.imported,{name:"default"})||H.isStringLiteral(e.node.imported,{value:"default"}))}function Gb(e,t){if(!H.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!ud(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function Yb(e,t){let n=e.program.body.filter(c=>H.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(Hb);if(o)return t.scope.getBinding(o.local.name)?.path.node!==o?{ok:!1,reason:"The next/link import is shadowed at the selected element"}:{ok:!0,localName:o.local.name};let i=t.scope.getProgramParent(),s=["Link","NextLink",...Array.from({length:20},(c,l)=>`NextLink${l+2}`)].find(c=>!i.hasBinding(c)&&!t.scope.hasBinding(c));if(!s)return{ok:!1,reason:"Cannot create an unshadowed runtime next/link import"};let a=H.importDefaultSpecifier(H.identifier(s));if(r)r.specifiers.unshift(a);else{let c=H.importDeclaration([a],H.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&H.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function Zb(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!ud(o.path)||o.referenced)return;let i=o.path.parentPath;if(!(!i?.isImportDeclaration()||i.node.source.value!=="next/link")&&(i.node.specifiers=i.node.specifiers.filter(s=>s!==o.path.node),i.node.specifiers.length===0)){let s=e.program.body.indexOf(i.node);s>=0&&e.program.body.splice(s,1)}}function Qb(e){return!e.value||H.isStringLiteral(e.value)}function qb(e){return H.isJSXIdentifier(e)?e.name:null}function Sa(e){return H.isJSXIdentifier(e.name)?e.name.name:null}function Gt(e,t){return J(e,"unsupported-syntax",t,"jsx-node")}import*as Ke from"@babel/types";import{classifySiteEditPropertyName as dd}from"@vcp-dev/contracts";function ci(e){let t=dd(e.name),n=dd(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(!fd(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=Ne(e.source,"jsx-node");if(!r.ok)return r.result;let o=Yn(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Ke.isJSXAttribute(l)&&tS(l)===e.name);if(s.length>1)return J(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=eS(e.object,e.property),c=s[0];if(c)c.value=Ke.jsxExpressionContainer(a);else{let l=Fr(e.name,"");l.value=Ke.jsxExpressionContainer(a),i.attributes.push(l)}return xe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function eS(e,t){return fd(t)?Ke.memberExpression(Ke.identifier(e),Ke.identifier(t)):Ke.memberExpression(Ke.identifier(e),Ke.stringLiteral(t),!0)}function fd(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function tS(e){return Ke.isJSXIdentifier(e.name)?e.name.name:Ke.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as rS,identifier as Lr,importDeclaration as oS,importDefaultSpecifier as iS,importNamespaceSpecifier as sS,importSpecifier as aS,isImportDefaultSpecifier as pd,isImportNamespaceSpecifier as md,isImportSpecifier as gd,stringLiteral as cS}from"@babel/types";function tr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!yS(y));if(o!==-1){let y=r[o],E=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return J(t,"unsupported-syntax",`Unsupported import spec kind: ${String(E)}`)}let i=mS(r);if(!i.ok)return J(t,"unsupported-syntax",i.message);let s=Ne(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(E=>{let x=xS(y,E);return x?[x]:[]}))),d=i.imports.filter(y=>!u.has(Ed(y)));if(d.length===0)return Tr(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let m=gS(c.body),g=d.find(y=>m.has(Ea(y)));if(g)return J(t,"unsupported-syntax",`Import local binding already exists: ${Ea(g)}`);let f=pS(d);if(f.reduce((y,E)=>y+E.length,0)!==d.length)return J(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of f){if(!bd(yd(y)))return J(t,"unsupported-syntax","Unsupported import specifier combination");let E=l.find(x=>lS(x,y));if(E)uS(E,y);else{let x=oS(hd(y),cS(n));hS(c.body,x),l.push(x)}}return xe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function lS(e,t){return e.importKind==="type"?!1:bd(fS(dS(e),yd(t)))}function uS(e,t){let n=!1,r=new Set(e.specifiers.map(o=>va(o)));for(let o of hd(t)){let i=va(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return Sd(e.specifiers),{changed:n}}function hd(e){let t=e.map(n=>{switch(n.kind){case"named":return aS(n.local?Lr(n.local):Lr(n.imported),Lr(n.imported));case"default":return iS(Lr(n.local));case"namespace":return sS(Lr(n.local));default:return n}});return Sd(t),t}function yd(e){let t=xd();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 dS(e){let t=xd();for(let n of e.specifiers)pd(n)?t.defaultLocals.add(n.local.name):md(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function xd(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function fS(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function bd(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function Sd(e){let t=[...e.filter(n=>pd(n)),...e.filter(n=>md(n)),...e.filter(n=>gd(n))];e.splice(0,e.length,...t)}function pS(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 mS(e){let t=new Map,n=new Map;for(let r of e){let o=Ed(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 gS(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(rS(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 hS(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 yS(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 Ed(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 xS(e,t){return e.importKind==="type"||gd(t)&&t.importKind==="type"?null:va(t)}function va(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 nr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!SS(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return J(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=Ne(t);if(!i.ok)return i.result;let{ast:s}=i,a=s.program,c=a.body.findIndex(u=>u.type==="ImportDeclaration"&&u.source.value===n);if(c===-1)return Tr(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>bS(u,d))),l.specifiers.length===0&&a.body.splice(c,1),xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function bS(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 SS(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 Dr(e){let{source:t,locator:n,next:r}=e,o=fi(t,n);return o.ok?(o.path.replaceWith(on(r)),xe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function li(e){let{source:t,locator:n,index:r,value:o}=e,i=fi(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,on(o)),xe(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 ui(e){let{source:t,locator:n,index:r}=e,o=fi(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),xe(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 di(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=fi(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),xe(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function fi(e,t){let n=Ne(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=ce(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 Xe from"@babel/types";function pi(e){let t=Ne(e.source,"value");if(!t.ok)return t.result;let n=ce(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=>Xe.isSpreadElement(a)||Xe.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=>Xe.isObjectProperty(a)&&ES(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"?Xe.unaryExpression("void",Xe.numericLiteral(0)):on(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Xe.objectProperty(fa(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return xe(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function ES(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)?e.value:Xe.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as vS,isSiteEditRuntimeVoidElementTag as kS}from"@vcp-dev/contracts/site-edit-runtime-capability";function rr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function IS(e,t,n){let r=rr(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(w=>({kind:w.kind,message:w.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,m=!d&&kS(u),g=d||vS(u),f=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(w=>w.editable);m&&!s.some(w=>w.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!m&&!g&&!s.some(w=>w.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),E=!i.isPublicUiComponent&&!m&&g&&(!a||f);return{composition:r,key:e,canUpdateText:y,canInsertChild:E,canMove:!l,canRemove:!l,constraints:s}}function vd(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,IS(r,e,t));return n}function ka(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:Ce(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=CS(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:Ce(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:Id(r),version:{documentVersion:e.route.graph.version,contentHash:Ce(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:kd(e.route.source,o),valueRaw:s?kd(e.route.source,s):null,attrRange:Id(o),diagnostics:[]}}function Cd(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 CS(e,t){let n=_t({source:e,profile:kn({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=ce(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:RS(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function Rd(e){let t=_t({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 kd(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Id(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 RS(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function wd(){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 wS}from"node:crypto";import mi from"node:fs/promises";import Ia from"node:path";import{setTimeout as NS}from"node:timers/promises";var PS={async mkdir(e,t){await mi.mkdir(e,t)},async writeFile(e,t,n){await mi.writeFile(e,t,n)},async rename(e,t){await mi.rename(e,t)},async rm(e,t){await mi.rm(e,t)}},AS=new Set(["EACCES","EBUSY","EPERM"]),TS=[10,20,40,80,160];async function FS(e,t,n){for(let r of TS)try{await e.rename(t,n);return}catch(o){if(!_S(o))throw o;await NS(r)}await e.rename(t,n)}function _S(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&AS.has(e.code)}async function gi(e,t,n=PS){let r=Ia.dirname(e),o=Ia.basename(e),i=Ia.join(r,`.${o}.${process.pid}.${wS()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await FS(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Ca from"@babel/traverse";import*as k from"@babel/types";import*as de from"@babel/types";function Dt(e,t={}){if(de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSNonNullExpression(e)||de.isTypeCastExpression(e)||de.isParenthesizedExpression(e))return Dt(e.expression,t);if(de.isStringLiteral(e))return{status:"resolved",value:e.value};if(de.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(de.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(de.isNullLiteral(e))return{status:"resolved",value:null};if(de.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(de.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(de.isUnaryExpression(e)&&e.operator==="void"&&de.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(de.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||de.isSpreadElement(r))return{status:"unresolved"};let o=Dt(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(de.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!de.isObjectProperty(r)||r.computed||!de.isExpression(r.value))return{status:"unresolved"};let o=MS(r.key);if(o===null)return{status:"unresolved"};let i=Dt(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 de.isMemberExpression(e)||de.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function MS(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:de.isNumericLiteral(e)?String(e.value):null}var OS=typeof Ca=="function"?Ca:Ca.default;function Ge(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 LS(e){return/^[A-Z]/.test(e)}function Aa(e){let t=e.openingElement;return k.isJSXIdentifier(t.name)?t.name.name==="Fragment":k.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function ir(e){return k.isJSXFragment(e)}function Pd(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?Ad(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Ad(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${Ad(e.object)}.${e.property.name}`:e.property.name}function DS(e){return e.split(".")[0]??e}function BS(e){let t=e;for(;t;){let n=t.node;if(k.isFunctionDeclaration(n)&&n.id||k.isVariableDeclarator(n)&&k.isIdentifier(n.id))return n.id.name;if(k.isExportDefaultDeclaration(n)){let r=n.declaration;if(k.isFunctionDeclaration(r)&&r.id)return r.id.name;if(k.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function jS(){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 $S(e){let t=new Map;for(let n of e.program.body){if(!k.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(k.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(k.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(k.isImportSpecifier(o)){let i=k.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Yt(e,t=[]){if(k.isIdentifier(e))return t.push(e.name),t;if(k.isObjectPattern(e)){for(let n of e.properties)k.isObjectProperty(n)?Yt(n.value,t):k.isRestElement(n)&&Yt(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?Yt(n.argument,t):Yt(n,t));return t}return k.isAssignmentPattern(e)?(Yt(e.left,t),t):(k.isRestElement(e)&&Yt(e.argument,t),t)}function It(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Br(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 VS(e,t,n){e.set(t,{resolved:!0,value:n})}function Ta(e,t){e.set(t,{resolved:!1})}function Td(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 $e(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return $e(e.expression,t,n);if(k.isLogicalExpression(e))return hi([$e(e.left,t,n),$e(e.right,t,n)]);if(k.isBinaryExpression(e))return hi([k.isExpression(e.left)?$e(e.left,t,n):null,k.isExpression(e.right)?$e(e.right,t,n):null]);if(k.isConditionalExpression(e))return hi([$e(e.consequent,t,n),$e(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return hi(e.expressions.filter(k.isExpression).map(i=>$e(i,t,n)));if(k.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!k.isMemberExpression(e)&&!k.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;k.isMemberExpression(o)||k.isOptionalMemberExpression(o);){if(o.computed)if(k.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(k.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&k.isExpression(o.property)){let i=cn(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(!k.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return k.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:It(e,t),base:o.name,path:r}:null}function hi(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 cn(e,t){if(k.isStringLiteral(e)||k.isNumericLiteral(e)||k.isBooleanLiteral(e))return e.value;if(k.isNullLiteral(e))return null;if(k.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(k.isIdentifier(e)){let n=Br(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return;let o=cn(r,t);if(o===void 0)return;n.push(o)}return n}if(k.isObjectExpression(e)){let n={};for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isExpression(r.value))return;let o=null;if(k.isIdentifier(r.key)?o=r.key.name:k.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!k.isIdentifier(r.value))return;let s=Br(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=cn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=$e(e,"",t);if(!n)return;let r=Br(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Td(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return _d(e,t)??void 0}function Fd(e,t,n){let r=$e(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:It(e,n),source:null}:null;let o=Br(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Td(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 Ra(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:jS(),parentStack:[],valueScopes:i,importMap:o}}function Na(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Yt(o.id))Ta(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=cn(o.init,t);i!==void 0&&VS(n,o.id.name,i)}}function KS(e){let t=[];for(let n of e){if(k.isVariableDeclaration(n)){t.push(n);continue}k.isExportNamedDeclaration(n)&&n.declaration&&k.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function US(e,t,n){let r=[],o=0;for(let i of e)if(k.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Ge(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Ge(i),editable:!0,source:null});else if(k.isJSXExpressionContainer(i)&&k.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:Ge(i),editable:!0,source:null}):r.push({index:o++,value:It(s,n),sourceRange:Ge(i),editable:!0,source:$e(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=Fd(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Ge(i),editable:!0,source:s.source})}return r}function JS(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=zS(i.name);if(!s)continue;let a=It(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Ge(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:Ge(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(k.isJSXExpressionContainer(i.value)&&k.isExpression(i.value.expression)){let c=cn(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?_d(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Ge(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=Fd(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:qS(c),sourceRange:Ge(i),source:$e(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=WS(i.value.expression,t),d=$e(i.value.expression,n,t),m=l?.value??It(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":m,sourceRange:Ge(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function XS(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:It(r.argument,n),sourceRange:Ge(r),order:o,source:$e(r.argument,n,t)}])}function zS(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function WS(e,t){return Dt(e,{resolveIdentifier(n){let r=Br(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=cn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function _d(e,t){let n=or(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function or(e,t){if(k.isStringLiteral(e))return[e.value];if(k.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(k.isNullLiteral(e))return[];if(k.isBooleanLiteral(e))return e.value?null:[];if(k.isIdentifier(e)||k.isMemberExpression(e)){if(k.isIdentifier(e)&&e.name==="undefined")return[];let n=cn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=or(e.consequent,t),r=or(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=cn(e.left,t);return n===!1||n===null?[]:or(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=or(r,t);if(!o)return null;n.push(...o)}return n}if(k.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!k.isObjectProperty(r))return null;let o=GS(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=HS(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!k.isExpression(o))return null;let i=or(o,t);if(!i)return null;r.push(...i)}return r}return null}function HS(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function GS(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function YS(e,t){let n=e.attributes.find(r=>k.isJSXAttribute(r)&&k.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!k.isJSXAttribute(n)||!k.isJSXExpressionContainer(n.value)?null:n.value.expression}function ZS(e,t){for(let n of t){let r=YS(e,n);if(r)return r}return null}function QS(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function qS(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function eE(e){if(!k.isCallExpression(e)&&!k.isOptionalCallExpression(e))return null;let t=e.callee;return!k.isMemberExpression(t)&&!k.isOptionalMemberExpression(t)||!k.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!k.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function wa(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function tE(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function nE(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function Nd(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:It(e,n),collectionSource:$e(e,n,r)};if(t){let i=t.params[0],s=t.params[1];k.isIdentifier(i)&&(o.itemParamName=i.name),k.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Zt(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(Aa(e))return Ei(e.children,t,n);let r=bi(e,t,n);return r?[r]:[]}return ir(e)?Si(e,t,n):k.isParenthesizedExpression(e)?Zt(e.expression,t,n):k.isExpression(e)?vi(e,t,n):[]}function yi(e,t,n){let r=new Map;for(let o of e.params)for(let i of Yt(o))Ta(r,i);t.valueScopes.push(r);try{if(!k.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(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Na([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...Zt(s.init,t,n))}continue}r.push(...Pa(o,t,n))}return r}function Pa(e,t,n){if(k.isReturnStatement(e))return e.argument?Zt(e.argument,t,n):[];if(k.isBlockStatement(e))return An(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?An(e.consequent.body,t,n):Pa(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?An(e.alternate.body,t,n):Pa(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return An(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=An(e.block.body,t,n);return e.handler&&r.push(...An(e.handler.body.body,t,n)),e.finalizer&&r.push(...An(e.finalizer.body,t,n)),r}return[]}function An(e,t,n){let r=new Map;t.valueScopes.push(r);try{return Md(e,t,n)}finally{t.valueScopes.pop()}}function xi(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Ge(r),sourceCandidates:i&&i.length>0?i:void 0})}function rE(e,t,n,r){let o=ZS(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Pd(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=QS(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(tE(a)&&wa(c)){let l=yi(c,n,r),u=Nd(o,c,r,n);xi(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(nE(a)){let l=wa(c)?yi(c,n,r):Zt(c,n,r);xi(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!wa(s.expression))continue;let a=yi(s.expression,n,r),c=Nd(o,s.expression,r,n);xi(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function bi(e,t,n){let r=Pd(e.openingElement);if(r==="Fragment"||Aa(e))return Ei(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=LS(r),a;if(s){let w=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${w}`}else{let w=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${w}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=_r(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},m=s?"component-boundary":null,g=US(e.children,t,n),f=JS(e.openingElement,t,n),h=XS(e.openingElement,t,n),y,E,x=!1;if(s){let w=t.importMap.get(r)??t.importMap.get(DS(r));w&&(y=w.specifier,E=w.exportName,x=In(w.specifier,t.file))}let v={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Ge(e),parentKey:i,childKeys:[],textSegments:g,attributes:f.length>0?f:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:m,isOpaque:s,...x?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:E};return t.elements.set(u,v),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),rE(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),oE(e.children,t,n),t.parentStack.pop()),u}function Si(e,t,n){return Ei(e.children,t,n)}function Ei(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(Aa(o))r.push(...Ei(o.children,t,n));else{let i=bi(o,t,n);i&&r.push(i)}else ir(o)?r.push(...Si(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...vi(o.expression,t,n));return r}function oE(e,t,n){for(let r of e)k.isJSXElement(r)?bi(r,t,n):ir(r)?Si(r,t,n):k.isJSXExpressionContainer(r)&&vi(r.expression,t,n)}function iE(e){return e==="&&"||e==="||"||e==="??"}function vi(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=eE(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:It(r.collection,n),collectionSource:$e(r.collection,n,t)};if(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];k.isIdentifier(u)&&(c.itemParamName=u.name),k.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Ge(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...yi(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:It(e.test,n),conditionSource:$e(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(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(k.isLogicalExpression(e)&&iE(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:It(e.left,n),conditionSource:$e(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Ge(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Zt(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return vi(e.expression,t,n);if(k.isJSXElement(e)){let o=bi(e,t,n);return o?[o]:[]}return ir(e)?Si(e,t,n):[]}function sE(e){let t=e.argument;return t&&(k.isExpression(t)||ir(t))?t:null}function jr(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=sE(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(k.isIfStatement(r)){let o=k.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...jr(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...jr(i,r.test))}continue}if(k.isSwitchStatement(r))for(let o of r.cases){let i=o.test?k.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...jr(o.consequent,i))}}return n}function ki(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Od(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(m=>m.specifier);if(!k.traverseFast(r,m=>{if(k.isJSXElement(m)||k.isJSXFragment(m))return k.traverseFast.stop}))return{graph:ki(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=$S(r);OS(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(m){let g=BS(m);if(!g)return;let f=m.node,h=[];if(k.isArrowFunctionExpression(f))k.isExpression(f.body)||ir(f.body)?h=[{argument:f.body,statement:k.returnStatement(k.isExpression(f.body)?f.body:null)}]:k.isBlockStatement(f.body)&&(h=jr(f.body.body));else{let N=f.body;k.isBlockStatement(N)&&(h=jr(N.body))}if(h.length===0){m.skip();return}let y=new Map;Na(KS(r.program.body),Ra(t,g,s,a,u,[y]),y);let E=new Map;for(let N of f.params)for(let T of Yt(N))Ta(E,T);let x=k.isBlockStatement(f.body)?f.body.body:[],v=h[0]?.statement??null;for(let N of x){if(v&&N===v)break;k.isVariableDeclaration(N)&&Na([N],Ra(t,g,s,a,u,[y,E]),E)}let w=Ra(t,g,s,a,u,[y,E]);for(let N of h){let T=Zt(N.argument,w,n);for(let C of T)c.includes(C)||c.push(C);if(N.condition){let C={kind:"conditional-branch",conditionExpression:It(N.condition,n),conditionSource:$e(N.condition,n,w)};xi(w,"conditional-region","",N.statement,T,[C])}}m.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function Fa(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ii(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ld(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=0,o=Array.from({length:Math.min(8,e.length)},async()=>{for(;r<e.length;){let s=r++;n[s]=await t(e[s])}}),i=await Promise.allSettled(o);for(let s of i)if(s.status==="rejected")throw s.reason;return n}async function Dd(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Xt,c=new Map,l=new Map,u=new Map,d=[],m=new Set,g=E=>{let x=`${E.path}\0${E.code}\0${E.message}\0${JSON.stringify(E.details??{})}`;m.has(x)||(m.add(x),d.push(E))},f=[{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(;f.length>0;){let E=f.shift(),{file:x,source:v,depth:w,diagnosticEntryFile:N,importStack:T}=E;if(h.has(x))continue;h.add(x),c.set(x,v);let C=o.validationOnly&&w<i?o.validatedImports?.(x,v):void 0,P,F;if(C)P=ki(x),F=C;else{let j=a(x,v);if(!j.ok){g(Ii(j.diagnostic,N,T));continue}u.set(x,j.module);let G=o.validationOnly&&w<i?{graph:ki(x),localImports:j.module.imports.map(pe=>pe.specifier)}:Od(j.module);P=G.graph,F=G.localImports}let L=[...new Set([...P.elements.values()].map(j=>j.importedFrom).filter(j=>typeof j=="string"&&kt(j)))],W=L.length?await Ld(L,j=>Do(x,j,r)):[],z=new Map(L.map((j,G)=>[j,W[G]]));for(let j of P.elements.values())if(j.importedFrom&&kt(j.importedFrom)){let G=j.importedFrom,pe=z.get(G);pe.ok?(j.importedFrom=pe.path,zt(pe.path)&&(j.isPublicUiComponent=!0)):In(G,x)||g(Ii(pe.diagnostic,N,Fa(T,x,G,pe.diagnostic.path)))}if(l.set(x,P),w>=i)continue;let he=await Ld(F,async j=>{if(yu(j))return null;let G=z.get(j)??await Do(x,j,r);if(!G.ok)return In(j,x)?null:{diagnostic:Ii(G.diagnostic,N,Fa(T,x,j,G.diagnostic.path))};let pe=G.path;if(h.has(pe)||zt(pe))return null;let st=Fa(T,x,j,pe);try{let tt=await n(pe);return{entry:{file:pe,source:tt,depth:w+1,diagnosticEntryFile:N,importStack:st}}}catch(tt){return{diagnostic:Ii({path:pe,code:"import-read-failed",message:`Failed to read imported file: ${pe}`,details:{fromFile:x,specifier:j,reason:tt instanceof Error?tt.message:String(tt)}},N,st)}}});for(let j of he)j&&"entry"in j?f.push(j.entry):j&&g(j.diagnostic)}let y=aE(e,l,s,(o.additionalEntries??[]).map(E=>E.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function aE(e,t,n,r=[]){let o=new Map,i=[],s=new Map,a=[];for(let[c,l]of t){for(let[u,d]of l.elements)o.set(u,d);for(let u of l.regions)i.push(u);for(let[u,d]of l.fileIndex){let m=s.get(u)??[];s.set(u,[...m,...d])}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}}function Bd(e=256){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Validated syntax capacity must be positive.");let t=new Map;return{remember(n){for(let r of n)t.get(r.file)?.source!==r.source&&(t.delete(r.file),t.size>=e&&t.delete(t.keys().next().value),t.set(r.file,{source:r.source,imports:Object.freeze(r.imports.map(o=>o.specifier))}))},getImports(n,r){let o=t.get(n);return o?.source===r?o.imports:void 0},clear(){t.clear()}}}import{SiteEditHistoryProvenanceSchema as LE}from"@vcp-dev/contracts";import{createHash as cE,randomUUID as Ka}from"node:crypto";import Le from"node:fs/promises";import De from"node:path";var Hd=new WeakMap;function sr(e){return Hd.get(e)?.()??e.readIndex()}var yt=1,Ma=1,lE=2,uE="index.json",dE="recovery.json",fE="transaction-journal.json",pE="document-version.json",wi={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},oe={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"},se=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Qt(){return{entries:new Map,blobSizes:new Map}}function Ci(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Gd(n,r,t);return n}function Gd(e,t,n){let r=e.entries.get(t);if(r){e.entries.set(t,{...r,references:r.references+1});return}let o=n.entries.get(t),i=new Map(o.entry.blobs.map(s=>[s.digest,n.blobSizes.get(s.digest)]));e.entries.set(t,{sizeBytes:o.sizeBytes,references:1,blobs:i}),e.objectBytes+=o.sizeBytes;for(let[s,a]of i){let c=e.blobs.get(s);e.blobs.set(s,{sizeBytes:a,references:(c?.references??0)+1}),c||(e.objectBytes+=a)}}function Yd(e,t){let n=e.entries.get(t);if(n.references>1){e.entries.set(t,{...n,references:n.references-1});return}e.entries.delete(t),e.objectBytes-=n.sizeBytes;for(let r of n.blobs.keys()){let o=e.blobs.get(r);o.references>1?e.blobs.set(r,{...o,references:o.references-1}):(e.blobs.delete(r),e.objectBytes-=o.sizeBytes)}}async function Zd(e,t={}){let n=AE(e),r=ME(t.limits),o=_a(n),i=TE(n),s=await nt(i),a=await nt(o)||s;a||(await vE(n),await kE(n)),a||await OE(n);let c=Qt(),l=await Pi(n,c),u=new Set(a?(await Mi(n)).map(x=>x.stageId):[]);a||await Ud(n,l.entryIds,c);let d=l.digest,m=Ci(l.entryIds,c),g=async x=>{let{index:v,sizeBytes:w}=await Jr(n);if(of(v,x),v.digest!==d){let N=Qt();await tf(n,v.entryIds,N,w),m=Ci(v.entryIds,N),d=v.digest}return{...Oi(v),totalBytes:m.objectBytes+w}},f=async x=>{Ua(x),await g(),await Vd(n,m,[x.entryId],x.blobIds,x.stageId),await Ni(n,x.stageId)},h=async(x,v)=>{let w=await g(v);qd(x,w.entryIds.length);let N=Qt();for(let T of w.entryIds.slice(Math.min(w.cursor,x)+1,Math.max(w.cursor,x)+1))await Vr(n,T,N);return w},y=async()=>{if(await nt(o)||s)throw new se(oe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},E={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return zd(n)},async writeDocumentVersion(x){if(await y(),!Number.isInteger(x)||x<0)throw new se(oe.INVALID_SCHEMA,"document version must be a non-negative integer");let v=await zd(n);x<=v||await $r(lf(n),{schemaVersion:1,version:Math.max(v,x)})},async stageAppend(x,v={}){await y();let w=await hE(x,r),N={schemaVersion:Ma,stageId:Ka(),entryId:w.entryId,blobIds:w.blobs.map(T=>T.digest)};try{await yE(n,w),await bE(n,N,v.durableManifest!==!1)}catch(T){try{await f(N)}catch(C){throw new se(oe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw T}return{stageId:N.stageId,entryId:N.entryId,blobIds:N.blobIds}},async discardStage(x){await y(),Da(x);let v=await Oa(n,x);v&&await f(v)},async previewStagedAppend(x,v){await y();let w=await g(v);return(await jd(n,r,x,w,m)).transition},async previewCursor(x,v){await y();let w=await h(x,v);return Qd(w,w.entryIds,x)},async publishStagedAppend(x,v,w){if(await y(),Ti(x,"entryId"),w){Da(w);let F=await Oa(n,w);if(!F||F.entryId!==x)throw new se(oe.INVALID_SCHEMA,"history stage does not match the published entry")}let N=await g(v),T=m,C=await jd(n,r,x,N,T),P=await Xd({rootDir:n,previousDigest:C.current.digest,entryIds:C.entryIds,cursor:C.cursor,readback:async()=>Jd(n,C.usage),afterWrite:async()=>{w?await Ni(n,w):await EE(n,x),await Vd(n,C.usage,[...T.entries.keys()].filter(F=>!C.usage.entries.has(F)),[...T.blobs.keys()].filter(F=>!C.usage.blobs.has(F)))}});return m=C.usage,d=P.digest,P},async append(x){await y();let v=await g(),w=await E.stageAppend(x);try{return await E.publishStagedAppend(w.entryId,v.digest,w.stageId)}catch(N){throw await E.discardStage(w.stageId),N}},async readEntry(x){return Ti(x,"entryId"),Vr(n,x)},async readBlob(x){Ti(x,"blobId");let v=await df(n,x),w=await Kr(v,oe.NOT_FOUND,"blob");return cf(w,x,v),w},async readIndex(){let x=Qt(),v=await Pi(n,x);return m=Ci(v.entryIds,x),d=v.digest,v},async readStatus(){let x=await Ai(n);return{canUndo:x.undoIds.length>0,canRedo:x.redoIds.length>0,undoDepth:x.undoIds.length,redoDepth:x.redoIds.length,cursor:x.cursor,recoveryRequired:await nt(o)||await nt(i)}},async readUndoRedoIds(){let x=await Ai(n);return{undoIds:x.undoIds,redoIds:x.redoIds,currentId:x.currentId}},async setCursor(x,v){await y();let w=await h(x,v),N=await Xd({rootDir:n,previousDigest:w.digest,entryIds:w.entryIds,cursor:x,readback:async()=>Jd(n,m)});return d=N.digest,N},async markRecoveryRequired(x){await nt(o)||await $r(_a(n),{schemaVersion:yt,reason:FE(x),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Le.rm(_a(n),{force:!0})},async readTransactionJournal(){return await nt(i)?Ri(i):null},async writeTransactionJournal(x){await y(),uf(x);try{await $r(i,x)}catch(w){let N=await Ri(i).catch(()=>null);if(N&&Buffer.from(rt(N)).equals(Buffer.from(rt(x))))return;throw N?new se(oe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:w}):w}let v=await Ri(i);if(!Buffer.from(rt(v)).equals(Buffer.from(rt(x))))throw new se(oe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(x){let v=await nt(i)?await Ri(i):null;if(v&&v.transactionId!==x)throw new se(oe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Le.rm(i,{force:!0})}catch(w){if(!await nt(i))return;throw w}if(await nt(i))throw new se(oe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let w of u)await Ni(n,w),u.delete(w);await IE(n);let x=Qt(),v=await Pi(n,x);await Ud(n,v.entryIds,x),m=Ci(v.entryIds,x),d=v.digest}};return Hd.set(E,()=>Ai(n)),E}async function jd(e,t,n,r,o){Ti(n,"entryId");let i=Qt(),s=await Vr(e,n,i),a={entries:new Map(o.entries),blobs:new Map(o.blobs),objectBytes:o.objectBytes},c=r.entryIds.slice(0,r.cursor+1);for(let u of r.entryIds.slice(r.cursor+1))Yd(a,u);Gd(a,s.id,i),c.push(s.id);let l=xE(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Qd(r,l.entryIds,l.cursor)}}function Qd(e,t,n){return qd(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:mE(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function mE(e,t){return ln(rt({schemaVersion:yt,entryIds:e,cursor:t}))}function qd(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new se(oe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function gE(e){if(!Ct(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 hE(e,t){if(!e.kind.trim())throw new se(oe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new se(oe.INVALID_JSON,"history blob name must not be empty");let l=PE(c.data),u=ln(l);n.push({name:c.name,bytes:l,digest:u,sizeBytes:l.byteLength}),r.push({name:c.name,digest:u,sizeBytes:l.byteLength})}let o={schemaVersion:yt,kind:e.kind,manifest:e.manifest,blobs:r},i=rt({...o}),s=ln(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new se(oe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function yE(e,t){let n=Wa(e,t.entryId),r={id:t.entryId,...t.entryBody},o=new Map(t.blobs.map(c=>[c.digest,c])),i=[...Array.from(o.values(),c=>$d(Ha(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Ya(e,c.digest))),$d(n,rt(r),{kind:"entry",digest:t.entryId},Ga(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function $d(e,t,n,r){let o=await $a(e)??(r?await $a(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new se(n.kind==="blob"?oe.BLOB_CORRUPT:oe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await sf(e,t)}function xE(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+rt(rf(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new se(oe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Yd(n,r.shift()),o-=1}}async function bE(e,t,n){Ua(t);let r=za(e,t.stageId);if(n){await $r(r,t);return}await NE(r,t)}async function Oa(e,t){let n=await $a(za(e,t));if(n===null)return null;let r=Xr(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Ua(r);if(o.stageId!==t)throw new se(oe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Mi(e){let t=[];for(let n of await _i(Xa(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Da(r);let o=await Oa(e,r);o&&t.push(o)}return t}async function Vd(e,t,n,r,o){if(n.length===0&&r.length===0)return;let i=new Set(t.entries.keys()),s=new Set;for(let a of await Mi(e))if(a.stageId!==o){i.add(a.entryId);for(let c of a.blobIds)s.add(c)}for(let a of new Set(n))i.has(a)||await Kd(Wa(e,a),Ga(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Kd(Ha(e,a),Ya(e,a));await Va(zr(e)),await Va(Wr(e))}async function Ni(e,t){await La(za(e,t)),await SE(e)}async function SE(e){try{await Le.rmdir(Xa(e))}catch(t){if(Hr(t)||Ct(t)&&t.code==="ENOTEMPTY")return;throw t}}async function EE(e,t){for(let n of await Mi(e))n.entryId===t&&await Ni(e,n.stageId)}async function La(e){if(await Le.rm(e,{force:!0}),await nt(e))throw new se(oe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Kd(e,t){await La(e),await La(t)}function Ua(e){if(!Ct(e)||e.schemaVersion!==Ma||typeof e.stageId!="string"||!ef(e.stageId)||!lt(e.entryId))throw new se(oe.INVALID_SCHEMA,"history stage schema is invalid");let t=af(e.blobIds,"history stage blobIds");return{schemaVersion:Ma,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Da(e){if(!ef(e))throw new se(oe.INVALID_PATH,"history stageId must be a UUID")}function ef(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 Ud(e,t,n=Qt()){let r=new Set(t),o=new Set;for(let l of t){let u=await Vr(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Mi(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=zr(e),s=await _i(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Wd(l.slice(0,-5));u&&!r.has(u)&&await Fi(De.join(i,l))}let a=Wr(e),c=await _i(a);for(let l of c){let u=Wd(l);u&&!o.has(u)&&await Fi(De.join(a,l))}}async function Pi(e,t=Qt()){let{index:n,sizeBytes:r}=await Jr(e),{totalBytes:o}=await tf(e,n.entryIds,t,r);return{...Oi(n),totalBytes:o}}async function Jd(e,t){let{index:n,sizeBytes:r}=await Jr(e);return{...Oi(n),totalBytes:t.objectBytes+r}}async function Jr(e){let t=Ja(e),n=await Kr(t,oe.NOT_FOUND,"index"),r=Xr(Buffer.from(n).toString("utf8"),"index");return{index:CE(r),sizeBytes:n.byteLength}}async function Ai(e){return Oi((await Jr(e)).index)}function Oi(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:yt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function tf(e,t,n,r){let o=0,i=new Set;o+=r??(await Jr(e)).sizeBytes;for(let s of new Set(t)){let a=await Vr(e,s,n);o+=n.entries.get(s).sizeBytes;for(let c of a.blobs)i.has(c.digest)||(i.add(c.digest),o+=n.blobSizes.get(c.digest))}return{totalBytes:o}}async function Vr(e,t,n=Qt()){let r=n.entries.get(t);if(r)return r.entry;let o=await _E(e,t),i=await Kr(o,oe.NOT_FOUND,"entry"),s=Xr(Buffer.from(i).toString("utf8"),`entry ${t}`),a=RE(s);if(a.id!==t)throw new se(oe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(ln(rt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new se(oe.ENTRY_CORRUPT,`entry hash mismatch for ${t}`);let l=[...new Set(a.blobs.map(d=>d.digest))].filter(d=>!n.blobSizes.has(d)),u=async d=>{let m=await df(e,d),g=await Kr(m,oe.NOT_FOUND,"blob");return cf(g,d,m),g.byteLength};if(l.length===1)n.blobSizes.set(l[0],await u(l[0]));else if(l.length>1){let d=new Array(l.length),m=[],g=0,f=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&m.length===0;){let E=g++;try{d[E]=await u(l[E])}catch(x){m.push({index:E,error:x})}}}),h=await Promise.allSettled(f),y=m.sort((E,x)=>E.index-x.index)[0];if(y)throw y.error;for(let E of h)if(E.status==="rejected")throw E.reason;for(let E=0;E<l.length;E++)n.blobSizes.set(l[E],d[E])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function nf(e,t,n){await $r(Ja(e),rf(t,n))}function rf(e,t){return{schemaVersion:yt,digest:ln(rt({schemaVersion:yt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function of(e,t){if(t!==void 0&&e.digest!==t)throw new se(oe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Xd(e){of(await Ai(e.rootDir),e.previousDigest);let t=ln(rt({schemaVersion:yt,entryIds:e.entryIds,cursor:e.cursor}));try{await nf(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new se(oe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Pi(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new se(oe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function vE(e){await Le.mkdir(e,{recursive:!0}),await Le.mkdir(zr(e),{recursive:!0}),await Le.mkdir(Wr(e),{recursive:!0}),await Le.mkdir(Ur(e),{recursive:!0})}async function kE(e){await Le.rm(Ur(e),{recursive:!0,force:!0}),await Le.mkdir(Ur(e),{recursive:!0})}async function IE(e){let t=Ur(e);await Le.mkdir(t,{recursive:!0});for(let n of await _i(t))n!=="stages"&&await Le.rm(De.join(t,n),{recursive:!0,force:!0})}function CE(e){if(!Ct(e))throw new se(oe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==yt)throw new se(oe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=af(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new se(oe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!lt(o))throw new se(oe.INDEX_CORRUPT,"index digest is invalid");let i=ln(rt({schemaVersion:yt,entryIds:t,cursor:r}));if(o!==i)throw new se(oe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:yt,digest:o,entryIds:t,cursor:r}}function RE(e){if(!Ct(e))throw new se(oe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==yt)throw new se(oe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!lt(t))throw new se(oe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new se(oe.ENTRY_CORRUPT,"entry kind is invalid");let r=ja(e.manifest,"entry.manifest"),o=wE(e.blobs);return{id:t,schemaVersion:yt,kind:n,manifest:r,blobs:o}}function wE(e){if(!Array.isArray(e))throw new se(oe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Ct(t))throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!lt(o))throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new se(oe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function $r(e,t){await sf(e,rt(t))}async function NE(e,t){let n=De.dirname(e),r=De.basename(e),o=De.join(n,`.${r}.${process.pid}.${Ka()}.tmp`);await Le.mkdir(n,{recursive:!0});try{await Le.writeFile(o,rt(t),{flag:"wx"}),await Le.rename(o,e)}finally{await Fi(o)}}async function sf(e,t){let n=De.dirname(e),r=De.basename(e),o=De.join(n,`.${r}.${process.pid}.${Ka()}.tmp`);await Le.mkdir(n,{recursive:!0});try{let i=await Le.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Le.rename(o,e),await Va(n)}finally{await Fi(o)}}function rt(e){return Buffer.from(JSON.stringify(Ba(e)),"utf8")}function Ba(e){if(Array.isArray(e))return e.map(t=>Ba(t));if(Ct(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Ba(e[n]);return t}return e}function Xr(e,t){try{return JSON.parse(e)}catch(n){throw new se(oe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function ja(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=>ja(n,t));if(Ct(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=ja(o,t);return n}break}throw new se(oe.INVALID_JSON,`${t} must be JSON-serializable`)}function af(e,t){if(!Array.isArray(e))throw new se(oe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!lt(n))throw new se(oe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ti(e,t){if(!lt(e))throw new se(oe.INVALID_PATH,`${t} must be a sha256 digest`)}function lt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function ln(e){return`sha256:${cE("sha256").update(e).digest("hex")}`}function PE(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Kr(e,t,n){try{return await Le.readFile(e)}catch(r){throw new se(t,`${n} not found: ${e}`,{cause:r})}}async function $a(e){try{return await Le.readFile(e)}catch(t){if(Hr(t))return null;throw t}}function cf(e,t,n){if(ln(e)!==t)throw new se(oe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function nt(e){try{return await Le.access(e),!0}catch(t){if(Hr(t))return!1;throw t}}async function Fi(e){try{await Le.rm(e,{force:!0,recursive:!0})}catch{}}async function Va(e){try{let t=await Le.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function _i(e){try{return await Le.readdir(e)}catch(t){if(Hr(t))return[];throw t}}function AE(e){if(typeof e!="string"||e.trim().length===0)throw new se(oe.INVALID_ROOT,"history store rootDir must be a non-empty string");return De.resolve(e)}function Ja(e){return De.join(e,uE)}function _a(e){return De.join(e,dE)}function TE(e){return De.join(e,fE)}function lf(e){return De.join(e,pE)}async function zd(e){try{let t=await Le.readFile(lf(e),"utf8"),n=Xr(t,"document version");if(!Ct(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new se(oe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Hr(t))return 0;throw t}}async function Ri(e){let t=await Kr(e,oe.RECOVERY_PENDING,"transaction journal"),n=Xr(Buffer.from(t).toString("utf8"),"transaction journal");return uf(n),n}function uf(e){if(!Ct(e)||e.schemaVersion!==lE||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!gE(e.historyTransition)||!Array.isArray(e.files))throw new se(oe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Ct(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!lt(t.preDigest)||t.postDigest!==null&&!lt(t.postDigest))throw new se(oe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function FE(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function zr(e){return De.join(e,"entries")}function Wr(e){return De.join(e,"blobs")}function Ur(e){return De.join(e,"tmp")}function Xa(e){return De.join(Ur(e),"stages")}function za(e,t){return De.join(Xa(e),`${t}.json`)}function Wa(e,t){return De.join(zr(e),`${pf(t)}.json`)}function Ha(e,t){return De.join(Wr(e),pf(t))}function Ga(e,t){return De.join(zr(e),`${t}.json`)}function Ya(e,t){return De.join(Wr(e),t)}async function _E(e,t){return ff(Wa(e,t),Ga(e,t))}async function df(e,t){return ff(Ha(e,t),Ya(e,t))}async function ff(e,t){return await nt(e)?e:await nt(t)?t:e}function pf(e){return e.slice(7)}function Wd(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return lt(t)?t:null}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function ME(e){return{maxEntries:e?.maxEntries??wi.maxEntries,maxSessionBytes:e?.maxSessionBytes??wi.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??wi.maxEntryBytes}}async function OE(e){let t=Ja(e);await nt(t)||await nf(e,[],-1)}var DE={affectedCompositions:[]};function xf(e){let t=null,n=new WeakMap;async function r(){return t??=BE(e),t}async function o(i){if(!i)return null;let s=Za(i);return s?jE(e,s):i}return{async prepareAppend(i){let s=await sr(e),a=await e.stageAppend(hf(i),{durableManifest:!1}),c;try{c=await e.previewStagedAppend(a.entryId,s.digest)}catch(u){throw await e.discardStage(a.stageId),u}let l={kind:"append",entry:i,historyTransition:c};return n.set(l,{expectedDigest:s.digest,stageId:a.stageId,entryId:a.entryId}),l},async prepareUndo(){let i=await r(),s=await o(i.undo.at(-1));if(!s?.historyId)return null;let a=await sr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("undo entry is missing from index");if(c!==a.cursor)throw new Error("undo state changed before prepare");let l=c-1,u=await e.previewCursor(l,a.digest),d={kind:"undo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async prepareRedo(){let i=await r(),s=await o(i.redo.at(-1));if(!s?.historyId)return null;let a=await sr(e),c=a.entryIds.indexOf(s.historyId);if(c<0)throw new Error("redo entry is missing from index");if(c!==a.cursor+1)throw new Error("redo state changed before prepare");let l=c,u=await e.previewCursor(l,a.digest),d={kind:"redo",entry:s,historyTransition:u};return n.set(d,{expectedDigest:a.digest,cursor:l}),d},async publishPrepared(i){let s=n.get(i);if(!s)throw new Error("history mutation was not prepared");let a=await r();if(i.kind==="append"){if(!s.entryId)throw new Error("staged entry id is missing");let c=await e.publishStagedAppend(s.entryId,s.expectedDigest,s.stageId);mf(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,ar(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Za(c.at(-1))!==Za(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);mf(l,i.historyTransition),Object.assign(a,ar(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await sr(e);if(c.digest===a.publishedIndexDigest&&c.cursor===a.publishedCursor&&c.currentId===a.publishedCurrentId)throw new Error("cannot discard a history mutation whose index was published")}s.stageId&&await e.discardStage(s.stageId),n.delete(i)},async peekUndo(){return o((await r()).undo.at(-1))},async pushUndo(i){let s=await r(),a=i;if(a.historyId){let u=s.entryIds.indexOf(a.historyId);if(u>=0)try{let d=await e.setCursor(u);Object.assign(s,ar(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(hf(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,ar(c))},async popUndo(){let i=await r(),s=await o(i.undo.at(-1));return i.undo.pop(),s},async peekRedo(){return o((await r()).redo.at(-1))},async pushRedo(i){let s=await r(),a=i;if(!a.historyId)throw s.undo.push(i),new Error("cannot move an unpersisted history entry to redo");let c=s.entryIds.indexOf(a.historyId);if(c<0)throw s.undo.push(i),new Error("history entry is missing from the durable index");try{let l=await e.setCursor(c-1);Object.assign(s,ar(l))}catch(l){throw s.undo.push(i),l}},async popRedo(){let i=await r(),s=await o(i.redo.at(-1));return i.redo.pop(),s},async clearRedo(){(await r()).redo.length=0},async getStatus(){let i=await e.readStatus();return{canUndo:i.canUndo,canRedo:i.canRedo,undoDepth:i.undoDepth,redoDepth:i.redoDepth,recoveryRequired:i.recoveryRequired}},async markRecoveryRequired(i){await e.markRecoveryRequired(i)}}}function mf(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")}function Za(e){return typeof e=="string"?e:e?.historyId}async function BE(e){let t=await sr(e);return ar(t)}function ar(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function jE(e,t){let n=await e.readEntry(t),r=$E(n),o=r.provenance??DE;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 gf(e,n,r.preSnapshots),postSnapshots:await gf(e,n,r.postSnapshots)}}async function gf(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(UE(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function hf(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 u=`${s}-${c}`;l.blobName=u,t.push({name:u,data:a.content})}return l}),r=VE(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 $E(e){if(!Sf(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:bf(t.provenance)}:{},preSnapshots:yf(t.preSnapshots,"preSnapshots"),postSnapshots:yf(t.postSnapshots,"postSnapshots")}}function VE(e){if(e.provenance!==void 0)return bf(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function bf(e){let t=LE.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 yf(e,t){return e.map((n,r)=>{if(!Sf(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&&!KE(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 KE(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function UE(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Sf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomBytes as ov}from"node:crypto";import Di from"node:path";import{parse as Af}from"@babel/parser";import iv from"@babel/traverse";import*as Tf from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as qa,PageResourceArtifactSchema as sv,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as av,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as cv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as lv,parseComponentI18nResourcesJson as uv}from"@vcp-dev/contracts";var vf=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,kf=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,JE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,XE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,zE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,WE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,HE=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,GE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,YE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,ZE=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,QE=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,qE=/\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,ev=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,tv=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Gr(e,t){let n=Li([...xt(e,JE),...xt(e,XE),...xt(e,zE),...xt(e,t.includeRgbBackgroundImage?WE:HE),...t.includeExtendedColorFunctions?[...xt(e,GE),...xt(e,YE)]:[]]),r=Li([...xt(e,ZE),...xt(e,QE)]).filter(o=>t.colorMixPolicy==="always"||vf.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...xt(e,qE).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...xt(e,tv).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Li(xt(e,kf)),hardCodedSurfaceOccurrences:rv(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Li(xt(e,ev)):[]}}function xt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var Ef=160,nv=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function rv(e){let t=new RegExp(kf.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),u=nv.exec(l),d=r(i.index),m=e.indexOf(`
|
|
6
|
+
`,i.index),g=e.slice(n[d]??0,m===-1?void 0:m).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>Ef?`${g.slice(0,Ef-1)}\u2026`:g})}return o}function Li(e){return[...new Set(e)]}var ec="{{$INSTANCE}}",dv=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,fv=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,tc="components/site/generated",pv=/\.(?:tsx?|json)$/,mv=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,gv=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],hv=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Qa=iv,yv=typeof Qa=="function"?Qa:Qa.default;async function nc(e){let t=sv.safeParse(e.artifact);if(!t.success)return Fe("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>ov(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=Rv(r());if(!i)return Fe("Random instance suffix must be 8 lowercase hex chars.");let s=`${wv(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let v of n.pages){let w=v.final_route.slice(1);a.set(v.template_page_id,v.final_route),c.set(v.template_page_id,v.title),l.push({template_page_id:v.template_page_id,title:v.title,final_route:v.final_route,route_file_path:`app/${w}/page.tsx`})}let u=[],d=new Set,m=new Set,g=new Map,f=new Map,h=[],y=new Set(n.pages.flatMap(v=>v.components.map(w=>w.component_id)));for(let v of n.components){if(!y.has(v.component_id))continue;let w=If({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!w.ok)return w;for(let N of w.files){let T=Rf(N,d,u);if(T)return T}m.add(w.entry),f.set(w.entry,w.entryExport),g.set(v.component_id,w.entry)}for(let[v,w]of n.pages.entries()){let N=l[v],T=If({materialization:w.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:N.route_file_path,pageTitle:N.title});if(!T.ok)return T;for(let C of T.files){let P=Rf(C,d,u);if(P)return P}m.add(T.entry),f.set(T.entry,T.entryExport),h.push({entry:T.entry,declaredComponentIds:new Set(w.components.map(C=>C.component_id))})}let E=bv(u,m,s,g,h,f);if(!E.ok)return E;for(let v of u)if(await e.exists(v.file))return!v.file.startsWith("app/")&&o>1?nc({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${v.file}`,path:v.file};let x=Sv(u);return x||(u.sort((v,w)=>v.file.localeCompare(w.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function If(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:Cf(o.pathTemplate,e.packageInstanceId);if(!s)return Fe("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=xv(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?vv(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??Cf(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Fe("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function xv(e,t,n,r){let o,i=e.replace(dv,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Fe(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(fv,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Fe(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ec,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Fe("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function Cf(e,t){let n=`${tc}/${t}`;if(e.split(ec).length>2)return null;let o=e.replace(ec,t),i=`${tc}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Di.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!pv.test(a)||mv.test(a)?null:a}function Rf(e,t,n){return t.has(e.file)?Fe(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function bv(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${tc}/${n}`,c=new Map(e.map(g=>[g.file,new Set])),l=new Map;for(let g of e){if(g.file.endsWith(".json")){try{JSON.parse(g.content)}catch{return Fe("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(qa)&&!uv(g.content).success)return Fe("Materialization component i18n resources are invalid.",g.file);continue}try{let h=Af(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,h);for(let E of h.program.body)if((E.type==="ImportDeclaration"||E.type==="ExportAllDeclaration"||E.type==="ExportNamedDeclaration"&&E.source)&&E.source){let x=E.source.value,v=Iv(g.file,x,s,a);if(!v.allowed)return Fe(`Materialization import is outside the controlled package: ${x}`,g.file);v.internalPath&&c.get(g.file).add(v.internalPath)}let y;if(yv(h,{Identifier(E){E.isReferencedIdentifier()&&hv.has(E.node.name)&&(y??=E.node.name,E.stop())},JSXAttribute(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name==="style"&&(y??="inline style",E.stop())},JSXOpeningElement(E){E.node.name.type==="JSXIdentifier"&&E.node.name.name.toLowerCase()==="style"&&(y??="style element",E.stop())}}),y)return Fe(`Materialization source uses forbidden capability: ${y}`,g.file)}catch{return Fe("Materialization source must parse as TS/TSX.",g.file)}let f=Gr(g.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(f.hardCodedSurfaceHits.length>0||f.rawColorHits.length>0||f.privateTokenHits.length>0)return Fe("Materialization source violates the public theme token policy.",g.file)}if([...t].some(g=>!s.has(g)))return Fe("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Fe("Materialization JSON files cannot be package entries.");for(let[g,f]of i){let h=l.get(g);if(!h||!Ev(h,f))return Fe("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,f])=>[f,g]));for(let g of o){let f=Pf(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!f.has(y))return Fe(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of f){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return Fe(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let f of Pf(g,c))d.add(f);if(d.size!==e.length)return Fe("Every materialization file must be reachable from a package entry.");let m=Cv(e,l,c);return m||{ok:!0}}function Sv(e){if(e.length>av)return Fe("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>cv)return Fe("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>lv?Fe("Page resource exceeds the aggregate content byte limit."):null}function Ev(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 vv(e,t,n){let r;try{r=Af(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Fe("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=wf(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&kv(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=wf(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"?{ok:!0,data:e}:{ok:!0,data:e.slice(0,l.start)+JSON.stringify(t)+e.slice(l.end)}:{ok:!0,data:e}}}return{ok:!0,data:e}}function wf(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Tf.isExpression(t)?t:null}function kv(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function Iv(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Nf(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:gv.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=Nf(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Nf(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 Cv(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(qa))continue;let i=o.file.slice(0,-qa.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Fe("Component i18n resources require a same-name TS/TSX companion.",o.file);let c=t.get(s)?.program.directives.some(u=>u.value.value==="use client"),l=[...n].filter(([,u])=>u.has(o.file));if(!c||l.length!==1||l[0]?.[0]!==s)return Fe("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Pf(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 Rv(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function wv(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Fe(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as Nv}from"node:crypto";import qt from"node:path";import{parse as Pv}from"@babel/parser";import Av from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Bi,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as Ff,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as Tv,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as Fv,SiteEditMaterializationSchema as _v,parseComponentI18nResourcesJson as Mv}from"@vcp-dev/contracts";var ic="components/site/generated",_f="{{$INSTANCE}}",ji=5,Ov=/^[a-z][a-z0-9-]{0,48}$/,Lv=/^[a-f0-9]{8}$/,Mf=/\.tsx?$/,Dv=/\.json$/,Bv=/\.(?:tsx?|json)$/,jv=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,$v=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Vv=["react","react/","next","next/","lucide-react","react-i18next","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],rc=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),oc=Av,Kv=typeof oc=="function"?oc:oc.default;function Uv(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>Ff)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=ek(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=_v.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=Zv(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ic}.`,path:e.generatedRoot}};if(!$f(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=Df(r.data.files),s=Df(e.controlledFiles);if(!tk(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>Ff)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 u=Buffer.byteLength(l.content,"utf8");if(u>Tv)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+=u}return a>Fv?{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 Jv(e){let t=Uv(e);if(!t.ok)return t;let n=Object.keys(e.manifest.projectDependencies??{}),r=new Set(e.availableHostDependencies??[]),o=n.find(u=>!jv.test(u)||!r.has(u));if(o)return{ok:!1,error:{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:`Declared project dependency is not available in the target site host: ${o}.`,path:o}};let i=n.flatMap(u=>[u,`${u}/`]),s=[...e.allowedExternalImports??Vv,...i],a=t.data.generatedRoot,c=$f(e.manifest.instanceBaseName),l=Math.max(1,Math.min(ji,e.maxAttempts??ji));for(let u=0;u<l;u+=1){let d=Qv(e.instanceNameGenerator?.()??Nv(4).toString("hex"));if(!d)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let m=`${c}-${d}`,g=Kf(a,m),f=Xv({manifest:e.manifest,generatedRoot:a,instanceName:m,instanceRoot:g,allowedExternalImports:s});if(!f.ok)return f;if(!await zv(e.exists,g,f.data.files))return{ok:!0,data:f.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function jf(e){let t=Math.max(1,Math.min(ji,e.maxAttempts??ji));for(let n=0;n<t;n+=1){let r=await Jv({...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 Xv(e){let t=[],n=new Set;for(let i of e.manifest.files){let s=Of({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=Of({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=Wv(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 zv(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Of(e){if(e.pathTemplate.split(_f).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(_f,e.instanceName),n=qv(t);return n?Kf(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||!Bv.test(n)||$v.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 Wv(e,t,n,r,o){let i=new Set(e.map(d=>d.path)),s=new Map,a=new Map(e.map(d=>[d.path,new Set])),c=new Map;for(let d of e){if(Dv.test(d.path)){if(d.path.endsWith(Bi)){let f=Mv(d.content);if(!f.success)return Tn("MATERIALIZATION_DATA_UNSUPPORTED",f.error.message,d.path);c.set(d.path,new Set)}else try{JSON.parse(d.content)}catch{return Tn("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",d.path)}continue}let m;try{m=Pv(d.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:d.path}}}let g=Gr(d.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{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:d.path}};s.set(d.path,m)}for(let d of e){if(!Mf.test(d.path))continue;let m=s.get(d.path),g=null;if(Kv(m,{ImportDeclaration(f){let h=Lf({importer:d.path,source:f.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});if(!h.allowed)g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:d.path},f.stop();else if(h.internalPath&&(a.get(d.path).add(h.internalPath),h.internalPath.endsWith(Bi))){let y=Hv({importer:d.path,imported:h.internalPath,source:f.node.source.value,ast:m});y.ok?c.get(h.internalPath).add(d.path):(g??=y.error,f.stop())}},ExportAllDeclaration(f){g??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:d.path},f.stop()},ExportNamedDeclaration(f){if(f.node.source){let h=Lf({importer:d.path,source:f.node.source.value,instanceRoot:t,filePaths:i,allowedExternalImports:o});!h.allowed||!h.internalPath?(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:d.path},f.stop()):a.get(d.path).add(h.internalPath)}},CallExpression(f){if(f.node.callee.type==="Import"){g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:d.path},f.stop();return}f.node.callee.type==="Identifier"&&f.node.callee.name==="require"&&(g??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:d.path},f.stop())},NewExpression(f){f.node.callee.type==="Identifier"&&f.node.callee.name==="Function"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:d.path},f.stop())},MetaProperty(f){f.node.meta.type==="Identifier"&&f.node.meta.name==="import"&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:d.path},f.stop())},MemberExpression(f){let h=Bf(f.node);h&&rc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},f.stop())},OptionalMemberExpression(f){let h=Bf(f.node);h&&rc.has(h)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${h}.`,file:d.path},f.stop())},Identifier(f){f.isReferencedIdentifier()&&rc.has(f.node.name)&&(g??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${f.node.name}.`,file:d.path},f.stop())},JSXAttribute(f){f.node.name.type==="JSXIdentifier"&&f.node.name.name==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:d.path},f.stop())},JSXOpeningElement(f){f.node.name.type==="JSXIdentifier"&&f.node.name.name.toLowerCase()==="style"&&(g??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:d.path},f.stop())}}),g)return{ok:!1,error:g}}if(!Mf.test(n))return Tn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",n);let l=s.get(n);if(!l)return Tn("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",n);if(!Gv(l,r))return Tn("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",n);for(let[d,m]of c)if(m.size!==1)return Tn("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",d);return Yv(n,a).size!==e.length?Tn("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",n):{ok:!0,data:{kind:"static-prefab-materialization",instanceName:"",generatedRoot:ic,instanceRoot:"",entry:{path:"",export:{kind:"default"}},files:[]}}}function Lf(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=qt.posix.normalize(qt.posix.join(qt.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 Hv(e){let t=qt.posix.dirname(e.importer),n=qt.posix.dirname(e.imported),r=qt.posix.basename(e.importer).replace(/\.tsx?$/,""),o=qt.posix.basename(e.imported).slice(0,-Bi.length),i=`./${r}${Bi}`;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 Gv(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 Yv(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 Tn(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function Zv(e){let t=Vf(e);return t===ic?t:null}function Qv(e){let t=e.trim().toLowerCase();return Lv.test(t)?t:null}function $f(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 Ov.test(t)?t:null}function Vf(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=qt.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function qv(e){let t=Vf(e);return!t||t!==e?null:t}function Kf(...e){return qt.posix.join(...e)}function Df(e){return new Set(e.map(t=>t.pathTemplate))}function ek(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 tk(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Bf(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 Sc}from"node:crypto";import pc from"@babel/traverse";function sc(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(u=>u.anchorSourceRange!==null&&u.members.length>0)??c.find(u=>u.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(u=>u.placementKey)),sourcePlacementKey:l.placementKey})))}return{placementByKey:t,unitByKey:r,placementsByUnitKey:o,sourcePlacementByUnitKey:i}}import{createHash as nk}from"node:crypto";import Uf from"node:path";import*as Hf from"@babel/parser";import ac from"@babel/generator";import*as Ue from"@babel/types";var Jf=typeof ac=="function"?ac:ac.default;function lc(e){let t=Yf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=fc(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=ik(n,o),s={jsx:`<${e.component.localName} />`},a=rk(e);if(i){let g=cc(e);return g.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:g.locator,sourceHash:g.sourceHash,node:s,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:g.result}let c=o.containerSourceRange??n.container.sourceRange,l=o.containerSourceHash??(dc(c,n.container.sourceRange)?n.container.sourceHash:null);if(!c||!l)return Yr("Route page composition does not expose a verifiable container boundary.");let u=Qr(c),d=zf(e.source,u,l,"Route page composition container");if(!d.ok)return d.result;let m=o.anchorSourceRange?Qr(o.anchorSourceRange):void 0;if(m){if(!o.anchorSourceHash)return Yr("Route page composition placement does not expose a verifiable anchor boundary.");let g=zf(e.source,m,o.anchorSourceHash,"Route page composition anchor");if(!g.ok)return g.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:u,node:s,placement:o.relation,...m?{anchorLocator:m}:{}}}}}function rk(e){let t=lk(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 $i(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Fn(e.source,"Root expression rewrite requires an exact expression locator.");let t=wr(e.source,"value");if(!t.ok)return Fn(e.source,t.diagnostic.message);let n=ce(t.ast,e.locator);if(!n.ok)return Fn(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Fn(e.source,"Resolved value locator does not point to an expression.");let o=cr(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Fn(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(Ue.nullLiteral()),{ok:!0,source:Jf(t.ast,{}).code};let i;try{i=Hf.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Fn(e.source,s instanceof Error?s.message:String(s))}return!Ue.isJSXElement(i)&&!Ue.isJSXFragment(i)?Fn(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(ok(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Jf(t.ast,{}).code})}function ok(e,t,n,r){if(Ue.isNullLiteral(e)||r)return t;let o=Ue.isJSXFragment(e)?[...e.children]:[Ue.isJSXElement(e)?e:Ue.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return Ue.jsxFragment(Ue.jsxOpeningFragment(),Ue.jsxClosingFragment(),s)}function Fn(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function uc(e){let t=Yf(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Zf(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(sk(n,o)){let h=cc(e);return h.ok?e.operation==="remove-node"&&!Xf(n,o.placementUnitKey)?Yr("The last editable page unit cannot be deleted."):e.operation==="move-node"?Yr("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=Qr(o.sourceRange),a=Ot(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?[]:[Zr(a.diagnostic)]}};if(cr(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=cc(e);return h.ok?Xf(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}}}:Yr("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||!ck(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=fc(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 u=l.placement;if(u.placementUnitKey!==e.targetPlacement.placementUnitKey||u.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 d=u.containerSourceRange;if(!d||!u.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=Qr(d),g=Ot(e.source,m);if(!g.ok||!g.match.node)return{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:g.ok===!1?g.diagnostic.message:"Route page composition target container could not be resolved.",diagnostics:g.ok?[]:[Zr(g.diagnostic)]}};if(cr(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Wf("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let h=u.anchorSourceRange,y=u.anchorSourceHash;if(!h||!y)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=Qr(h),x=Ot(e.source,E);return!x.ok||!x.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:x.ok===!1?x.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:x.ok?[]:[Zr(x.diagnostic)]}}:cr(e.source,x.match.node.start??null,x.match.node.end??null)!==y?Wf("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:u.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:u.relation}}}}function Xf(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function ik(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&dc(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 sk(e,t){return e.container.kind!=="jsx-container"&&dc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function cc(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Ot(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?[]:[Zr(r.diagnostic)]}}}:cr(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Gf("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function zf(e,t,n,r){let o=Ot(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?[]:[Zr(o.diagnostic)]}}}:cr(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Gf(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Gf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Yr(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Wf(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Zr(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Yf(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&&!ak(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 ak(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function ck(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function lk(e,t){let n=Uf.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Uf.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Qr(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function cr(e,t,n){return t==null||n==null?null:`sha256:${nk("sha256").update(e.slice(t,n)).digest("hex")}`}function dc(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 uk=typeof pc=="function"?pc:pc.default;function tp(e){if(!e.ast)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=xk(e.ast);if(!t)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Sk(t);if(!n.ok)return Rt(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=vk(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Ik(r,t))return Rt(e,[Ve("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return gc(e,t,"virtual-route-root",r);if(kk(r)){let o=Nk({input:e,source:e.source,expression:r});return mc(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Oe(r)&&!un(r)){let o=xc(r),i=ep({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return mc(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Rk(r);if(!o.ok)return Rt(e,[o.diagnostic]);let i=lr(o.path);if(i.unsupported)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Ck(e.source,r,i.members))return gc(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Oe(r);if(i.members.length===0&&s)return gc(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=ep({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return mc(e,t,l,{kind:a,sourceKind:c},r)}return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function fc(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Zf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ve("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:Ve("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function np(e){return e.ok?dk(e.projection):fk(e.projection)}function dk(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,u]of t){let d=u.members.flatMap((h,y)=>rp(e,u,h,y,e.container.placementKey)),m=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>mk(l,h,u.independent)),g=d.length>0?d:[{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,g.map(({sourceMember:h})=>h)),o.set(l,m);let f=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:f,businessMemberKeys:m.map(h=>h.key),isMultiMember:u.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:pk(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function fk(e){let t=e.diagnostics.map(gk);return{status:"unsupported",version:e.version,composition:e.composition,reason:hk(e.diagnostics),diagnostics:t}}function pk(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 rp(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)=>rp(e,t,a,c,i))]}function mk(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function gk(e){return{code:yk(e),message:e.message}}function hk(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 yk(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 xk(e){let t=null;return uk(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=bk(o.path);i&&(t=i,n.stop())}}),t}function bk(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 Sk(e){let t=e.get("body");if(!t.isBlockStatement()){let s=eo(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ve("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:Ve("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ve("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(!Ek(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(op(s)||ip(s))return{ok:!1,diagnostic:Ve("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=eo(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ve("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Ek(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(op(o)||ip(o))return null;return r}function op(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function ip(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function vk(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=eo(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 kk(e){return e.isConditionalExpression()?Qf(eo(e.get("consequent")))&&Qf(eo(e.get("alternate"))):!1}function Qf(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function eo(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 Ik(e,t){if(e.isIdentifier())return qf(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return qf(n.node.name,t)}return!1}function qf(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 Ck(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&yc(t)}function yc(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(!yc(t))return!1;continue}if(t.isJSXElement()&&!yc(t))return!1}return!0}function Rk(e){let t=e;if(e.isJSXFragment()||Oe(e)){let r=qr(e),o=r[0];if(r.length===1&&o?.isJSXElement()&&un(o))t=o;else return{ok:!0,path:t}}for(;t.isJSXElement()&&un(t);){let r=qr(t);if(r.length!==1)return{ok:!0,path:t};let o=r[0];if(!o?.isJSXElement()||!un(o))return{ok:!0,path:t};if(qr(o).length<=1)return{ok:!0,path:t};t=o}return{ok:!0,path:t}}function qr(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(...qr(n));continue}n.isJSXElement()&&(Oe(n)?t.push(...qr(n)):t.push(n))}return t}function lr(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:bc(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:bt(r.node.loc),businessMemberCount:0,parentSourceRange:bt(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=lr(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=un(o)?lr(o):null;n||=i?.unsupported??!1,t.push({...xc(o,i?.members),sourceRange:bt(r.node.loc),parentSourceRange:bt(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:bc(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:bt(r.node.loc),businessMemberCount:1,parentSourceRange:bt(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Oe(r)){let o=lr(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=un(r)?lr(r):null;n||=o?.unsupported??!1,t.push({...xc(r,o?.members),parentSourceRange:bt(e.node.loc)})}}return{members:t,unsupported:n}}function xc(e,t){let n=e.isJSXElement()&&un(e)?t??lr(e).members:[],r=e.isJSXElement()&&!un(e)&&!Oe(e);return{memberKey:bc(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:bt(e.node.loc),businessMemberCount:r?1:sp(n),parentSourceRange:bt(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:wk(e)}}function un(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function wk(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 sp(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Vi(e){return e.length===0?0:Math.max(1,sp(e))}function ep(e){let t=bt(e.containerPath.node.loc),n=Ec(e.source,e.containerPath.node.start,e.containerPath.node.end),r=St(e.input,e.containerKind,e.sourceKind,t),o=St(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Vi(e.members)<=1,memberCount:Vi(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Nk(e){let t=bt(e.expression.node.loc),n=Ec(e.source,e.expression.node.start,e.expression.node.end),r=St(e.input,"virtual-route-root","atomic-expression",t),o=St(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:St(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 ap(e,t){let n=bt(t.node.loc),r=Ec(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function mc(e,t,n,r,o){let i=ap(e,o);if(!i)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=Pk(e,n,s),c=sc(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:lp(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 Pk(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,m,g,f,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Vi(f)<=1,memberCount:Vi(f),sourceRange:m,sourceHash:m?hc(e.source,m):null,relation:l,containerSourceRange:h,containerSourceHash:h?hc(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?hc(e.source,g):null,members:f}),i=t.placementKey,s=t.members.map(l=>St(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",St(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=St(e,i,"placement-unit",l.sourceRange);r.push(o("before",St(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",St(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function gc(e,t,n,r){let o=ap(e,r);if(!o)return Rt(e,[Ve("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=St(e,n,"empty-container",void 0),s=St(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=sc([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:lp(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 Rt(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 Ve(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function St(e,t,n,r){return cp([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function bc(e,t,n){return cp(["member",e,String(t??-1),String(n??-1)])}function cp(e){return`pc_${Sc("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Ec(e,t,n){return t==null||n==null?null:`sha256:${Sc("sha256").update(e.slice(t,n)).digest("hex")}`}function hc(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:${Sc("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function bt(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function lp(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 Vk}from"@vcp-dev/contracts";import h_ from"node:fs";import x_ from"node:path";var Tk=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function to(e){let t=e.map(r=>$k(r.path)),n=Fk(t);return n?t.filter(r=>Mk(n,r)).map(r=>({routeId:Ok(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function vc(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=jk(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Fk(e){return e.some(r=>r.startsWith("app/")&&!_k(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function _k(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function Mk(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Tk.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function Ok(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(Dk).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function Lk(e){return e.startsWith("(")&&e.endsWith(")")}function Dk(e){return!e||e.startsWith("@")||e.startsWith("_")||Lk(e)?null:Bk(e)}function Bk(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function jk(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function $k(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var no=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function ot(e,t={}){throw new no("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function kc(e){return Vk.safeParse(e).success||ot("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function up(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||ot("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return ot("invalid-template-key",{path:e})}return kc(t)!==e&&ot("noncanonical-template-key",{path:e}),t}function Kk(e){let t=vc(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("(")||Uk(r)&&!dp(r)))&&ot("invalid-public-route",{routeId:e}),t}function Uk(e){return e.includes("[")||e.includes("]")}function dp(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function fp(e){return e.some(dp)}function pp(e,t,n="app"){n!=="app"&&n!=="src/app"&&ot("invalid-app-root");let r=Kk(e),o=kc(t),i=fp(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))&&ot("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function mp(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function gp(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===".")&&ot("invalid-file-path",{path:i}),n.has(i)&&ot("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Ui(e){let t=gp(e.files),n=to([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new no("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(!mp(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||ot("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=fp(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,m=up(u),g=d.length?`/${d.join("/")}`:"/";pp(g,m,a).templateEntryFile!==i&&ot("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&ot("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:m,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>Ki(i.routeId,s.routeId)||Ki(i.templateId,s.templateId))}function hp(e){let t=gp(e.files),n=Ui({files:t}),r=to([...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)=>Ki(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Ki(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function Jk(e){let t=vc(e.selector.routeId),n=hp({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&ot("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||ot("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Ki(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as rI}from"@vcp-dev/contracts";import{parse as bM}from"@babel/parser";import{parse as w_}from"@babel/parser";import{FormBlockIdSchema as P_,FormSpecV1Schema as A_}from"@vcp-dev/contracts";var ro="components/site/generated/forms",T_=`${ro}/vcp-form-runtime.tsx`,Ji="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",F_=new RegExp(`^${ro}/form-(${Ji})\\.spec\\.ts$`),__=new RegExp(`^${ro}/form-(${Ji})\\.tsx$`),M_=new RegExp(`^@/${ro}/form-(${Ji})$`),O_=new RegExp(`(?:^|/)${ro}/form-(${Ji})(?:\\.tsx?)?$`);var L_=Symbol("invalid-literal");import{createHash as j_}from"node:crypto";import{posix as V_}from"node:path";import{parse as U_}from"@babel/parser";import{FormSpecV1Schema as X_}from"@vcp-dev/contracts";var z_=Symbol("dynamic");import{parse as Xk}from"@babel/parser";function Xi(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var zk=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function yp(e){let t=zk.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 Wk(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function xp(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Hk(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Ic(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(Ic);if(t?.type==="ObjectExpression"){let n={};for(let r of Xi(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=xp(r.key);if(!o)throw new Error("unsupported object key");n[o]=Ic(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Cc(e,t){let n=[],r=yp(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=Xk(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 Xi(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Xi(u.declarations)){let m=d.id;m?.type==="Identifier"&&m.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=Hk(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 Xi(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=xp(l.key);if(!(u!=="path"&&u!=="title"&&u!=="description"&&u!=="keywords"&&u!=="meta_tags_json"&&u!=="schema_json"&&u!=="breadcrumbs_json")){if(u==="path"||u==="title"||u==="description"||u==="keywords"){let d=Wk(l.value);if(d===void 0){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static string; skipped`});continue}a[u]=d;continue}try{let d=Ic(l.value);u==="meta_tags_json"&&d!==null&&typeof d=="object"&&!Array.isArray(d)?a.meta_tags_json=d:u==="schema_json"&&d!==null&&typeof d=="object"?a.schema_json=d:u==="breadcrumbs_json"&&Array.isArray(d)?a.breadcrumbs_json=d:n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} has unsupported static shape; skipped`})}catch(d){n.push({code:"page-seo.dynamic-field",message:`PAGE_SEO.${u} is not a static JSON-like value; skipped: ${d instanceof Error?d.message:String(d)}`})}}}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 Gk}from"@babel/parser";var bp=["page","anchor","external","email","phone","group","file"],Yk=["link","cta"],Ep=["description","badge","iconKey"],Rc=["label","targetType","href","role","openInNewTab","nofollow","children",...Ep],Zk=new Set(Rc);function io(e){return Array.isArray(e)?e:[]}function oo(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Qk(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Sp(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function wc(e){let t=[],n;try{n=Gk(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 io(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of io(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 io(r.elements).forEach((i,s)=>{let a=vp(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function vp(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 io(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Qk(l.key);u&&(r[u]=l.value)}let o=oo(r.label),i=oo(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!bp.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${bp.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 Ep){if(r[l]===void 0)continue;let u=oo(r[l]);u!==void 0?s[l]=u: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))Zk.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 ${Rc.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=[];io(r.children.elements).forEach((u,d)=>{let m=vp(u,`${t}.children[${d}]`,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=oo(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=oo(r.role);if(c!==void 0&&(Yk.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Sp(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=Sp(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 qk}from"@babel/parser";function so(e){return Array.isArray(e)?e:[]}function kp(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function eI(e){let t;try{t=qk(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of so(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of so(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=kp(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 Nc(e,t){let n=Ip(t);if(!n)return{status:"unsupported",source:e};let r=eI(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(wc(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=so(l.elements);for(let[d,m]of u.entries()){if(nI(m,n)){let f=u[d+1],h=u[d-1],y=m.start,E=m.end;if(typeof y!="number"||typeof E!="number")continue;if(f&&typeof f.start=="number")s.push({start:y,end:f.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:E});else{let x=/^\s*,/.exec(e.slice(E));s.push({start:y,end:x?E+x[0].length:E})}continue}let g=tI(m);g&&a(g)}};if(a(o),s.length===0)return{status:"not_found",source:e};let c=e;for(let l of s.sort((u,d)=>d.start-u.start))c=c.slice(0,l.start)+c.slice(l.end);return{status:"removed",source:c,removedCount:s.length}}function tI(e){if(e.type==="ObjectExpression")for(let t of so(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return kp(t.value)}}function Ip(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function nI(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of so(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"&&Ip(n??"")===t}import{estimateNavLabelWidth as nM}from"@vcp-dev/contracts";import{parse as iM}from"@babel/parser";var oI="components/site/generated/",ao=[".tsx",".ts",".jsx",".js"];function Cp(e){if(e.expectedUrlPath===rI)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(to(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let E=h.replace(/\\/g,"/");if(!t.has(E))return!1;let x=Cc(y,E);return x.found&&x.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=Ui({files:new Map(Object.entries(e.files))});for(let y of h)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(h){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:h instanceof Error?h.message:"Invalid page template source."}}let i=iI(e.files);if(!i.ok)return i.error;let s=i.graph,a=lI(o,s),c=uI(o,a,s),l=[...a].filter(h=>!c.has(h)).sort((h,y)=>h.localeCompare(y)),u=[...o,...[...c].sort((h,y)=>h.localeCompare(y))],d=new Set(u),m=u.map(h=>({operation:"delete",file:h})),g=[],f=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let E=Nc(y,e.expectedUrlPath);E.status==="removed"?(m.push({operation:"upsert",file:h,content:E.source}),g.push(h)):E.status==="unsupported"&&f.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&f.push(`preserved_link:${h}`)}return{ok:!0,edits:m,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:f}}function iI(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")||!sI(r))continue;let s=Xt(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(aI(c))continue;let l=Sn(r,c),u=cI(l,t);if(!u)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(u)}n.set(r,a)}return{ok:!0,graph:n}}function sI(e){let t=e.toLowerCase();return ao.some(n=>t.endsWith(n))}function aI(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!ao.some(n=>e.endsWith(n)))}function cI(e,t){let n=e.replace(/\\/g,"/");return(ao.some(o=>n.endsWith(o))?[n]:[...ao.map(o=>`${n}${o}`),...ao.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function lI(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(oI)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function uI(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 Rm from"@babel/parser";import*as fe from"@babel/types";import*as cs from"node:path";import*as ve from"@babel/types";function Rp(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 Bt(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return _n(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ve.isObjectPattern(n)||ve.isArrayPattern(n))return _n(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(fI(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function _n(e,t,n=!1){return ve.isIdentifier(e)?e.name===t&&n:ve.isObjectPattern(e)?e.properties.some(r=>ve.isObjectProperty(r)?_n(r.value,t,n):_n(r.argument,t,n)):ve.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ve.isRestElement(r)?r.argument:r;return _n(o,t,n)}):ve.isAssignmentPattern(e)?_n(e.left,t,!0):ve.isRestElement(e)?_n(e.argument,t,n):!1}function ur(e,t){if(e.path.isObjectPattern()){if(t){let r=wt(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Bt(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Bt(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=wp(r),i=!1,s=o?o.initBinding&&Pc(o.initBinding)?(i=Bt(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=ur(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=wt(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Bt(e)}}}}let n=gI(e);if(n){let r=dI(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||Bt(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=pI(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Bt(e)}}let i=co(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Bt(e)}:null}if(Pc(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Bt(e)}}return null}function dI(e,t){let n=e.findParent(u=>u.isVariableDeclarator());if(!n?.isVariableDeclarator())return null;let r=n.get("init");if(!r?.isExpression())return null;let o=wp(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Pc(i)?(a=Bt(i),[...s]):(()=>{let u=ur(i,{kind:"identifier",expression:i.identifier.name,base:i.identifier.name,path:[]});return a=u?.hasDefault??!1,u?[{kind:"property",name:u.propName},...u.remainingPath,...s]:null})();if(!c)return null;let l=wt(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Bt(t)}:null}function wp(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=hI(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Pc(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function fI(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function pI(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=wt(i.node,t);if(a)return a}return null}function Np(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=zi(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=co(a.node);if(!c||n&&c!==n)continue;let l=a.get("value");if(!l.isAssignmentPattern())continue;let u=l.get("right");if(u.isExpression())return{propName:c,componentName:t,expressionPath:u,displayPath:`${t}.${c}.default`}}let r=mI(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=co(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 zi(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=co(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&wt(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=zi(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=zi(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=zi(r,t);if(o)return o}}return null}function wt(e,t,n=[]){if(ve.isIdentifier(e))return e.name===t?n:null;if(ve.isObjectPattern(e)){for(let r of e.properties)if(ve.isObjectProperty(r)){let o=co(r);if(!o)continue;let i=wt(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ve.isRestElement(r)){let o=wt(r.argument,t,n);if(o)return o}}if(ve.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ve.isRestElement(o)?o.argument:o,s=wt(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ve.isAssignmentPattern(e)?wt(e.left,t,n):null}function mI(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function gI(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 co(e){return e.computed?null:ve.isIdentifier(e.key)?e.key.name:ve.isStringLiteral(e.key)?e.key.value:null}function hI(e){let t=[],n=e;for(;ve.isMemberExpression(n);){if(n.computed)if(ve.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ve.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ve.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ve.isIdentifier(n)?{base:n.name,path:t}:null}import*as Mp from"@babel/parser";import Fc from"@babel/traverse";import*as dr from"@babel/types";import*as le from"@babel/types";var Pp=new WeakMap;function Gi(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Wi(n,t):null}if(e.isMemberExpression()){let n=vI(e.node),r=yI(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Wi(o,[...r,...t]):null}return e.isAwaitExpression()||Tc(e.node)?dn(II(e.node),t,"awaited or fetched expression"):null}function yI(e){let t=[],n=e;for(;le.isMemberExpression(n);){if(n.computed)if(le.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(le.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(le.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return le.isIdentifier(n)?t:null}function Wi(e,t=[],n){let r=xI(e,t);if(r)return r;let o=bI(e,t,n);if(o)return o;let i=SI(e,t,n);return i||null}function uo(e){return e?.kind==="api-source"}function xI(e,t){if(e.path.isVariableDeclarator()&&le.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Ac(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return dn(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&le.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>le.isObjectProperty(c)&&Fp(c)==="data"&&lo(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Ac(a.node))return dn(e.identifier.name,t,"query hook data binding")}let n=EI(e);if(!n||Fp(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()||!Ac(i.node)?null:dn(e.identifier.name,t,"query hook data binding")}function bI(e,t,n){if(e.path.isVariableDeclarator()&&le.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Tp(c.node))return null;let[l,u]=e.path.node.id.elements;return!le.isIdentifier(l)||l.name!==e.identifier.name||!le.isIdentifier(u)?null:Ap(e,u.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}if(!e.path.isIdentifier())return null;let r=e.path.parentPath;if(!r?.isArrayPattern())return null;let o=r.parentPath;if(!o?.isVariableDeclarator())return null;let i=o.get("init");if(!i?.isCallExpression()||!Tp(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return le.isIdentifier(a)&&Ap(e,a.name,n)?dn(e.identifier.name,t,"state setter is updated by API data"):null}function SI(e,t,n){let r=e.path.isVariableDeclarator()?e.path:e.path.findParent(i=>i.isVariableDeclarator());if(!r?.isVariableDeclarator())return null;let o=r.get("init");return o?.isExpression()?o.isAwaitExpression()?dn(e.identifier.name,t,"awaited binding result"):Tc(o.node,n)?dn(e.identifier.name,t,"fetch-backed binding result"):null:null}function EI(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 lo(e,t){return le.isIdentifier(e)?e.name===t:le.isAssignmentPattern(e)?lo(e.left,t):le.isObjectPattern(e)?e.properties.some(n=>le.isObjectProperty(n)?lo(n.value,t):lo(n.argument,t)):le.isArrayPattern(e)?e.elements.some(n=>!!n&&lo(le.isRestElement(n)?n.argument:n,t)):!1}function Ap(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Pp.get(n);c||(c=new WeakMap,Pp.set(n,c)),s=c.get(i.node),s||(s=new Map,c.set(i.node,s));let l=s.get(t);if(l!==void 0)return l}i.traverse({CallExpression(c){Tc(c.node)&&(r=!0),(kI(c.node.callee,t)||c.node.arguments.some(l=>le.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Ac(e){let t=Yi(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Tp(e){return Yi(e.callee)==="useState"}function Tc(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Hi(e,o=>le.isCallExpression(o)&&Yi(o.callee)==="fetch");return t?.set(e,r),r}function vI(e){let t=e;for(;le.isMemberExpression(t);)t=t.object;return le.isIdentifier(t)?t.name:null}function Fp(e){return e.computed?null:le.isIdentifier(e.key)?e.key.name:le.isStringLiteral(e.key)?e.key.value:null}function Yi(e){return le.isIdentifier(e)?e.name:le.isMemberExpression(e)&&le.isIdentifier(e.property)?e.property.name:null}function kI(e,t){return Hi(e,n=>le.isIdentifier(n)&&n.name===t)}function Hi(e,t){if(t(e))return!0;let n=le.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(le.isNode(i)&&Hi(i,t))return!0;continue}if(le.isNode(o)&&Hi(o,t))return!0}return!1}function II(e){return le.isIdentifier(e)?e.name:le.isCallExpression(e)?Yi(e.callee)??"api":le.isAwaitExpression(e)?"awaited-api":"api"}function dn(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:CI(e,t),reason:n}}function CI(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Op=typeof Fc=="function"?Fc:Fc.default;function Lp(e,t){let n=Bp(e);if(!n)return{allowed:!0};let r=!1;return Op(n,{CallExpression(o){if(!jp(o.node,t.sourceRange)||!RI(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||uo(Gi(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Dp(e,t){let n=Bp(e);if(!n)return{allowed:!0};let r=!1;return Op(n,{JSXExpressionContainer(o){jp(o.node,t.sourceRange)&&(dr.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 Bp(e){try{return Mp.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function RI(e){let t=e.callee;return dr.isMemberExpression(t)&&dr.isIdentifier(t.property)&&t.property.name==="map"}function jp(e,t){let n=e.loc;return n?_p({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&_p({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function _p(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 $p from"@babel/parser";import _c from"@babel/traverse";import*as _e from"@babel/types";import*as fr from"node:path";var Nt=typeof _c=="function"?_c:_c.default;function Je(e){try{return $p.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Mc(e){return e.computed?_e.isStringLiteral(e.key)||_e.isNumericLiteral(e.key)?String(e.key.value):null:wI(e.key)}function wI(e){return _e.isIdentifier(e)?e.name:_e.isStringLiteral(e)||_e.isNumericLiteral(e)?String(e.value):null}function Mn(e){return _e.isParenthesizedExpression(e)||_e.isTSAsExpression(e)||_e.isTSSatisfiesExpression(e)||_e.isTSNonNullExpression(e)||_e.isTSTypeAssertion(e)?Mn(e.expression):_e.isExpression(e)?e:null}function Oc(e){if(_e.isIdentifier(e))return[e.name];if((_e.isMemberExpression(e)||_e.isOptionalMemberExpression(e))&&!e.computed&&_e.isIdentifier(e.property)){let t=Mn(e.object),n=t?Oc(t):null;return n?[...n,e.property.name]:null}return null}function On(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?fr.normalize(fr.join(fr.dirname(e),t)).replace(/\\/g,"/"):t}function ut(e,t){return Zi(e)===Zi(t)}function Zi(e){let t=pr(e);return t.endsWith("/index")?t.slice(0,-6):t}function pr(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Up(e,t,n){let r=Wp(e,t);if(Hp(e,r),Gp(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 Nt(e,{JSXElement(s){qp(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Qi(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 Jp(e,t){let n=new Map,r=i=>{let s=mr(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 NI(i,n))o=r(s)||o}return[...n.values()]}function NI(e,t){let n=[],r=PI(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=fo(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=On(e.file,o.source.value);for(let s of o.specifiers){if(X.isExportNamespaceSpecifier(s)){let l=fn(s.exported);for(let u of t.values())ut(u.file,i)&&n.push({file:e.file,namespace:Lc(l,u.namespace),exportName:u.exportName});continue}if(!X.isExportSpecifier(s))continue;let a=fn(s.local),c=[...t.values()].filter(l=>ut(l.file,i)&&Ln(l.namespace,a));if(c.length>0){let l=fn(s.exported);for(let u of c){let d=fo(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(mr({file:i,exportName:a}))&&n.push({file:e.file,exportName:fn(s.exported)})}continue}if(X.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!X.isExportSpecifier(i))continue;let s=fn(i.local),a=r.get(s)??[];if(a.length>0){let c=fn(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=fo(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(X.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=On(e.file,o.source.value),s=o.exported;if(s){let a=fn(s);for(let c of t.values())ut(c.file,i)&&n.push({file:e.file,namespace:Lc(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())ut(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Lc(e,t){return t?`${e}.${t}`:e}function Ln(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function fo(e,t,n){return!Ln(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function PI(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=On(e.file,i.source.value);for(let a of i.specifiers){if(X.isImportDefaultSpecifier(a)){let c=t.get(mr({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>ut(u.file,s)&&Ln(u.namespace,"default"));for(let u of l){let d=fo(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(X.isImportSpecifier(a)){let c=fn(a.imported),l=[...t.values()].filter(d=>ut(d.file,s)&&Ln(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(mr({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(X.isImportNamespaceSpecifier(a))for(let c of t.values())ut(c.file,s)&&r(a.local.name,{...c,namespace:Lc(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=Mn(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)??[],u=new Set(l.map(mr));for(let d of c){let m=fo(d.namespace,a.name,s.id.name),g=m?{...d,namespace:m}:d,f=mr(g);u.has(f)||(r(s.id.name,g),u.add(f),o=!0)}}}return n}function mr(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Zi(e.file)}#${t}`}function fn(e){return X.isIdentifier(e)?e.name:e.value}function Xp(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 Bc(e){let t=AI(e),n=[],r=Gp(e.ast,t);return Nt(e.ast,{JSXElement(o){ut(e.file,e.sourceFile)&&Qi(o)===e.sourceComponent||qp(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function zp(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function Wp(e,t){let n=zp();return Nt(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function AI(e){let t=zp();return ut(e.file,e.sourceFile)&&TI(t,Wp(e.ast,e.sourceComponent)),Nt(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=On(e.file,o),s=e.componentIdentities.filter(a=>ut(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(u=>Ln(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let m=Kp(d,"default");m&&u.add(m)}t.namespaceMembers.set(c,u)}continue}if(X.isImportSpecifier(a)){let l=X.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Ln(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let m of u){let g=Kp(m,l);g&&d.add(g)}t.namespaceMembers.set(c,d);continue}s.some(d=>!d.namespace&&d.exportName===l)&&t.localBindings.add(c);continue}if(X.isImportNamespaceSpecifier(a))for(let l of s){let u=l.namespace?`${l.namespace}.${l.exportName}`:l.exportName,d=t.namespaceMembers.get(c)??new Set;d.add(u),t.namespaceMembers.set(c,d)}}}}}),Hp(e.ast,t),t}function TI(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 Hp(e,t){Nt(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Mn(n.node.init);if(r){if(X.isIdentifier(n.node.id)){let o=Dn(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Dc(t,i,o);return}if(X.isObjectPattern(n.node.id)){let o=Dn(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&Qp(n.node.id,o.namespaceMembers,t,n)}}}})}function Gp(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Nt(e,{ReferencedIdentifier(r){if(n){r.stop();return}FI(r)||!r.isIdentifier()||!Yp(r,t)||_I(r,t)||MI(r)||(n=!0,r.stop())}}),n}function FI(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 Yp(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)&&Dn(r.node,t,r)?r:null}function _I(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Vp(e,r))return!1;let o=Yp(e,t);if(!o)return!1;if(Mn(r.node)===o.node)return!!Dn(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Vp(e,a)&&!!Dn(a.node,t,a)}function MI(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Vp(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Dn(e,t,n){let r=Mn(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 OI(r,t,n);let o=Oc(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?Zp(s,o.slice(1).join(".")):null}function OI(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!X.isObjectProperty(i))continue;let s=Mc(i);if(!s||!X.isExpression(i.value)){X.isExpression(i.value)&&(o||=Dn(i.value,t,n)!==null);continue}let a=Dn(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 Zp(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 Dc(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 Qp(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&&Dc(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!X.isObjectProperty(o))continue;let i=Mc(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Zp(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&&Dc(n,c,s);continue}if(X.isObjectPattern(a)&&s.namespaceMembers.size>0){Qp(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Kp(e,t){if(!Ln(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 qp(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=em(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 em(e){if(X.isJSXIdentifier(e))return[e.name];if(X.isJSXMemberExpression(e)){let t=em(e.object);return t?[...t,e.property.name]:null}return null}function Qi(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 tm(e,t){let n=Je(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Bc({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 Se(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 be(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function jt(e,t){let n=be(e);return!!(n&&dt(t,n))}function dt(e,t){return t.start>=e.start&&t.end<=e.end}function Et(e,t){let n=ce(e,Se(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:qi(e,t)}function gr(e,t){let n=be(t);return n?e.slice(n.start,n.end):""}function nm(e,t){return e.start===t.start&&e.end===t.end}function qi(e,t){let n=null;return Nt(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 es(e,t){return jc(e,t).length>0}function ts(e,t){let n=be(e.node),r=be(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()&&!LI(o,n,r)))return!0;o=o.parentPath}return!1}function LI(e,t,n){let r=be(e.node.consequent);if(r&&dt(r,t)&&!dt(r,n))return!1;let o=e.node.alternate?be(e.node.alternate):null;return!(o&&dt(o,t)&&!dt(o,n))}function jc(e,t){let n=be(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=be(o.node.consequent),a=be(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()&&$c(o.node.operator)){let s=be(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 $c(e){return e==="&&"||e==="||"||e==="??"}function rm(e,t){let n=be(e.consequent);if(n&&dt(n,t))return n;let r=be(e.alternate);return r&&dt(r,t)?r:null}function om(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=>pr(a.file)));if(!t.has(pr(e.sourceFile))||!t.has(pr(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(pr(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=Xp(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=Je(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=Jp(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Bc({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!ut(s.file,e.targetFile)||Qi(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 KI}from"@vcp-dev/contracts";function ns(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 po();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return po();let u=DI(a,l,o?.instanceCount);if(!u)return po();c=u}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"?po():{ok:!0,target:{kind:"jsx-attribute"}}}function po(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function DI(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 $t from"@babel/types";import{SiteEditSetPropsParamsSchema as BI}from"@vcp-dev/contracts";function im(e){let t=e.changes??(e.change?[e.change]:[]);if(!BI.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return mo("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return mo("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=Ne(e.source,"value");if(!o.ok)return mo("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=ce(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return mo("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?jI(r):$I(c.match.path.node,r.name);if(!l)return mo("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 jI(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function $I(e,t){let n=e.properties.filter(i=>$t.isObjectProperty(i)&&VI(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!$t.isExpression(r.value))return null;let o=Dt(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function VI(e){return $t.isIdentifier(e)?e.name:$t.isStringLiteral(e)?e.value:$t.isNumericLiteral(e)?String(e.value):null}function mo(e,t){return{ok:!1,errorCode:e,reason:t}}function sm(e){if(e.change.name!=="className"&&e.change.name!=="class")return go("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return go("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return go("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return go("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 go("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 go(e,t){return{ok:!1,errorCode:e,reason:t}}async function cm(e){let t=KI.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return pn("invalid-change","Typed property changes are invalid");if(e.node.importedFrom==="next/link"&&e.node.exportName==="default"){let r=t.data.changes.find(o=>o.name==="href");if(r&&(r.operation==="remove"||typeof r.value!="string"||r.value.trim().length===0))return pn("invalid-change","next/link requires a non-empty href; use the dedicated link-target operation to remove the link")}let n=[];for(let r of t.data.changes){let o=await UI(e,r);if(o){if(!o.ok)return pn("owner-plan-failed",o.reason);am(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(zI(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=ns({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"){Vc(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=im({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return pn("repeat-target-failed",l.reason);am(n,l.steps);continue}Vc(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:JI(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),XI(n)?pn("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function UI(e,t){return t.name!=="className"&&t.name!=="class"?null:sm({node:e.node,change:t,classNameSource:e.classNameSource})}function JI(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 XI(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 am(e,t){for(let n of t)Vc(e,{...n,order:e.length})}function Vc(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 zI(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Kc(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Kc(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)=>Kc(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=>Kc(n[i],r[i]))}return!1}function pn(e,t){return{ok:!1,errorCode:e,reason:t}}import*as yr from"@babel/types";import*as Q from"@babel/types";function Uc(e,t,n){let r=Et(t,n);return r?Vt(e,r):null}function Vt(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(!Q.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=gr(e,u.node),m=r.node.params.map(h=>gr(e,h)),g=be(i.node),f=be(r.node);return!d||m.some(h=>h.length===0)||!g||!f?null:{callStart:g.start,callEnd:g.end,callbackStart:f.start,callbackEnd:f.end,collectionExpression:d,callbackParams:m,mapOperator:Q.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:rs(u.node),callbackPath:r,collectionPath:u}}function ho(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function WI(e,t){let n=be(e.node);return n?HI(t).some(r=>{let o=be(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function HI(e){let t=e.callbackPath.node.body;return Q.isBlockStatement(t)?mn(t.body):gn(t)}function mn(e){let t=[];for(let n of e){if(Q.isReturnStatement(n)){n.argument&&t.push(...gn(n.argument));continue}if(Q.isBlockStatement(n)){t.push(...mn(n.body));continue}if(Q.isIfStatement(n)){let r=Q.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...mn(r)),n.alternate){let o=Q.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...mn(o))}continue}if(Q.isSwitchStatement(n)){for(let r of n.cases)t.push(...mn(r.consequent));continue}Q.isTryStatement(n)&&(t.push(...mn(n.block.body)),n.handler&&t.push(...mn(n.handler.body.body)),n.finalizer&&t.push(...mn(n.finalizer.body)))}return t}function gn(e){return Q.isJSXElement(e)?GI(e)?lm(e.children):[e]:Q.isJSXFragment(e)?lm(e.children):Q.isParenthesizedExpression(e)||Q.isTSAsExpression(e)||Q.isTSSatisfiesExpression(e)||Q.isTSNonNullExpression(e)||Q.isTSTypeAssertion(e)?gn(e.expression):Q.isConditionalExpression(e)?[...gn(e.consequent),...gn(e.alternate)]:Q.isLogicalExpression(e)&&$c(e.operator)?gn(e.right):[]}function lm(e){return e.flatMap(t=>Q.isJSXElement(t)||Q.isJSXFragment(t)?gn(t):Q.isJSXExpressionContainer(t)&&(Q.isJSXElement(t.expression)||Q.isJSXFragment(t.expression)||Q.isConditionalExpression(t.expression)||Q.isLogicalExpression(t.expression))?gn(t.expression):[])}function GI(e){let t=e.openingElement.name;return Q.isJSXIdentifier(t)?t.name==="Fragment":Q.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function um(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function rs(e){return!(Q.isIdentifier(e)||Q.isThisExpression(e)||Q.isMemberExpression(e)||Q.isOptionalMemberExpression(e)||Q.isCallExpression(e)||Q.isOptionalCallExpression(e))}function dm(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(Q.isMemberExpression(n)||Q.isOptionalMemberExpression(n))&&Q.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function hr(e,t){let n=Je(e);if(!n)return t.isRepeatItemRoot===!0;let r=ce(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:qi(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Vt(e,o);return i?WI(o,i):t.isRepeatItemRoot===!0}function fm(e,t){let n=Je(e);if(!n)return!1;let r=ce(n,Se(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:qi(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(Q.isMemberExpression(s)||Q.isOptionalMemberExpression(s))&&Q.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Re from"@babel/types";function Jc(e){if(Re.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Re.isJSXMemberExpression(e)){let t=e;for(;Re.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function YI(e,t){let n=be(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||jt(a.path.node,n)||hn(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Jc(i.node.name);s&&o(s,i)}}),[...r].sort()}function Xc(e,t,n){let r=Je(e);if(!r)return{ok:!0};let o=ce(r,Se(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=ce(r,Se(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Or(o.match.path,i.match.path);if(es(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=YI(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function mm(e){let t=e;for(;Re.isTSQualifiedName(t);)t=t.left;return Re.isIdentifier(t)?t.name:null}function yo(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function os(e){let t=[],n=r=>{if(r){if(Re.isIdentifier(r)){t.push(r.name);return}if(Re.isObjectPattern(r)){for(let o of r.properties){if(Re.isRestElement(o)){n(o.argument);continue}Re.isObjectProperty(o)&&n(o.value)}return}if(Re.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Re.isAssignmentPattern(r)){n(r.left);return}if(Re.isRestElement(r)){n(r.argument);return}Re.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function zc(e,t){let n=be(e.node),r=be(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=pm(e),i=pm(t);if(!o||!i||!nm(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=rm(s.node,n);if(a&&!dt(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=be(s.node.right);if(a&&dt(a,n)&&!dt(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())&&dm(s)){let a=be(s.node.body)??be(s.node);if(a&&!dt(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 pm(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?be(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Re.isJSXElement(t.node.body)||Re.isJSXFragment(t.node.body)||Re.isConditionalExpression(t.node.body)||Re.isLogicalExpression(t.node.body)))return be(t.node.body);t=t.parentPath}return null}function hn(e,t,n){return n.scope.getBinding(t)===e}function Wc(e,t,n,r={}){if(!r.preserveConditionalBoundary&&es(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=be(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>os(c)).map(c=>n.callbackPath.scope.getBinding(c)?.path.node).filter(Boolean)),s=new Set,a=(c,l)=>{let u=l.scope.getBinding(c);!u||jt(u.path.node,o)||i.has(u.path.node)||hn(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Jc(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Hc(e,t,n){let r=be(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>os(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return yo(e,s=>{let a=s.scope.getBinding(s.node.name);!a||jt(a.path.node,r)||o.has(a.path.node)||hn(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function gm(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>os(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)||hn(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(yr.isIdentifier(l))o(l.name,c);else{let u=mm(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Gc(e,t){let n=be(e.node),r=new Set;return yo(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&jt(i.path.node,n)||hn(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 hm(e){let t=[];for(let n of e.callbackPath.node.params){if(yr.isIdentifier(n)){t.push(n.name);continue}if(yr.isRestElement(n)&&yr.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 ym(e,t){return{...e,callbackParams:t}}function Yc(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function xo(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 xm(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 Bn(e){return{file:e.file,component:e.component}}function ZI(e){return e.target.kind==="node"?e.target.key:null}function QI(e){return"kind"in e}function is(e){return!QI(e)}function tl(e,t){let n=cs.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=cs.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Zc(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Ot(n,Se(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function rl(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 qI(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function eC(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 Qc(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function tC(e){let t=Up(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=zc(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=nC({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=wm(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?rs(o):!0}}}function nC(e){let t=be(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||jt(a.path.node,t))return;let c=iC(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=aC(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=rC(l.expression,c.remainingPath);if(!u){o="Cannot move prop-backed repeat child because the mapped prop path is not a portable expression";return}let d=Gc(l.expressionPath,e.targetParentPath);if(!d.ok){o=d.reason??`Cannot move prop-backed repeat child because the mapped prop source is not visible at the target: ${d.bindingNames.join(", ")}`;return}n.set(`${c.range.start}:${c.range.end}`,{...c.range,text:u});return}hn(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:cC(e.source,t,[...n.values()])}}function rC(e,t){if(t.length===0)return e;let n=wm(e);if(!n)return null;let r=rs(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=oC(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function oC(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function iC(e,t,n){let r=sC(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=ur(t,o);if(!i)return null;let s=r?.range??be(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function sC(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!jt(n.node,t)||n.node.computed||!fe.isIdentifier(n.node.property))return null;let r=be(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function aC(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()&&fe.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=gr(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 cC(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 wm(e){try{let n=Rm.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=fe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&fe.isExpression(r)?r:null}catch{return null}}function lC(e){let t=be(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||jt(s.path.node,t))return;let a=bm(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=bm(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!uC(u.importSpec,a.importSpec))&&r.add(a.localName);return}let l=n.get(a.moduleSpecifier)??[];l.some(u=>JSON.stringify(u)===JSON.stringify(a.importSpec))||l.push(a.importSpec),n.set(a.moduleSpecifier,l);return}r.add(i.node.name)};return yo(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 uC(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 bm(e,t,n){let r=dC(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=On(t,i),a=i.startsWith(".")?tl(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=fe.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 dC(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Sm(e,t,n,r){let o=jc(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=gr(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=fC(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${mC(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function fC(e,t){return pC(e.node)?t:`(${t})`}function pC(e){return fe.isIdentifier(e)||fe.isThisExpression(e)||fe.isSuper(e)||fe.isMemberExpression(e)||fe.isOptionalMemberExpression(e)||fe.isCallExpression(e)||fe.isOptionalCallExpression(e)||fe.isBooleanLiteral(e)||fe.isNumericLiteral(e)||fe.isStringLiteral(e)||fe.isNullLiteral(e)||fe.isUnaryExpression(e)}function mC(e){return e.trim().startsWith("<")?e:`(${e})`}var gC={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 ss(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=gC[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 hC(e,t){for(let n of e.program.body){if(!fe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>fe.isImportDefaultSpecifier(o));if(r&&fe.isImportDefaultSpecifier(r))return r.local.name}return null}function yC(e,t,n){for(let r of e.program.body){if(!fe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>fe.isImportSpecifier(i)&&(fe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&fe.isImportSpecifier(o))return o.local.name}return null}function Em(e){let t=new Set;return Nt(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function vm(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function xC(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=rl(e),o=Je(t);if(n.exportName!=="default"){let a=o?yC(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?vm(r,Em(o)):r;return{localName:c,importStep:qc(e,c)}}if(!o)return{localName:r,importStep:qc(e,r)};let i=hC(o,n.source);if(i)return{localName:i};let s=vm(r,Em(o));return{localName:s,importStep:qc(e,s)}}function bC(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??rl(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 SC(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?EC(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function EC(e){return Object.fromEntries(Object.entries(e).filter(t=>nl(t[1])))}function nl(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(nl):typeof e=="object"?Object.values(e).every(nl):!1}function qc(e,t=rl(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 km(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 vC(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function xr(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function ol(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function bo(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:ol(e,t.slice(0,n)),index:r.index}}return null}function el(e,t){return e.locator?e.collectionPathMap?.[t]?ol(e.locator,e.collectionPathMap[t]):bo(e.locator)?IC(e.locator,CC(t,e.collectionIndexMap)):null:null}function kC(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:Nm(o,t)}function Nm(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Nm(r,t);return o===void 0?void 0:{[n.name]:o}}function IC(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},ol(e,i)}return null}function CC(e,t){return t?.[e]??e}function Im(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 RC(e,t){return wC(e.root,t.root)&&PC(e.path??[],t.path??[])}function wC(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&&NC(e.sourceRange,t.sourceRange)}}function NC(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function PC(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 as=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:xr(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:xr(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:xr(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:xr(t.kind,t.params.kind)};let r=t;if(!is(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=km(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:xr(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"set-link-target":{if(t.params.kind!=="set-link-target")return{ok:!1,errorCode:"invalid-params",reason:xr(t.kind,t.params.kind)};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.planSetLinkTarget(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=ZI(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):Cm(i)}async planSetLinkTarget(t,n,r){if(r.tag!=="a"&&!(r.importedFrom==="next/link"&&r.exportName==="default"))return{ok:!1,errorCode:"capability-denied",reason:"Only native anchors and source-verified next/link nodes can be changed"};if(r.structuralPath.includes("#repeat:")||r.isRepeatRegion||r.isRepeatItemRoot)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes are not supported inside repeat templates"};if(n.selectionRef?.instanceIndex!==void 0||(n.selectionRef?.instanceCount??1)>1)return{ok:!1,errorCode:"capability-denied",reason:"Link target changes require a single non-repeated selection"};if(n.params.changes.length>0){let o=await this.buildTypedPropertySteps({node:r,scope:"selection",changes:n.params.changes,selectionRef:n.selectionRef});if(!o.ok)return Cm(o);if(o.steps.some(i=>i.type!=="set-property-changes"||i.file!==r.file))return{ok:!1,errorCode:"capability-denied",reason:"Link descriptions must have a direct, unique source in the selected file"}}return this.buildPlan(t,n,[{type:"set-link-target",order:0,file:r.file,locator:Se(r),link:n.params.link,changes:n.params.changes}],this.graph.getCapability(r.key))}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?cm({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 u=await this.graph.getElementPropertyWriteTarget?.(r.key,c),d=r.attributes?.find(g=>g.name===c);if((await this.graph.getPropertyState?.(r.key,c,i))?.status==="blocked"||!u&&d?.source)return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite a derived or unresolved property '${c}'`};if(!(typeof d?.resolvedValue=="string"&&d.resolvedValue===l||d?.source===null&&d.value===l)){if(u?.kind==="external-entry")return{ok:!1,errorCode:"capability-denied",reason:`apply-style-draft cannot overwrite readonly external property '${c}'`};if(u?.kind==="value-binding"&&u.locator){let g=u.locator;if(u.sourceKind==="repeat-template"&&typeof i?.instanceIndex=="number"){let f=el(u,i.instanceIndex);if(!f)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=f}s.push({order:n+s.length,file:u.file,type:"update-value",locator:g,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:Se(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=el(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:Se(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Je(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=ce(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!qI(a.match.path))return{ok:!0,value:r};let c=eC(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=el(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=Je(this.graph.getFileContent(t));if(!o)return!1;let i=ce(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 d=i;if(d?.kind==="value-binding"&&d.locator){let m=bo(d.locator);if(m)return this.buildPlan(t,n,[{order:0,file:d.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=xo(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:Se(r),removeWhitespace:!0}],u=this.buildRemoveComponentImportStep(r);return u&&l.push({...u,order:l.length}),this.buildPlan(t,n,l,o)}buildRemoveComponentImportStep(t,n=this.graph.getFileContent(t.file)){if(!t.importedFrom||!t.exportName||!t.tag||tm(n,t)>1)return null;let r=tl(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(!is(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=xo(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 u=await this.planExternalBackedInsertChild(t,n,r,o,i,a);if(u)return u;let d=await this.planRepeatBackedInsertChild(t,n,r,o);if(d)return d;let m=this.getRepeatBackedTemplateStructureReason(r);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let g=Lp(this.graph.getFileContent(r.file),r);if(!g.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:g.reason??"Cannot insert child into this node"};let f=ss(r,n.params.node);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let h=[],y=0,E=n.params.node.kind==="component-call"?xC(n.params.node,this.graph.getFileContent(r.file)):void 0,x=E?.importStep;return x&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:x.moduleSpecifier,imports:x.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Se(r),node:{jsx:bC(n.params.node,E?.localName)},placement:n.params.position.relation,anchorLocator:i?Se(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!is(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:SC(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(!is(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(d=>d.isRepeatItemRoot&&d.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=bo(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=kC(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 u=n.params.position.relation==="prepend"?Im(0,a.collectionIndexMap):Im(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:u,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=xo(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 hr(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:")||fm(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&&hr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let m=Vt(c,u),g=Vt(c,d);if(!ho(m,g))return null;if(a&&(s==="before"||s==="after")){let h=Et(l,a),y=h?Vt(c,h):null;if(!ho(m,y))return null}if(ts(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let f=Xc(c,r,o);return f.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Bn(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:f.reason??`Cannot move node because it depends on bindings outside the target scope: ${f.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&hr(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Je(c);if(!l)return null;let u=Et(l,r),d=Et(l,o);if(!u||!d)return null;let m=Vt(c,u);if(!m)return null;let g=Vt(c,d);if(ho(m,g))return null;if(g&&!um(g,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 v=Uc(c,l,a);if(g&&!ho(g,v)||!g&&v)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 v=ss(o,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}let f=Zc(this.graph,r);if(!f)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ts(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Sm(c,u,d,f);for(let v of h.conditionPaths){let w=Hc(v,d,m);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${w.bindingNames.join(", ")}`}}let y=Wc(u,d,m,{preserveConditionalBoundary:h.conditionPaths.length>0});if(!y.ok)return{ok:!1,errorCode:"unsupported-operation",reason:y.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${y.bindingNames.join(", ")}`};let E=gm(m,d);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 x=m;if(r.component!==o.component){let v=tC({source:c,ast:l,sourceContext:m,sourceNode:r,targetParent:o,targetParentPath:d});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};x=v.context}else{let v=Gc(m.collectionPath,d);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${v.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Se(r),targetParentLocator:Se(o),placement:s,anchorLocator:a?Se(a):void 0,repeatExpression:Yc(x,h.sourceJsx),selectionContext:Bn(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&hr(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),u=Je(c),d=Je(l);if(!u||!d)return null;let m=om({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,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 g=Et(u,r),f=Et(d,o);if(!g||!f)return null;let h=zc(m.callSitePath,f);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=Vt(c,g);if(!y)return null;if(Vt(l,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Uc(l,d,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=ss(o,{kind:"native-tag",tag:r.tag});if(F)return{ok:!1,errorCode:"unsupported-operation",reason:F}}let x=Zc(this.graph,r);if(!x)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(ts(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let v=Sm(c,g,f,x);for(let F of v.conditionPaths){let L=Hc(F,f,y);if(!L.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${L.bindingNames.join(", ")}`}}let w=Wc(g,f,y,{preserveConditionalBoundary:v.conditionPaths.length>0});if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${w.bindingNames.join(", ")}`};let N=lC({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:f});if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let T=hm(y);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=ym(y,T.callbackParams),P=[{order:0,file:r.file,type:"remove-node",locator:Se(r),removeWhitespace:!0}];for(let F of N.imports)P.push({order:P.length,file:o.file,type:"add-import",moduleSpecifier:F.moduleSpecifier,imports:F.imports});return P.push({order:P.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Se(o),expression:Yc(C,v.sourceJsx),placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Bn(o)}),this.buildPlan(t,n,P,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 v=n.params.target,w=this.graph.getNode(v.anchorKey);if(!w||r.file!==w.file||r.component!==w.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let N=this.graph.getFileVersion(r.file);if(n.documentVersion!==N)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${N})`};let T=this.graph.getFileContent(r.file),C=Je(T),P=C?Et(C,r):null,F=C?Et(C,w):null,L=P?.parentPath,W=F?.parentPath;if(!P||!F||!L||!W||L.node!==W.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Oe(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let z=L.node.loc;return z?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:z.start.line,startColumn:z.start.column,endLine:z.end.line,endColumn:z.end.column}},placement:v.relation,anchorLocator:Se(w),selectionContext:Bn(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=km(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(vC(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 v=n.params.target.relation,w=i.anchorNode&&(v==="before"||v==="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:v,anchorSourceId:w?.kind==="external-entry"?w.sourceId:null,parentKey:"parentKey"in n.params.target?n.params.target.parentKey:null}}],o)}let l=r.file!==s.file,u=n.params.target.relation,d=i.anchorNode,m=this.graph.getTextProvenance?.(r.key,0)??null,g=xo(r,c,m);if(g&&!Qc(g)&&!xm(r,s,c,m))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let v=c,w=await this.graph.getTextWriteTarget(d.key,0);if(v?.kind==="value-binding"&&w?.kind==="value-binding"&&v.locator&&w.locator){let N=bo(v.locator),T=bo(w.locator);if(N&&T&&v.file===w.file&&RC(N.locator,T.locator)){let C=N.index,P=T.index,F=u==="before"?P-(C<P?1:0):P+(C<P?0:1);return this.buildPlan(t,n,[{order:0,file:v.file,type:"move-array-item",locator:N.locator,fromIndex:C,toIndex:F}],o)}}}if(r.isRepeatItemRoot&&hr(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let f=this.getRepeatBackedTemplateStructureReason(r),h=Qc(g)?g:f;if(h&&Qc(h)){let v=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(v)return v;let w=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(w)return w;let N=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return N||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let y=await this.getUpstreamBackedDescendantReason(r);if(y)return{ok:!1,errorCode:"unsupported-operation",reason:y};if(r.tag&&r.tag.toLowerCase()===r.tag){let v=ss(s,{kind:"native-tag",tag:r.tag});if(v)return{ok:!1,errorCode:"unsupported-operation",reason:v}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let E=Xc(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 x=[{order:0,file:r.file,type:"move-node",locator:Se(r),targetParentLocator:Se(s),placement:u,anchorLocator:d?Se(d):void 0,selectionContext:Bn(s)}];return this.buildPlan(t,n,x,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Zc(this.graph,r)??`<${r.component} />`,m=Dp(u,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:Se(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let f=r.tag??r.component,y={moduleSpecifier:tl(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:f}]:[{kind:"named",imported:r.exportName,local:f===r.exportName?void 0:f}]};c.push({order:l++,file:o.file,type:"add-import",moduleSpecifier:y.moduleSpecifier,imports:y.imports}),c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:d},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Bn(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Se(o),node:{jsx:d},placement:s,anchorLocator:a?Se(a):void 0,selectionContext:Bn(o)});let g=this.buildRemoveComponentImportStep(r,u);return g&&c.push({...g,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:Ce(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 Cm(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 ll from"@babel/generator";import{parse as JC}from"@babel/parser";import*as I from"@babel/types";import*as Kt from"@babel/types";import il from"@babel/generator";import*as ke from"@babel/types";var AC=typeof il=="function"?il:il.default,TC=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,FC=/^((?:https?:)?\/\/)[^/@\s]+@/i,_C=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Am(e,t){let n=Pt(e.callee);if(!n)return null;if(n==="fetch")return sl(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Pm(r))return sl(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Pm(r))return sl(e.arguments[0],r,t,["ky client contract"])}return null}function sl(e,t,n,r){if(!e||ke.isSpreadElement(e)||ke.isJSXNamespacedName(e))return DC(t,n,r,"missing url argument");let o=So(e);return{sourceKind:LC(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 So(e){if(ke.isStringLiteral(e))return ls(e.value);if(ke.isTemplateLiteral(e))return ls(MC(e));if(ke.isBinaryExpression(e)&&e.operator==="+"){let t=So(e.left),n=So(e.right);return!t&&!n?void 0:ls(`${t??al(e.left)}${n??al(e.right)}`)}if(ke.isMemberExpression(e)){let t=Tm(e);if(t)return`env:${t}`}if(!(ke.isCallExpression(e)&&Pt(e.callee)==="new URL")){if(ke.isNewExpression(e)&&ke.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!ke.isSpreadElement(t)?So(t):void 0,o=n&&!ke.isSpreadElement(n)?So(n):void 0;return o&&r?ls(`${o} + ${r}`):r??o}if(ke.isIdentifier(e))return`:${e.name}`}}function MC(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+=al(r))}return t}function al(e){if(ke.isIdentifier(e))return`:${e.name}`;if(ke.isMemberExpression(e)){let t=Tm(e);if(t)return`env:${t}`}return`:${OC(e)}`}function OC(e){return AC(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function ls(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(FC,"$1<redacted>@").replace(_C,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?TC.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function LC(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 DC(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Pm(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function Tm(e){return!ke.isMemberExpression(e.object)||!ke.isIdentifier(e.object.object,{name:"process"})||!BC(e.object.property,"env")?null:ke.isIdentifier(e.property)?e.property.name:ke.isStringLiteral(e.property)?e.property.value:null}function BC(e,t){return ke.isIdentifier(e)&&e.name===t}function Pt(e){if(ke.isIdentifier(e))return e.name;if(ke.isMemberExpression(e)){let t=Pt(e.object),n=ke.isIdentifier(e.property)?e.property.name:ke.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var jC=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),$C=new Set(["getConfig","submit"]);function Fm(e,t){let n=VC(Pt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!jC.has(i))return null;let s=cl(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(!$C.has(i))return null;let s=cl(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=cl(e,0)??KC(e,0,"path")??"/cms/:path",s=UC(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 VC(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 _m(e,t){let n=Pt(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 Mm(e){let t=Pt(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function cl(e,t){let n=e.arguments[t];return Kt.isStringLiteral(n)?n.value:null}function KC(e,t,n){let r=e.arguments[t];if(!Kt.isObjectExpression(r))return null;for(let o of r.properties)if(Kt.isObjectProperty(o)&&!o.computed&&(Kt.isIdentifier(o.key)&&o.key.name===n||Kt.isStringLiteral(o.key)&&o.key.value===n)&&Kt.isStringLiteral(o.value))return o.value.value;return null}function UC(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Om(e=4096){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Re-export relation capacity must be positive.");let t=new Map,n=new Set,r=o=>{let i=t.get(o.fromFile),s=i?.get(o.exportName),a=s?.get(o.targetFile);a?.get(o.maxImportDepth)===o&&(a.delete(o.maxImportDepth),a.size===0&&s.delete(o.targetFile),s.size===0&&i.delete(o.exportName),i.size===0&&t.delete(o.fromFile),n.delete(o))};return{resolve(o,i){let{fromFile:s,exportName:a,targetFile:c,maxImportDepth:l}=o,u=t.get(s)?.get(a)?.get(c)?.get(l);if(u)return u.pending;let d=i();n.size>=e&&r(n.values().next().value);let m={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,f=g.get(a)??new Map,h=f.get(c)??new Map;return h.set(l,m),f.set(c,h),g.set(a,f),t.set(s,g),n.add(m),d.catch(()=>{r(m)}),d}}}var oL=typeof ll=="function"?ll:ll.default,Um=new WeakMap;function Jm(e){let t=new Map;return Um.set(t,new Map([...e].map(n=>[n.file,n]))),t}var XC={maxFunctionDepth:8,maxImportDepth:6},zC=new Set(["src","href","alt","poster","content","title","aria-label"]),Lm=new WeakMap;function WC(e,t,n){let r=Lm.get(t.fileCache);r||(r=new WeakMap,Lm.set(t.fileCache,r));let o=r.get(e);if(!o){o={imported:[],local:new Map};let u=0;for(let d of e.elements.values()){let m={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(m);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let f=g.get(d.tag)??[];f.push(m),g.set(d.tag,f)}r.set(e,o)}let i=o.local.get(t.file)?.get(n)??[],s=o.imported,a=[],c=0,l=0;for(;c<s.length||l<i.length;){let u=s[c],d=i[l];u&&(!d||u.order<d.order)?(a.push(u.element),c++):d&&(!u||d.order<u.order)?(a.push(d.element),l++):(a.push(u.element),c++,l++)}return a}async function Xm(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&Bm(s,e.element))&&!e.graph.regions.some(s=>s.ownerKey===e.element.identity.key&&(s.kind==="repeat-region"||s.kind==="conditional-region")))return{hasDynamicData:!1,bindings:[]};let t=e.fileCache??new Map,n=yl(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...XC,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:og(n,e.element.componentName)};await zm(e.element.componentName,e.graph,r);let o=[];o.push(...await ZC(e.element,e.graph,r),...await QC(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await qC(s,e.element,e.graph,r);a&&o.push(gs(a,"text","children"))}for(let s of e.element.attributes??[]){let a=Bm(s,e.element);if(!a)continue;let c=await Gm(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"){let u=n.jsxElementsByRange.get(pl(e.element.sourceRange))?.openingElement.attributes.find(d=>I.isJSXAttribute(d)&&I.isJSXIdentifier(d.name,{name:s.name}));I.isJSXExpressionContainer(u?.value)&&I.isExpression(u.value.expression)&&(c=await Me(u.value.expression,r))}c&&o.push(gs(c,a,s.name))}let i=pR(o).sort(ng);return{hasDynamicData:i.length>0,bindings:i}}async function zm(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 WC(t,n,e)){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 HC(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 u=`${n.file}#${e}<-${l.identity.key}`;if(!n.resolvingComponentProps.has(u)){n.resolvingComponentProps.add(u);try{let d=await Hm(l.sourceFile,n);if(!d)continue;let m=ko(d,n,{importDepth:n.importDepth+1});m.paramSources.clear(),m.scopeVariables=og(d,l.componentName),await zm(l.componentName,t,m);let g=await GC(l,t,m);for(let[f,h]of g){if(!h)continue;let y=a.get(f)??[];y.push(h),a.set(f,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=hl(u);d.length===1&&c.set(l,d[0])}YC(o,c,n)}var Dm=new WeakMap;function HC(e,t,n,r){let o=Dm.get(r.fileCache);return o||(o=Om(),Dm.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>Wm(e,t,n,r))}async function Wm(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 Hm(e,r))?.imports.get(t);if(!s||!kt(s.source))return!1;let a=await ag(e,s.source,r.exists);return a?a===n?!0:Wm(a,s.importedName,n,r,o):!1}async function GC(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(pl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!I.isJSXAttribute(s)||!I.isJSXIdentifier(s.name)||!I.isJSXExpressionContainer(s.value)||!I.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=await Ym(e.attributes?.find(l=>l.name===s)?.source??null,e,t,n)??await Me(a,n);c&&i.set(s,c)}return i}function pl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function Hm(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 yl(e,r,t.fileCache)}function YC(e,t,n){if(I.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,ms(Object.fromEntries(t),n.file));return}if(I.isObjectPattern(e))for(let r of e.properties){if(!I.isObjectProperty(r)||r.computed||!I.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=I.isAssignmentPattern(r.value)?r.value.left:r.value;I.isIdentifier(i)&&n.paramSources.set(i.name,ze(o))}}function Bm(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":zC.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function ZC(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 hs(i.collectionSource,n);s&&r.push(gs(yn(s),"repeat-region",i.collectionExpression))}return r}async function QC(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 hs(i.conditionSource,n);s&&r.push(gs(yn(s),"conditional-region",i.conditionExpression))}return r}async function qC(e,t,n,r){return Gm(e.source,t,n,r)}async function Gm(e,t,n,r){let o=await Ym(e,t,n,r);return o||hs(e,r)}async function Ym(e,t,n,r){if(!e)return null;let o=eR(e.base,t,n);if(!o)return null;let i=await hs(o.collectionSource,r);return i?vo(i,e.path,!0):null}function eR(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 hs(e,t){if(!e)return null;let n=await Zm(e.base,t);return n?vo(n,e.path,!1):null}async function Zm(e,t){let n=t.paramSources.get(e);if(n)return ze(n);if(t.variableCache.has(e))return mR(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await nR(e,t);if(r)return t.variableCache.set(e,ze(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=I.isArrayExpression(o)&&o.elements.length===0?await tR(e,t):await Me(o,t);return t.variableCache.set(e,s?ze(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await ig(i,t);if(s){let a=ko(s,t,{importDepth:t.importDepth+1}),c=sg(i,s);if(c){let d=(await $n(c,[],a)).returnSource;return t.variableCache.set(e,d?ze(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await Me(l,a);return t.variableCache.set(e,u?ze(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function ul(e,t,n=new Set){if(n.has(e))return null;if(n.add(e),I.isStringLiteral(e))return e.value;if(!I.isIdentifier(e))return null;let r=t.paramArguments.get(e.name);if(r)return ul(r.expression,r.context,n);let o=t.scopeVariables?.get(e.name)??t.analysis.variables.get(e.name);return o?ul(o,t,n):null}async function tR(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return I.traverseFast(u,m=>{I.isIdentifier(m,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;I.isMemberExpression(d);)d=d.object;return I.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(I.isFunction(u)){s(u)&&(o=!0);return}if(I.isVariableDeclarator(u)&&(jn(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(I.isAssignmentExpression(u)||I.isUpdateExpression(u))&&a(I.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(I.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(I.isCallExpression(u)){if(I.isMemberExpression(u.callee)&&I.isIdentifier(u.callee.object,{name:e})){if(!I.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let m of u.arguments){let g=I.isSpreadElement(m)?m.argument:m,f=I.isExpression(g)?await Me(g,d):null;f?r.push(dl(f)):o=!0}return}if(u.arguments.some(m=>s(m))){o=!0;return}}if(I.isForOfStatement(u)){let m=await Me(u.right,d),g=ko(d.analysis,d),f=I.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;m&&f&&fs(f,dl(m),g),await c(u.body,g);return}for(let m of I.VISITOR_KEYS[u.type]??[]){let g=u[m];for(let f of Array.isArray(g)?g:[g])I.isNode(f)&&await c(f,d)}}};await c(n.body,t);let l=hl(r);return!o&&i===1&&l.length===1?yn(l[0]):null}async function nR(e,t){let n=t.analysis.stateSetters.get(e);if(!n)return null;let r=t.analysis.stateSetterCandidates.get(n)??[];for(let o of r){let i=await Me(o,t);if(i)return i}return null}async function Me(e,t){if(I.isIdentifier(e))return Zm(e.name,t);if(I.isMemberExpression(e)||I.isOptionalMemberExpression(e)){let n=I.isMemberExpression(e)?_m(e,{file:t.file}):null;if(n)return eg(n);let r=await rR(e,t);if(!r)return null;let o=fR(e);return vo(r,o,!1)}if(I.isAwaitExpression(e))return I.isExpression(e.argument)?Me(e.argument,t):null;if((I.isCallExpression(e)||I.isOptionalCallExpression(e))&&(I.isMemberExpression(e.callee)||I.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&I.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&I.isExpression(e.callee.object))return br(await Me(e.callee.object,t));if(I.isCallExpression(e))return Qm(e,t);if(I.isObjectExpression(e)){let n=await qm(e,t);return Object.keys(n).length>0?ms(n,t.file):null}if(I.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!I.isExpression(o))continue;let i=await Me(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?ms(n,t.file):null}if(I.isConditionalExpression(e)){let n=await Me(e.consequent,t),r=await Me(e.alternate,t);return br($m(n,r))}if(I.isLogicalExpression(e)){let n=await Me(e.left,t),r=await Me(e.right,t);return br($m(n,r))}return I.isTSAsExpression(e)||I.isTSSatisfiesExpression(e)||I.isTSNonNullExpression(e)||I.isTypeCastExpression(e)||I.isParenthesizedExpression(e)?Me(e.expression,t):null}async function rR(e,t){let n=e;for(;I.isMemberExpression(n)||I.isOptionalMemberExpression(n);)n=n.object;return I.isExpression(n)?Me(n,t):null}async function Qm(e,t){let n=e.arguments[0],r=I.isExpression(n)?ul(n,t):null,o=Fm(r!==null&&!I.isStringLiteral(n)?{...e,arguments:[I.stringLiteral(r),...e.arguments.slice(1)]}:e,{file:t.file,imports:t.analysis.imports});if(o)return eg(o);if(Pt(e.callee)==="Promise.all"&&I.isArrayExpression(n))return Me(n,t);if(Mm(e)){let g=e.arguments[0];if(g&&I.isExpression(g))return br(await Me(g,t))}let i=await oR(e,t);if(i)return i;let s=Am(e,{file:t.file});if(s)return{sourceKind:s.sourceKind,sourceType:"api-field",endpointPattern:s.endpointPattern,valuePath:s.valuePath,confidence:s.confidence,readonly:!0,evidence:s.evidence};let a=await aR(e,t);if(a)return a;let c=await cR(e,t);if(c)return c;let l=await lR(e,t);if(l)return l;let u=await uR(e,t);if(u)return u;let d=[];for(let g of e.arguments)if(I.isExpression(g)){let f=await Me(g,t);f&&d.push(f)}let m=hl(d);return m.length===1?br(m[0]):null}async function oR(e,t){let n=Pt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=sR(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(I.isIdentifier(s)){let a=await Sr(s.name,t);if(a)return(await $n(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!I.isObjectExpression(r))return us(t.file,`${n} without static options`);let o=iR(r,"queryFn");if(!o)return us(t.file,`${n} without queryFn`);if(I.isIdentifier(o)){let i=await Sr(o.name,t);return i?(await $n(i.node,[],i.context)).returnSource:us(t.file,`${n} queryFn unresolved`)}return I.isArrowFunctionExpression(o)||I.isFunctionExpression(o)?(await $n(o,[],t)).returnSource:I.isCallExpression(o)?Qm(o,t):null}function iR(e,t){for(let n of e.properties){if(!I.isObjectProperty(n)||!I.isExpression(n.value))continue;if(ml(n)===t)return n.value}return null}function sR(e,t,n){return I.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 aR(e,t){if(!I.isMemberExpression(e.callee)||!I.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=I.isExpression(e.callee.object)?await Me(e.callee.object,t):null;if(!r)return null;if(n!=="map")return yn(r);let o=e.arguments[0];if(I.isIdentifier(o)){let i=await Sr(o.name,t);if(!i)return yn(r);let s=await $n(i.node,[r],i.context);return{...yn(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(I.isArrowFunctionExpression(o)||I.isFunctionExpression(o)){let i=await $n(o,[r],t);return{...yn(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return yn(r)}async function cR(e,t){return!I.isMemberExpression(e.callee)||!I.isIdentifier(e.callee.property,{name:"json"})||!I.isExpression(e.callee.object)?null:Me(e.callee.object,t)}async function lR(e,t){return!I.isMemberExpression(e.callee)||!I.isIdentifier(e.callee.property,{name:"then"})||!I.isExpression(e.callee.object)?null:br(await Me(e.callee.object,t))}async function uR(e,t){if(!I.isIdentifier(e.callee))return null;let n=await Sr(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!I.isExpression(i)){r.push(us(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await Me(i,t);r.push(s)}return(await $n(n.node,r,n.context,{arguments:e.arguments,context:t})).returnSource}async function Sr(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),fl(r.expression))return{node:r.expression,context:r.context};if(I.isIdentifier(r.expression))return Sr(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await ig(i,t);if(!s)return null;let a=ko(s,t,{importDepth:t.importDepth+1}),c=sg(i,s);return c?{node:c,context:a}:Sr(i.importedName,a)}async function $n(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=ko(n.analysis,n,{functionDepth:n.functionDepth+1});o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((l,u)=>{for(let f of jn(l))o.paramSources.delete(f),o.paramArguments.delete(f);let d=I.isAssignmentPattern(l)?l.left:l,m=r?.arguments[u];I.isIdentifier(d)&&I.isExpression(m)&&r&&o.paramArguments.set(d.name,{expression:m,context:r.context});let g=t[u];g&&fs(l,dl(g),o)});let i=dR(e),s=null,a,c=!1;for(let l of i){if(I.isObjectExpression(l)){a={...a??{},...await qm(l,o)},s=s??ms(a,n.file);continue}let u=await Me(l,o);if(u){if(!s){s=u;continue}let d=gl(s,u);if(!d){c=!0,s=null;continue}s=d}}return{returnSource:c?null:s,...a?{objectReturnMap:a}:{}}}function fs(e,t,n){if(I.isIdentifier(e)){n.paramSources.set(e.name,ze(t));return}if(I.isAssignmentPattern(e)){fs(e.left,t,n);return}if(I.isObjectPattern(e))for(let r of e.properties){if(!I.isObjectProperty(r)||r.computed||!I.isIdentifier(r.key))continue;let o=vo(t,[{kind:"property",name:r.key.name}],!0),i=I.isAssignmentPattern(r.value)?r.value.left:r.value;o&&fs(i,o,n)}}function dR(e){if(I.isArrowFunctionExpression(e)&&I.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!I.isBlockStatement(n))return t;let r=o=>{if(I.isFunction(o)&&o!==e)return;if(I.isReturnStatement(o)){o.argument&&I.isExpression(o.argument)&&t.push(o.argument);return}let i=I.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)I.isNode(c)&&r(c);else I.isNode(a)&&r(a)}};return r(n),t}async function qm(e,t){let n={};for(let r of e.properties){if(!I.isObjectProperty(r))continue;let o=ml(r);if(!o||!I.isExpression(r.value))continue;let i=await Me(r.value,t);i&&(n[o]=i)}return n}function ml(e){return I.isIdentifier(e.key)&&!e.computed?e.key.name:I.isStringLiteral(e.key)?e.key.value:null}function fR(e){let t=[],n=e;for(;I.isMemberExpression(n)||I.isOptionalMemberExpression(n);){let r=n.property;n.computed?I.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):I.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):I.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return I.isIdentifier(n),t}function vo(e,t,n){if(t.length===0)return ze(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?vo(s,t.slice(1),n):null}let i=ze(e);if(i.sourceType==="cms-field"){let s=t.filter(a=>a.kind==="property").map(a=>a.name);return s[0]==="data"&&s[1]==="items"?(i.valuePath=Eo(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i):s[0]==="fields"?(i.fieldPath=Eo(i.fieldPath,s.slice(1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Eo(i.fieldPath,s.join(".")),i):(i.valuePath=Eo(i.valuePath,jm(t)),i)}return i.valuePath=Eo(i.valuePath,jm(t)),i}function jm(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Eo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function eg(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 yn(e){let t=ze(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function dl(e){let t=ze(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function br(e){return e?{...ze(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function $m(e,t){return e?t?gl(e,t):ze(e):t?ze(t):null}function gl(e,t){if(ps(e)!==ps(t))return null;let n=rg(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function hl(e){let t=new Map;for(let n of e){let r=ps(n),o=t.get(r);t.set(r,o?gl(o,n):ze(n))}return[...t.values()]}function ps(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ps(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 ms(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 us(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function gs(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 tg(e){let t=[...e].sort(ng),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 pR(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 ng(e,t){return Vm(e.targetKind)-Vm(t.targetKind)||rg(e.confidence,t.confidence)||Km(e.sourceKind)-Km(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Vm(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Km(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function rg(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function yl(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Um.get(n)?.get(e),i=o?.source===t?o.ast:JC(t,{sourceType:"module",plugins:["jsx","typescript"]}),s={file:e,source:t,ast:i,variables:new Map,functions:new Map,imports:new Map,stateSetters:new Map,stateSetterCandidates:new Map,jsxElementsByRange:new Map,functionVariables:new WeakMap},a=[],c=[];I.traverse(i,{enter(d){switch(I.isFunction(d)&&a.push(d),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let m=d.loc;if(!m)return;let g=pl({startLine:m.start.line,startColumn:m.start.column,endLine:m.end.line,endColumn:m.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let m=d.source.value;for(let g of d.specifiers)I.isImportSpecifier(g)&&I.isIdentifier(g.local)?s.imports.set(g.local.name,{source:m,importedName:I.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):I.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:m,importedName:"default",localName:g.local.name,isDefault:!0});break}case"FunctionDeclaration":{d.id?.name&&s.functions.set(d.id.name,d);break}case"VariableDeclarator":{let m=a.at(-1),g=m&&(I.isFunctionDeclaration(m)||I.isFunctionExpression(m)||I.isArrowFunctionExpression(m))?m:null,f=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,f);for(let[h,y]of ds(d.id,I.isExpression(d.init)?d.init:null))f.set(h,y);if(I.isArrayPattern(d.id)&&I.isCallExpression(d.init)&&Pt(d.init.callee)==="useState"){let[h,y]=d.id.elements;I.isIdentifier(h)&&I.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}I.isIdentifier(d.id)&&fl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let m=d.declaration,g=d.source?.value;if(g)for(let f of d.specifiers){if(!I.isExportSpecifier(f))continue;let h=I.isIdentifier(f.exported)?f.exported.name:f.exported.value,y=f.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(I.isFunctionDeclaration(m)&&m.id?.name&&s.functions.set(m.id.name,m),I.isVariableDeclaration(m))for(let f of m.declarations)I.isIdentifier(f.id)&&fl(f.init)&&s.functions.set(f.id.name,f.init);break}case"ExportDefaultDeclaration":{let m=d.declaration;if((I.isFunctionDeclaration(m)||I.isFunctionExpression(m)||I.isArrowFunctionExpression(m))&&s.functions.set("default",m),I.isIdentifier(m)){let g=s.functions.get(m.name);g&&s.functions.set("default",g)}break}}},exit(d){I.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,m)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(m),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let m=I.isIdentifier(d.callee)?d.callee.name:null;m&&l.has(m)&&I.isExpression(d.arguments[0])&&u(m,d.arguments[0]);let g=new Set;for(let f of d.arguments)I.isIdentifier(f)&&f.name!==m&&l.has(f.name)&&g.add(f.name);for(let f of g)u(f,d)}return n.set(e,s),s}function ds(e,t){return I.isIdentifier(e)?[[e.name,t]]:I.isAssignmentPattern(e)?ds(e.left,t):I.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!I.isRestElement(n)?ds(n,t?I.memberExpression(t,I.numericLiteral(r),!0):null):[]):I.isObjectPattern(e)?e.properties.flatMap(n=>{if(!I.isObjectProperty(n)||n.computed)return[];let r=ml(n);return r?ds(n.value,t?I.memberExpression(t,I.stringLiteral(r),!0):null):[]}):[]}function jn(e){return!e||I.isVoidPattern(e)?[]:I.isIdentifier(e)?[e.name]:I.isObjectPattern(e)?e.properties.flatMap(t=>I.isObjectProperty(t)?jn(t.value):jn(t.argument)):I.isArrayPattern(e)?e.elements.flatMap(t=>t?jn(I.isRestElement(t)?t.argument:t):[]):I.isAssignmentPattern(e)?jn(e.left):I.isRestElement(e)?jn(e.argument):[]}function fl(e){return I.isFunctionExpression(e)||I.isArrowFunctionExpression(e)}function og(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function ig(e,t){let n=await ag(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return yl(n,r,t.fileCache)}function sg(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function ag(e,t,n){return kt(t)?En(e,t,n):null}function ko(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),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0}}function mR(e){return e?ze(e):null}function ze(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,ze(n)]))}:{}}}import*as bl from"@babel/parser";import xl from"@babel/traverse";import*as q from"@babel/types";import{classifySiteEditPropertyName as gR}from"@vcp-dev/contracts";var Sl=typeof xl=="function"?xl:xl.default;function El(e){let t=gR(e.propertyName);if(t.owner!=="generic")return ft("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return ft("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return ft("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return ft("missing-instance-index","A repeat property target requires an instance index");let r;try{r=bl.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return ft("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=hR(r,e.element.sourceRange);if(!o)return ft("repeat-not-found","The selected element is not inside a supported map repeat");if(!q.isIdentifier(o.callback.params[0]))return ft("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=yR(r,o.collection,e.file,e.sources);if(!i)return ft("collection-not-found","The repeat collection is not a visible local static array");let{array:s,locator:a,sourceFile:c}=i,l=[],u=[];for(let[y,E]of s.elements.entries()){if(!E||!q.isObjectExpression(E)||!pg(E))return ft("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let x=[{kind:"index",index:y}];l.push(x),u.push({kind:"value",root:a.root,path:x})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return ft("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let m=n.instanceIndex;if(m>=d)return ft("index-out-of-range",`Selected repeat instance ${m} is outside the source collection`);let g=s.elements[m];if(!g||!q.isObjectExpression(g))return ft("unsafe-collection","Selected repeat item is not an object");let f=kR(e.element,e.propertyName),h=ER(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[m],sourceItemIndex:m,sourceItemPath:l[m],collectionIndexMap:Array.from({length:d},(y,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:vR(g,e.propertyName),...f?{property:f}:{},selectionRef:n}:ft("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function hR(e,t){let n=[];return Sl(e,{CallExpression(r){let o=cg(r.node);o&&ug(o.callback,t)&&n.push({...o,span:lg(r.node)})},OptionalCallExpression(r){let o=cg(r.node);o&&ug(o.callback,t)&&n.push({...o,span:lg(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function cg(e){let t=e.callee;if(!q.isMemberExpression(t)&&!q.isOptionalMemberExpression(t)||t.computed||!q.isIdentifier(t.property)||t.property.name!=="map"||!q.isExpression(t.object))return null;let n=e.arguments[0];return!n||!q.isExpression(n)||!q.isArrowFunctionExpression(n)&&!q.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function yR(e,t,n,r){let o=Io(t);if(o&&q.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:gg(o)}},sourceFile:n};if(!q.isIdentifier(t))return null;let i=[];if(Sl(e,{VariableDeclarator(s){q.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||!q.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return xR(e,t.name,n,r)}function xR(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!q.isImportDeclaration(o))continue;let i=o.specifiers.find(m=>m.local.name===t);if(!i||!q.isStringLiteral(o.source)||!q.isImportSpecifier(i))continue;let s=SR(n,o.source.value,r);if(!s)return null;let a=q.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=bl.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=bR(l,a),d=u?Io(u):null;return!d||!q.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function bR(e,t){let n=null;return Sl(e,{VariableDeclarator(r){n||!q.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!q.isExpression(r.node.init)||(n=r.node.init)}}),n}function SR(e,t,n){let r=Sn(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 q.isParenthesizedExpression(e)?Io(e.expression):q.isTSAsExpression(e)?fg(e.typeAnnotation)?Io(e.expression):null:q.isTSSatisfiesExpression(e)?null:e}function fg(e){return q.isTSTypeReference(e)&&q.isIdentifier(e.typeName)&&e.typeName.name==="const"}function pg(e){return e.properties.every(t=>!q.isObjectProperty(t)||t.computed||!q.isExpression(t.value)?!1:ys(t.value))}function ys(e){if(q.isTSAsExpression(e)&&fg(e.typeAnnotation))return ys(e.expression);if(q.isTSSatisfiesExpression(e))return!1;if(q.isArrayExpression(e))return e.elements.every(n=>!n||q.isSpreadElement(n)||!q.isExpression(n)?!1:ys(n));if(q.isObjectExpression(e))return pg(e);let t=Dt(e);return t.status==="resolved"||t.status==="undefined"}function ER(e,t){let n=e.properties.filter(o=>q.isObjectProperty(o)&&mg(o.key)===t);if(n.length>1)return null;let r=n[0];return r?q.isExpression(r.value)?ys(r.value)?"static":q.isIdentifier(r.value)||q.isMemberExpression(r.value)?"binding":null:null:"missing"}function vR(e,t){let n=e.properties.filter(o=>q.isObjectProperty(o)&&mg(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!q.isExpression(r.value)?{status:"undefined"}:Dt(r.value)}function kR(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function mg(e){return q.isIdentifier(e)?e.name:q.isStringLiteral(e)?e.value:q.isNumericLiteral(e)?String(e.value):null}function gg(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 lg(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function ug(e,t){let n=gg(e);return dg(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&dg(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function dg(e,t,n,r){return e===n?t-r:e-n}function ft(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as aw}from"@vcp-dev/contracts";import*as te from"@babel/types";import Po from"node:path";import*as B from"@babel/types";import*as Eg from"@babel/parser";import vl from"@babel/traverse";import*as ie from"@babel/types";function bs(e,t){let n=[],r=e;for(;ie.isMemberExpression(r);){if(r.computed)if(ie.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(ie.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!ie.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!ie.isIdentifier(r)||r.name!==t?null:n}function hg(e){if(ie.isIdentifier(e))return{base:e.name,path:[]};if(!ie.isMemberExpression(e))return null;let t=[],n=e;for(;ie.isMemberExpression(n);){if(n.computed)if(ie.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ie.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!ie.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return ie.isIdentifier(n)?{base:n.name,path:t}:null}function Ye(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}var Ut=Symbol("not-closed-literal");function xs(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":return e.value;case"NullLiteral":return null;case"TemplateLiteral":return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:Ut;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return xs(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||ie.isSpreadElement(n))return Ut;let r=xs(n);if(r===Ut)return Ut;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!ie.isObjectProperty(n)||n.computed||n.shorthand||!ie.isExpression(n.value))return Ut;let r=ie.isIdentifier(n.key)?n.key.name:ie.isStringLiteral(n.key)?n.key.value:null;if(!r)return Ut;let o=xs(n.value);if(o===Ut)return Ut;t[r]=o}return t}default:return Ut}}function yg(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let m=xs(i);if(m!==Ut)return m;if(!ie.isTemplateLiteral(i)){if(ie.isTSAsExpression(i)||ie.isTSSatisfiesExpression(i)||ie.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(ie.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let f=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return f?.kind==="static"?f.value:void 0}if(ie.isArrayExpression(i)){let g=[];for(let f of i.elements){if(!f||ie.isSpreadElement(f))return;let h=await r(f,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(ie.isObjectExpression(i)){let g={};for(let f of i.properties){if(!ie.isObjectProperty(f)||f.computed)return;let h=null;if(ie.isIdentifier(f.key)?h=f.key.name:ie.isStringLiteral(f.key)&&(h=f.key.value),!h)return;if(f.shorthand){if(!ie.isIdentifier(f.value))return;let E=await r(f.value,s,a,c,l,u,d);if(E===void 0)return;g[h]=E;continue}if(!ie.isExpression(f.value))return;let y=await r(f.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(ie.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let f=s.getBinding(g.base);if(!f)return;let h=await t({currentFile:a,binding:f,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:Ye(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!ie.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(ie.isIdentifier(i))return{base:i.name,path:[]};if(!ie.isMemberExpression(i))return null;let m=[],g=i;for(;ie.isMemberExpression(g);){if(g.computed){let f=g.property;if(ie.isNumericLiteral(f))m.unshift({kind:"index",index:f.value});else if(ie.isStringLiteral(f))m.unshift({kind:"property",name:f.value});else{let h=ie.isExpression(f)?await n(f,s,a,c,l,u,d):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(!ie.isIdentifier(g.property))return null;m.unshift({kind:"property",name:g.property.name})}g=g.object}return ie.isIdentifier(g)?{base:g.name,path:m}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var vg=typeof vl=="function"?vl:vl.default,xg=new WeakMap;function kg(e){try{return Eg.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ss(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=kg(n);return e.set(t,{source:n,ast:o}),o}function Es(e,t){return kl(Co(e).expressionRanges,t,!1)}function Ig(e,t){return Co(e).exactExpressions.get(Cg(t))??null}function vs(e,t){return kl(Co(e).jsxRanges,t,!0)}function Co(e){let t=xg.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return vg(e,{Expression(r){let o=r;n.expressions.push(o);let i=bg(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=Cg(i.range),a=n.exactExpressions.get(s);(!a||i.span<=(a.node.end??0)-(a.node.start??0))&&n.exactExpressions.set(s,o)},JSXElement(r){let o=bg(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(Sg),n.jsxRanges.sort(Sg),xg.set(e,n),n}function bg(e,t){let n=Ro(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Cg(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function Sg(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function kl(e,t,n,r){let o=0,i=e.length;for(;o<i;){let c=o+Math.floor((i-o)/2),l=e[c].range;l.startLine<t.startLine||l.startLine===t.startLine&&l.startColumn<t.startColumn?o=c+1:i=c}let s=null,a=n?1/0:-1;for(let c=o;c<e.length;c++){let l=e[c],u=l.range;if(u.startLine>t.endLine||u.startLine===t.endLine&&u.startColumn>t.endColumn)break;if(u.endLine>t.endLine||u.endLine===t.endLine&&u.endColumn>t.endColumn||r&&!r(l.path))continue;((n?l.span<a:l.span>a)||l.span===a&&(!s||l.traversalIndex>s.traversalIndex))&&(s=l,a=l.span)}return s?.path??null}function Ro(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 Er(e,t){if(t)return Il(e,t);let n=hg(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Il(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function wo(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Co(e).expressions){if(Il(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Rg(e,t,n,r){return kl(Co(e).expressionRanges,r,!0,o=>Il(o.node,t)===n)}function vr(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function No(e){let t=null;if(vg(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function At(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=kg(o),s={source:o,ast:i};return n.set(e,s),s}function IR(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 CR(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,u=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(u)||!B.isMemberExpression(u.callee)||!B.isIdentifier(u.callee.object,{name:"Reflect"})||!B.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!B.isIdentifier(u.arguments[0],{name:n.name})||!B.isIdentifier(u.arguments[1],{name:r.name})||!B.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function RR(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 wg(e,t){let n=RR(e.path);if(!n)return null;let r=ur(e,t);return r?{...n,...r}:null}function Ng(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Cl(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 Rl(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 Pg(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:w}=f,N=`${h}::${y.kind}::${y.identifier.name}`;if(w.has(N))return null;w.add(N);try{let T=await a({currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:w});if(T)return T;if(y.path.isImportSpecifier()||y.path.isImportDefaultSpecifier())return await m({currentFile:h,binding:y,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,fileCache:v,visited:w});if(y.kind==="param")return null;if(y.path.isVariableDeclarator()){let C=y.path.node.init;if(!C||!B.isExpression(C))return null;let P=CR(C);if(P&&!y.path.scope.getBinding("Proxy")&&!y.path.scope.getBinding("Reflect")){let W=y.path.scope.getBinding(P),z=W?await s({...f,binding:W}):null;if(z?.kind==="static"&&z.value!==null&&!Array.isArray(z.value)&&typeof z.value=="object")return z}let F=y.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let W=await t({currentFile:h,expressionPath:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});if(W)return W;if(F.isCallExpression()){let z=await n({currentFile:h,callPath:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});if(z)return z}}let L=await r(C,y.path.scope,h,E,x,v,w);return L===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:L,sourceKind:"binding"}}if(y.path.isIdentifier()&&y.path.parentPath?.isExportDefaultDeclaration()){let C=y.path.parentPath.node.declaration;if(!B.isExpression(C))return null;let P=await r(C,y.path.scope,h,E,x,v,w);return P===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:P,sourceKind:"binding"}}return null}finally{w.delete(N)}}async function a(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:w}=f;if(!y.path.isVariableDeclarator()||!y.path.get("id").isArrayPattern())return null;let N=y.path,T=N.node.init;if(!T||!B.isCallExpression(T))return null;let C=IR(T);if(!C||!B.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(z=>B.isIdentifier(z)&&z.name===y.identifier.name)!==0)return null;let F=C==="useReducer"?1:0,L=T.arguments[F];if(!L||!B.isExpression(L))return null;let W=await r(L,N.scope,h,E,x,v,w);return W===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:y.identifier.name,hook:C},value:W,sourceKind:"binding"}}async function c(f){let h=f.expressionPath.scope.getBinding(f.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!f.graph)return null;let y=wg(h,f.sourceInfo);if(!y)return null;let E=[...f.graph.elements.values()].filter(v=>Ng(v,f.currentFile,y.componentName,y.exportName));if(!E.length)return null;let x=[];for(let v of E){if(v.sourceFile!==E[0].sourceFile||v.componentName!==E[0].componentName||v.attributeSpreads?.length)return null;let w=await At(v.sourceFile,f.readFile,f.fileCache),N=w.ast?vs(w.ast,v.sourceRange):null;if(!N)return null;let T=N.parentPath;for(;T&&!T.isFunction();){if(T.isJSXElement()){let he=T.node.openingElement.name;if(!B.isJSXIdentifier(he)||!/^[a-z]/.test(he.name))return null}else if(!T.isJSXFragment()&&!T.isReturnStatement()&&!T.isBlockStatement())return null;T=T.parentPath}if(!T)return null;let C=N.get("openingElement").get("attributes").filter(he=>he.isJSXAttribute()&&B.isJSXIdentifier(he.node.name,{name:y.propName}));if(C.length!==1)return null;let P=C[0];if(!P?.isJSXAttribute())return null;let F=P.get("value"),L=F.isJSXExpressionContainer()?F.get("expression"):F;if(!L.isExpression())return null;let W=await r(L.node,L.scope,v.sourceFile,f.readFile,f.exists,f.fileCache,f.visited),z=W===void 0?void 0:Ye(W,y.remainingPath);if(z===void 0)return null;x.push(z)}return x}async function l(f){let h=wg(f.binding,f.sourceInfo);if(!h||!f.graph)return null;let y=[...f.graph.elements.values()].filter(C=>Ng(C,f.currentFile,h.componentName,h.exportName));if(y.length!==1)return null;let E=y[0],x=E.attributes?.find(C=>C.name===h.propName);if(x&&!x.source){let C=await u({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,fileCache:f.fileCache});if(C)return Cl(C,{componentName:h.componentName,propName:h.propName,file:E.sourceFile})}if(!x?.source){let C=await d({caller:E,propName:h.propName,remainingPath:h.remainingPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(C)return Cl(C,{componentName:h.componentName,propName:h.propName,file:E.sourceFile});let P=Np(f.binding,h.componentName,h.propName);if(!P||P.propName!==h.propName)return null;let F=await r(P.expressionPath.node,P.expressionPath.scope,f.currentFile,f.readFile,f.exists,f.fileCache,f.visited);if(F===void 0)return null;let L=h.remainingPath;return L.length>0&&Ye(F,L)===void 0?null:{kind:"value",file:f.currentFile,root:{kind:"binding",name:h.propName},path:L,sourceKind:"binding",semanticKind:"component-prop",displayExpression:P.displayPath,chainPrefix:[{kind:"component-prop",file:f.currentFile,displayName:P.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await At(E.sourceFile,f.readFile,f.fileCache);if(!v.ast)return null;let w=Rg(v.ast,v.source,x.source.expression,x.sourceRange)??wo(v.ast,v.source,x.source.expression);if(!w)return null;let N={...x.source,expression:vr(x.source.expression,h.remainingPath),path:[...x.source.path,...h.remainingPath]},T=await o({currentFile:E.sourceFile,expressionPath:w,sourceInfo:N,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});return T?Cl(T.kind==="external"?T:{...T,displayExpression:N.expression},{componentName:h.componentName,propName:h.propName,file:E.sourceFile}):null}async function u(f){let h=await At(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=vs(h.ast,f.caller.sourceRange);if(!y)return null;let E=y.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===f.propName);if(!E?.isJSXAttribute())return null;let x=E.get("value"),v=x.isStringLiteral()?x:x.isJSXExpressionContainer()?x.get("expression"):null;if(!v?.isExpression())return null;let w=Ro(v.node);return w?{kind:"value",file:f.caller.sourceFile,root:{kind:"expression",sourceRange:w},path:f.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:f.propName,editMode:"upstream",diagnostics:[]}:null}async function d(f){let h=await At(f.caller.sourceFile,f.readFile,f.fileCache);if(!h.ast)return null;let y=vs(h.ast,f.caller.sourceRange);if(!y)return null;let E=y.get("openingElement");for(let x of E.get("attributes")){if(!x.isJSXSpreadAttribute())continue;let v=x.get("argument");if(!v.isExpression())continue;let w=await i({expression:v.node,scope:v.scope,source:h.source,currentFile:f.caller.sourceFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!w)continue;let N=[{kind:"property",name:f.propName},...f.remainingPath],T={...w,expression:vr(w.expression,N),path:[...w.path,...N]},C=await o({currentFile:f.caller.sourceFile,expressionPath:v,sourceInfo:T,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(C)return C.kind==="external"?C:{...C,displayExpression:T.expression}}return null}async function m(f){let{currentFile:h,binding:y,readFile:E,exists:x,fileCache:v,visited:w}=f,N=y.path.parentPath;if(!N||!N.isImportDeclaration())return null;let T=N.node.source.value;if(typeof T!="string")return null;let C=await En(h,T,x);if(!C)return null;if(y.path.isImportDefaultSpecifier()){let he=await At(C,E,v),j=he.ast?Rl(he.ast,"default"):null,G=await g({file:C,exportName:"default",readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});return!G||G.kind!=="static"?null:{kind:"static",file:j?.kind==="default-expression"?G.file:C,root:j?.kind==="default-expression"?G.root:{kind:"default-export"},value:G.value,sourceKind:"imported-binding"}}if(!y.path.isImportSpecifier())return null;let P=y.path.node.imported,F=B.isIdentifier(P)?P.name:P.value,L=await At(C,E,v),W=L.ast?Rl(L.ast,F):null,z=await g({file:C,exportName:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});return z?z.kind==="external"?z:{kind:"static",file:W?.kind==="re-export"?z.file:C,root:W?.kind==="re-export"||z.root.kind==="binding"&&z.root.name!==W?.name?z.root:{kind:"named-export",name:F},value:z.value,sourceKind:"imported-binding"}:null}async function g(f){let{file:h,exportName:y,readFile:E,exists:x,fileCache:v,visited:w}=f,N=`export::${h}::${y}`;if(!w.has(N)){w.add(N);try{let T=await At(h,E,v);if(!T.ast)return;let C=Rl(T.ast,y);if(!C)return;if(C.kind==="default-expression"){let W=C.expression;if(!W||!B.isIdentifier(W))return;let z=No(T.ast).getBinding(W.name);return z?await s({currentFile:h,binding:z,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w})??void 0:void 0}if(C.kind==="re-export"){if(!C.source||!C.name)return;let W=await En(h,C.source,x);return W?g({...f,file:W,exportName:C.name}):void 0}let P=C.name;if(!P)return;let F=No(T.ast).getBinding(P);return F?await s({currentFile:h,binding:F,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w})??void 0:void 0}finally{w.delete(N)}}}return{resolveExportValue:g,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as Z from"@babel/types";function Nl(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=wt(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!wR(s,r)?null:{callPath:s,basePath:i}}function wR(e,t){let n=e.node.callee;return!Z.isMemberExpression(n)||!Z.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function _g(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Gi(r,t)}function Ag(e,t){return e?Z.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Tg(e,t,n,r,o){let i=Z.isExpression(e.body)?e.body:e.body.body.find(a=>Z.isReturnStatement(a))?.argument;if(!i||!Z.isExpression(i))return;let s=wl(i,t,n,r,o);return typeof s=="number"?s:void 0}function wl(e,t,n,r,o){if(Z.isNumericLiteral(e)||Z.isStringLiteral(e)||Z.isBooleanLiteral(e))return e.value;if(Z.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(Z.isMemberExpression(e)){let i=bs(e,t);if(i)return Ye(r,i);let s=bs(e,n);return s?Ye(o,s):void 0}if(Z.isBinaryExpression(e)&&e.operator==="-"){let i=Z.isExpression(e.left)?wl(e.left,t,n,r,o):void 0,s=Z.isExpression(e.right)?wl(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function NR(e){if(Z.isExpression(e.body))return e.body;for(let t of e.body.body)if(Z.isReturnStatement(t)&&t.argument&&Z.isExpression(t.argument))return t.argument;return null}function PR(e,t,n){let r=Vn(e,t,n);return typeof r=="boolean"?r:void 0}function Vn(e,t,n){if(Z.isStringLiteral(e)||Z.isNumericLiteral(e)||Z.isBooleanLiteral(e))return e.value;if(Z.isNullLiteral(e))return null;if(Z.isIdentifier(e))return e.name===t?n:void 0;if(Z.isMemberExpression(e)){let r=bs(e,t);return r?Ye(n,r):void 0}if(Z.isUnaryExpression(e)&&e.operator==="!"){let r=Vn(e.argument,t,n);return r===void 0?void 0:!r}if(Z.isLogicalExpression(e)){let r=Vn(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Vn(e.right,t,n);if(e.operator==="||")return r||Vn(e.right,t,n)}if(Z.isBinaryExpression(e)){let r=Z.isExpression(e.left)?Vn(e.left,t,n):void 0,o=Z.isExpression(e.right)?Vn(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 Mg(e){let t=[],n=e;for(;Z.isMemberExpression(n)||Z.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(Z.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(Z.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(Z.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(Z.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return Z.isIdentifier(n)?{base:n.name,segments:t}:null}function Og(e){return e.some(t=>t.kind==="dynamic")}function Fg(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Lg(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 AR(e,t){let n=[],r=[];for(let o of t){let i=Ye(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 Dg(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(f){let{currentFile:h,callPath:y,readFile:E,exists:x,fileCache:v,visited:w}=f,N=y.node.callee;if(!Z.isMemberExpression(N)||!Z.isIdentifier(N.property)||N.property.name!=="map")return null;let T=y.get("callee");if(!T.isMemberExpression())return null;let C=T.get("object");if(Array.isArray(C)||!C.isExpression())return null;let P=await a({currentFile:h,expressionPath:C,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});return!P||!Array.isArray(P.value)||P.value.length===0?null:P}async function a(f){let{currentFile:h,expressionPath:y,readFile:E,exists:x,fileCache:v,visited:w}=f;if(y.isIdentifier()){let N=y.scope.getBinding(y.node.name);if(!N)return null;let T=await t({currentFile:h,binding:N,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});return T?.kind==="static"?T:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let N=y.get("expression");if(!Array.isArray(N)&&N.isExpression())return a({...f,expressionPath:N})}if(y.isArrayExpression()){let N=Ro(y.node);if(!N)return null;let T=await n(y.node,y.scope,h,E,x,v,w);return Array.isArray(T)?{kind:"static",file:h,root:{kind:"expression",sourceRange:N},value:T,sourceKind:"binding"}:null}if(y.isMemberExpression()){let N=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:E,exists:x,fileCache:v,visited:w});if(!N)return null;let T=await o({currentFile:h,expressionPath:y,sourceInfo:N,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});if(!T||T.kind==="external")return null;let C=await c({currentFile:h,expressionPath:y,provenance:T,readFile:E,exists:x,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:v,visited:w});if(!C||C.kind!=="static")return null;if(T.collectionPathMap?.length){let F=AR(C.value,T.collectionPathMap);if(F)return{kind:"static",file:T.file,root:T.root,value:F.value,sourceKind:T.sourceKind,collectionPathMap:F.collectionPathMap}}let P=Ye(C.value,T.path);return Array.isArray(P)?{kind:"static",file:T.file,root:T.root,value:P,sourceKind:T.sourceKind,pathPrefix:T.path,collectionIndexMap:T.collectionIndexMap,collectionPathMap:T.collectionPathMap}:null}return null}async function c(f){let{provenance:h}=f;if(h.root.kind==="binding"){let v=f.expressionPath.scope.getBinding(h.root.name);if(!v&&h.file!==f.currentFile){let w=await At(h.file,f.readFile,f.fileCache);v=w.ast?No(w.ast).getBinding(h.root.name):void 0}return v?await t({currentFile:h.file,binding:v,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited}):null}if(h.root.kind!=="expression")return null;let y=await At(h.file,f.readFile,f.fileCache);if(!y.ast)return null;let E=Ig(y.ast,h.root.sourceRange);if(!E)return null;let x=await n(E.node,E.scope,h.file,f.readFile,f.exists,f.fileCache,f.visited);return x===void 0?null:{kind:"static",file:h.file,root:h.root,value:x,sourceKind:h.sourceKind}}async function l(f){return await u(f)??await d(f)??await m(f)}async function u(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="filter")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[w]=h.node.arguments;if(!Z.isArrowFunctionExpression(w)&&!Z.isFunctionExpression(w))return null;let N=w.params[0];if(!Z.isIdentifier(N))return null;let T=NR(w);if(!T)return null;let C=[],P=[],F=[];for(let[L,W]of v.value.entries()){let z=PR(T,N.name,W);if(typeof z!="boolean")return null;if(z){C.push(W),P.push(v.collectionIndexMap?.[L]??L);let he=v.collectionPathMap?.[L];he&&F.push(he)}}return{...v,value:C,pathPrefix:v.pathPrefix,collectionIndexMap:P,...F.length>0?{collectionPathMap:F}:{}}}async function d(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="slice")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[w,N]=h.node.arguments,T=Ag(w,0),C=Ag(N,v.value.length);if(T===null||C===null)return null;let P=Math.max(0,T<0?v.value.length+T:T),F=Math.max(0,C<0?v.value.length+C:C),L=v.value.map((z,he)=>v.collectionIndexMap?.[he]??he).slice(P,F),W=v.collectionPathMap?.slice(P,F);return{...v,value:v.value.slice(P,F),pathPrefix:v.pathPrefix,collectionIndexMap:L,...W?{collectionPathMap:W}:{}}}async function m(f){let{callPath:h}=f,y=h.node.callee;if(!Z.isMemberExpression(y)||!Z.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let E=h.get("callee");if(!E.isMemberExpression())return null;let x=E.get("object");if(Array.isArray(x)||!x.isExpression())return null;let v=await a({currentFile:f.currentFile,expressionPath:x,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!v||!Array.isArray(v.value))return null;let[w]=h.node.arguments;if(!Z.isArrowFunctionExpression(w)&&!Z.isFunctionExpression(w))return null;let[N,T]=w.params;if(!Z.isIdentifier(N)||!Z.isIdentifier(T))return null;let C=v.value.map((F,L)=>({value:F,sourceIndex:v.collectionIndexMap?.[L]??L,originalIndex:L})),P=[...C];for(let F of C)for(let L of C)if(Tg(w,N.name,T.name,F.value,L.value)===void 0)return null;return P.sort((F,L)=>{let W=Tg(w,N.name,T.name,F.value,L.value)??0;return W===0?F.originalIndex-L.originalIndex:W}),{...v,value:P.map(F=>F.value),pathPrefix:v.pathPrefix,collectionIndexMap:P.map(F=>F.sourceIndex),...v.collectionPathMap?{collectionPathMap:P.map(F=>v.collectionPathMap?.[F.originalIndex]).filter(F=>!!F)}:{}}}async function g(f){let h=null,y=!1,E,x=[];for(let w of f.segments){if(w.kind!=="dynamic")continue;let N=await r({expression:w.expression,scope:f.expressionPath.scope,source:f.fileCache.get(f.currentFile)?.source,currentFile:f.currentFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!N)return null;let T=Nl(f.expressionPath,N.base),C;if(T){y=!0;let P=await s({currentFile:f.currentFile,callPath:T.callPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(!P||!Array.isArray(P.value))return null;C=P.value.map((F,L)=>{let W=Ye(P.value,[{kind:"index",index:L},...T.basePath,...N.path]);return Fg(W)}),E??=P.collectionIndexMap}else{let P=await i({...f,sourceInfo:N});if(!P)return null;C=P.map(Fg)}if(C.some(P=>P===null)||h!==null&&h!==C.length)return null;h=C.length,x.push(C)}if(h===null||h===0)return null;let v=[];for(let w=0;w<h;w+=1){let N=[...f.rootPath],T=0;for(let C of f.segments){if(C.kind==="dynamic"){let P=x[T]?.[w];if(!P)return null;N.push(P),T+=1;continue}N.push({...C})}v.push(N)}return{sourceKind:y||h>1?"repeat-template":"binding",...E?{collectionIndexMap:E}:{},collectionPathMap:v}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:TR,evaluateStaticExpression:ks}=yg({resolveBindingTarget:e=>Is(e)}),{resolveRepeatCollectionTarget:FR,resolveCollectionCallTarget:_R,resolveDynamicMemberPathMap:MR}=Dg({resolveBindingTarget:e=>Is(e),evaluateStaticExpression:ks,buildExpressionSourceInfo:Jt,resolveSourceInfoProvenance:vt,resolveComponentPropValues:e=>DR(e)}),{resolveExportValue:OR,resolveComponentPropBinding:LR,resolveComponentPropValues:DR,resolveBindingTarget:Is}=Pg({resolveExternalExpression:Ol,resolveCollectionCallTarget:_R,evaluateStaticExpression:ks,resolveSourceInfoProvenance:vt,buildExpressionSourceInfo:Jt});function zg(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Bg=new WeakMap;function BR(e){let t=Bg.get(e);return t||(t=new WeakMap,Bg.set(e,t)),t}function jg(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 Wg(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ss(s,t,n);if(!a)return null;let c=Es(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 jl({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?Tl(m,Er(c.node,n)):null}let u=new Set,d=await sw({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:u});return d?Tl(d,l.expression):null}async function kr(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ss(i,t,n);if(!s)return null;let a=e.sourceRange?Es(s,e.sourceRange):e.expression!==void 0?wo(s,n,e.expression):null;if(!a)return null;let c=Cs(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Jt({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await vt({currentFile:t,expressionPath:c,sourceInfo:u,readFile:r,exists:o,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:i,visited:l}):await th({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 Tl(d,e.expression??Er(c.node,n))}async function Ml(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ss(i,t,n);if(!s)return pt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?jR({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}):$R({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(te.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!te.isMemberExpression(e.expression))return null;let t=await TR(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:Er(e.expression,e.source),base:t.base,path:t.path}:null}function Tl(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 jR(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Es(r,o.sourceRange),u=l?await Jt({expression:l.node,scope:l.scope,source:n,currentFile:t,readFile:i,exists:s,fileCache:a,visited:c}):null;if(!u){if(!l||l.isStringLiteral()||l.isTemplateLiteral()&&l.node.expressions.length===0)return $g(t,o.value);let m=await jl({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"?Xg(t,m):_l(t,Er(l.node,n),m):VR({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return pt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await vt({currentFile:t,expressionPath:l,sourceInfo:u,readFile:i,exists:s,graph:e.graph,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters,functionCallContracts:e.functionCallContracts,fileCache:a,visited:c});if(!d){let m=Fl(l.node);if(m)return pt(m.code,m.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let f=Fl(g.path.node.init);if(f)return pt(f.code,f.message)}return g?.path.isVariableDeclarator()&&te.isCallExpression(g.path.node.init)?KR("unsupported-expression",Qg(g.path.node.init,e.functionCallContracts)):pt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?Xg(t,d):_l(t,u.expression,d)}async function $R(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=wo(r,n,o.conditionExpression);if(!l)return pt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await vt({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(!u)return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return pt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=_l(t,o.conditionExpression,u);return d.finalSource?{...d,finalSource:{...d.finalSource,kind:"conditional-branch",displayPath:o.conditionExpression},chain:[...d.chain,{kind:"conditional-branch",file:u.file,displayName:o.conditionExpression,canEditHere:!0}]}:d}function $g(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 VR(e){let t=await Gg(e);if(t.length===0)return pt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(UR(e.expression))return Hg(t);if(Zg(e.expression))return pt("unsupported-expression","i18n helpers require a static message id string");if(te.isMemberExpression(e.expression)&&e.expression.computed&&!te.isNumericLiteral(e.expression.property)&&!te.isStringLiteral(e.expression.property))return pt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return pt(n.code,n.message)}function pt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function KR(e,t){return Hg([{code:e,message:t}])}function Hg(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function UR(e){return te.isCallExpression(e)||te.isConditionalExpression(e)||te.isLogicalExpression(e)||te.isBinaryExpression(e)}function Ao(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 Gg(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Fl(t);if(l)return[l];if(te.isCallExpression(t))return[{code:"unsupported-expression",message:Qg(t,c)}];if(te.isMemberExpression(t)&&t.computed){let u=t.property;if(!te.isNumericLiteral(u)&&!te.isStringLiteral(u)){if(!te.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let m=await ks(u,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 te.isBinaryExpression(t)?Ao([...await Pl(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):te.isLogicalExpression(t)?Ao([...await Pl(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"}]):te.isConditionalExpression(t)?Ao([...await Pl(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 Fl(e){return Zg(e)?Vg("i18n helpers require a static message id string"):HR(e)?Vg("CMS helpers require static entry id and field path string arguments"):null}async function Pl(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await Gg({...t,expression:o}));return r}function JR(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:[XR(e.sourceType)]}}async function Ol(e){for(let n of QR){if(!Kg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return Jg(Ug(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(!Kg(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return Jg(Ug(r),e.externalAdapters)}return null}function XR(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function zR(e){return{code:"external-source-readonly",message:e}}function Vg(e){return{code:"unsupported-expression",message:e}}function Ll(e){return!e||!te.isCallExpression(e)?null:te.isIdentifier(e.callee)?e.callee.name:te.isMemberExpression(e.callee)&&!e.callee.computed&&te.isIdentifier(e.callee.object)&&te.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function Kg(e,t){if(!t||t.length===0)return!0;let n=Ll(e.node);return n?t.includes(n):!1}function Ug(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Ao(e.diagnostics??[])}:{match:e,diagnostics:[]}}function Jg(e,t){let n=JR(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:Ao([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function WR(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!te.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!te.isStringLiteral(n)||!te.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 HR(e){return!!e&&te.isCallExpression(e)&&te.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!te.isStringLiteral(e.arguments[0])||!te.isStringLiteral(e.arguments[1]))}function Yg(e){if(!(!e||!te.isCallExpression(e))){if(te.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&te.isStringLiteral(t)?t.value:null}if(te.isMemberExpression(e.callee)&&!e.callee.computed&&te.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&te.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!te.isObjectExpression(t))return null;for(let n of t.properties)if(te.isObjectProperty(n)&&!n.computed&&(te.isIdentifier(n.key)&&n.key.name==="id"||te.isStringLiteral(n.key)&&n.key.value==="id")&&te.isStringLiteral(n.value))return n.value.value;return null}}}function Zg(e){return Yg(e)===null}async function GR(e,t,n){let r=new Set,o=Po.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Po.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"]:[Po.posix.join(i,"locales"),Po.posix.join(i,"messages")];for(let a of s){let c=Po.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function YR(e){let t=Yg(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await GR(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function ZR(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!te.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!te.isExpression(n))return null;let o=await ks(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:[zR("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var QR=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>WR(e)},{helperNames:["apiField"],resolve:e=>ZR(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>YR({currentFile:e,expressionPath:t,exists:n})}];function Dl(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function Xg(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 _l(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=iw(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 qR=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Bl(e,t){let n=[...qR,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function Qg(e,t){let n=e.callee;return te.isIdentifier(n)&&Bl(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 jl(e){let t=await Ol(e);if(t)return t;let n=await qg({...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 vt({...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 rw(e)}async function qg(e){let t=await Tt({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Cs(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Dl(t.provenance)}async function Tt(e){let t=Cs(e.expressionPath),n=nw(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 vt({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 vt({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 Tt({...e,expressionPath:r,allowComposed:!0}),a=await Tt({...e,expressionPath:o,allowComposed:!1}),c=await Tt({...e,expressionPath:i,allowComposed:!1});return Al(s,a,c)}if(t.isCallExpression())return ew({...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 Tt({...e,expressionPath:r,allowComposed:!0}),s=await Tt({...e,expressionPath:o,allowComposed:!0});return Al(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 Tt({...e,expressionPath:r,allowComposed:!0}),s=await Tt({...e,expressionPath:o,allowComposed:!0});return Al(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Tt({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Cs(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 ew(e){let t=Ll(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:Tt({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(te.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Tt({...e,expressionPath:o,allowComposed:!1})}}return null}function Al(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!tw(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function tw(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 nw(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function rw(e){if(!e.expressionPath.isCallExpression())return null;let t=Ll(e.expressionPath.node);if(!t)return null;let n=Bl(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 eh({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?Dl(i):null}async function eh(e){let t=await Ol({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 vt({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 jl({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 ow(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!te.isCallExpression(t))return null;let n=t.callee;if(!te.isIdentifier(n))return null;let r=Bl(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 eh({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?Dl(a):null}function iw(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=vr(t,e.path);return{sourceId:o,displayPath:o}}async function sw(e){let t=e.segment.source;return t?vt({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 vt(e){let t=e.sourceInfo,n=Nl(e.expressionPath,t.base);if(n){let l=await FR({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=_g(n.callPath,[...n.basePath,...t.path]);return uo(h)?jg(e.currentFile,h.sourceId,h.displayPath):null}let u=Lg(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,m=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return Ye(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??m,sourceKind:"repeat-template",collectionIndexMap:l.collectionIndexMap,...u?{collectionPathMap:u}:{}}}let r=e.expressionPath.scope.getBinding(t.base);if(!r)return null;if(r.path.isImportNamespaceSpecifier()){let l=t.path[0],u=r.path.parentPath;if(!l||l.kind!=="property"||!u?.isImportDeclaration())return null;let d=await En(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let m=await OR({file:d,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 g=t.path.slice(1);return Ye(m.value,g)===void 0?null:{kind:"value",file:m.file,root:m.root,path:g,sourceKind:"imported-binding",collectionIndexMap:m.collectionIndexMap}}let o=Rp(r);if(o){let l=o.expressionPath,u=await Jt({expression:l.node,scope:l.scope,currentFile:e.currentFile,readFile:e.readFile,exists:e.exists,fileCache:e.fileCache,visited:e.visited});if(u){let d=await vt({...e,expressionPath:l,sourceInfo:{...u,expression:vr(u.expression,t.path),path:[...u.path,...t.path]}});if(d)return d}else if(r.constant){let d=`dynamic-alias:${e.currentFile}:${l.node.start}`;if(e.visited.has(d))return null;e.visited.add(d);try{let m=await th({...e,expressionPath:Cs(l),memberSuffix:t.path});if(m?.kind==="value")return m}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await qg({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(d)return d}}if(r.kind==="param")return LR({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 ow({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=Wi(r,t.path,BR(e.fileCache));if(uo(s))return jg(e.currentFile,s.sourceId,s.displayPath);let a=await Is({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:Ye(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 th(e){let t=Mg(e.expressionPath.node);if(!t||!Og(t.segments))return null;let n=await vt({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 MR({...e,rootPath:n.path,segments:t.segments});if(!r)return null;let o=r.collectionPathMap.map(i=>[...i,...e.memberSuffix??[]]);if(e.memberSuffix){let i=e.expressionPath.scope.getBinding(t.base),s=i?await Is({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Ye(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:Er(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function nh(e){let t=aw(e.propertyName);if(t.owner==="blocked")return xn(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return xn(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 xn("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 lw(e,l)});o.sort((l,u)=>l.order-u.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 xn("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}:xn("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?xn("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):cw(e,s.attribute)}async function cw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await kr({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}}:xn("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 kr({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"?xn("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 lw(e,t){let n=t.source?.expression;if(!n)return;let r=await kr({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:uw(r,e.propertyName)}}function uw(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 xn(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function rh(e){let t=new Map;for(let r of e.elements.values()){if(r.importedFrom===void 0)continue;let o=t.get(r.importedFrom);o||(o={candidates:[],keys:new Map},t.set(r.importedFrom,o)),o.candidates.push(r)}let n=r=>{if(Kn(r.tag))return r.identity.key;let o=t.get(r.sourceFile);if(!o)return null;if(o.keys.has(r.componentName))return o.keys.get(r.componentName);let i=o.candidates.filter(a=>mw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>dw({...r,graph:e},n)}function dw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=pw(n,r,o,t),a=s?.tag??(Kn(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=hw(s),u=yw(n,r,o,i,s),d=fw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:gw(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:xw(d),alternativeStrategies:bw(d)}}function fw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return $l(e,n)?"instance":!Kn(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function pw(e,t,n,r){if(Kn(t.tag))return t;let o=$l(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function mw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function gw(e,t){return Kn(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function hw(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 yw(e,t,n,r,o){let i=new Set,s=$l(e,n);s&&o?.identity.key===s.identity.key&&i.add("children");for(let a of r.values()){let c=a?.chain.find(u=>u.kind==="component-prop");if(!c)continue;let l=c.displayName.split(".").pop();l&&i.add(l)}return i.size===0&&Kn(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function $l(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Kn(r.tag))return r;n=r.parentKey}return null}function Kn(e){return/^[A-Z]/.test(e)}function xw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function bw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function sh(e){let t=e.isRepeat??(e.graph?Nw(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=ww(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>Sw({attribute:u,element:e.element,isRepeat:t,selectionRef:e.selectionRef,provenance:n.get(u.name),repeatTarget:r.get(u.name)})),a=(e.element.attributeSpreads?.length??0)>0,c=(e.element.attributeSpreads??[]).slice().sort((u,d)=>u.order-d.order).map(u=>({raw:u.raw,sourceRange:Pw(u.sourceRange,e.source),order:u.order,diagnostics:u.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 Sw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=Ew(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:ns({state:n,scope:y,operation:"set",selectionRef:e.selectionRef,isRepeat:e.isRepeat,repeatTarget:r})})),a=s.find(({result:y})=>y.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,u=vw(t,n,l,e.isRepeat),d=c?Cw(c,e.element,t.name):void 0,m=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=m.length>0?Iw(n,o,e.element):"unsupported",f=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=Rw(t,n,r);if(m.length===0&&h.length===0){let y=s.find(({result:E})=>!E.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:f,allowedWriteScopes:m,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function Ew(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 vw(e,t,n,r){return n?oh(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:oh(kw(e))}function kw(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 oh(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function Iw(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 Cw(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:ih({...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:ih(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function Rw(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 ww(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function Nw(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 ih(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 Pw(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 Aw(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var Tw=160;function ah(e,t,n,r={}){let o=rr(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 ch(e,t,n,r,o,i,s,a,c,l,u){let d=rr(t),m=t.elements.get(e),g=n.nodes.get(e),f=r.get(e);if(!m||!g||!f)throw new Error(`Node not found: ${e}`);let h=ph(m.textSegments,s),y=mh(e,t,m,f,h),E=h?Ow(h):void 0,x=Lw(i,h),v=m.textSegments.map(C=>({index:C.index,value:C.value,editable:gh(C,f,s?.get(C.index)??null),source:o.get(C.index)??null})),w=dh(m,t),N=m.childKeys.map(C=>{let P=t.elements.get(C);return P?{key:C,tag:P.tag,label:P.tag}:null}).filter(C=>C!==null),T=[];if(m.parentKey){let C=t.elements.get(m.parentKey);if(C)for(let P of C.childKeys){if(P===e)continue;let F=t.elements.get(P);F&&T.push({key:P,tag:F.tag,label:F.tag})}}return{composition:d,key:e,tag:m.tag,componentName:m.componentName,sourceFile:m.sourceFile,sourceLocator:uh(m),label:m.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:x,provenanceChain:E,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:v,boundaryKind:m.boundaryKind,isOpaque:m.isOpaque,ancestors:w,children:N,siblings:T}}function lh(e,t,n,r,o,i,s,a){let c=rr(t),l=t.elements.get(e),u=n.nodes.get(e),d=r.get(e);if(!l||!u||!d)throw new Error(`Node not found: ${e}`);let m=ph(l.textSegments,i),g=Fw(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:uh(l),label:l.tag,capabilities:mh(e,t,l,d,m),provenanceChain:m?{editMode:m.editMode,diagnostics:m.diagnostics.map(f=>({code:f.code,message:f.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(f=>{let h=o.get(f.index);return{index:f.index,editable:gh(f,d,i?.get(f.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:dh(l,t)}}function Fw(e){if(e.tag==="a")return"native-anchor";if(e.importedFrom==="next/link"&&e.exportName==="default")return"next-link";if(e.tag==="Link")return"unsupported"}function uh(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:_w(e.sourceRange),structuralPath:e.identity.structuralPath,...Mw(e.textSegments)}}function dh(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 _w(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Mw(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,Tw)}:{}}function fh(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 ph(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function mh(e,t,n,r,o){let i=n.identity.structuralPath.includes("#repeat:"),s=t.regions.some(u=>u.kind==="repeat-region"&&u.childKeys.includes(e)),a=o?.diagnostics.find(u=>u.code==="missing-adapter"||u.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&&hh(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 gh(e,t,n){return!e.editable||!t.canUpdateText?!1:n?hh(n.editMode):!0}function hh(e){return e==="direct"||e==="proxy"||e==="upstream"}function Ow(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 Lw(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}:Aw(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 Vl=["set-class-name-source","apply-style-draft"];function yh(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Vl,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:Vl,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Vl}}function xh(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}),bh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function bh(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}),bh(s,t,n,r,o))}}import Sh from"node:path";function Ul(){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 vh(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=$w(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 Rs(e){let t=()=>Dw(e);return e.mutex?e.mutex.runExclusive(t):t()}async function Dw(e){let t=await vh(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=Bw(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 Kl({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 Kl({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 Kl({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 Eh("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Eh("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 Bw(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 Kl(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:jw(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 Eh(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function jw(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 $w(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)||Sh.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Sh.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 Vw=50,Kw=8*1024*1024;function Rh(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??Vw),s=Math.max(0,t.maxUndoBytes??Kw);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(C){let P=[...C.steps].sort((j,G)=>j.order-G.order),F=P.filter(j=>j.type!=="invoke-external-adapter");if(F.length!==P.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(F.map(j=>j.file)),W=await x(L),z=new Map(W.map(j=>[j.file,j.exists===!1?"":j.content])),he;for(let j of F){let G=Ch(j,z.get(j.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};z.set(j.file,G.source),he=G.selectionRef??he}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...z].map(([j,G])=>({operation:"upsert",file:j,content:G,baseContentHash:W.find(pe=>pe.file===j)?.sha256??null}))},...he?{selectionRef:he}:{}}}async function c(C){let P=[...C.steps].sort((pe,st)=>pe.order-st.order),F=P.filter(pe=>pe.type!=="invoke-external-adapter"),L=P.filter(pe=>pe.type==="invoke-external-adapter"),W=new Set(F.map(pe=>pe.file));if(F.length>0&&L.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 y(C,L);let z=await x(W),he=new Map;for(let pe of z)he.set(pe.file,pe.exists===!1?"":pe.content);let j;for(let pe of F){let st=he.get(pe.file)??"",tt=Ch(pe,st);if(!tt.ok)return{ok:!1,operationId:C.operationId,errorCode:tt.errorCode,reason:tt.reason,rolledBack:!1};he.set(pe.file,tt.source),tt.selectionRef&&(j=tt.selectionRef)}let G=await w([...he].map(([pe,st])=>({file:pe,content:st,exists:!0,version:0,sha256:Ce(st)})),z);return G.ok===!1?{ok:!1,operationId:C.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:z,postSnapshots:G.snapshots,plan:C}),m(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...G.snapshots.map(pe=>pe.version)),affectedFiles:[...W],...j?{selectionRef:j}:{}})}async function l(C){let P=new Set(C.edits.map(G=>G.file)),F=await x(P),L=E(C,F);if(L)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let W=new Map(F.map(G=>[G.file,G])),z=C.edits.find(G=>G.operation==="create-only"&&W.get(G.file)?.exists!==!1);if(z)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${z.file}`,affectedFiles:[z.file],rolledBack:!1};let he=C.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:Ce(G.content)}),j=await w(he,F,new Set(C.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return j.ok===!1?{ok:!1,operationId:C.operationId,errorCode:j.rolledBack?"writeback-failed":"rollback-failed",reason:j.reason,rolledBack:j.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:F,postSnapshots:j.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(...j.snapshots.map(G=>G.version)),affectedFiles:[...P]})}async function u(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let P=await w(C.preSnapshots,C.postSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(F=>F.version)),affectedFiles:C.preSnapshots.map(F=>F.file)})}async function d(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let P=await w(C.postSnapshots,C.preSnapshots);return P.ok===!1?{ok:!1,operationId:C.operationId,errorCode:P.rolledBack?"writeback-failed":"rollback-failed",reason:P.reason,rolledBack:P.rolledBack}:(r.pop(),n.push(C),m(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...P.snapshots.map(F=>F.version)),affectedFiles:C.postSnapshots.map(F=>F.file)})}function m(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((C,P)=>C+f(P),0)}function f(C){return h(C.preSnapshots)+h(C.postSnapshots)}function h(C){return C.reduce((P,F)=>P+F.file.length+F.content.length,0)}async function y(C,P){let F=[];for(let L of P){let W=L.capability??"write-text",z=o.find(j=>j.sourceType===L.sourceType&&(L.adapterId===void 0||j.adapterId===L.adapterId)&&(j.capabilities===void 0||j.capabilities.includes(W)));if(!z)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let he=await z.execute(L);if(!he.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:he.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};F.push(L.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:F}}function E(C,P){if(C.conflictPolicy!=="compare-and-swap")return null;let F=new Map(P.map(L=>[L.file,L]));for(let L of C.edits){if(L.operation==="create-only")continue;if(L.baseContentHash===void 0)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};let W=F.get(L.file),z=L.baseContentHash;if(z===null){if(W?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!z)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if(W?.exists===!1||W?.sha256!==z)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function x(C){let P=[];for(let F of C)P.push(await v(F));return P}async function v(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let F=Math.max(1,e.getVersion(C)),L=await e.readFile(C);return{file:C,content:L,version:F,exists:!0,sha256:Ce(L)}}async function w(C,P,F=new Set){let L=[];try{for(let W of C){if(F.has(W.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(W.file,W.content)}else await N(W);let z=e.bumpVersion(W.file);L.push(W.file),W.version=z}}catch(W){let z=await T(P.filter(j=>L.includes(j.file)));if(z.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${z.failedFiles.join(", ")}: ${Ih(W)}`,rolledBack:!1,instanceConflict:kh(W)};let he=kh(W);return{ok:!1,reason:`${he?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Ih(W)}`,rolledBack:!0,instanceConflict:he}}return{ok:!0,snapshots:C.map(Uw)}}async function N(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let P=[];for(let F of C)try{await N(F),e.bumpVersion(F.file)}catch{P.push(F.file)}return P.length===0?{ok:!0}:{ok:!1,failedFiles:P}}}function kh(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function Uw(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ce(e.content)}:{}}}function Ih(e){return e instanceof Error?e.message:String(e)}function Ch(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(tr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return We(nr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return We(Zn({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return We(Qn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return We(ni({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return We(Dr({source:t,locator:e.locator,next:e.value}));case"update-array-item":return We(Dr({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return We(li({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return We(oi({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return We(ui({source:t,locator:e.locator,index:e.index}));case"move-array-item":return We(di({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return We(qn({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return We(ii({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 Jw(e,t);case"set-property-changes":return We(si({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return We(ai({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return We(ci({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return We(pi({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function Jw(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Rd(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!==Ce(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:Cd({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 ws,SiteEditCompositionContextSchema as Xw,SiteEditCompositionSelectorSchema as zw}from"@vcp-dev/contracts";var Ze=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function wh(e,t){throw new Ze("INVALID_COMPOSITION",e,{value:t})}function Ns(e){let t=Xw.safeParse(e);return t.success?t.data:wh("Invalid SiteEditCompositionContext.",e)}function Nh(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Ns(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=ws(u);if(n.has(d))throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let m=r.get(l.entryFile);if(m)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:m});let g={context:u,entryFile:l.entryFile,key:d};t.push(g),n.set(d,g),r.set(l.entryFile,d)}if(t.length===0)throw new Ze("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Ns(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ze("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=ws(u);if(!n.has(d))throw new Ze("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Ze("DUPLICATE_COMPOSITION","Initial document versions must contain each composition at most once.",{context:u,key:d});o.set(d,l.version)}function i(l){let u=zw.safeParse(l);if(!u.success)return wh("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:m})=>m.routeId===u.data.routeId&&(u.data.templateId===void 0?m.effectiveTemplateId===void 0:m.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Ze("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ze("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Ns(l),d=ws(u),m=n.get(d);if(!m)throw new Ze("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return m}function a(l){let u=Ns(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ze("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=ws(u),m=n.get(d);if(m){if(m.entryFile===l.entryFile)return m;throw new Ze("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(h=>h.entryFile===l.entryFile);if(g)throw new Ze("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let f={context:u,entryFile:l.entryFile,key:d};return t.push(f),n.set(d,f),f}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(m=>m.key===l);return d>=0&&t.splice(d,1),o.delete(l),u}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))]}}function Jl(e){let t=new Map,n=new Map;return{readFile(r){let o=t.get(r);return o||(o=e.readFile(r),t.set(r,o)),o},exists(r){let o=n.get(r);return o||(o=e.exists(r),n.set(r,o)),o}}}async function Ph(e,t){if(e.length===0)return[];if(e.length===1)return[await t(e[0])];let n=new Array(e.length),r=[],o=0,i=Array.from({length:Math.min(4,e.length)},async()=>{for(;o<e.length&&r.length===0;){let c=o++;try{n[c]=await t(e[c])}catch(l){r.push({index:c,error:l})}}}),s=await Promise.allSettled(i),a=r.sort((c,l)=>c.index-l.index)[0];if(a)throw a.error;for(let c of s)if(c.status==="rejected")throw c.reason;return n}import{composeSiteEditRepeatInstanceKey as Ww,stripSiteEditRepeatInstanceKeys as Ah}from"@vcp-dev/contracts";function Th(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Ah(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 Hw(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 Ps(e){return e?.map(t=>({...t}))}function Xl(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Ps(e.collectionPathMap?.[t])??Ps(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:Ps(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Ps(o)??[])}}function Fh(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let f of g.childKeys)r.add(f);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,f)=>Ww(g,f),c=(g,f,h)=>{let y=o.get(g);if(!y)return a(g,h);let E=a(g,h),x={...y,key:E,parentKey:f,childKeys:[]};return i.push(x),x.childKeys=y.childKeys.flatMap(v=>l(v,h,E)),E},l=(g,f,h)=>{if(!r.has(g))return[c(g,h,f)];let y=d(g,f),E=[];for(let x=0;x<y;x+=1)E.push(c(g,h,[...f,x]));return E},u=Array.from(new Set([...e.rootKeys,...e.entries.filter(g=>g.parentKey===null).map(g=>g.key)]));for(let g of u){if(!r.has(g)){c(g,null,[]);continue}let f=d(g,[]);for(let h=0;h<f;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,f){let h=new Set;for(let y of m(g)){let E=n.get(y);if(E){for(let x of[...E.textTargets.values(),...E.elementPropertyTargets.values()])if(!(x?.kind!=="value-binding"||x.sourceKind!=="repeat-template"))for(let v of Gw(x))v.length<=f.length||Yw(v,f)&&h.add(v[f.length])}}return h.size>0?h.size:Hw(n.get(g))}function m(g){let f=s.get(g);if(f)return f;let h=[g],y=o.get(g);for(let E of y?.childKeys??[])h.push(...m(E));return s.set(g,h),h}}function _h(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Mh(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((Ah(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function Gw(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 Yw(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 Oh(e,t,n,r){if(!n)return{...e,key:t};let o=r??new Map(n.entries.map(u=>[u.key,u])),i=o.get(t);if(!i)return{...e,key:t};let s=[],a=i.parentKey;for(;a;){let u=o.get(a);if(!u)break;s.push({key:u.key,tag:u.tag,label:u.label}),a=u.parentKey}s.reverse();let c=i.childKeys.map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label})),l=i.parentKey===null?[]:(o.get(i.parentKey)?.childKeys??[]).filter(u=>u!==i.key).map(u=>o.get(u)).filter(u=>u!==void 0).map(u=>({key:u.key,tag:u.tag,label:u.label}));return{...e,key:i.key,ancestors:s,children:c,siblings:l}}function Lh(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 Dh(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function Zw(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var To=class extends Error{constructor(t){let n=t.map(Dh);super(Zw(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Bh(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof To?{routeId:e,message:n,diagnostics:t.diagnostics.map(Dh)}:{routeId:e,message:n}}function zl(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Wl(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Ir(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function jh(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Hl(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 $h(e){let{journal:t,index:n,observedFileDigests:r}=e;if(r.length!==t.files.length)return"ambiguous";let o=t.files.every((l,u)=>l.preDigest===r[u]),i=t.files.every((l,u)=>l.postDigest===r[u]),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 iN=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,sN=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Vh=32,Gl=256;function aN(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Kh={maxEntries:50,maxBytes:8*1024*1024};function cN(){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 gi(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}}}async function lN(e,t){if(t.length===0)return[];let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return[]}if(!n||typeof n!="object")return[];let r=n.dependencies;return!r||typeof r!="object"||Array.isArray(r)?[]:t.filter(o=>{if(!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];return typeof i=="string"&&i.trim().length>0})}function uN(){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>Kh.maxEntries||dN(e)>Kh.maxBytes;)e.shift()}}function dN(e){return e.reduce((t,n)=>t+fN(n),0)}function fN(e){return Uh(e.preSnapshots)+Uh(e.postSnapshots)+pN(e.provenance)}function pN(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Uh(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Jh(e,t){return{key:qw(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}},Un=class extends Error{constructor(t){super(zl(t)),this.failedRoutes=t}};function Xh(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=it(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(it(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function mN(e,t,n){if(!n)return;let r=it(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 gN=/\.(?:[cm]?[jt]sx?)$/i,hN=/\.json$/i,yN=/\.(?:css|scss|sass)$/i,xN=/\.mdx$/i,bN=/\.ya?ml$/i;function SN(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 EN(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function vN(e,t){let n=new Map;for(let i of t)n.set(i.path,i.operation==="delete"?{exists:!1}:{exists:!0,content:i.content});let r=new Map,o=new Map;return{async readFile(i){let s=n.get(i);if(s){if(!s.exists)throw new Error(`Source file not found: ${i}`);return s.content}let a=r.get(i);return a||(a=e.readFile(i),r.set(i,a)),a},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(i){let s=n.get(i);if(s)return s.exists;let a=o.get(i);return a||(a=e.exists(i),o.set(i,a)),a},async getFileInfo(i){let s=n.get(i);return s?s.exists?{path:i,sizeBytes:Buffer.byteLength(s.content,"utf8")}:null:e.getFileInfo?.(i)??null},async listFiles(i={}){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let s=Zh(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(kN(l,i.roots??[])){if(!u.exists){a.delete(l);continue}a.set(l,{path:l,sizeBytes:Buffer.byteLength(u.content,"utf8")})}let c=[...a.values()].sort((l,u)=>l.path.localeCompare(u.path));return s.truncated?{files:c,truncated:s.truncated}:c},getVersion(i){return e.getVersion(i)},bumpVersion(i){return e.getVersion(i)}}}function kN(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Zh(e){return Array.isArray(e)?{files:e}:e}function IN(e){if(!tN(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!==rN||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=eN(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(gN.test(e.path)){let t=_t({source:e.content,profile:kn({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(hN.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${qe(t)}`,details:{path:e.path}}}if(yN.test(e.path)){let t=zh({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(xN.test(e.path)){let t=zh({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(bN.test(e.path))try{oN(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${qe(t)}`,details:{path:e.path}}}return{ok:!0}}function zh({content:e,path:t,profile:n}){let r=[],o=null,i=!1,s=!1,a=!1,c=!1,l=!0;for(let d=0;d<e.length;d+=1){let m=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let f=e.indexOf(`
|
|
8
8
|
`,d);if(f===-1){l=!0;break}d=f,l=!0;continue}if(c){l=m===`
|
|
9
9
|
`||m==="\r";continue}if(s){m==="*"&&g==="/"&&(s=!1,d+=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
|
|
13
|
-
`||m==="\r";continue}if(m==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:d}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let f=m==="}"?"{":m===")"?"(":"[",h=r.pop();if(!h||h.char!==f)return
|
|
14
|
-
`||m==="\r"}if(s)return kr(t,`Unterminated block comment in ${t}.`);if(o)return kr(t,`Unterminated string literal in ${t}.`);if(c)return kr(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?kr(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function kr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Ps(e){let t="idle",n=e.fileSystem??iN(),r=Sd(),o=Ih({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?df(e.historyStore):aN()),u=vh(n,{externalAdapters:e.externalAdapters}),d=new Map,m=Td(Kl),g=new Set,f=0,h=e.historyStore?.recoveryRequired??!1,y=Ll(),E=N();function x(p){return(ws.isAbsolute(p)?ws.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,S){let b=ws.posix.dirname(p),C=S.replace(/\.(?:tsx?|jsx?)$/i,""),A=ws.posix.relative(b,C);return A.startsWith(".")?A:`./${A}`}function R(p,S){return p.startLine===S.startLine&&p.startColumn===S.startColumn&&p.endLine===S.endLine&&p.endColumn===S.endColumn}async function N(){let p=e.historyStore;if(p)try{let S=await p.readTransactionJournal();if(!S)return;let b=await p.readIndex(),C=await Promise.all(S.files.map(async M=>await n.exists(M.path)?Ce(await n.readFile(M.path)):null));if(Lh({journal:S,index:b,observedFileDigests:C})!=="ambiguous"){await p.clearTransactionJournal(S.transactionId);let M=await p.readStatus();M.recoveryRequired||(await p.cleanupTmp(),M=await p.readStatus()),h=M.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${S.transactionId} at phase ${S.phase}`),h=!0}catch(S){h=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(S)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let S=$h(p.context,p.entryFile);i.set(p.key,S),I(S,S.dependencyFiles)}function I(p,S){let b=new Set(S);P(p),p.dependencyFiles=b;for(let C of p.dependencyFiles){let A=s.get(C);A||(A=new Set,s.set(C,A)),A.add(p.key)}}function P(p){for(let S of p.dependencyFiles){let b=s.get(S);b&&(b.delete(p.key),b.size===0&&s.delete(S))}p.dependencyFiles.clear()}function F(p){let S=new Set;for(let b of p)for(let C of s.get(b)??[])S.add(C);return S}function L(p){for(let S of p)if(!s.has(S))return!1;return!0}async function W(p,S,b,C,A,M){let _=new Map,$=qg(p),Y=Kg(A.values()),K=Bm(A.values()),D=typeof M.exists=="function"?ee=>M.exists(ee):async()=>!1;for(let[ee,re]of p.elements){let ye=S.nodes.get(ee);if(!ye)continue;let me=b.get(re.sourceFile)??C.get(re.sourceFile),Ie=new Map,Ae=new Map,O=new Map,U=[];for(let Pe of re.textSegments){if(!me){Ie.set(Pe.index,null);continue}let Ir=await Ug({file:re.sourceFile,source:me,segment:Pe,readFile:ct=>M.readFile(ct),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ct,adapterId:xn,capabilities:$s})=>({sourceType:ct,adapterId:xn,capabilities:$s})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Qe=await wl({file:re.sourceFile,source:me,target:{kind:"text-segment",segment:Pe},readFile:ct=>M.readFile(ct),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ct,adapterId:xn,capabilities:$s})=>({sourceType:ct,adapterId:xn,capabilities:$s})),functionCallContracts:e.functionCallContracts,fileCache:Y}),mt=yN(Ir);Ie.set(Pe.index,mt),Ae.set(Pe.index,Ir),O.set(Pe.index,Qe),U.push({editable:Pe.editable,source:mt})}let ae=new Map,ge=new Map;if(me)for(let Pe of re.attributes??[]){let Ir=await Er({file:re.sourceFile,source:me,sourceRange:Pe.sourceRange,expression:Pe.source?.expression??Pe.value,sourceInfo:Pe.source,readFile:mt=>M.readFile(mt),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mt,adapterId:ct,capabilities:xn})=>({sourceType:mt,adapterId:ct,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Qe=await Qg({element:re,file:re.sourceFile,source:me,propertyName:Pe.name,readFile:mt=>M.readFile(mt),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mt,adapterId:ct,capabilities:xn})=>({sourceType:mt,adapterId:ct,capabilities:xn})),functionCallContracts:e.functionCallContracts,fileCache:Y});ge.set(Pe.name,Qe),ae.set(Pe.name,Ir)}let Ee=ch(xN(ye.writeTarget),U),Te=$({key:ee,element:re,provenances:O}),en=ph(re),at=me?await jm({element:re,graph:p,file:re.sourceFile,source:me,readFile:Pe=>M.readFile(Pe),exists:D,fileCache:K}):void 0,Hn=p.regions.find(Pe=>Pe.kind==="conditional-region"&&Pe.childKeys.includes(ee)),lu,js=Hn?.sourceCandidates?.[0];if(me&&Hn&&js?.kind==="conditional-branch"){let Pe=await wl({file:re.sourceFile,source:me,target:{kind:"conditional-branch",candidate:js},readFile:Qe=>M.readFile(Qe),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Qe,adapterId:mt,capabilities:ct})=>({sourceType:Qe,adapterId:mt,capabilities:ct})),functionCallContracts:e.functionCallContracts,fileCache:Y});lu={currentBranch:Hn.childKeys.indexOf(ee)<=0?"then":"else",availableBranches:Hn.childKeys.length>1?["then","else"]:["then"],conditionExpression:js.conditionExpression,provenance:{finalSource:Pe.finalSource?{kind:Pe.finalSource.kind,file:Pe.finalSource.file,displayPath:Pe.finalSource.displayPath}:null,chain:Pe.chain.map(Qe=>({kind:Qe.kind,file:Qe.file,displayName:Qe.displayName,canEditHere:Qe.canEditHere})),confidence:Pe.confidence,editMode:Pe.editMode,diagnostics:Pe.diagnostics.map(Qe=>({code:Qe.code,message:Qe.message}))}}}_.set(ee,{textSources:Ie,textTargets:Ae,elementPropertyTargets:ae,propertyProvenances:ge,isRepeat:DN(ee,p),provenances:O,writeTarget:Ee,componentSemantic:Te,styleSource:en,conditional:lu,dynamicData:at})}return _}function z(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function he(p,S){let b=o.initialVersions.get(p.key)??0;for(let C of S.values())b=Math.max(b,C);return Math.max(b,p.graph?.version??0)}function j(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function G(p){try{return j(o.resolveSelector(p.composition).key)}catch{return 0}}async function pe(p,S,b=n,C={}){let A=await Ad(p,S,M=>b.readFile(M),M=>b.exists(M),{additionalEntries:await tt(p,b),...C});if(A.diagnostics.length>0)throw new Ao(A.diagnostics);return C.validationOnly||m.remember(A.parsedModules.values()),A}async function st(p,S,b={}){let C=i.get(p);if(!C)return null;let A=b.sourceCache??$l(d,[]),M=b.fileSystem??Dl(n),{graph:_,allSources:$,parsedModules:Y,entryModule:K}=await pe(C.entryFile,S,M,{version:C.graph?.version??1}),D=new Map;for(let at of $.keys())D.set(at,z(at));let ee=Math.max(he(C,D),b.minimumVersion??0);b.changed&&ee<=(C.graph?.version??0)&&(ee=(C.graph?.version??0)+1),_.version=ee;for(let[at,Hn]of $)Vl(A,at,Hn,Kl);let re=await Yh(C.composition,C.entryFile,$,A,M);_.routeId=C.routeId,_.composition=C.composition;let ye=mh(_),me=gd(ye,_),Ie=await W(_,ye,$,A,Y,M),Ae=qh(_,me,Ie),O=Qh(Ie),U=Nh(rh(_,ye,me,{canUpdateTextByKey:Ae,dynamicDataSummaryByKey:O}),_,Ie),ae=Hf({route:C.routeId,composition:C.composition,entryFile:C.entryFile,version:ee,source:S,ast:K?.ast}),ge=Gf(ae);ae.ok&&kN(U,_,ae.projection,Y);let Ee={...U,composition:C.composition,...re?{styleContext:re}:{},pageComposition:ge},Te=new Set([C.entryFile,...$.keys()]);if(re){Te.add(re.entryCss.path);for(let at of re.stylesheets)Te.add(at.path)}let en={...C,dependencyFiles:Te,graph:_,topology:ye,capabilities:me,document:Ee,pageComposition:ge,pageCompositionProjection:ae.projection,pagePlacementByKey:ae.ok?ae.projection.placementByKey:null,pagePlacementUnitByKey:ae.ok?ae.projection.placementUnitByKey:null,pageUnitByKey:ae.ok?ae.projection.unitByKey:null,pagePlacementsByUnitKey:ae.ok?ae.projection.placementsByUnitKey:null,documentIndex:wh(Ee),detailProjections:Ie,fileVersions:D,styleContext:re};if(b.publish===!1)return en;vr(d,A);for(let at of A.keys())g.delete(at);return I(C,Te),Object.assign(C,en),C}async function tt(p,S=n){let b=[];for(let C of TN(p))typeof S.exists=="function"&&await S.exists(C)&&b.push({file:C,source:await S.readFile(C)});return b}async function Yh(p,S,b,C,A){let M=[];for(let[D,ee]of b){if(Ul(D)){M.push(D);continue}for(let re of _N(ee)){let ye=zh(D,re);ye&&M.push(ye)}}if(!M.length){for(let D of FN(S))if(await A.exists(D)){M.push(D);break}}let _=new Map,$=LN(M).slice(0,Dh);for(;$.length>0&&_.size<Dh;){let D=$.shift();if(_.has(D)||!Ul(D))continue;let ee=await Zh(D,C,A);if(ee!==null){_.set(D,{path:D,content:ee});for(let re of MN(ee)){let ye=zh(D,re);ye&&!_.has(ye)&&!$.includes(ye)&&$.push(ye)}}}let Y=[..._.values()].map(D=>({...D,hash:Ce(D.content)})),K=Y[0];return K?{composition:p,revision:Ce(JSON.stringify(Y.map(({path:D,hash:ee})=>({path:D,hash:ee})))),entryCss:K,stylesheets:Y.slice(1)}:null}async function Zh(p,S,b){let C=S.get(p);if(C!==void 0)return C;if(!await b.exists(p))return null;let A=await b.readFile(p);return Vl(S,p,A,Kl),A}function Qh(p){let S=new Map;for(let[b,C]of p)C.dynamicData?.bindings.length&&S.set(b,Zm(C.dynamicData.bindings));return S}function qh(p,S,b){let C=new Map;for(let[A,M]of p.elements){if(!S.get(A)?.canUpdateText){C.set(A,!1);continue}let $=b.get(A),Y=M.textSegments.some(K=>{if(!K.editable)return!1;let D=$?.provenances.get(K.index)??null;return!D||ey(D)});C.set(A,Y)}return C}function ey(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function _o(p,S={}){let b=[...new Set(p)],C=S.affectedCompositionKeys!==void 0,A=C?new Set(S.affectedCompositionKeys):F(b);if(!C&&(A.size===0||!L(b)))for(let K of i.values())Xl(K,b)&&A.add(K.key);let M=!C&&A.size===0&&b.some(Xh),_=S.publish===!1?$l(d,b):void 0,$={rebuiltRoutes:[],failedRoutes:[],...S.publish===!1?{candidateRouteStates:[],candidateSourceCache:_}:{}},Y=Dl(n);for(let K of i.values())if(!(S.excludedCompositionKeys?.has(K.key)||!(A.has(K.key)||M)))try{let ee=!!K.graph,re=await Y.readFile(K.entryFile),ye=await st(K.key,re,{...S,fileSystem:Y,..._?{sourceCache:_}:{}});ye?.graph&&($.rebuiltRoutes.push({documentChanged:ee,composition:K.composition,routeId:K.routeId,version:ye.graph.version}),$.candidateRouteStates?.push({composition:K.composition,key:K.key,routeId:K.routeId,state:ye}))}catch(ee){$.failedRoutes.push({...Mh(K.routeId,ee),composition:K.composition})}return $}function Jn(p){let S=[...new Set(p)],b=F(S);if(b.size>0&&L(S))return[...b];for(let C of i.values())Xl(C,S)&&b.add(C.key);return[...b]}function ty(p){let S=new Set(Jn(p));return o.entries.filter(b=>S.has(b.key)).map(b=>b.context)}function ny(p){return[...new Set(Jn(p))].sort((b,C)=>b<C?-1:b>C?1:0).map(b=>o.getByKey(b)?.context).filter(b=>b!==void 0)}function ry(p,S){let b=new Set(Jn(S)),C=p.provenance?.affectedCompositions??[];if(C.length===0)return b;if([...new Set(C.map(M=>o.resolveContext(M).key))].some(M=>!b.has(M)))throw new Error("History provenance does not match the affected composition index.");return b}function oy(p,S){let b=p.composition??p.provenance?.initiatingComposition;if(b){let M=o.resolveContext(b);return{context:M.context,key:M.key}}let C=[...new Set(Jn(S))];if(C.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${C.length}).`);let A=o.getByKey(C[0]);if(!A)throw new Error("Legacy history entry references an unknown affected composition.");return{context:A.context,key:A.key}}function _s(p,S){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:b,version:C}of S.rebuiltRoutes)r.emit({type:"document-changed",composition:b,version:C});for(let{composition:b,message:C}of S.failedRoutes)r.emit({type:"graph-error",composition:b,message:C})}function Xl(p,S){return S.some(b=>p.dependencyFiles.has(b)||p.entryFile===b||p.graph?.fileIndex.has(b))}function zl(p){for(let S of p)a.add(S);c||T()||(c=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(T())return;await iy(),await y.runExclusive(async()=>{if(f>0||T())return;let b=[...a];a.clear();let C=await Wl(b);if(C.length===0)return;let A=Jn(C);for(let $ of A){let Y=i.get($)?.composition;Y&&r.emit({type:"graph-invalidated",composition:Y})}let{rebuiltRoutes:M,failedRoutes:_}=await _o(C,{changed:!0});for(let{documentChanged:$,composition:Y,version:K}of M)r.emit({type:"graph-ready",composition:Y,version:K}),$&&r.emit({type:"document-changed",composition:Y,version:K});for(let{composition:$,message:Y}of _)S=!0,r.emit({type:"graph-error",composition:$,message:Y})})}}finally{c=null,t!=="disposed"&&(t=!S&&[...i.values()].some(b=>b.graph)?"ready":"idle"),a.size>0&&zl([])}})())}async function iy(){for(;f>0;)await new Promise(p=>setTimeout(p,0))}async function Wl(p){let S=[];for(let b of new Set(p)){let C=d.get(b);if(C===void 0){if(g.has(b)&&!await n.exists(b))continue;g.delete(b),S.push(b);continue}try{await n.readFile(b)!==C&&(g.delete(b),S.push(b))}catch(A){if(!vN(A))try{if(await n.exists(b))continue}catch{continue}g.add(b),S.push(b)}}return S}function Hl(p){Oh(d,p);for(let S of p)S.exists===!1?g.add(S.file):g.delete(S.file)}function Gl(p){g.clear();for(let S of p)g.add(S)}async function Yl(p){let S=await Wl(p);if(S.length===0)return;let b=Jn(S);for(let M of b){let _=i.get(M)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:C,failedRoutes:A}=await _o(S,{changed:!0});for(let{documentChanged:M,composition:_,version:$}of C)r.emit({type:"graph-ready",composition:_,version:$}),M&&r.emit({type:"document-changed",composition:_,version:$});for(let{composition:M,message:_}of A)r.emit({type:"graph-error",composition:M,message:_})}async function sy(p,S){let b=Wn(p,S);if(!b?.graph)return;let C=it(p)??p,A=b.graph.elements.get(C);A&&await Yl([A.sourceFile])}async function Zl(p){let S=new Set;if(p.target.kind==="node"){let b=Wn(p.target.key,p.composition),C=it(p.target.key)??p.target.key,A=b?.graph?.elements.get(C);A&&S.add(A.sourceFile)}else if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="source-file")S.add(p.target.path);else if(p.target.kind==="source-batch")for(let b of p.target.paths)S.add(b);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let b=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let C of b){let A=Wn(C,p.composition),M=it(C)??C,_=A?.graph?.elements.get(M);_&&S.add(_.sourceFile)}}await Yl(S)}async function ay(p){if(p.params.kind!=="source-edit")return Ms(p,"invalid-params","source-edit requires source-edit params");for(let S of p.params.edits){let b=EN(S);if(!b.ok)return Ms(p,b.errorCode,b.message,b.details)}f+=1;try{let S=await fy(p.params.edits);if(!S.ok)return Ms(p,S.errorCode,S.message,S.details);await Zl(p);let b={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(C=>C.operation==="delete"?{operation:"delete",file:C.path,baseContentHash:C.baseContentHash??null}:{operation:"upsert",file:C.path,baseContentHash:C.baseContentHash??null,content:C.content})};return await zn({request:p,filePlan:b})}catch(S){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.INTERNAL_ERROR,message:qe(S)}}}finally{f-=1}}async function cy(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ue(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");f+=1;try{let S=await Do({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(C=>C.materialization.files.map(A=>({path:A.pathTemplate,content:A.content}))),...p.params.artifact.pages.flatMap(C=>C.materialization.files.map(A=>({path:A.pathTemplate,content:A.content})))],exists:C=>n.exists(C),readFile:C=>n.readFile(C)});if(!S.ok)return ue(p,V.MATERIALIZATION_REJECTED,S.message);let b=await qa({artifact:p.params.artifact,exists:C=>n.exists(C)});return b.ok?await zn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:b.files},output:{kind:"insert-page-resource",package_instance_id:b.packageInstanceId,pages:b.pages},historyPolicy:"none"}):ue(p,b.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,b.message,b.path?{path:b.path}:void 0)}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{f-=1}}async function ly(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ue(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ue(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");f+=1;try{let S=Wh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(S.truncated)return ue(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:S.truncated.reasons});let b=S.files.filter(({path:_})=>/\.(?:tsx?|jsx?)$/.test(_)),C=Object.fromEntries(await Promise.all(b.map(async({path:_})=>[_,await n.readFile(_)]))),A=xp({expectedUrlPath:p.params.expectedUrlPath,files:C});if(!A.ok)return ue(p,A.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:A.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,A.message);let M=await Promise.all(A.edits.map(async _=>({..._,baseContentHash:Ce(await n.readFile(_.file))})));return zn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:M},output:{kind:"delete-page-source",deleted_files:A.deletedFiles,updated_files:A.updatedFiles,preserved_shared_files:A.preservedSharedFiles,warnings:A.warnings},historyPolicy:"none"})}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{f-=1}}async function uy(p,S){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ue(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ue(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let b=S.document,C=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!C||C.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||C.documentVersion!==b.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!A)return ue(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=p.params.kind==="insert-child"?p.params.position:null,_=await Do({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:A.files.map(K=>({path:K.pathTemplate,content:K.content})),exists:K=>n.exists(K),readFile:K=>n.readFile(K)});if(!_.ok)return ue(p,V.MATERIALIZATION_REJECTED,_.message);let $=await sN(n,Object.keys(A.projectDependencies??{})),Y=await Ff({manifest:A,generatedRoot:"components/site/generated",controlledFiles:A.files.map(K=>({pathTemplate:K.pathTemplate})),exists:K=>n.exists(K),availableHostDependencies:$,commit:async K=>{let D=await n.readFile(S.entryFile),ee=S.document,re=S.pageCompositionProjection;if(!ee||ee.pageComposition?.status!=="supported"||ee.version!==p.documentVersion||!re||re.status!=="supported"||re.documentVersion!==ee.version)return{ok:!0,data:ue(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ye=K.entry.path,me=by(K.instanceName),Ie,Ae=[];if(p.params.kind==="insert-child"){if(!M||!("kind"in M)||M.kind!=="page-composition")return{ok:!0,data:ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ge=sc({routeId:S.routeId,entryFile:S.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:p.documentVersion,source:D,projection:re,placementKey:M.placementKey,component:{source:ye,exportName:K.entry.export.kind==="default"?"default":K.entry.export.name,localName:me}});if(!ge.ok)return{ok:!0,data:ue(p,Bs(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Ee=ge.plan.rewriteStep,Te;switch(Ee.kind){case"insert-root-expression":Te=ji({source:D,locator:Ee.locator,expectedSourceHash:Ee.sourceHash,action:{kind:"insert",jsx:Ee.node.jsx,placement:Ee.placement,replaceOriginal:Ee.replaceOriginal}});break;case"insert-child":Te=Zn({source:D,locator:Ee.parentLocator,node:Ee.node,placement:Ee.placement,...Ee.anchorLocator?{anchorLocator:Ee.anchorLocator}:{}});break;default:Te={ok:!1,source:D,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ee)}`}}}if(!Te.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};Ie=Te.source}else{let ge=ac({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:p.documentVersion,source:D,projection:re,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ge.ok)return{ok:!0,data:ue(p,Bs(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Ee=ge.plan.rewriteStep,Te;switch(Ee.kind){case"replace-root-expression":Te=ji({source:D,locator:Ee.locator,expectedSourceHash:Ee.sourceHash,action:{kind:"replace",jsx:`<${me} />`}});break;case"replace-node":Te=ni({source:D,locator:Ee.locator,node:{jsx:`<${me} />`}});break;default:Te={ok:!1,source:D,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ee.kind}`}}}if(!Te.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};let en=await Ql({routeState:S,placementUnitKey:p.target.placementUnitKey,source:D,mutatedSource:Te.source});Ie=en.source,Ae=await Promise.all(en.files.map(async at=>({operation:"delete",file:at,baseContentHash:Ce(await n.readFile(at))})))}let O=er({source:Ie,moduleSpecifier:v(S.entryFile,ye),imports:K.entry.export.kind==="default"?[{kind:"default",local:me}]:[{kind:"named",imported:K.entry.export.name,local:me}]});if(!O.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let U=K.files.map(ge=>({operation:"create-only",file:ge.path,content:ge.content})),ae=[{operation:"upsert",file:S.entryFile,content:O.source,baseContentHash:Ce(D)},...U,...Ae];f+=1;try{let ge=await zn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ae}});return!ge.ok&&ge.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ge.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ge}}finally{f-=1}}});return Y.ok?Y.data:ue(p,Y.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,Y.error.message,{materializationCode:Y.error.code})}async function dy(p,S){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let b=S.document,C=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!C||C.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||C.documentVersion!==b.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=await n.readFile(S.entryFile),M=ac({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:b.version,expectedDocumentVersion:p.documentVersion,source:A,projection:C,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(!M.ok)return ue(p,Bs(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let _=M.plan.rewriteStep,$;switch(_.kind){case"move-node":$=Qn({source:A,locator:_.locator,targetParentLocator:_.targetParentLocator,placement:_.placement,..._.anchorLocator?{anchorLocator:_.anchorLocator}:{}});break;case"remove-node":$=Yn({source:A,locator:_.locator});break;case"remove-root-expression":$=ji({source:A,locator:_.locator,expectedSourceHash:_.sourceHash,action:{kind:"remove"}});break;default:$={ok:!1,source:A,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${_.kind}`}}}if(!$.ok)return ue(p,V.AST_PARSE_ERROR,$.diagnostic.message);let Y=$.source,K=[];if(p.kind==="remove-node"){let ee=await Ql({routeState:S,placementUnitKey:p.target.placementUnitKey,source:A,mutatedSource:Y});Y=ee.source,K=await Promise.all(ee.files.map(async re=>({operation:"delete",file:re,baseContentHash:Ce(await n.readFile(re))})))}let D=[{operation:"upsert",file:S.entryFile,content:Y,baseContentHash:Ce(A)},...K];f+=1;try{return await zn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:D}})}finally{f-=1}}async function Ql(p){let S={source:p.mutatedSource,files:[]},b=p.routeState.graph,C=p.routeState.pageCompositionProjection;if(!b||!C||C.status!=="supported"||!n.listFiles)return S;let M=C.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!M)return S;let _=[...b.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&R(O.sourceRange,M));if(!_?.importedFrom||!_.exportName)return S;let $=x(_.importedFrom),Y="components/site/generated/";if(!$.startsWith(Y))return S;let K=$.slice(Y.length).split("/")[0];if(!K||!/-[0-9a-f]{8}$/i.test(K))return S;let D=`${Y}${K}`;if([...b.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&x(O.importedFrom??"")===$).length!==1)return S;let re=await n.listFiles({maxFiles:5e3,maxDepth:32}),ye=Array.isArray(re)?re:re.files;if(!Array.isArray(re)&&re.truncated)return S;let me=ye.map(({path:O})=>O).filter(O=>O===D||O.startsWith(`${D}/`));if(me.length===0||!me.includes($))return S;for(let{path:O}of ye)if(!(O===p.routeState.entryFile||O===D||O.startsWith(`${D}/`)))try{if((await n.readFile(O)).includes(K))return S}catch{return S}let Ie=v(p.routeState.entryFile,$),Ae=tr({source:p.mutatedSource,moduleSpecifier:Ie,imports:_.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:_.exportName}]});return Ae.ok?Ae.source.includes(K)?{source:Ae.source,files:[]}:{source:Ae.source,files:me.sort((O,U)=>O.localeCompare(U))}:S}async function fy(p){if(n.getFileInfo){for(let _ of p)if(await n.exists(_.path)&&await n.getFileInfo(_.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${_.path}`,details:{path:_.path}}}for(let _ of p){if(_.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(_.path))continue;let $=await n.exists(_.path)?await ta(n,_.path):null;if($?.ok){let Y=Gw($.content,_.content);if(!Y.ok)return{ok:!1,errorCode:"invalid-params",message:Y.message,details:{path:_.path,code:Y.code}}}}let S=py(p);if(S.length===0)return{ok:!0};let b=bN(n,p),C=new Map,A=(_,$)=>{let Y=C.get(_);if(Y?.source===$)return Y.result;let K=Xt(_,$);return C.set(_,{source:$,result:K}),K},M;try{M=await Ch(S,async _=>{let $=i.get(_);return $?[...(await pe($.entryFile,await b.readFile($.entryFile),b,{validationOnly:!0,parseModule:A,validatedImports:m.getImports})).parsedModules.values()]:[]})}catch(_){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(_)}`,details:{compositionKeys:S}}}for(let _ of M)m.remember(_);return{ok:!0}}function py(p){return p.map(b=>b.path).some(Xh)?[...i.keys()]:[]}function Ms(p,S,b,C){let A=To(S);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:A,message:b,...C?{details:C}:{}}}}async function Os(p){let S=[];for(let b of new Set(p))S.push(await my(b));return S}async function my(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,z(p)),exists:!1};let b=await n.readFile(p);return{file:p,content:b,version:Math.max(1,z(p)),exists:!0,sha256:Ce(b)}}async function ql(p,S,b,C){if(!e.historyStore)return null;let A=new Map(S.map($=>[$.file,$])),M=new Map(b.map($=>[$.file,$])),_=[...new Set([...A.keys(),...M.keys()])].sort().map($=>{let Y=A.get($),K=M.get($);return{path:$,preDigest:Y?.exists===!1||!Y?null:Ce(Y.content),postDigest:K?.exists===!1||!K?null:Ce(K.content)}});return{schemaVersion:2,transactionId:`${p}:${C.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:C,files:_}}async function eu(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function Xn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function Ls(p,S){let b=[];try{for(let C of p)await tu(C),typeof n.bumpVersion=="function"&&n.bumpVersion(C.file),b.push(C.file)}catch(C){let A=await gy(S.filter(M=>b.includes(M.file)));return A.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(C)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${A.failedFiles.join(", ")}: ${qe(C)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(hy)}}async function tu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function gy(p){let S=[];for(let b of p)try{await tu(b),typeof n.bumpVersion=="function"&&n.bumpVersion(b.file)}catch{S.push(b.file)}return S.length===0?{ok:!0}:{ok:!1,failedFiles:S}}function hy(p){let S=p.exists!==!1;return{file:p.file,content:S?p.content:"",version:p.version,exists:S,...S?{sha256:Ce(p.content)}:{}}}async function zn(p){return y.runExclusive(()=>yy(p))}async function yy(p){let S=p.filePlan.edits.map(O=>O.file),b=o.resolveSelector(p.request.composition),C=b.context,A=p.historyPolicy==="none"?void 0:{initiatingComposition:C,affectedCompositions:ny(S)},M=await Os(S),_=new Map(M.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),$=ru(),Y=new Map(d),K=new Set(g),D=new Set([...i.values()].filter(O=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===O.entryFile)).map(O=>O.key)),ee=p.filePlan.edits.map(O=>O.operation==="delete"?{file:O.file,content:"",version:0,exists:!1}:{file:O.file,content:O.content,version:0,exists:!0,sha256:Ce(O.content)}),re={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(O=>O.operation==="delete"?{kind:"delete",path:O.file}:{kind:O.operation==="create-only"?"create-only":"upsert",path:O.file,content:O.content})},ye=null,me=!1,Ie=await ks({overlay:_,exists:O=>n.exists(O),plan:re,buildCandidate:async({plan:O})=>({plan:O}),prepareHistory:async()=>{let O=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:M,postSnapshots:ee,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...A?{provenance:A}:{}}),U=O?.historyTransition?O.historyTransition:e.historyStore?oN(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return ye=await ql(p.request.id,M,ee,U),ye=await eu(ye),{history:O,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let O=await u.executeFilePlan(p.filePlan);if(!O.ok)throw new Ns(O);return{postSnapshots:await Os(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:U})=>{let ae=await _o(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:D});if(ae.failedRoutes.length>0)throw new Kn(ae.failedRoutes);let ge=iu($,ae.candidateRouteStates??[]),Ee=ou(ge,b.key);return{...O,rebuild:ae,routeSnapshots:ge,resultVersion:Ee,...Vh(p.selectionRef,ge.map(Te=>Te.state.document))?{selectionRef:Vh(p.selectionRef,ge.map(Te=>Te.state.document))}:{}}},publishCandidate:async({candidate:O,history:U,receipt:ae})=>{U?.history&&(await l.publishPrepared(U.history),me=!0);let ge=O.resultVersion??ae.internalResultVersion;return{composition:C,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ge,affectedFiles:ae.affectedFiles,fileChanges:ae.postSnapshots.map(Ee=>({path:Ee.file,operation:Ee.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:U})=>{O.routeSnapshots&&Mo(O.routeSnapshots),O.rebuild?.candidateSourceCache&&vr(d,O.rebuild.candidateSourceCache),Hl(U.postSnapshots)},finalizeCandidate:async()=>{await Xn(ye);for(let O of D)i.delete(O)},emitCommitted:({candidate:O,published:U})=>{_s(U,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:U})=>{if(me)throw new Error("history was published before transaction finalization failed");if(U){let ae=await Ls(M,U.postSnapshots);if(!ae.ok)throw new Error(ae.reason)}Mo($),vr(d,Y),Gl(K),O?.history&&await l.discardPrepared?.(O.history),await Xn(ye)}});if(Ie.ok)return Ie.published;if(Ie.stage==="precheck"||Ie.stage==="build")try{await Xn(ye)}catch(O){let U=await Oo(qe(O));return ue(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(Ie.recoveryRequired){let O=await Oo(Ie.reason);return ue(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,Ie.reason)}let Ae=Ie.error;return Ae instanceof Ns?{...ue(p.request,To(Ae.result.errorCode),Ae.result.reason),...Ae.result.affectedFiles?{affectedFiles:Ae.result.affectedFiles}:{}}:Ae instanceof Kn?ue(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${jl(Ae.failedRoutes)}`,{failedRoutes:Ae.failedRoutes}):ue(p.request,au(Ie.stage),qe(Ae))}async function nu(p){return y.runExclusive(async()=>{let S=p==="undo"?await l.prepareUndo():await l.prepareRedo();return S?xy(p,S):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function xy(p,S){let b=S.entry,C=p==="undo"?b.preSnapshots:b.postSnapshots,A=p==="undo"?b.postSnapshots:b.preSnapshots,M=C.map(U=>U.file),{context:_,key:$}=oy(b,M),Y=await Os(M),K=new Map(Y.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),D=j($),ee=ru(),re=new Map(d),ye=new Set(g),me=null,Ie=!1,Ae,O=await ks({overlay:K,plan:{operationId:`${p}:${b.operationId}`,intents:C.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(me=await ql(`${p}:${b.operationId}`,Y,C,S.historyTransition),me=await eu(me),S),reverify:async()=>{},writeCandidate:async()=>{let U=await Ls(C,A);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Ae=ry(b,M);let ae=await _o(M,{changed:!0,minimumVersion:D+1,publish:!1,affectedCompositionKeys:Ae});if(ae.failedRoutes.length>0)throw new Kn(ae.failedRoutes);let ge=iu(ee,ae.candidateRouteStates??[]),Ee=ou(ge,$);return{...U,rebuild:ae,routeSnapshots:ge,resultVersion:Ee}},publishCandidate:async({candidate:U,history:ae,receipt:ge})=>{if(!ae)throw new Error("history cursor intent is missing");await l.publishPrepared(ae),Ie=!0;let Ee=U.resultVersion??D+1;return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!0,resultVersion:Ee,affectedFiles:M,fileChanges:ge.snapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...b.output?{output:b.output}:{}}},swapCandidate:({candidate:U,receipt:ae})=>{U.routeSnapshots&&Mo(U.routeSnapshots),U.rebuild?.candidateSourceCache&&vr(d,U.rebuild.candidateSourceCache),Hl(ae.snapshots)},finalizeCandidate:async()=>{await Xn(me)},emitCommitted:({candidate:U,published:ae})=>_s(ae,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ae})=>{if(Ie)throw new Error("history cursor was published before transaction finalization failed");if(ae){let ge=await Ls(A,ae.snapshots);if(!ge.ok)throw new Error(ge.reason)}Mo(ee),vr(d,re),Gl(ye),U&&await l.discardPrepared?.(U),await Xn(me)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await Xn(me)}catch(U){let ae=await Oo(qe(U));return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,error:{code:ae,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let U=await Oo(O.reason);return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,affectedFiles:M,error:{code:U===V.RECOVERY_PERSIST_FAILED?U:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,affectedFiles:M,error:{code:O.error instanceof Kn?V.ROUTE_REBUILD_FAILED:au(O.stage),message:qe(O.error),...O.error instanceof Kn?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function ru(){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 ou(p,S){return p.find(C=>C.key===S)?.state.graph?.version??o.initialVersions.get(S)??0}function iu(p,S){let b=new Map(p.map(C=>[C.key,C]));for(let C of S)b.set(C.key,C);return[...b.values()]}function Mo(p){for(let S of i.values())P(S);for(let S of p){let b={...S.state,dependencyFiles:new Set(S.state.dependencyFiles),fileVersions:new Map(S.state.fileVersions)};i.set(S.key,b),I(b,b.dependencyFiles)}}async function Ds(p){let S=i.get(p);if(!S)throw new Error(`Composition not found: ${p}`);if(S.graph)return;let b=await n.readFile(S.entryFile);await st(p,b)}function Wn(p,S){let b=i.get(o.resolveSelector(S).key)??null;return!b||!su(b,p)?null:b}function su(p,S){if(p.documentIndex?.entriesByKey.has(S)||p.graph?.elements.has(S))return!0;let b=it(S);return b&&b!==S?p.graph?.elements.has(b)===!0:!1}function ue(p,S,b,C){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:S,message:b,...C?{details:C}:{}}}}function au(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function Oo(p){if(h=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function by(p){let b=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return b?`Prefab${b}`:"GeneratedPrefab"}function Bs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function cu(p){if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Ds(b.key),b):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await Ds(b.key),b):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ue(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let S=i.get(o.resolveSelector(p.composition).key)??null;return S?(S.graph||await Ds(S.key),su(S,p.target.key)?S:ue(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),m.clear(),g.clear()},registerComposition(p,S){let b=o.register({context:p,entryFile:S}),C=i.get(b.key);if(C?.entryFile===S)return;C&&P(C);let A=$h(b.context,S);i.set(b.key,A),I(A,A.dependencyFiles),r.emit({type:"graph-invalidated",composition:b.context})},unregisterComposition(p){let S=o.resolveSelector(p),b=i.get(S.key);b&&(P(b),i.delete(S.key),o.unregister(S.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:S.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let S=o.resolveSelector(p),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(b.graph)t="ready";else{t="building";try{let C=await n.readFile(b.entryFile);await st(S.key,C),t="ready",r.emit({type:"graph-ready",composition:S.context,version:i.get(S.key)?.graph?.version??0})}catch(C){throw t="idle",r.emit({type:"graph-error",composition:S.context,message:qe(C)}),C}}},getDocument(p){let S=o.resolveSelector(p),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(!b.document)throw new Error(`Composition not built: ${S.key}`);return b.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,S,b){let C=Wn(p,S),A=it(p)??p;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let M=C.detailProjections.get(A);if(M){let _=C.graph.elements.get(A);if(!_)throw new Error(`Key not found: ${p}`);let $=dN(p,A,b),Y=new Map;if(M.isRepeat&&$?.instanceIndex!==void 0)for(let ee of _.attributes??[])Y.set(ee.name,ml({file:_.sourceFile,source:d.get(_.sourceFile)??"",element:_,propertyName:ee.name,selectionRef:$,graph:C.graph,sources:d}));let K=nh({element:_,graph:C.graph,source:d.get(_.sourceFile),documentVersion:C.graph.version,selectionRef:b,isRepeat:M.isRepeat,propertyProvenance:M.propertyProvenances,repeatTargets:Y}),D=ih(A,C.graph,C.topology,C.capabilities,M.textSources,M.provenances,M.dynamicData,K);return p===A?D:Fh(D,p,C.document??null,C.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,S){let b=Wn(p,S),C=it(p)??p;if(b?.graph&&b.topology&&b.capabilities&&b.detailProjections){let A=b.detailProjections.get(C);if(A){let M=oh(C,b.graph,b.topology,b.capabilities,A.textSources,A.writeTarget,A.provenances,A.conditional,A.componentSemantic,A.styleSource,A.dynamicData);return p===C?M:Th(M,p,b.document??null,b.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,S){let b=Wn(p,S),C=it(p)??p;if(!b?.graph)throw new Error(`Key not found: ${p}`);let A=b.graph.elements.get(C);if(!A)throw new Error(`Key not found: ${p}`);let M=d.get(A.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${A.sourceFile}`);return Sa({key:C,route:{composition:b.composition,routeId:b.routeId,graph:b.graph,source:M}})},refreshSourceForKey:sy,async execute(p){if(await E,h)return ue(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return ay(p);if(p.kind==="insert-page-resource")return cy(p);if(p.kind==="delete-page-source")return ly(p);let S=await cu(p);if("ok"in S)return S;await Zl(p);let b=await cu(p);if("ok"in b)return b;let C=b;if(p.target.kind==="page-unit"){let D=p;return p.kind==="insert-child"||p.kind==="replace-node"?uy(D,C):p.kind==="move-node"||p.kind==="remove-node"?dy(D,C):ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let M=p.params,_=p.target.kind==="node"?p.target.key:null;if(M.kind==="move-node"&&"kind"in M.target&&M.target.kind==="source-sibling"){let D=M.target,ee=_?C.document?.entries.find(U=>U.key===_):null,re=C.document?.entries.find(U=>U.key===D.anchorKey),ye=ee?.pageCompositionActionScope,me=ye?.kind==="source-siblings"?ye.siblingKeys:null,Ie=me?.indexOf(ee?.key??"")??-1,Ae=me?.indexOf(D.anchorKey)??-1,O=D.relation==="before"?Ie-1:Ie+1;if(!ee||!re||!me||Ie<0||Ae!==O||re.pageCompositionActionScope?.kind!=="source-siblings"||re.pageCompositionActionScope.siblingKeys.length!==me.length||re.pageCompositionActionScope.siblingKeys.some((U,ae)=>U!==me[ae])||!ee.operationSummary.canMove)return ue(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!C.graph||!C.topology||!C.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let $=PN(C,C.graph,C.capabilities,d,i),Y=await new ss($).plan(p);if(!Y.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:To(Y.errorCode),message:Y.reason}};let K=Y.plan;if(K.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:G(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};f+=1;try{if(K.steps.some(ee=>ee.type==="invoke-external-adapter")){let ee=await u.execute(K);if(!ee.ok)return ue(p,To(ee.errorCode),ee.reason);let re={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(G(p),ee.resultVersion),affectedFiles:ee.affectedFiles,...ee.selectionRef?{selectionRef:ee.selectionRef}:{}};return _s(re,{rebuiltRoutes:[],failedRoutes:[]}),re}let D=await u.prepareRewritePlan(K);return D.ok?await zn({request:p,filePlan:D.filePlan,...D.selectionRef?{selectionRef:D.selectionRef}:{}}):ue(p,To(D.errorCode),D.reason)}catch(D){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.INTERNAL_ERROR,message:qe(D)}}}finally{f-=1}},async undo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:j(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};f+=1;try{return await nu("undo")}finally{f-=1}},async redo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:j(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};f+=1;try{return await nu("redo")}finally{f-=1}},notifyFileChanged(p){zl([p])},getAffectedCompositions(p){return ty(p)},subscribe(p){return r.subscribe(p)}}}function vN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function kN(e,t,n,r){let o=new Map,i=new Map,s=(d,m,g)=>{let f=d.get(m)??new Set,h=f.size;return f.add(g),d.set(m,f),f.size!==h},a=(d,m)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,m);let g=s(o,`${d.importedFrom}#${d.tag}`,m);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,m)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let m=n.placements.find(f=>f.members.some(h=>h.sourceRange!==null&&Fo(d.sourceRange,h.sourceRange)));if(!m)continue;let g=m.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let m=c(d);if(m)for(let g of m)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let m=it(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(m);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&Fo(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(E=>E.members.some(x=>x.sourceRange!==null&&(Fo(g.sourceRange,x.sourceRange)||NN(x.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let f=o.get(`${g.sourceFile}#${g.componentName}`);if(f){f.size===1&&(d.pageCompositionUnitKey=f.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}IN(e,t,n,r)}function IN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let g=m.pageCompositionUnitKey;return g?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(m,g)=>{s.set(m,Math.min(2,(s.get(m)??0)+g))},c=m=>n.placements.some(g=>g.members.some(f=>f.sourceRange!==null&&Fo(m.sourceRange,f.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 g=!1;for(let f of l){let h=s.get(f.owner)??s.get(f.ownerDefault)??0;if(!h)continue;let y=s.get(f.target)??0,E=Math.min(2,y+h);E!==y&&(s.set(f.target,E),g=!0)}if(!g)break}let u=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(m.key);m.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let m of i){let g=t.elements.get(m.key);if(!g||g.sourceFile===n.entryFile||m.key!==(it(m.key)??m.key))continue;let f=r.get(g.sourceFile);if(!f)continue;let h=ce(f.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,E=y.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Me(E))){u(g)===1&&Uh(y)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Uh(E))continue;let x=d.get(E.node)??[];x.push({entry:m,element:g,parentPath:E}),d.set(E.node,x)}for(let m of d.values()){let g=m[0];if(!g)continue;let f=g.entry.pageCompositionUnitKey,h=[],y=!!(f&&u(g.element)===1);for(let x of g.parentPath.node.children){if(CN(x))continue;if(!RN(x)){y=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===g.element.sourceFile&&N.componentName===g.element.componentName&&Fo(N.sourceRange,wN(x))),R=v?o.get(v.identity.key):null;if(!v||!R||R.parentKey||R.pageCompositionUnitKey!==f||u(v)!==1){y=!1;break}h.push(R)}if(!y||h.length!==m.length||m.some(({entry:x})=>!h.some(v=>v.key===x.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(x=>x.key);for(let x of h)x.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Uh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function CN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function RN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function wN(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 Fo(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function NN(e,t){return Jh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Jh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Jh(e,t,n,r){return e!==n?e-n:t-r}function PN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let m=t.elements.get(u);for(let g of m?.childKeys??[])a(g,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),m=t.elements.get(d.baseKey);return m?l(u,m):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=it(h)??h,E=t.elements.get(y);return E?l(h,E):null}).filter(h=>h!==null);let f=t.elements.get(d.baseKey);return f?f.childKeys.map(h=>{let y=t.elements.get(h);return y?l(h,y):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),m=n.get(d.baseKey);return m?{...m,key:u,constraints:m.constraints.map(g=>({...g})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),m=t.elements.get(d.baseKey),g=m?r.get(m.sourceFile):void 0;return!m||g===void 0?null:Sa({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let m=c(u);return Bl(e.detailProjections?.get(m.baseKey)?.textTargets.get(d)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,d){let m=c(u);return Bl(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(d)??null,m.repeatIndex)},getPropertyState(u,d,m){let g=c(u),f=t.elements.get(g.baseKey);if(!f)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let E=f.attributes?.find(x=>x.name===d);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:f.sourceFile,sourceRange:E.sourceRange}}:(f.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,m){let g=c(u),f=t.elements.get(g.baseKey);if(!f)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return ml({file:f.sourceFile,source:r.get(f.sourceFile)??"",element:f,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(d)??null}};function c(u){let d=qw(u);return d?{baseKey:d.baseKey,repeatIndex:Ah(e.document??null,u,d.baseKey,e.documentIndex)??Ph(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let m=it(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:d.attributes?.map(f=>({name:f.name,value:f.value,source:f.source?{expression:f.source.expression,base:f.source.base,path:f.source.path.map(h=>({...h}))}:null,resolvedValue:f.resolvedValue}))}}}var AN={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function To(e){return AN[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Xh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function TN(e){let t=Un(e);if(!nN.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=>rN.map(a=>`${s}/${a}`))}function FN(e){let n=Un(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function _N(e){return Hh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function MN(e){return Hh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Hh(e,t){let n=[];for(let r of e.matchAll(t)){let o=Gh(r[1]??"");o&&n.push(o)}return n}function zh(e,t){let n=Gh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Un(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Un(`${ON(e)}/${n}`):n.startsWith("/")?Un(n.slice(1)):Ul(n)?Un(n):null}function Gh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Ul(e){return/\.css$/i.test(e)}function ON(e){let t=Un(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function LN(e){return Array.from(new Set(e))}function Un(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 DN(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 Rr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Uo(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 Jo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Wo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Ho(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Go(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=jN.safeParse(t);if(!n.success)return{result:Ko(t,n.error.issues.map(i=>i.message))};let r=new Rr(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:Cn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=$N.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>VN(l,t.kind==="source-edit")),changedCompositions:o.getAffectedCompositions(a.map(l=>l.path)),diagnostics:[]});return this.options.onEvent?.({type:"site-edit.operation.planned",siteId:t.siteId,operationId:t.id,baseSnapshotId:t.baseSnapshotId,changedFiles:c.patches.map(l=>l.path),composition:i.composition,at:new Date().toISOString()}),{result:s,patchPlan:c}}finally{o.dispose()}}dispose(){this.engine.dispose()}createEngine(t,n={}){let r=n.emitEvents??!0;return Ps({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Xo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function VN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ce(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ce(e.before)},fullContent:e.after}}function KN(e){return new As(e)}import{SiteEditOperationRequestSchema as XN}from"@vcp-dev/contracts";import Tt from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as UN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as JN}from"@vcp-dev/contracts";var Ts=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Ps({...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 Wo(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Ho(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Go(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 Tt.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return Tt.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await Tt.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await mi(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await Tt.mkdir(et.dirname(i),{recursive:!0});let s=await Tt.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Tt.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Tt.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await Tt.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await Tt.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...JN,...UN],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,m)=>d.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,m,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let f=et.join(n,...d.split("/")),h;try{h=await Tt.lstat(f)}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:d,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 y=await Tt.readdir(f,{withFileTypes:!0});for(let E of y)E.isSymbolicLink()||await u(`${d}/${E.name}`,m,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Jl(e){return new Ts(e)}var Fs=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Jl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Xo(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:Uo(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:Jo(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=XN.safeParse(r);if(!o.success)return Ko(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:Cn(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:Cn(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:Cn(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 zN(e){return new Fs(e)}export{se as FileHistoryStoreError,eo as PageTemplateManagedSourceError,Fs as PreviewFileSystemSiteEditEngineRuntime,gf as SITE_EDIT_RAW_COLOR_LITERAL_RE,As as SnapshotSiteEditEngineRuntime,Do as checkComponentI18nHostCompatibility,sp as computeManagedPageTemplatePaths,zN as createPreviewSiteEditEngineRuntime,KN as createSiteEditEngineRuntime,rp as decodePageTemplateKey,Sc as encodePageTemplateId,Uy as instrumentSiteEditRuntimeAttributes,ap as isManagedPageTemplateSourcePath,Jd as openFileHistoryStore,wy as parseSourceModule,Ny as resolveImportBase,$k as resolveManagedPageTemplateComposition,Ki as scanManagedPageTemplateCandidates,lp as scanSiteEditCompositionsFromFiles,Wr as scanSiteEditThemeStyleViolations};
|
|
12
|
+
`||m==="\r"))return Cr(t,`Unterminated string literal in ${t}.`);l=m===`
|
|
13
|
+
`||m==="\r";continue}if(m==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&m==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(m==="'"||m==='"'||n==="mdx"&&m==="`"){o=m,l=!1;continue}if(m==="{"||m==="("||m==="["){r.push({char:m,offset:d}),l=!1;continue}if(m==="}"||m===")"||m==="]"){let f=m==="}"?"{":m===")"?"(":"[",h=r.pop();if(!h||h.char!==f)return Cr(t,`Unexpected closing token "${m}" in ${t}.`);l=!1;continue}l=m===`
|
|
14
|
+
`||m==="\r"}if(s)return Cr(t,`Unterminated block comment in ${t}.`);if(o)return Cr(t,`Unterminated string literal in ${t}.`);if(c)return Cr(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Cr(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Cr(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Fs(e){let t="idle",n=e.fileSystem??cN(),r=wd(),o=Nh({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?xf(e.historyStore):uN()),u=Rh(n,{externalAdapters:e.externalAdapters}),d=new Map,m=Bd(Gl),g=new Set,f=0,h=e.historyStore?.recoveryRequired??!1,y=Ul(),E=N();function x(p){return(As.isAbsolute(p)?As.relative(e.projectRoot,p):p).replace(/\\/g,"/").replace(/^\.\//,"")}function v(p,S){let b=As.posix.dirname(p),R=S.replace(/\.(?:tsx?|jsx?)$/i,""),A=As.posix.relative(b,R);return A.startsWith(".")?A:`./${A}`}function w(p,S){return p.startLine===S.startLine&&p.startColumn===S.startColumn&&p.endLine===S.endLine&&p.endColumn===S.endColumn}async function N(){let p=e.historyStore;if(p)try{let S=await p.readTransactionJournal();if(!S)return;let b=await p.readIndex(),R=await Promise.all(S.files.map(async M=>await n.exists(M.path)?Ce(await n.readFile(M.path)):null));if($h({journal:S,index:b,observedFileDigests:R})!=="ambiguous"){await p.clearTransactionJournal(S.transactionId);let M=await p.readStatus();M.recoveryRequired||(await p.cleanupTmp(),M=await p.readStatus()),h=M.recoveryRequired;return}await p.markRecoveryRequired(`Ambiguous transaction journal ${S.transactionId} at phase ${S.phase}`),h=!0}catch(S){h=!0,await p.markRecoveryRequired(`Transaction journal recovery failed: ${qe(S)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let p of o.entries){let S=Jh(p.context,p.entryFile);i.set(p.key,S),C(S,S.dependencyFiles)}function C(p,S){let b=new Set(S);P(p),p.dependencyFiles=b;for(let R of p.dependencyFiles){let A=s.get(R);A||(A=new Set,s.set(R,A)),A.add(p.key)}}function P(p){for(let S of p.dependencyFiles){let b=s.get(S);b&&(b.delete(p.key),b.size===0&&s.delete(S))}p.dependencyFiles.clear()}function F(p){let S=new Set;for(let b of p)for(let R of s.get(b)??[])S.add(R);return S}function L(p){for(let S of p)if(!s.has(S))return!1;return!0}async function W(p,S,b,R,A,M){let _=new Map,$=rh(p),Y=zg(A.values()),K=Jm(A.values()),D=typeof M.exists=="function"?ee=>M.exists(ee):async()=>!1;for(let[ee,re]of p.elements){let ye=S.nodes.get(ee);if(!ye)continue;let me=b.get(re.sourceFile)??R.get(re.sourceFile),Ie=new Map,Ae=new Map,O=new Map,U=[];for(let Pe of re.textSegments){if(!me){Ie.set(Pe.index,null);continue}let Rr=await Wg({file:re.sourceFile,source:me,segment:Pe,readFile:ct=>M.readFile(ct),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ct,adapterId:bn,capabilities:Us})=>({sourceType:ct,adapterId:bn,capabilities:Us})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Qe=await Ml({file:re.sourceFile,source:me,target:{kind:"text-segment",segment:Pe},readFile:ct=>M.readFile(ct),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:ct,adapterId:bn,capabilities:Us})=>({sourceType:ct,adapterId:bn,capabilities:Us})),functionCallContracts:e.functionCallContracts,fileCache:Y}),mt=SN(Rr);Ie.set(Pe.index,mt),Ae.set(Pe.index,Rr),O.set(Pe.index,Qe),U.push({editable:Pe.editable,source:mt})}let ae=new Map,ge=new Map;if(me)for(let Pe of re.attributes??[]){let Rr=await kr({file:re.sourceFile,source:me,sourceRange:Pe.sourceRange,expression:Pe.source?.expression??Pe.value,sourceInfo:Pe.source,readFile:mt=>M.readFile(mt),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mt,adapterId:ct,capabilities:bn})=>({sourceType:mt,adapterId:ct,capabilities:bn})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Qe=await nh({element:re,file:re.sourceFile,source:me,propertyName:Pe.name,readFile:mt=>M.readFile(mt),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mt,adapterId:ct,capabilities:bn})=>({sourceType:mt,adapterId:ct,capabilities:bn})),functionCallContracts:e.functionCallContracts,fileCache:Y});ge.set(Pe.name,Qe),ae.set(Pe.name,Rr)}let Ee=fh(EN(ye.writeTarget),U),Te=$({key:ee,element:re,provenances:O}),en=yh(re),at=me?await Xm({element:re,graph:p,file:re.sourceFile,source:me,readFile:Pe=>M.readFile(Pe),exists:D,fileCache:K}):void 0,Gn=p.regions.find(Pe=>Pe.kind==="conditional-region"&&Pe.childKeys.includes(ee)),hu,Ks=Gn?.sourceCandidates?.[0];if(me&&Gn&&Ks?.kind==="conditional-branch"){let Pe=await Ml({file:re.sourceFile,source:me,target:{kind:"conditional-branch",candidate:Ks},readFile:Qe=>M.readFile(Qe),exists:D,graph:p,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Qe,adapterId:mt,capabilities:ct})=>({sourceType:Qe,adapterId:mt,capabilities:ct})),functionCallContracts:e.functionCallContracts,fileCache:Y});hu={currentBranch:Gn.childKeys.indexOf(ee)<=0?"then":"else",availableBranches:Gn.childKeys.length>1?["then","else"]:["then"],conditionExpression:Ks.conditionExpression,provenance:{finalSource:Pe.finalSource?{kind:Pe.finalSource.kind,file:Pe.finalSource.file,displayPath:Pe.finalSource.displayPath}:null,chain:Pe.chain.map(Qe=>({kind:Qe.kind,file:Qe.file,displayName:Qe.displayName,canEditHere:Qe.canEditHere})),confidence:Pe.confidence,editMode:Pe.editMode,diagnostics:Pe.diagnostics.map(Qe=>({code:Qe.code,message:Qe.message}))}}}_.set(ee,{textSources:Ie,textTargets:Ae,elementPropertyTargets:ae,propertyProvenances:ge,isRepeat:$N(ee,p),provenances:O,writeTarget:Ee,componentSemantic:Te,styleSource:en,conditional:hu,dynamicData:at})}return _}function z(p){return typeof n.getVersion=="function"?n.getVersion(p):0}function he(p,S){let b=o.initialVersions.get(p.key)??0;for(let R of S.values())b=Math.max(b,R);return Math.max(b,p.graph?.version??0)}function j(p){return i.get(p)?.graph?.version??o.initialVersions.get(p)??0}function G(p){try{return j(o.resolveSelector(p.composition).key)}catch{return 0}}async function pe(p,S,b=n,R={}){let A=await Dd(p,S,M=>b.readFile(M),M=>b.exists(M),{additionalEntries:await tt(p,b),...R});if(A.diagnostics.length>0)throw new To(A.diagnostics);return R.validationOnly||m.remember(A.parsedModules.values()),A}async function st(p,S,b={}){let R=i.get(p);if(!R)return null;let A=b.sourceCache??Wl(d,[]),M=b.fileSystem??Jl(n),{graph:_,allSources:$,parsedModules:Y,entryModule:K}=await pe(R.entryFile,S,M,{version:R.graph?.version??1}),D=new Map;for(let at of $.keys())D.set(at,z(at));let ee=Math.max(he(R,D),b.minimumVersion??0);b.changed&&ee<=(R.graph?.version??0)&&(ee=(R.graph?.version??0)+1),_.version=ee;for(let[at,Gn]of $)Hl(A,at,Gn,Gl);let re=await ey(R.composition,R.entryFile,$,A,M);_.routeId=R.routeId,_.composition=R.composition;let ye=xh(_),me=vd(ye,_),Ie=await W(_,ye,$,A,Y,M),Ae=ry(_,me,Ie),O=ny(Ie),U=Fh(ah(_,ye,me,{canUpdateTextByKey:Ae,dynamicDataSummaryByKey:O}),_,Ie),ae=tp({route:R.routeId,composition:R.composition,entryFile:R.entryFile,version:ee,source:S,ast:K?.ast}),ge=np(ae);ae.ok&&RN(U,_,ae.projection,Y);let Ee={...U,composition:R.composition,...re?{styleContext:re}:{},pageComposition:ge},Te=new Set([R.entryFile,...$.keys()]);if(re){Te.add(re.entryCss.path);for(let at of re.stylesheets)Te.add(at.path)}let en={...R,dependencyFiles:Te,graph:_,topology:ye,capabilities:me,document:Ee,pageComposition:ge,pageCompositionProjection:ae.projection,pagePlacementByKey:ae.ok?ae.projection.placementByKey:null,pagePlacementUnitByKey:ae.ok?ae.projection.placementUnitByKey:null,pageUnitByKey:ae.ok?ae.projection.unitByKey:null,pagePlacementsByUnitKey:ae.ok?ae.projection.placementsByUnitKey:null,documentIndex:Th(Ee),detailProjections:Ie,fileVersions:D,styleContext:re};if(b.publish===!1)return en;Ir(d,A);for(let at of A.keys())g.delete(at);return C(R,Te),Object.assign(R,en),R}async function tt(p,S=n){let b=[];for(let R of MN(p))typeof S.exists=="function"&&await S.exists(R)&&b.push({file:R,source:await S.readFile(R)});return b}async function ey(p,S,b,R,A){let M=[];for(let[D,ee]of b){if(Yl(D)){M.push(D);continue}for(let re of LN(ee)){let ye=Yh(D,re);ye&&M.push(ye)}}if(!M.length){for(let D of ON(S))if(await A.exists(D)){M.push(D);break}}let _=new Map,$=jN(M).slice(0,Vh);for(;$.length>0&&_.size<Vh;){let D=$.shift();if(_.has(D)||!Yl(D))continue;let ee=await ty(D,R,A);if(ee!==null){_.set(D,{path:D,content:ee});for(let re of DN(ee)){let ye=Yh(D,re);ye&&!_.has(ye)&&!$.includes(ye)&&$.push(ye)}}}let Y=[..._.values()].map(D=>({...D,hash:Ce(D.content)})),K=Y[0];return K?{composition:p,revision:Ce(JSON.stringify(Y.map(({path:D,hash:ee})=>({path:D,hash:ee})))),entryCss:K,stylesheets:Y.slice(1)}:null}async function ty(p,S,b){let R=S.get(p);if(R!==void 0)return R;if(!await b.exists(p))return null;let A=await b.readFile(p);return Hl(S,p,A,Gl),A}function ny(p){let S=new Map;for(let[b,R]of p)R.dynamicData?.bindings.length&&S.set(b,tg(R.dynamicData.bindings));return S}function ry(p,S,b){let R=new Map;for(let[A,M]of p.elements){if(!S.get(A)?.canUpdateText){R.set(A,!1);continue}let $=b.get(A),Y=M.textSegments.some(K=>{if(!K.editable)return!1;let D=$?.provenances.get(K.index)??null;return!D||oy(D)});R.set(A,Y)}return R}function oy(p){return p.editMode==="direct"||p.editMode==="proxy"||p.editMode==="upstream"}async function Mo(p,S={}){let b=[...new Set(p)],R=S.affectedCompositionKeys!==void 0,A=R?new Set(S.affectedCompositionKeys):F(b);if(!R&&(A.size===0||!L(b)))for(let K of i.values())Ql(K,b)&&A.add(K.key);let M=!R&&A.size===0&&b.some(Gh),_=S.publish===!1?Wl(d,b):void 0,$={rebuiltRoutes:[],failedRoutes:[],...S.publish===!1?{candidateRouteStates:[],candidateSourceCache:_}:{}},Y=Jl(n);for(let K of i.values())if(!(S.excludedCompositionKeys?.has(K.key)||!(A.has(K.key)||M)))try{let ee=!!K.graph,re=await Y.readFile(K.entryFile),ye=await st(K.key,re,{...S,fileSystem:Y,..._?{sourceCache:_}:{}});ye?.graph&&($.rebuiltRoutes.push({documentChanged:ee,composition:K.composition,routeId:K.routeId,version:ye.graph.version}),$.candidateRouteStates?.push({composition:K.composition,key:K.key,routeId:K.routeId,state:ye}))}catch(ee){$.failedRoutes.push({...Bh(K.routeId,ee),composition:K.composition})}return $}function Xn(p){let S=[...new Set(p)],b=F(S);if(b.size>0&&L(S))return[...b];for(let R of i.values())Ql(R,S)&&b.add(R.key);return[...b]}function iy(p){let S=new Set(Xn(p));return o.entries.filter(b=>S.has(b.key)).map(b=>b.context)}function sy(p){return[...new Set(Xn(p))].sort((b,R)=>b<R?-1:b>R?1:0).map(b=>o.getByKey(b)?.context).filter(b=>b!==void 0)}function ay(p,S){let b=new Set(Xn(S)),R=p.provenance?.affectedCompositions??[];if(R.length===0)return b;if([...new Set(R.map(M=>o.resolveContext(M).key))].some(M=>!b.has(M)))throw new Error("History provenance does not match the affected composition index.");return b}function cy(p,S){let b=p.composition??p.provenance?.initiatingComposition;if(b){let M=o.resolveContext(b);return{context:M.context,key:M.key}}let R=[...new Set(Xn(S))];if(R.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${R.length}).`);let A=o.getByKey(R[0]);if(!A)throw new Error("Legacy history entry references an unknown affected composition.");return{context:A.context,key:A.key}}function Ls(p,S){r.emit({type:"operation-completed",composition:p.composition,result:p});for(let{composition:b,version:R}of S.rebuiltRoutes)r.emit({type:"document-changed",composition:b,version:R});for(let{composition:b,message:R}of S.failedRoutes)r.emit({type:"graph-error",composition:b,message:R})}function Ql(p,S){return S.some(b=>p.dependencyFiles.has(b)||p.entryFile===b||p.graph?.fileIndex.has(b))}function ql(p){for(let S of p)a.add(S);c||T()||(c=(async()=>{t="building";let S=!1;try{for(;a.size>0;){if(T())return;await ly(),await y.runExclusive(async()=>{if(f>0||T())return;let b=[...a];a.clear();let R=await eu(b);if(R.length===0)return;let A=Xn(R);for(let $ of A){let Y=i.get($)?.composition;Y&&r.emit({type:"graph-invalidated",composition:Y})}let{rebuiltRoutes:M,failedRoutes:_}=await Mo(R,{changed:!0});for(let{documentChanged:$,composition:Y,version:K}of M)r.emit({type:"graph-ready",composition:Y,version:K}),$&&r.emit({type:"document-changed",composition:Y,version:K});for(let{composition:$,message:Y}of _)S=!0,r.emit({type:"graph-error",composition:$,message:Y})})}}finally{c=null,t!=="disposed"&&(t=!S&&[...i.values()].some(b=>b.graph)?"ready":"idle"),a.size>0&&ql([])}})())}async function ly(){for(;f>0;)await new Promise(p=>setTimeout(p,0))}async function eu(p){let S=[];for(let b of new Set(p)){let R=d.get(b);if(R===void 0){if(g.has(b)&&!await n.exists(b))continue;g.delete(b),S.push(b);continue}try{await n.readFile(b)!==R&&(g.delete(b),S.push(b))}catch(A){if(!CN(A))try{if(await n.exists(b))continue}catch{continue}g.add(b),S.push(b)}}return S}function tu(p){jh(d,p);for(let S of p)S.exists===!1?g.add(S.file):g.delete(S.file)}function nu(p){g.clear();for(let S of p)g.add(S)}async function ru(p){let S=await eu(p);if(S.length===0)return;let b=Xn(S);for(let M of b){let _=i.get(M)?.composition;_&&r.emit({type:"graph-invalidated",composition:_})}let{rebuiltRoutes:R,failedRoutes:A}=await Mo(S,{changed:!0});for(let{documentChanged:M,composition:_,version:$}of R)r.emit({type:"graph-ready",composition:_,version:$}),M&&r.emit({type:"document-changed",composition:_,version:$});for(let{composition:M,message:_}of A)r.emit({type:"graph-error",composition:M,message:_})}async function uy(p,S){let b=Hn(p,S);if(!b?.graph)return;let R=it(p)??p,A=b.graph.elements.get(R);A&&await ru([A.sourceFile])}async function ou(p){let S=new Set;if(p.target.kind==="node"){let b=Hn(p.target.key,p.composition),R=it(p.target.key)??p.target.key,A=b?.graph?.elements.get(R);A&&S.add(A.sourceFile)}else if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key);b&&S.add(b.entryFile)}else if(p.target.kind==="source-file")S.add(p.target.path);else if(p.target.kind==="source-batch")for(let b of p.target.paths)S.add(b);if(p.params.kind==="move-node"&&!("kind"in p.params.target)){let b=[p.params.target.parentKey,...p.params.target.relation==="before"||p.params.target.relation==="after"?[p.params.target.anchorKey]:[]];for(let R of b){let A=Hn(R,p.composition),M=it(R)??R,_=A?.graph?.elements.get(M);_&&S.add(_.sourceFile)}}await ru(S)}async function dy(p){if(p.params.kind!=="source-edit")return Ds(p,"invalid-params","source-edit requires source-edit params");for(let S of p.params.edits){let b=IN(S);if(!b.ok)return Ds(p,b.errorCode,b.message,b.details)}f+=1;try{let S=await hy(p.params.edits);if(!S.ok)return Ds(p,S.errorCode,S.message,S.details);await ou(p);let b={operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:p.params.conflictPolicy,edits:p.params.edits.map(R=>R.operation==="delete"?{operation:"delete",file:R.path,baseContentHash:R.baseContentHash??null}:{operation:"upsert",file:R.path,baseContentHash:R.baseContentHash??null,content:R.content})};return await Wn({request:p,filePlan:b})}catch(S){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.INTERNAL_ERROR,message:qe(S)}}}finally{f-=1}}async function fy(p){if(p.target.kind!=="project"||p.params.kind!=="insert-page-resource")return ue(p,V.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");f+=1;try{let S=await Bo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...p.params.artifact.components.flatMap(R=>R.materialization.files.map(A=>({path:A.pathTemplate,content:A.content}))),...p.params.artifact.pages.flatMap(R=>R.materialization.files.map(A=>({path:A.pathTemplate,content:A.content})))],exists:R=>n.exists(R),readFile:R=>n.readFile(R)});if(!S.ok)return ue(p,V.MATERIALIZATION_REJECTED,S.message);let b=await nc({artifact:p.params.artifact,exists:R=>n.exists(R)});return b.ok?await Wn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"overwrite",edits:b.files},output:{kind:"insert-page-resource",package_instance_id:b.packageInstanceId,pages:b.pages},historyPolicy:"none"}):ue(p,b.code==="MATERIALIZATION_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,b.message,b.path?{path:b.path}:void 0)}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{f-=1}}async function py(p){if(p.target.kind!=="project"||p.params.kind!=="delete-page-source")return ue(p,V.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return ue(p,V.PLAN_FAILED,"Complete project file listing is required for page deletion.");f+=1;try{let S=Zh(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(S.truncated)return ue(p,V.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:S.truncated.reasons});let b=S.files.filter(({path:_})=>/\.(?:tsx?|jsx?)$/.test(_)),R=Object.fromEntries(await Promise.all(b.map(async({path:_})=>[_,await n.readFile(_)]))),A=Cp({expectedUrlPath:p.params.expectedUrlPath,files:R});if(!A.ok)return ue(p,A.code==="HOME_PAGE_LOCKED"?V.HOME_PAGE_LOCKED:A.code==="ROUTE_NOT_FOUND"?V.ROUTE_NOT_FOUND:V.PLAN_FAILED,A.message);let M=await Promise.all(A.edits.map(async _=>({..._,baseContentHash:Ce(await n.readFile(_.file))})));return Wn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:p.target,documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:M},output:{kind:"delete-page-source",deleted_files:A.deletedFiles,updated_files:A.updatedFiles,preserved_shared_files:A.preservedSharedFiles,warnings:A.warnings},historyPolicy:"none"})}catch(S){return ue(p,V.INTERNAL_ERROR,qe(S))}finally{f-=1}}async function my(p,S){if(p.kind!=="insert-child"&&p.kind!=="replace-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(p.params.kind!=="insert-child"&&p.params.kind!=="replace-node"||p.kind!==p.params.kind)return ue(p,V.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(p.params.kind==="insert-child"){if(!("kind"in p.params.position)||p.params.position.kind!=="page-composition")return ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(p.params.position.documentVersion!==p.documentVersion)return ue(p,V.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let b=S.document,R=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!R||R.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||R.documentVersion!==b.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=p.params.node.kind==="component-call"?p.params.node.materialization:void 0;if(!A)return ue(p,V.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let M=p.params.kind==="insert-child"?p.params.position:null,_=await Bo({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:A.files.map(K=>({path:K.pathTemplate,content:K.content})),exists:K=>n.exists(K),readFile:K=>n.readFile(K)});if(!_.ok)return ue(p,V.MATERIALIZATION_REJECTED,_.message);let $=await lN(n,Object.keys(A.projectDependencies??{})),Y=await jf({manifest:A,generatedRoot:"components/site/generated",controlledFiles:A.files.map(K=>({pathTemplate:K.pathTemplate})),exists:K=>n.exists(K),availableHostDependencies:$,commit:async K=>{let D=await n.readFile(S.entryFile),ee=S.document,re=S.pageCompositionProjection;if(!ee||ee.pageComposition?.status!=="supported"||ee.version!==p.documentVersion||!re||re.status!=="supported"||re.documentVersion!==ee.version)return{ok:!0,data:ue(p,V.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ye=K.entry.path,me=ky(K.instanceName),Ie,Ae=[];if(p.params.kind==="insert-child"){if(!M||!("kind"in M)||M.kind!=="page-composition")return{ok:!0,data:ue(p,V.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let ge=lc({routeId:S.routeId,entryFile:S.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:p.documentVersion,source:D,projection:re,placementKey:M.placementKey,component:{source:ye,exportName:K.entry.export.kind==="default"?"default":K.entry.export.name,localName:me}});if(!ge.ok)return{ok:!0,data:ue(p,Vs(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Ee=ge.plan.rewriteStep,Te;switch(Ee.kind){case"insert-root-expression":Te=$i({source:D,locator:Ee.locator,expectedSourceHash:Ee.sourceHash,action:{kind:"insert",jsx:Ee.node.jsx,placement:Ee.placement,replaceOriginal:Ee.replaceOriginal}});break;case"insert-child":Te=Qn({source:D,locator:Ee.parentLocator,node:Ee.node,placement:Ee.placement,...Ee.anchorLocator?{anchorLocator:Ee.anchorLocator}:{}});break;default:Te={ok:!1,source:D,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ee)}`}}}if(!Te.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};Ie=Te.source}else{let ge=uc({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:p.documentVersion,source:D,projection:re,placementUnitKey:p.target.placementUnitKey,operation:"replace-node"});if(!ge.ok)return{ok:!0,data:ue(p,Vs(ge.error.code),ge.error.message,{diagnostics:ge.error.diagnostics})};let Ee=ge.plan.rewriteStep,Te;switch(Ee.kind){case"replace-root-expression":Te=$i({source:D,locator:Ee.locator,expectedSourceHash:Ee.sourceHash,action:{kind:"replace",jsx:`<${me} />`}});break;case"replace-node":Te=ri({source:D,locator:Ee.locator,node:{jsx:`<${me} />`}});break;default:Te={ok:!1,source:D,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ee.kind}`}}}if(!Te.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,Te.diagnostic.message)};let en=await iu({routeState:S,placementUnitKey:p.target.placementUnitKey,source:D,mutatedSource:Te.source});Ie=en.source,Ae=await Promise.all(en.files.map(async at=>({operation:"delete",file:at,baseContentHash:Ce(await n.readFile(at))})))}let O=tr({source:Ie,moduleSpecifier:v(S.entryFile,ye),imports:K.entry.export.kind==="default"?[{kind:"default",local:me}]:[{kind:"named",imported:K.entry.export.name,local:me}]});if(!O.ok)return{ok:!0,data:ue(p,V.AST_PARSE_ERROR,O.diagnostic.message)};let U=K.files.map(ge=>({operation:"create-only",file:ge.path,content:ge.content})),ae=[{operation:"upsert",file:S.entryFile,content:O.source,baseContentHash:Ce(D)},...U,...Ae];f+=1;try{let ge=await Wn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:ae}});return!ge.ok&&ge.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ge.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:ge}}finally{f-=1}}});return Y.ok?Y.data:ue(p,Y.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?V.MATERIALIZATION_CONFLICT:V.MATERIALIZATION_REJECTED,Y.error.message,{materializationCode:Y.error.code})}async function gy(p,S){if(p.kind!=="move-node"&&p.kind!=="remove-node")return ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let b=S.document,R=S.pageCompositionProjection;if(!b||b.pageComposition?.status!=="supported"||!R||R.status!=="supported")return ue(p,V.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(p.documentVersion!==b.version||R.documentVersion!==b.version)return ue(p,V.VERSION_STALE,`Document version ${p.documentVersion} is stale (current: ${b.version}).`);let A=await n.readFile(S.entryFile),M=uc({routeId:S.routeId,composition:S.composition,entryFile:S.entryFile,currentDocumentVersion:b.version,expectedDocumentVersion:p.documentVersion,source:A,projection:R,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(!M.ok)return ue(p,Vs(M.error.code),M.error.message,{diagnostics:M.error.diagnostics});let _=M.plan.rewriteStep,$;switch(_.kind){case"move-node":$=qn({source:A,locator:_.locator,targetParentLocator:_.targetParentLocator,placement:_.placement,..._.anchorLocator?{anchorLocator:_.anchorLocator}:{}});break;case"remove-node":$=Zn({source:A,locator:_.locator});break;case"remove-root-expression":$=$i({source:A,locator:_.locator,expectedSourceHash:_.sourceHash,action:{kind:"remove"}});break;default:$={ok:!1,source:A,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${_.kind}`}}}if(!$.ok)return ue(p,V.AST_PARSE_ERROR,$.diagnostic.message);let Y=$.source,K=[];if(p.kind==="remove-node"){let ee=await iu({routeState:S,placementUnitKey:p.target.placementUnitKey,source:A,mutatedSource:Y});Y=ee.source,K=await Promise.all(ee.files.map(async re=>({operation:"delete",file:re,baseContentHash:Ce(await n.readFile(re))})))}let D=[{operation:"upsert",file:S.entryFile,content:Y,baseContentHash:Ce(A)},...K];f+=1;try{return await Wn({request:p,filePlan:{operationId:p.id,kind:"source-edit",target:{kind:"source-file",path:S.entryFile},documentVersion:p.documentVersion,conflictPolicy:"compare-and-swap",edits:D}})}finally{f-=1}}async function iu(p){let S={source:p.mutatedSource,files:[]},b=p.routeState.graph,R=p.routeState.pageCompositionProjection;if(!b||!R||R.status!=="supported"||!n.listFiles)return S;let M=R.placementUnitByKey.get(p.placementUnitKey)?.sourceRange;if(!M)return S;let _=[...b.elements.values()].find(O=>O.sourceFile===p.routeState.entryFile&&O.importedFrom&&w(O.sourceRange,M));if(!_?.importedFrom||!_.exportName)return S;let $=x(_.importedFrom),Y="components/site/generated/";if(!$.startsWith(Y))return S;let K=$.slice(Y.length).split("/")[0];if(!K||!/-[0-9a-f]{8}$/i.test(K))return S;let D=`${Y}${K}`;if([...b.elements.values()].filter(O=>O.sourceFile===p.routeState.entryFile&&x(O.importedFrom??"")===$).length!==1)return S;let re=await n.listFiles({maxFiles:5e3,maxDepth:32}),ye=Array.isArray(re)?re:re.files;if(!Array.isArray(re)&&re.truncated)return S;let me=ye.map(({path:O})=>O).filter(O=>O===D||O.startsWith(`${D}/`));if(me.length===0||!me.includes($))return S;for(let{path:O}of ye)if(!(O===p.routeState.entryFile||O===D||O.startsWith(`${D}/`)))try{if((await n.readFile(O)).includes(K))return S}catch{return S}let Ie=v(p.routeState.entryFile,$),Ae=nr({source:p.mutatedSource,moduleSpecifier:Ie,imports:_.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:_.exportName}]});return Ae.ok?Ae.source.includes(K)?{source:Ae.source,files:[]}:{source:Ae.source,files:me.sort((O,U)=>O.localeCompare(U))}:S}async function hy(p){if(n.getFileInfo){for(let _ of p)if(await n.exists(_.path)&&await n.getFileInfo(_.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${_.path}`,details:{path:_.path}}}for(let _ of p){if(_.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(_.path))continue;let $=await n.exists(_.path)?await oa(n,_.path):null;if($?.ok){let Y=Qw($.content,_.content);if(!Y.ok)return{ok:!1,errorCode:"invalid-params",message:Y.message,details:{path:_.path,code:Y.code}}}}let S=yy(p);if(S.length===0)return{ok:!0};let b=vN(n,p),R=new Map,A=(_,$)=>{let Y=R.get(_);if(Y?.source===$)return Y.result;let K=Xt(_,$);return R.set(_,{source:$,result:K}),K},M;try{M=await Ph(S,async _=>{let $=i.get(_);return $?[...(await pe($.entryFile,await b.readFile($.entryFile),b,{validationOnly:!0,parseModule:A,validatedImports:m.getImports})).parsedModules.values()]:[]})}catch(_){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${qe(_)}`,details:{compositionKeys:S}}}for(let _ of M)m.remember(_);return{ok:!0}}function yy(p){return p.map(b=>b.path).some(Gh)?[...i.keys()]:[]}function Ds(p,S,b,R){let A=Fo(S);return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:A,message:b,...R?{details:R}:{}}}}async function Bs(p){let S=[];for(let b of new Set(p))S.push(await xy(b));return S}async function xy(p){if(!(typeof n.exists=="function"?await n.exists(p):!0))return{file:p,content:"",version:Math.max(0,z(p)),exists:!1};let b=await n.readFile(p);return{file:p,content:b,version:Math.max(1,z(p)),exists:!0,sha256:Ce(b)}}async function su(p,S,b,R){if(!e.historyStore)return null;let A=new Map(S.map($=>[$.file,$])),M=new Map(b.map($=>[$.file,$])),_=[...new Set([...A.keys(),...M.keys()])].sort().map($=>{let Y=A.get($),K=M.get($);return{path:$,preDigest:Y?.exists===!1||!Y?null:Ce(Y.content),postDigest:K?.exists===!1||!K?null:Ce(K.content)}});return{schemaVersion:2,transactionId:`${p}:${R.expectedIndexDigest}`,operationId:p,phase:"prepared",historyTransition:R,files:_}}async function au(p){return!p||!e.historyStore||await e.historyStore.writeTransactionJournal(p),p}async function zn(p){p&&e.historyStore&&await e.historyStore.clearTransactionJournal(p.transactionId)}async function js(p,S){let b=[];try{for(let R of p)await cu(R),typeof n.bumpVersion=="function"&&n.bumpVersion(R.file),b.push(R.file)}catch(R){let A=await by(S.filter(M=>b.includes(M.file)));return A.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${qe(R)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${A.failedFiles.join(", ")}: ${qe(R)}`,rolledBack:!1}}return{ok:!0,snapshots:p.map(Sy)}}async function cu(p){if(p.exists===!1){await n.deleteFile(p.file);return}await n.writeFile(p.file,p.content)}async function by(p){let S=[];for(let b of p)try{await cu(b),typeof n.bumpVersion=="function"&&n.bumpVersion(b.file)}catch{S.push(b.file)}return S.length===0?{ok:!0}:{ok:!1,failedFiles:S}}function Sy(p){let S=p.exists!==!1;return{file:p.file,content:S?p.content:"",version:p.version,exists:S,...S?{sha256:Ce(p.content)}:{}}}async function Wn(p){return y.runExclusive(()=>Ey(p))}async function Ey(p){let S=p.filePlan.edits.map(O=>O.file),b=o.resolveSelector(p.request.composition),R=b.context,A=p.historyPolicy==="none"?void 0:{initiatingComposition:R,affectedCompositions:sy(S)},M=await Bs(S),_=new Map(M.filter(O=>O.exists!==!1).map(O=>[O.file,O.content])),$=uu(),Y=new Map(d),K=new Set(g),D=new Set([...i.values()].filter(O=>p.filePlan.edits.some(U=>U.operation==="delete"&&U.file===O.entryFile)).map(O=>O.key)),ee=p.filePlan.edits.map(O=>O.operation==="delete"?{file:O.file,content:"",version:0,exists:!1}:{file:O.file,content:O.content,version:0,exists:!0,sha256:Ce(O.content)}),re={operationId:p.filePlan.operationId,intents:p.filePlan.edits.map(O=>O.operation==="delete"?{kind:"delete",path:O.file}:{kind:O.operation==="create-only"?"create-only":"upsert",path:O.file,content:O.content})},ye=null,me=!1,Ie=await Rs({overlay:_,exists:O=>n.exists(O),plan:re,buildCandidate:async({plan:O})=>({plan:O}),prepareHistory:async()=>{let O=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:M,postSnapshots:ee,...p.selectionRef?{selectionRef:p.selectionRef}:{},...p.output?{output:p.output}:{},...A?{provenance:A}:{}}),U=O?.historyTransition?O.historyTransition:e.historyStore?aN(await e.historyStore.readIndex()):null;if(e.historyStore&&!U)throw new Error("Durable history did not provide an exact index transition.");return ye=await su(p.request.id,M,ee,U),ye=await au(ye),{history:O,historyTransition:U}},reverify:async()=>{},writeCandidate:async()=>{let O=await u.executeFilePlan(p.filePlan);if(!O.ok)throw new Ts(O);return{postSnapshots:await Bs(O.affectedFiles),affectedFiles:O.affectedFiles,internalResultVersion:O.resultVersion}},validateCandidate:async({candidate:O,receipt:U})=>{let ae=await Mo(U.affectedFiles,{changed:!0,minimumVersion:U.internalResultVersion,publish:!1,excludedCompositionKeys:D});if(ae.failedRoutes.length>0)throw new Un(ae.failedRoutes);let ge=fu($,ae.candidateRouteStates??[]),Ee=du(ge,b.key);return{...O,rebuild:ae,routeSnapshots:ge,resultVersion:Ee,...Xh(p.selectionRef,ge.map(Te=>Te.state.document))?{selectionRef:Xh(p.selectionRef,ge.map(Te=>Te.state.document))}:{}}},publishCandidate:async({candidate:O,history:U,receipt:ae})=>{U?.history&&(await l.publishPrepared(U.history),me=!0);let ge=O.resultVersion??ae.internalResultVersion;return{composition:R,requestId:p.request.id,kind:p.request.kind,target:p.request.target,ok:!0,resultVersion:ge,affectedFiles:ae.affectedFiles,fileChanges:ae.postSnapshots.map(Ee=>({path:Ee.file,operation:Ee.exists===!1?"delete":"upsert"})),...p.output?{output:p.output}:{},...O.selectionRef?{selectionRef:O.selectionRef}:{}}},swapCandidate:({candidate:O,receipt:U})=>{O.routeSnapshots&&Oo(O.routeSnapshots),O.rebuild?.candidateSourceCache&&Ir(d,O.rebuild.candidateSourceCache),tu(U.postSnapshots)},finalizeCandidate:async()=>{await zn(ye);for(let O of D)i.delete(O)},emitCommitted:({candidate:O,published:U})=>{Ls(U,O.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:O,receipt:U})=>{if(me)throw new Error("history was published before transaction finalization failed");if(U){let ae=await js(M,U.postSnapshots);if(!ae.ok)throw new Error(ae.reason)}Oo($),Ir(d,Y),nu(K),O?.history&&await l.discardPrepared?.(O.history),await zn(ye)}});if(Ie.ok)return Ie.published;if(Ie.stage==="precheck"||Ie.stage==="build")try{await zn(ye)}catch(O){let U=await Lo(qe(O));return ue(p.request,U,"Unable to clear an uncommitted transaction journal.")}if(Ie.recoveryRequired){let O=await Lo(Ie.reason);return ue(p.request,O===V.RECOVERY_PERSIST_FAILED?O:V.ROLLBACK_FAILED,Ie.reason)}let Ae=Ie.error;return Ae instanceof Ts?{...ue(p.request,Fo(Ae.result.errorCode),Ae.result.reason),...Ae.result.affectedFiles?{affectedFiles:Ae.result.affectedFiles}:{}}:Ae instanceof Un?ue(p.request,V.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${zl(Ae.failedRoutes)}`,{failedRoutes:Ae.failedRoutes}):ue(p.request,mu(Ie.stage),qe(Ae))}async function lu(p){return y.runExclusive(async()=>{let S=p==="undo"?await l.prepareUndo():await l.prepareRedo();return S?vy(p,S):{composition:o.entries[0].context,requestId:p,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:V.INTERNAL_ERROR,message:p==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function vy(p,S){let b=S.entry,R=p==="undo"?b.preSnapshots:b.postSnapshots,A=p==="undo"?b.postSnapshots:b.preSnapshots,M=R.map(U=>U.file),{context:_,key:$}=cy(b,M),Y=await Bs(M),K=new Map(Y.filter(U=>U.exists!==!1).map(U=>[U.file,U.content])),D=j($),ee=uu(),re=new Map(d),ye=new Set(g),me=null,Ie=!1,Ae,O=await Rs({overlay:K,plan:{operationId:`${p}:${b.operationId}`,intents:R.map(U=>U.exists===!1?{kind:"delete",path:U.file}:{kind:"upsert",path:U.file,content:U.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(me=await su(`${p}:${b.operationId}`,Y,R,S.historyTransition),me=await au(me),S),reverify:async()=>{},writeCandidate:async()=>{let U=await js(R,A);if(!U.ok)throw new Error(U.reason);return{snapshots:U.snapshots}},validateCandidate:async({candidate:U})=>{Ae=ay(b,M);let ae=await Mo(M,{changed:!0,minimumVersion:D+1,publish:!1,affectedCompositionKeys:Ae});if(ae.failedRoutes.length>0)throw new Un(ae.failedRoutes);let ge=fu(ee,ae.candidateRouteStates??[]),Ee=du(ge,$);return{...U,rebuild:ae,routeSnapshots:ge,resultVersion:Ee}},publishCandidate:async({candidate:U,history:ae,receipt:ge})=>{if(!ae)throw new Error("history cursor intent is missing");await l.publishPrepared(ae),Ie=!0;let Ee=U.resultVersion??D+1;return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!0,resultVersion:Ee,affectedFiles:M,fileChanges:ge.snapshots.map(Te=>({path:Te.file,operation:Te.exists===!1?"delete":"upsert"})),...b.output?{output:b.output}:{}}},swapCandidate:({candidate:U,receipt:ae})=>{U.routeSnapshots&&Oo(U.routeSnapshots),U.rebuild?.candidateSourceCache&&Ir(d,U.rebuild.candidateSourceCache),tu(ae.snapshots)},finalizeCandidate:async()=>{await zn(me)},emitCommitted:({candidate:U,published:ae})=>Ls(ae,U.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:U,receipt:ae})=>{if(Ie)throw new Error("history cursor was published before transaction finalization failed");if(ae){let ge=await js(A,ae.snapshots);if(!ge.ok)throw new Error(ge.reason)}Oo(ee),Ir(d,re),nu(ye),U&&await l.discardPrepared?.(U),await zn(me)}});if(O.ok)return O.published;if(O.stage==="precheck"||O.stage==="build")try{await zn(me)}catch(U){let ae=await Lo(qe(U));return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,error:{code:ae,message:"Unable to clear an uncommitted transaction journal."}}}if(O.recoveryRequired){let U=await Lo(O.reason);return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,affectedFiles:M,error:{code:U===V.RECOVERY_PERSIST_FAILED?U:V.ROLLBACK_FAILED,message:O.reason}}}return{composition:_,requestId:p,kind:b.kind,target:b.target,ok:!1,resultVersion:D,affectedFiles:M,error:{code:O.error instanceof Un?V.ROUTE_REBUILD_FAILED:mu(O.stage),message:qe(O.error),...O.error instanceof Un?{details:{failedRoutes:O.error.failedRoutes}}:{}}}}function uu(){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 du(p,S){return p.find(R=>R.key===S)?.state.graph?.version??o.initialVersions.get(S)??0}function fu(p,S){let b=new Map(p.map(R=>[R.key,R]));for(let R of S)b.set(R.key,R);return[...b.values()]}function Oo(p){for(let S of i.values())P(S);for(let S of p){let b={...S.state,dependencyFiles:new Set(S.state.dependencyFiles),fileVersions:new Map(S.state.fileVersions)};i.set(S.key,b),C(b,b.dependencyFiles)}}async function $s(p){let S=i.get(p);if(!S)throw new Error(`Composition not found: ${p}`);if(S.graph)return;let b=await n.readFile(S.entryFile);await st(p,b)}function Hn(p,S){let b=i.get(o.resolveSelector(S).key)??null;return!b||!pu(b,p)?null:b}function pu(p,S){if(p.documentIndex?.entriesByKey.has(S)||p.graph?.elements.has(S))return!0;let b=it(S);return b&&b!==S?p.graph?.elements.has(b)===!0:!1}function ue(p,S,b,R){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:S,message:b,...R?{details:R}:{}}}}function mu(p){return p==="validate"?V.ROUTE_REBUILD_FAILED:p==="publish"?V.HISTORY_COMMIT_FAILED:V.WRITE_IO_ERROR}async function Lo(p){if(h=!0,!l.markRecoveryRequired)return V.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(p),V.RECOVERY_REQUIRED}catch{return V.RECOVERY_PERSIST_FAILED}}function ky(p){let b=p.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(R=>R.charAt(0).toUpperCase()+R.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return b?`Prefab${b}`:"GeneratedPrefab"}function Vs(p){return p==="VERSION_STALE"?V.VERSION_STALE:p==="CROSS_PAGE_MOVE_UNSUPPORTED"?V.CROSS_PAGE_MOVE_UNSUPPORTED:V.UNSUPPORTED_OPERATION}async function gu(p){if(p.target.kind==="route"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await $s(b.key),b):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(p.target.kind==="page-unit"){let b=i.get(o.resolveSelector(p.target.composition).key)??null;return b?(b.graph||await $s(b.key),b):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(p.target.kind!=="node")return ue(p,V.UNSUPPORTED_OPERATION,`${p.kind} source target execution is not implemented yet.`);let S=i.get(o.resolveSelector(p.composition).key)??null;return S?(S.graph||await $s(S.key),pu(S,p.target.key)?S:ue(p,V.NODE_NOT_FOUND,`Target key not found: ${p.target.key}`)):ue(p,V.ROUTE_NOT_FOUND,"Composition not found for node target.")}return{get status(){return t},dispose(){t="disposed",a.clear(),i.clear(),s.clear(),d.clear(),m.clear(),g.clear()},registerComposition(p,S){let b=o.register({context:p,entryFile:S}),R=i.get(b.key);if(R?.entryFile===S)return;R&&P(R);let A=Jh(b.context,S);i.set(b.key,A),C(A,A.dependencyFiles),r.emit({type:"graph-invalidated",composition:b.context})},unregisterComposition(p){let S=o.resolveSelector(p),b=i.get(S.key);b&&(P(b),i.delete(S.key),o.unregister(S.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:S.context}))},getCompositionEntryFiles(){return[...i.values()].map(p=>p.entryFile)},getCompositionContext(p){return o.resolveSelector(p).context},async initializeComposition(p){let S=o.resolveSelector(p),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(b.graph)t="ready";else{t="building";try{let R=await n.readFile(b.entryFile);await st(S.key,R),t="ready",r.emit({type:"graph-ready",composition:S.context,version:i.get(S.key)?.graph?.version??0})}catch(R){throw t="idle",r.emit({type:"graph-error",composition:S.context,message:qe(R)}),R}}},getDocument(p){let S=o.resolveSelector(p),b=i.get(S.key);if(!b)throw new Error(`Composition not registered: ${S.key}`);if(!b.document)throw new Error(`Composition not built: ${S.key}`);return b.document},async getHistoryStatus(){await E;let p=await l.getStatus?.();return p?{...p,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(p,S,b){let R=Hn(p,S),A=it(p)??p;if(R?.graph&&R.topology&&R.capabilities&&R.detailProjections){let M=R.detailProjections.get(A);if(M){let _=R.graph.elements.get(A);if(!_)throw new Error(`Key not found: ${p}`);let $=mN(p,A,b),Y=new Map;if(M.isRepeat&&$?.instanceIndex!==void 0)for(let ee of _.attributes??[])Y.set(ee.name,El({file:_.sourceFile,source:d.get(_.sourceFile)??"",element:_,propertyName:ee.name,selectionRef:$,graph:R.graph,sources:d}));let K=sh({element:_,graph:R.graph,source:d.get(_.sourceFile),documentVersion:R.graph.version,selectionRef:b,isRepeat:M.isRepeat,propertyProvenance:M.propertyProvenances,repeatTargets:Y}),D=lh(A,R.graph,R.topology,R.capabilities,M.textSources,M.provenances,M.dynamicData,K);return p===A?D:Lh(D,p,R.document??null,R.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getRenderDetail(p,S){let b=Hn(p,S),R=it(p)??p;if(b?.graph&&b.topology&&b.capabilities&&b.detailProjections){let A=b.detailProjections.get(R);if(A){let M=ch(R,b.graph,b.topology,b.capabilities,A.textSources,A.writeTarget,A.provenances,A.conditional,A.componentSemantic,A.styleSource,A.dynamicData);return p===R?M:Oh(M,p,b.document??null,b.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${p}`)},getClassNameSource(p,S){let b=Hn(p,S),R=it(p)??p;if(!b?.graph)throw new Error(`Key not found: ${p}`);let A=b.graph.elements.get(R);if(!A)throw new Error(`Key not found: ${p}`);let M=d.get(A.sourceFile);if(M===void 0)throw new Error(`Source not loaded: ${A.sourceFile}`);return ka({key:R,route:{composition:b.composition,routeId:b.routeId,graph:b.graph,source:M}})},refreshSourceForKey:uy,async execute(p){if(await E,h)return ue(p,V.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(p.kind==="source-edit")return dy(p);if(p.kind==="insert-page-resource")return fy(p);if(p.kind==="delete-page-source")return py(p);let S=await gu(p);if("ok"in S)return S;await ou(p);let b=await gu(p);if("ok"in b)return b;let R=b;if(p.target.kind==="page-unit"){let D=p;return p.kind==="insert-child"||p.kind==="replace-node"?my(D,R):p.kind==="move-node"||p.kind==="remove-node"?gy(D,R):ue(p,V.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}let M=p.params,_=p.target.kind==="node"?p.target.key:null;if(M.kind==="move-node"&&"kind"in M.target&&M.target.kind==="source-sibling"){let D=M.target,ee=_?R.document?.entries.find(U=>U.key===_):null,re=R.document?.entries.find(U=>U.key===D.anchorKey),ye=ee?.pageCompositionActionScope,me=ye?.kind==="source-siblings"?ye.siblingKeys:null,Ie=me?.indexOf(ee?.key??"")??-1,Ae=me?.indexOf(D.anchorKey)??-1,O=D.relation==="before"?Ie-1:Ie+1;if(!ee||!re||!me||Ie<0||Ae!==O||re.pageCompositionActionScope?.kind!=="source-siblings"||re.pageCompositionActionScope.siblingKeys.length!==me.length||re.pageCompositionActionScope.siblingKeys.some((U,ae)=>U!==me[ae])||!ee.operationSummary.canMove)return ue(p,V.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!R.graph||!R.topology||!R.capabilities)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:p.target.kind==="route"?V.ROUTE_NOT_FOUND:V.NODE_NOT_FOUND,message:p.target.kind==="route"?"Composition not ready for route target.":p.target.kind==="node"?`Target key not found: ${p.target.key}`:`${p.kind} source target execution is not implemented yet.`}};let $=FN(R,R.graph,R.capabilities,d,i),Y=await new as($).plan(p);if(!Y.ok)return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:Fo(Y.errorCode),message:Y.reason}};let K=Y.plan;if(K.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:G(p),affectedFiles:[]}:{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};f+=1;try{if(K.steps.some(ee=>ee.type==="invoke-external-adapter")){let ee=await u.execute(K);if(!ee.ok)return ue(p,Fo(ee.errorCode),ee.reason);let re={composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!0,resultVersion:Math.max(G(p),ee.resultVersion),affectedFiles:ee.affectedFiles,...ee.selectionRef?{selectionRef:ee.selectionRef}:{}};return Ls(re,{rebuiltRoutes:[],failedRoutes:[]}),re}let D=await u.prepareRewritePlan(K);return D.ok?await Wn({request:p,filePlan:D.filePlan,...D.selectionRef?{selectionRef:D.selectionRef}:{}}):ue(p,Fo(D.errorCode),D.reason)}catch(D){return{composition:o.resolveSelector(p.composition).context,requestId:p.id,kind:p.kind,target:p.target,ok:!1,resultVersion:G(p),error:{code:V.INTERNAL_ERROR,message:qe(D)}}}finally{f-=1}},async undo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:j(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};f+=1;try{return await lu("undo")}finally{f-=1}},async redo(p){if(await E,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:j(o.entries[0].key),error:{code:V.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};f+=1;try{return await lu("redo")}finally{f-=1}},notifyFileChanged(p){ql([p])},getAffectedCompositions(p){return iy(p)},subscribe(p){return r.subscribe(p)}}}function CN(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function RN(e,t,n,r){let o=new Map,i=new Map,s=(d,m,g)=>{let f=d.get(m)??new Set,h=f.size;return f.add(g),d.set(m,f),f.size!==h},a=(d,m)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,m);let g=s(o,`${d.importedFrom}#${d.tag}`,m);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,m)||g),g},c=d=>o.get(`${d.sourceFile}#${d.componentName}`)??i.get(d.sourceFile);for(let d of t.elements.values()){if(d.sourceFile!==n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let m=n.placements.find(f=>f.members.some(h=>h.sourceRange!==null&&_o(d.sourceRange,h.sourceRange)));if(!m)continue;let g=m.placementUnitKey;a(d,g)}let l=!0;for(;l;){l=!1;for(let d of t.elements.values()){if(d.sourceFile===n.entryFile||!d.importedFrom||!/^[A-Z]/.test(d.tag))continue;let m=c(d);if(m)for(let g of m)l=a(d,g)||l}}let u=n.placements.find(d=>d.placementKey===n.container.placementKey&&d.relation==="append");for(let d of e.entries){let m=it(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(m);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&_o(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(E=>E.members.some(x=>x.sourceRange!==null&&(_o(g.sourceRange,x.sourceRange)||TN(x.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let f=o.get(`${g.sourceFile}#${g.componentName}`);if(f){f.size===1&&(d.pageCompositionUnitKey=f.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}wN(e,t,n,r)}function wN(e,t,n,r){let o=new Map(e.entries.map(m=>[m.key,m])),i=e.entries.filter(m=>{let g=m.pageCompositionUnitKey;return g?m.parentKey?o.get(m.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(m,g)=>{s.set(m,Math.min(2,(s.get(m)??0)+g))},c=m=>n.placements.some(g=>g.members.some(f=>f.sourceRange!==null&&_o(m.sourceRange,f.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 g=!1;for(let f of l){let h=s.get(f.owner)??s.get(f.ownerDefault)??0;if(!h)continue;let y=s.get(f.target)??0,E=Math.min(2,y+h);E!==y&&(s.set(f.target,E),g=!0)}if(!g)break}let u=m=>s.get(`${m.sourceFile}#${m.componentName}`)??s.get(`${m.sourceFile}#default`)??0;for(let m of i){m.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(m.key);m.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(m.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let m of i){let g=t.elements.get(m.key);if(!g||g.sourceFile===n.entryFile||m.key!==(it(m.key)??m.key))continue;let f=r.get(g.sourceFile);if(!f)continue;let h=ce(f.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,E=y.parentPath;if(!E||!E.isJSXFragment()&&!(E.isJSXElement()&&Oe(E))){u(g)===1&&Wh(y)&&(m.pageCompositionActionScope={kind:"route-unit"});continue}if(!Wh(E))continue;let x=d.get(E.node)??[];x.push({entry:m,element:g,parentPath:E}),d.set(E.node,x)}for(let m of d.values()){let g=m[0];if(!g)continue;let f=g.entry.pageCompositionUnitKey,h=[],y=!!(f&&u(g.element)===1);for(let x of g.parentPath.node.children){if(NN(x))continue;if(!PN(x)){y=!1;break}let v=[...t.elements.values()].find(N=>N.sourceFile===g.element.sourceFile&&N.componentName===g.element.componentName&&_o(N.sourceRange,AN(x))),w=v?o.get(v.identity.key):null;if(!v||!w||w.parentKey||w.pageCompositionUnitKey!==f||u(v)!==1){y=!1;break}h.push(w)}if(!y||h.length!==m.length||m.some(({entry:x})=>!h.some(v=>v.key===x.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let E=h.map(x=>x.key);for(let x of h)x.pageCompositionActionScope={kind:"source-siblings",siblingKeys:E}}}function Wh(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function NN(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function PN(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function AN(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 _o(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function TN(e,t){return Hh(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Hh(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Hh(e,t,n,r){return e!==n?e-n:t-r}function FN(e,t,n,r,o){let i=new Map,s=new Map,a=(u,d)=>{if(s.has(u))return;s.set(u,d);let m=t.elements.get(u);for(let g of m?.childKeys??[])a(g,d)};for(let u of t.regions)if(u.kind==="repeat-region")for(let d of u.childKeys)i.set(d,u.ownerKey),a(d,u.ownerKey);return{getNode(u){let d=c(u),m=t.elements.get(d.baseKey);return m?l(u,m):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=it(h)??h,E=t.elements.get(y);return E?l(h,E):null}).filter(h=>h!==null);let f=t.elements.get(d.baseKey);return f?f.childKeys.map(h=>{let y=t.elements.get(h);return y?l(h,y):null}).filter(h=>h!==null):[]},getKnownSourceFiles(){return[...r.entries()].map(([u,d])=>({file:u,content:d}))},getRouteEntryFiles(){return[...o.values()].map(u=>u.entryFile)},getCapability(u){let d=c(u),m=n.get(d.baseKey);return m?{...m,key:u,constraints:m.constraints.map(g=>({...g})),...m.editModes?{editModes:{...m.editModes}}:{}}:{composition:e.composition,key:u,canUpdateText:!1,canRemove:!1,canInsertChild:!1,canMove:!1,constraints:[]}},getFileContent(u){return r.get(u)??""},getFileVersion(u){return Math.max(e.fileVersions.get(u)??0,t.version)},getRouteEntryFile(u){return e.routeId===u?e.entryFile:null},getComponentSemantic(u){let d=c(u);return e.detailProjections?.get(d.baseKey)?.componentSemantic??null},getClassNameSource(u){let d=c(u),m=t.elements.get(d.baseKey),g=m?r.get(m.sourceFile):void 0;return!m||g===void 0?null:ka({key:d.baseKey,route:{composition:e.composition,routeId:e.routeId,graph:t,source:g}})},getEditableTextSegmentIndex(u){let d=c(u),g=e.detailProjections?.get(d.baseKey)?.textTargets.keys()?.next();return g&&!g.done?g.value:null},async getTextWriteTarget(u,d){let m=c(u);return Xl(e.detailProjections?.get(m.baseKey)?.textTargets.get(d)??null,m.repeatIndex)},async getElementPropertyWriteTarget(u,d){let m=c(u);return Xl(e.detailProjections?.get(m.baseKey)?.elementPropertyTargets.get(d)??null,m.repeatIndex)},getPropertyState(u,d,m){let g=c(u),f=t.elements.get(g.baseKey);if(!f)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let E=f.attributes?.find(x=>x.name===d);return E?E.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:E,target:{kind:"jsx-attribute",file:f.sourceFile,sourceRange:E.sourceRange}}:(f.attributeSpreads?.length??0)>0?{status:"blocked",owner:"generic",diagnostic:{code:"ambiguous-property-source",message:`A spread may provide or override property '${d}'`}}:{status:"missing",owner:"generic"}},getRepeatPropertyTarget(u,d,m){let g=c(u),f=t.elements.get(g.baseKey);if(!f)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=m?{...m,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return El({file:f.sourceFile,source:r.get(f.sourceFile)??"",element:f,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let m=c(u);return e.detailProjections?.get(m.baseKey)?.provenances.get(d)??null}};function c(u){let d=nN(u);return d?{baseKey:d.baseKey,repeatIndex:Mh(e.document??null,u,d.baseKey,e.documentIndex)??_h(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let m=it(u)??u,g=e.documentIndex?.entriesByKey.get(u);return{key:u,file:d.sourceFile,component:d.componentName,tag:d.tag,structuralPath:d.identity.structuralPath,sourceRange:d.sourceRange,parentKey:g?.parentKey??d.parentKey??void 0,isRepeatRegion:d.boundaryKind==="repeat-region"||s.has(m),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(m),repeatOwnerKey:i.get(m)??s.get(m),attributes:d.attributes?.map(f=>({name:f.name,value:f.value,source:f.source?{expression:f.source.expression,base:f.source.base,path:f.source.path.map(h=>({...h}))}:null,resolvedValue:f.resolvedValue}))}}}var _N={"stale-version":V.VERSION_STALE,"capability-denied":V.CAPABILITY_REJECTED,"invalid-params":V.INVALID_PARAMS,"locator-miss":V.LOCATOR_FAILED,"route-not-found":V.ROUTE_NOT_FOUND,"unsupported-operation":V.UNSUPPORTED_OPERATION,"invalid-target":V.INVALID_TARGET,"ast-error":V.AST_PARSE_ERROR,"writeback-failed":V.WRITE_IO_ERROR,"rollback-failed":V.RECOVERY_REQUIRED,unknown:V.INTERNAL_ERROR};function Fo(e){return _N[e]}function qe(e){return e instanceof Error&&e.message?e.message:String(e)}function Gh(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function MN(e){let t=Jn(e);if(!iN.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=>sN.map(a=>`${s}/${a}`))}function ON(e){let n=Jn(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function LN(e){return Qh(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function DN(e){return Qh(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Qh(e,t){let n=[];for(let r of e.matchAll(t)){let o=qh(r[1]??"");o&&n.push(o)}return n}function Yh(e,t){let n=qh(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Jn(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Jn(`${BN(e)}/${n}`):n.startsWith("/")?Jn(n.slice(1)):Yl(n)?Jn(n):null}function qh(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Yl(e){return/\.css$/i.test(e)}function BN(e){let t=Jn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function jN(e){return Array.from(new Set(e))}function Jn(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 $N(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 _s=class{constructor(t){this.options=t,this.fileSystem=new Nr(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return this.engine.getDocument(t).styleContext??null}getObjectEditContext(t,n,r){return Xo(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Ho(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Go(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Yo(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=KN.safeParse(t);if(!n.success)return{result:Uo(t,n.error.issues.map(i=>i.message))};let r=new Nr(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:Rn(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=UN.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>JN(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 Fs({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=zo(o,{siteId:this.options.siteId,snapshotId:this.options.snapshotId});i&&this.options.onEvent?.(i)}:void 0,dev:this.options.dev,...this.options.historyStore?{historyStore:this.options.historyStore}:{},...this.options.tenantId?{tenantId:this.options.tenantId}:{},siteId:this.options.siteId,snapshotId:this.options.snapshotId,...this.options.initialDocumentVersions?{initialDocumentVersions:this.options.initialDocumentVersions}:{},resourceTranslationLocale:this.options.resourceTranslationLocale})}};function JN(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ce(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ce(e.before)},fullContent:e.after}}function XN(e){return new _s(e)}import{SiteEditOperationRequestSchema as HN}from"@vcp-dev/contracts";import Ft from"node:fs/promises";import et from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as zN,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as WN}from"@vcp-dev/contracts";var Ms=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Fs({...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 Ho(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Go(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Yo(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 Ft.readFile(et.join(n,r),"utf8")},async readFileBytes(r){return Ft.readFile(et.join(n,r))},async getFileInfo(r){let o=et.join(n,...r.split("/"));try{let i=await Ft.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await gi(et.join(n,r),o)},async createExclusive(r,o){let i=et.join(n,r);await Ft.mkdir(et.dirname(i),{recursive:!0});let s=await Ft.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Ft.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Ft.rm(et.join(n,r),{force:!0});let o=r.replace(/\\/g,"/"),i=["components/site/generated","src/components/site/generated"].find(c=>o.startsWith(`${c}/`));if(!i)return;let s=et.join(n,i),a=et.dirname(et.join(n,o));for(;a!==s&&a.startsWith(`${s}${et.sep}`);){try{await Ft.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=et.dirname(a);continue}break}a=et.dirname(a)}},async exists(r){try{return await Ft.access(et.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...WN,...zN],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,m)=>d.path.localeCompare(m.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,m,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let f=et.join(n,...d.split("/")),h;try{h=await Ft.lstat(f)}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:d,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 y=await Ft.readdir(f,{withFileTypes:!0});for(let E of y)E.isSymbolicLink()||await u(`${d}/${E.name}`,m,g+1)}},getVersion(r){return t.get(r)??1},bumpVersion(r){let o=(t.get(r)??1)+1;return t.set(r,o),o}}}};function Zl(e){return new Ms(e)}var Os=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Zl({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=zo(n,{siteId:t.siteId,snapshotId:t.snapshotId});if(r){t.onEvent?.(r);for(let o of this.listeners)o(r)}},dev:t.dev,...t.historyStore?{historyStore:t.historyStore}:{},...t.tenantId?{tenantId:t.tenantId}:{},...t.initialDocumentVersions!==void 0?{initialDocumentVersions:t.initialDocumentVersions}:{},siteId:t.siteId,snapshotId:t.snapshotId})}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}registerComposition(t,n){this.engine.registerComposition(t,n)}unregisterComposition(t){this.engine.unregisterComposition(t)}getDocument(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:Jo(this.engine.getDocument(t),{siteId:this.options.siteId,snapshotId:this.options.snapshotId})}}getInternalDocument(t){return this.engine.getDocument(t)}getStyleContext(t){return{ok:!0,composition:this.engine.getCompositionContext(t),data:this.engine.getDocument(t).styleContext??null}}async getHistoryStatus(){return{ok:!0,composition:this.options.compositions[0].context,data:await this.engine.getHistoryStatus()}}getObjectEditContext(t,n,r){return{ok:!0,composition:this.engine.getCompositionContext(n),data:Xo(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=HN.safeParse(r);if(!o.success)return Uo(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:Rn(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:Rn(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:Rn(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 GN(e){return new Os(e)}export{se as FileHistoryStoreError,no as PageTemplateManagedSourceError,Os as PreviewFileSystemSiteEditEngineRuntime,vf as SITE_EDIT_RAW_COLOR_LITERAL_RE,_s as SnapshotSiteEditEngineRuntime,Bo as checkComponentI18nHostCompatibility,pp as computeManagedPageTemplatePaths,GN as createPreviewSiteEditEngineRuntime,XN as createSiteEditEngineRuntime,up as decodePageTemplateKey,kc as encodePageTemplateId,Wy as instrumentSiteEditRuntimeAttributes,mp as isManagedPageTemplateSourcePath,Zd as openFileHistoryStore,Ty as parseSourceModule,Fy as resolveImportBase,Jk as resolveManagedPageTemplateComposition,Ui as scanManagedPageTemplateCandidates,hp as scanSiteEditCompositionsFromFiles,Gr as scanSiteEditThemeStyleViolations};
|