@vcp-dev/site-edit-engine 0.11.1 → 0.11.3
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,19 +1,19 @@
|
|
|
1
|
-
import*as _S from"@babel/parser";import*as ht from"@babel/types";import*as Kn from"node:path";var Nc=[".tsx",".ts",".jsx",".js"],PS=Nc.map(e=>`/index${e}`),AS=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 Yp(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&AS.has(n[1].toLowerCase())}function Zp(e){let t=[];for(let n of e.program.body)ht.isImportDeclaration(n)&&typeof n.source.value=="string"&&Rt(n.source.value)&&t.push(n.source.value),ht.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Rt(n.source.value)&&t.push(n.source.value),ht.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Rt(n.source.value)&&t.push(n.source.value);return ht.traverseFast(e.program,n=>{let r=ht.isImportExpression(n)?n.source:ht.isCallExpression(n)&&ht.isImport(n.callee)?n.arguments[0]:null;ht.isStringLiteral(r)&&Rt(r.value)&&t.push(r.value)}),t}function Rt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Nn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Kn.dirname(e);return Kn.join(n,t).replace(/\\/g,"/")}async function TS(e,t){if(Nc.some(n=>e.endsWith(n))&&await t(e))return e;for(let n of Nc){let r=`${e}${n}`;if(await t(r))return r}for(let n of PS){let r=`${e}${n}`;if(await t(r))return r}return null}async function mr(e,t,n){let r=await Zi(e,t,n);return r.ok?r.path:null}async function Zi(e,t,n){let r=Nn(e,t);try{if(!wS(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 TS(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 wS(e,t,n){if(!Rt(t)||t.includes("\0")||t.includes("\\")||Kn.posix.isAbsolute(n))return!1;let r=Kn.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!Kn.posix.isAbsolute(e)}import{createHash as FS}from"node:crypto";import*as Qp from"@babel/parser";function gr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function Z(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gr(t,n,r,o)}}function _c(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gr(t,n,r,o)}}var OS={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function un(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Qp.parse(t,{sourceType:"module",plugins:OS[n]})}}catch(r){return{ok:!1,source:t,diagnostic:gr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Pc(e,t){return un({source:e,profile:qp(t.kind)})}function _o(e,t){return un({source:e,profile:qp(t)})}function qp(e){return"next-app-entry"}function hr(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 Ke=(e,t)=>{let n=un({source:t,profile:hr({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${FS("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Zp(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function LS(e,t){return Ke(e,t)}function DS(e,t){return Nn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as MS,parseComponentI18nResourcesJson as BS,resolveSiteTextDirection as jS,SiteLocaleSchema as $S}from"@vcp-dev/contracts";var VS=["i18next","react-i18next"],US="components/ui/site-locale-provider.tsx",KS="components/ui/component-i18n-provider.tsx",ef="app/layout.tsx";async function Po(e){let t=e.files.filter(f=>f.path.endsWith(MS));if(t.length===0)return{ok:!0};for(let f of["package.json",ef,US,KS])if(!await e.exists(f))return Jn(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return Jn("Target snapshot package.json is invalid.")}let r=tf(n)&&tf(n.dependencies)?n.dependencies:{},o=VS.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return Jn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(ef),s=Ac(i,"html","lang"),a=Ac(i,"html","dir"),c=Ac(i,"SiteLocaleProvider","locale"),l=$S.safeParse(s);if(!l.success||!a||!c||s!==c||a!==jS(l.data))return Jn("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 Jn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return Jn("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=BS(f.content);if(!g.success)return Jn(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return Jn(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Ac(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 tf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jn(e){return{ok:!1,message:e}}import wc from"@babel/generator";import*as cf from"@babel/parser";import Oc from"@babel/traverse";import*as Be from"@babel/types";import{computeSiteEditSourceIdentityKey as XS}from"@vcp-dev/contracts";var nf="data-vcp-ui-component",Qi="components/ui";function _n(e){if(!e)return!1;let t=Tc(e);return t===Qi||t.startsWith(`${Qi}/`)||t.includes(`/${Qi}/`)||t.endsWith(`/${Qi}`)}function yr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?_n(e.slice(2)):e.startsWith("./")||e.startsWith("../")?_n(Tc(`${JS(t)}/${e}`)):_n(e):!1}function Tc(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 JS(e){let t=Tc(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as VM}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as KM,isSiteEditRuntimeTextTag as JM}from"@vcp-dev/contracts/site-edit-runtime-capability";var rf={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 zS=typeof wc=="function"?wc:wc.default,HS=typeof Oc=="function"?Oc:Oc.default,WS=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),GS="suppressHydrationWarning",YS=new Set(["SiteEditBootstrap"]);function ZS(e){let t=ev(e.file,e.projectRoot);if(!qS(e.source)||_n(t))return{code:e.source,elements:[]};let n=e.attributes??rf,r=cf.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=nv(r,t);return HS(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!ov(c)||lf(a,n.key))return;let l=sv(s)??"default",u=cv(s),d=XS(t,l,u),f=es(c)??"unknown",g=tv(c)?"jsx":"component-call";if(g==="component-call"&&!av(s.node.children)&&YS.has(f))return;let p=g==="component-call"&&rv(f,i);iv(a,n.key,d),p&&of(a,nf),QS(s)&&of(a,GS),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:zS(r,{jsescOption:{minimal:!0}}).code,elements:o}}function QS(e){return!e.findParent(t=>t.isJSXElement())}function qS(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function ev(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 tv(e){return Be.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function es(e){return Be.isJSXIdentifier(e)?e.name:Be.isJSXMemberExpression(e)?df(e):null}function nv(e,t){let n=new Set;for(let r of e.program.body)if(!(!Be.isImportDeclaration(r)||!yr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function rv(e,t){let n=e.split(".")[0]??e;return t.has(n)}function ov(e){let t=es(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!WS.has(t)}function lf(e,t){return e.attributes.some(n=>Be.isJSXAttribute(n)&&Be.isJSXIdentifier(n.name,{name:t}))}function iv(e,t,n){uf(e,Be.jsxAttribute(Be.jsxIdentifier(t),Be.stringLiteral(n)))}function of(e,t){lf(e,t)||uf(e,Be.jsxAttribute(Be.jsxIdentifier(t),null))}function uf(e,t){let n=e.attributes.findIndex(r=>Be.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function df(e){return`${Be.isJSXIdentifier(e.object)?e.object.name:df(e.object)}.${e.property.name}`}function sv(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&Be.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 av(e){return e.some(t=>Be.isJSXElement(t)||Be.isJSXFragment(t))}var sf=new WeakMap,qi=new WeakMap,Fc=new WeakMap;function cv(e){let t=sf.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=lv(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return sf.set(e.node,o),o}function lv(e){let t=es(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${af(e,t)}`:`${t}#${af(e,t)}`}function af(e,t){let n=pf(e)??e.getFunctionParent();if(!n)return 0;let r=Fc.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Fc.get(n.node);o||(o=new Map,Fc.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()?ts(n):uv(n);for(let c of a)if(es(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 uv(e){let t=qi.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!pf(r)&&n.push(r)}}),qi.set(e.node,n),n}function pf(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 ts(e){let t=qi.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(...ts(o));continue}o.isJSXExpressionContainer()&&n.push(...xr(o.get("expression")))}return qi.set(e.node,n),n}function xr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return ts(e);if(e.isParenthesizedExpression())return xr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return xr(e.get("right"));if(e.isConditionalExpression())return[...xr(e.get("consequent")),...xr(e.get("alternate"))];if(e.isCallExpression()&&pv(e.node)){let t=e.get("arguments")[0];return dv(t)}return[]}function dv(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return ts(t);if(t.isParenthesizedExpression())return xr(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?xr(r):[]}return[]}function pv(e){return Be.isMemberExpression(e.callee)&&Be.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as hF,SiteEditPatchPlanSchema as yF}from"@vcp-dev/contracts";function br(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 ns(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 rs(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}:{}})),...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{},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 os(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:fv(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 is(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:br(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 fv(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 NO,computeSiteEditCompositionKey as _O,getSiteEditSourceDeleteProtectionReason as PO,isSiteEditTextSourcePath as AO,parseSiteEditRepeatInstanceKey as TO,SITE_EDIT_SOURCE_DELETE_CAPABILITY as wO,stripSiteEditRepeatInstanceKeys as At}from"@vcp-dev/contracts";import ec from"node:path";import{parse as OO}from"yaml";import jc from"node:path";import{TextDecoder as gv}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as mf,SITE_EDIT_SOURCE_ALLOWED_DIRS as gf,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as hf,SiteEditCompositionContextSchema as hv,SiteEditSourceFileResponseSchema as Lc,SiteEditSourceLocationSchema as yv,SiteEditSourcePathSchema as ss,SiteEditSourceTreeResponseSchema as xv,isSiteEditTextSourcePath as bv}from"@vcp-dev/contracts";import{createHash as mv}from"node:crypto";var Ao=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ve(e){return`sha256:${mv("sha256").update(e).digest("hex")}`}var Ev=[...hf,...mf,...gf];function $c(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return hv.parse(e.composition)}var Dc=2e3,Mc=12,Bc=24*1024*1024,ff=512*1024,Sv=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),vv={".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"},Iv={".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"},kv=new gv("utf-8",{fatal:!0});async function as(e,t={}){let n=$c(t),{files:r,truncated:o}=await Tv(e,t),i=Fv(r.map(s=>s.metadata));return xv.parse({composition:n,nodes:i,defaultPath:Lv(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function cs(e,t,n={}){let r=$c(n),o=ss.parse(t.path),i=await Cv(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Uc(o)){let a=bf(o),c=await _v(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Lc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Vc(e,o);return s.ok?Lc.parse({composition:r,path:o,kind:"text",language:Ef(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):Lc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Vc(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Rv(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 Rv(e){if(e.includes(0))return null;try{return kv.decode(e)}catch{return null}}async function Cv(e,t,n){if(!Pv(t,n))return null;let r=await Nv(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Nv(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=yf(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(Uc(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function _v(e,t){if(!Sv.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>ff)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>ff?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Pv(e,t){return hf.some(n=>n===e)||mf.some(n=>n===e)||gf.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ss.safeParse(n);return r.success&&r.data===e})}function ls(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return yv.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 yf(e){return Array.isArray(e)?{files:e}:e}function Av(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Tv(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=yf(await e.listFiles({roots:wv(t),maxFiles:Dc+1,maxDepth:Mc,maxTotalBytes:Bc+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=ss.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Mc){o.add("max-depth");continue}if(r.size>=Dc){o.add("max-files");break}if(i+a.sizeBytes>Bc){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:Ov(l,a.sizeBytes,$c(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Av([...o]),maxFiles:Dc,maxDepth:Mc,maxTotalBytes:Bc}}:{}}}function wv(e){let t=new Set(Ev);for(let n of e.routeEntryFiles??[]){let r=ss.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function Ov(e,t,n){return Uc(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:bf(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Ef(e),sizeBytes:t,readonly:!1}}function Fv(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 xf(t)}function xf(e){return e.map(t=>t.kind==="directory"?{...t,children:xf(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Lv(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 Uc(e){return!bv(e)}function bf(e){let t=jc.posix.extname(e).toLowerCase();return!t&&jc.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":vv[t]??"application/octet-stream"}function Ef(e){let t=jc.posix.extname(e).toLowerCase();return Iv[t]??"plaintext"}import*as Sr from"@babel/types";import Kc from"@babel/traverse";import*as dn from"@babel/types";function Ue(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(dn.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(dn.isIdentifier(s)&&s.name==="Fragment"||dn.isStringLiteral(s)&&s.value==="Fragment")&&Sf(i.parentPath)}if(!dn.isJSXMemberExpression(t)||!dn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!dn.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())&&Sf(r.parentPath)}function Sf(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Xn=typeof Kc=="function"?Kc:Kc.default,us=new WeakMap,ds=new WeakMap;function pn(e,t){let n=Pc(e,t);if(!n.ok)return _c(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=xe(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}}:_c(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function xe(e,t){return t.kind==="jsx-node"?Rf(e,t):t.kind==="jsx-attribute"?Vv(e,t):t.kind==="value"?Uv(e,t):t.kind==="expression"?Kv(e,t):t.kind==="directive"?Jv(e,t):t.kind==="export"?Xv(e,t):{ok:!1,diagnostic:gr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Rf(e,t){return t.strategy==="source-range"?Dv(e,t):Mv(e,t)}function Dv(e,t){let n=null;if(Xn(e,{JSXElement(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return qe("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!rI(r.path,t.expectedIdentity)?qe("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Mv(e,t){if(t.structuralPath===""){let r=jv(e,t.component);if(r){let o=$v(r);if(o)return o}}let n=null;return Xn(e,{JSXElement(r){if(wo(r)!==t.component||Xc(r)!==t.structuralPath)return;let i=Ye("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(wo(r)!==t.component||Xc(r)!==t.structuralPath)return;let i=Ye("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Bv(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:qe("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Bv(e,t,n){let r=null;return Xn(e,{JSXElement(o){if(wo(o)!==t||!Er(o.node,n))return;let i=Ye("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(wo(o)!==t||!Er(o.node,n))return;let i=Ye("jsx-node",o);i&&(r=i,o.stop())}}),r}function jv(e,t){let n=null;return Xn(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 $v(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 qe("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?qe("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 qe("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Vv(e,t){let n=Rf(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>oI(c,t.name));if(!s||!s.isJSXAttribute())return qe("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ye("jsx-attribute",s);return a?{ok:!0,match:a}:qe("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Uv(e,t){let n=zv(e,t);if(!n.ok)return n;let r=Hv(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!An(r.match.path.node.loc,t.expectedRange)?qe("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Kv(e,t){let n=null;return Xn(e,{Identifier(r){if(!qv(r))return;let o=If(r);if(!o||!kf(o,t))return;let i=Ye("expression",r);i&&(t.expectedRange&&!An(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=If(r);if(!o||!kf(o,t))return;let i=Ye("expression",r);i&&(t.expectedRange&&!An(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:qe("expression","locator-miss","Expression not found")}function Jv(e,t){let n=null;return Xn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!An(i.node.loc,t.expectedRange))return;let s=Ye("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:qe("directive","locator-miss",`Directive '${t.value}' not found`)}function Xv(e,t){let n=null;return Xn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=Ye("export",c);if(!f||t.expectedRange&&!An(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=zc(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ye("export",u);if(!d||t.expectedRange&&!An(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=zc(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!An(s.node.loc,t.expectedRange))return;let a=Ye("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ye("export",o);i&&(t.expectedRange&&!An(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:qe("export","export-not-found",`Export '${nI(t)}' not found`)}function zv(e,t){let n=null;return Xn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Er(r.node,t.root.sourceRange))return;let o=Ye("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 p=Ye("value",g);if(!p)return;n=p,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 f=Ye("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=zc(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ye("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ye("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:qe("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 Hv(e,t){let n=Jc(e);for(let o of t){if(n=Jc(n),o.kind==="property"){if(!n.isObjectExpression())return qe("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return qe("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>iI(l,o.name));if(!c||!c.isObjectProperty())return qe("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return qe("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return qe("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return qe("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Jc(n);let r=Ye("value",n);return r?{ok:!0,match:r}:qe("value","locator-miss","Resolved value has no source range")}function Jc(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ye(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 Er(e,t){return An(e.loc,t)}function An(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 Xc(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ue(n)){let o=Nf(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${vf(n,o)}`):t.unshift(`${o}#${vf(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||Zv(n.parentPath)&&!Qv(n.parentPath))break;n=n.parentPath}return t.join("/")}function vf(e,t){let n=Cf(e)??e.getFunctionParent();if(!n)return 0;let r=us.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=us.get(n.node)?.get(t);if(!i){let a=us.get(n.node);a||(a=new Map,us.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?To(n):Wv(n);for(let a of s)if(Nf(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function Wv(e){let t=ds.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Cf(r)&&n.push(r)}}),ds.set(e.node,n),n}function Cf(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ue(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function To(e){let t=ds.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(Ue(o)){n.push(...To(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...To(o));continue}o.isJSXExpressionContainer()&&n.push(...Pn(o.get("expression")))}return ds.set(e.node,n),n}function Pn(e){if(e.isJSXElement())return Ue(e)?To(e):[e];if(e.isJSXFragment())return To(e);if(e.isParenthesizedExpression())return Pn(e.get("expression"));if(e.isLogicalExpression()&&Gv(e.node.operator))return Pn(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(...Pn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Pn(a));break}}return i}else if(o.node&&o.isExpression())return Pn(o)}}}}return e.isConditionalExpression()?[...Pn(e.get("consequent")),...Pn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Pn(t)):[]}function Gv(e){return e==="&&"||e==="||"||e==="??"}function Nf(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?Yv(e.name):null}function Yv(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 wo(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 Zv(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function Qv(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 qv(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function If(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 kf(e,t){return e.base===t.base&&eI(e.path,t.path??[])}function eI(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 tI(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function nI(e){return e.exportKind==="named"?e.name:e.exportKind}function qe(e,t,n,r){return{ok:!1,diagnostic:gr(t,n,e,r)}}function rI(e,t){return wo(e)!==t.component?!1:Xc(e)===t.structuralPath}function oI(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function zc(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function iI(e,t){return e.isObjectProperty()?tI(e.node)===t:!1}import*as Pf from"@babel/parser";import{arrayExpression as uI,booleanLiteral as dI,identifier as pI,jsxAttribute as fI,jsxExpressionContainer as mI,jsxIdentifier as gI,nullLiteral as hI,numericLiteral as yI,objectExpression as xI,objectProperty as bI,stringLiteral as Wc}from"@babel/types";import Hc from"@babel/generator";var sI=typeof Hc=="function"?Hc:Hc.default;function aI(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 ps(e){let{ast:t,source:n}=e;try{let r=aI(n),i=sI(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=lI(i,r)),{ok:!0,source:i}}catch(r){return Z(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function _f(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 Oo(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:_f(e),afterSourceHash:_f(t),inverse:n.inverse}}}function Ae(e,t,n){let r=ps({ast:e,source:t});return r.ok?Oo(t,r.source,n):r}function je(e,t){let n=_o(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function fs(e,t){return ps({ast:e,source:t})}function EI(e,t,n){let r=xe(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Kr(e,t,n){let r=EI(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:Z(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function zn(e){return typeof e=="string"?Wc(e):typeof e=="number"?yI(e):typeof e=="boolean"?dI(e):e===null?hI():Array.isArray(e)?uI(e.map(t=>zn(t))):xI(Object.entries(e).map(([t,n])=>{let r=bI(Gc(t),zn(n));return t==="__proto__"&&(r.computed=!0),r}))}function SI(e){return typeof e=="string"?Wc(e):mI(zn(e))}function Fo(e,t){return fI(gI(e),SI(t))}function ms(e,t){try{let r=Pf.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:Z(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:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Gc(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?pI(e):Wc(e)}function gs(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=je(t,"jsx-node");if(!i.ok)return i.result;let s=xe(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=vI(s.match.path)[r];if(!c)return Z(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]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Sr.jsxText(d)]:[],Sr.jsxExpressionContainer(Sr.stringLiteral("")),...f?[Sr.jsxText(f)]:[]]);break}let u=II(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 Ae(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function vI(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=kI(r.get("expression"));o.length>0&&t.push(...o)}}return t}function II(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function kI(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 Yc}from"@babel/types";function vr(e){let{source:t,locator:n}=e,r=je(t,"jsx-node");if(!r.ok)return r.result;let o=xe(r.ast,n);return o.ok?(RI(o.match.path),Ae(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function RI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Yc());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Yc());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Yc());return}e.remove()}import{cloneNode as CI}from"@babel/types";function Jr(e){let t=je(e.source,"jsx-node");if(!t.ok)return t.result;let n=xe(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ms(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(CI(r.node,!0)),Ae(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as MI}from"@babel/types";import Zc from"@babel/traverse";import*as ue from"@babel/types";function Lo(e,t,n){return`${e}::${t}::${n}`}var M={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 NI=typeof Zc=="function"?Zc:Zc.default;function Ut(e,t,n,r){if(!e.ok)return e;let o=Vt(n,t);if(!o)return e;let i=_I(t,o,r);return i?{...e,selectionRef:i}:e}function _I(e,t,n){let r=PI(e,t);if(!r)return;let o=n.sourceLocator?Af(n.sourceLocator):void 0,i=n.targetParentLocator?Af(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??TI(r)??i?.component??o?.component;if(!(!s||!a))return{key:Lo(s,a,wI(r))}}function Af(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function PI(e,t){let n=Df(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Df(e,t){let n=null;return NI(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Vt(e,t){if(!e)return null;if(ue.isJSXElement(e))return DI(t,e)?Tf(e.children,t):e;if(ue.isJSXFragment(e))return Tf(e.children,t);if(ue.isJSXExpressionContainer(e)||ue.isParenthesizedExpression(e)||ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSTypeAssertion(e)||ue.isTSNonNullExpression(e))return Vt(e.expression,t);if(ue.isLogicalExpression(e))return Vt(e.right,t);if(ue.isConditionalExpression(e))return Vt(e.consequent,t)??Vt(e.alternate,t);if(ue.isCallExpression(e)||ue.isOptionalCallExpression(e))return Mf(e)?AI(e.arguments[0],t):null;if(ue.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Vt(n,t);if(r)return r}return null}function Tf(e,t){for(let n of e){let r=Vt(n,t);if(r)return r}return null}function AI(e,t){return!e||!ue.isArrowFunctionExpression(e)&&!ue.isFunctionExpression(e)?null:ue.isBlockStatement(e.body)?Do(e.body.body,t):Vt(e.body,t)}function Do(e,t){for(let n of e){if(ue.isReturnStatement(n)){let r=Vt(n.argument,t);if(r)return r;continue}if(ue.isBlockStatement(n)){let r=Do(n.body,t);if(r)return r;continue}if(ue.isIfStatement(n)){let r=wf(n.consequent,t);if(r)return r;let o=n.alternate?wf(n.alternate,t):null;if(o)return o;continue}if(ue.isSwitchStatement(n))for(let r of n.cases){let o=Do(r.consequent,t);if(o)return o}}return null}function wf(e,t){return ue.isBlockStatement(e)?Do(e.body,t):Do([e],t)}function TI(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(ue.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&ue.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 Of=new WeakMap,Ff=new WeakMap,Qc=new WeakMap;function wI(e){let t=Of.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=OI(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Of.set(e.node,o),o}function OI(e){let t=Bf(e.node.openingElement.name);return!t||Ue(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Lf(e,t)}`:`${t}#${Lf(e,t)}`}function Lf(e,t){let n=FI(e);if(!n)return 0;let r=Qc.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Qc.get(n.node);o||(o=new Map,Qc.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Ir(n))if(Bf(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 FI(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ue(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ir(e){let t=Ff.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(Ue(o)){n.push(...Ir(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ir(o));continue}o.isJSXExpressionContainer()&&n.push(...fn(o.get("expression")))}return Ff.set(e.node,n),n}function fn(e){if(e.isJSXElement())return Ue(e)?Ir(e):[e];if(e.isJSXFragment())return Ir(e);if(e.isParenthesizedExpression())return fn(e.get("expression"));if(e.isLogicalExpression())return fn(e.get("right"));if(e.isConditionalExpression())return[...fn(e.get("consequent")),...fn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:fn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Mf(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?LI(n):[]}return[]}function LI(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ue(t)?Ir(t):[t];if(t.isJSXFragment())return Ir(t);if(t.isParenthesizedExpression())return fn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return fn(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(...fn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...fn(o)),n}return n}function Mf(e){let t=e.callee;return(ue.isMemberExpression(t)||ue.isOptionalMemberExpression(t))&&ue.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function DI(e,t){let n=Df(e,t);return n?Ue(n):!1}function Bf(e){return ue.isJSXIdentifier(e)?e.name:ue.isJSXMemberExpression(e)?jf(e):ue.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function jf(e){return`${ue.isJSXIdentifier(e.object)?e.object.name:jf(e.object)}.${e.property.name}`}function Hn(e,t){if(t.parentPath===e&&t.listKey==="children"&&qc(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!qc(n))return null;let r=n;for(;r&&r!==e;){if(!qc(r)||!Ue(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function qc(e){return e.isJSXElement()||e.isJSXFragment()}function Kt(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=je(t,"jsx-node");if(!a.ok)return a.result;let c=xe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return Z(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 b=c.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ms(t,r.jsx);if(!u.ok)return u.result;let d=MI(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=b=>s?Ut(b,a.ast,d,g):b;if(o==="append")return f.push(d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=xe(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=Hn(c.match.path,h.match.path);if(!y)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let x=l.node.children,E=x.findIndex(b=>b===h.match.path.node);return E===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as $f from"@babel/parser";import{cloneNode as BI}from"@babel/types";function hs(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=je(t,"jsx-node");if(!a.ok)return a.result;let c=jI(t,r);if(!c.ok)return c.result;let l=xe(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Z(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=xe(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=Hn(l.match.path,x.match.path);if(!E)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=x.match.path.node}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=BI(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},h=x=>s?Ut(x,a.ast,f,p):x;if(o==="append")return g.push(f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function jI(e,t){try{let r=$f.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:Z(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as $I,nullLiteral as el}from"@babel/types";import*as Wn from"@babel/types";import*as Vf from"@babel/types";function Mo(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Vf.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function kr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=je(t,"jsx-node");if(!a.ok)return a.result;let c=xe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=xe(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Z(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 b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=xe(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let v=b.match.path.isJSXElement()?Mo(b.match.path,l.match.path):b.match.path,_=Hn(l.match.path,v);if(!_)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=_,d=v}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return Z(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?Mo(c.match.path,l.match.path):c.match.path,p=$I(g.node,!0);if(!Wn.isJSXElement(p)&&!Wn.isJSXExpressionContainer(p)&&!Wn.isJSXFragment(p)&&!Wn.isJSXText(p))return Z(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 Z(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");VI(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),Ut(fs(a.ast,t),a.ast,p,x);if(o==="prepend")return y.unshift(p),Ut(fs(a.ast,t),a.ast,p,x);let E=f-(h!==-1&&h<f?1:0);return y.splice(o==="before"?E:E+1,0,p),Ut(fs(a.ast,t),a.ast,p,x)}function VI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(el());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(el());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(el());return}e.remove()}import*as Uf from"@babel/parser";import{cloneNode as UI,nullLiteral as tl}from"@babel/types";function ys(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=je(t,"jsx-node");if(!c.ok)return c.result;let l=KI(t,s);if(!l.ok)return l.result;let u=xe(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=xe(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return Z(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let b=d.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let b=xe(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let v=Hn(d.match.path,b.match.path);if(!v)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=v,g=b.match.path.node}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return Z(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,h=UI(l.node,!0);JI(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=p.children;if(o==="append")return x.push(h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return x.unshift(h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let E=x.findIndex(b=>b===g);return E===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function KI(e,t){try{let r=Uf.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:Z(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function JI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(tl());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(tl());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(tl());return}e.remove()}import{SiteEditSetPropsParamsSchema as XI,classifySiteEditPropertyName as zI}from"@vcp-dev/contracts";import*as Xr from"@babel/types";function xs(e){let t=XI.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return Z(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=je(e.source,"jsx-node");if(!n.ok)return n.result;let r=Kr(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=zI(a.name);if(c.owner!=="generic")return Z(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(Xr.isJSXAttribute),s=new Map;for(let a of i){let c=HI(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 Z(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=Fo(a.name,a.value).value;c?c.value=l:o.attributes.push(Fo(a.name,a.value))}return Ae(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function HI(e){return Xr.isJSXIdentifier(e.name)?e.name.name:Xr.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as WI}from"@vcp-dev/contracts";import*as te from"@babel/types";var Kf=["prefetch","replace","scroll","locale","onNavigate"],GI=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function YI(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>te.isJSXAttribute(n)&&te.isJSXIdentifier(n.name)&&GI.test(n.name.name)))return!0;t=t.parentPath}return!1}function bs(e){let t=je(e.source,"jsx-node");if(!t.ok)return t.result;let n=Kr(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=WI.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Tn(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=rk(s.name);if(!a)return Tn(e.source,"Unsupported JSX link tag");if(s.attributes.some(te.isJSXSpreadAttribute))return Tn(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!te.isJSXAttribute(p))continue;let h=rl(p);if(!h)return Tn(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(p),c.set(h,y)}if([...c.values()].some(p=>p.length>1))return Tn(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!nk(l))return Tn(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:qI(o,s.name);if(!u&&!d)return Tn(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&YI(o))return Tn(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let p=ek(t.ast,o);if(!p.ok)return Tn(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=te.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=te.jsxIdentifier("a")),tk(t.ast,d,o)}else f&&u&&(s.name=te.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=te.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Kf.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&Kf.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!te.isJSXAttribute(p))return!0;let h=rl(p);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(te.jsxAttribute(te.jsxIdentifier("href"),te.stringLiteral(e.link.href))),ZI(s,e.changes),Ae(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function ZI(e,t){for(let n of t){let r=e.attributes.find(s=>te.isJSXAttribute(s)&&rl(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?te.stringLiteral(n.value):te.jsxExpressionContainer(nl(n.value)),i=te.jsxAttribute(te.jsxIdentifier(n.name),o);r&&te.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function nl(e){return e===null?te.nullLiteral():typeof e=="string"?te.stringLiteral(e):typeof e=="number"?te.numericLiteral(e):typeof e=="boolean"?te.booleanLiteral(e):Array.isArray(e)?te.arrayExpression(e.map(t=>nl(t))):typeof e=="object"?te.objectExpression(Object.entries(e).map(([t,n])=>te.objectProperty(te.isValidIdentifier(t)?te.identifier(t):te.stringLiteral(t),nl(n)))):te.nullLiteral()}function QI(e){return te.isImportDefaultSpecifier(e)||te.isImportSpecifier(e)&&e.importKind!=="type"&&(te.isIdentifier(e.imported,{name:"default"})||te.isStringLiteral(e.imported,{value:"default"}))}function Jf(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(te.isIdentifier(e.node.imported,{name:"default"})||te.isStringLiteral(e.node.imported,{value:"default"}))}function qI(e,t){if(!te.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Jf(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function ek(e,t){let n=e.program.body.filter(c=>te.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(QI);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=te.importDefaultSpecifier(te.identifier(s));if(r)r.specifiers.unshift(a);else{let c=te.importDeclaration([a],te.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&te.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function tk(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Jf(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 nk(e){return!e.value||te.isStringLiteral(e.value)}function rk(e){return te.isJSXIdentifier(e)?e.name:null}function rl(e){return te.isJSXIdentifier(e.name)?e.name.name:null}function Tn(e,t){return Z(e,"unsupported-syntax",t,"jsx-node")}import*as ot from"@babel/types";import{classifySiteEditPropertyName as Xf}from"@vcp-dev/contracts";function Es(e){let t=Xf(e.name),n=Xf(e.property);if(t.owner!=="generic"||n.owner!=="generic")return Z(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!zf(e.object))return Z(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return Z(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=je(e.source,"jsx-node");if(!r.ok)return r.result;let o=Kr(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ot.isJSXAttribute(l)&&ik(l)===e.name);if(s.length>1)return Z(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=ok(e.object,e.property),c=s[0];if(c)c.value=ot.jsxExpressionContainer(a);else{let l=Fo(e.name,"");l.value=ot.jsxExpressionContainer(a),i.attributes.push(l)}return Ae(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function ok(e,t){return zf(t)?ot.memberExpression(ot.identifier(e),ot.identifier(t)):ot.memberExpression(ot.identifier(e),ot.stringLiteral(t),!0)}function zf(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function ik(e){return ot.isJSXIdentifier(e.name)?e.name.name:ot.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as ak,identifier as Bo,importDeclaration as ck,importDefaultSpecifier as lk,importNamespaceSpecifier as uk,importSpecifier as dk,isImportDefaultSpecifier as Hf,isImportNamespaceSpecifier as Wf,isImportSpecifier as Gf,stringLiteral as pk}from"@babel/types";function Jt(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!Sk(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return Z(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=xk(r);if(!i.ok)return Z(t,"unsupported-syntax",i.message);let s=je(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(x=>{let E=vk(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(tm(y)));if(d.length===0)return Oo(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=bk(c.body),g=d.find(y=>f.has(ol(y)));if(g)return Z(t,"unsupported-syntax",`Import local binding already exists: ${ol(g)}`);let p=yk(d);if(p.reduce((y,x)=>y+x.length,0)!==d.length)return Z(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!qf(Zf(y)))return Z(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>fk(E,y));if(x)mk(x,y);else{let E=ck(Yf(y),pk(n));Ek(c.body,E),l.push(E)}}return Ae(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function fk(e,t){return e.importKind==="type"?!1:qf(hk(gk(e),Zf(t)))}function mk(e,t){let n=!1,r=new Set(e.specifiers.map(o=>il(o)));for(let o of Yf(t)){let i=il(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return em(e.specifiers),{changed:n}}function Yf(e){let t=e.map(n=>{switch(n.kind){case"named":return dk(n.local?Bo(n.local):Bo(n.imported),Bo(n.imported));case"default":return lk(Bo(n.local));case"namespace":return uk(Bo(n.local));default:return n}});return em(t),t}function Zf(e){let t=Qf();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 gk(e){let t=Qf();for(let n of e.specifiers)Hf(n)?t.defaultLocals.add(n.local.name):Wf(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Qf(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function hk(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function qf(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function em(e){let t=[...e.filter(n=>Hf(n)),...e.filter(n=>Wf(n)),...e.filter(n=>Gf(n))];e.splice(0,e.length,...t)}function yk(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 xk(e){let t=new Map,n=new Map;for(let r of e){let o=tm(r);if(t.has(o))continue;let i=ol(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 bk(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(ak(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 Ek(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 Sk(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 tm(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 ol(e){return e.kind==="named"?e.local??e.imported:e.local}function vk(e,t){return e.importKind==="type"||Gf(t)&&t.importKind==="type"?null:il(t)}function il(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 zr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!kk(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return Z(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=je(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 Oo(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),Ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>Ik(u,d))),l.specifiers.length===0&&a.body.splice(c,1),Ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Ik(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 kk(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 jo(e){let{source:t,locator:n,next:r}=e,o=ks(t,n);return o.ok?(o.path.replaceWith(zn(r)),Ae(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Ss(e){let{source:t,locator:n,index:r,value:o}=e,i=ks(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?Z(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?Z(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,zn(o)),Ae(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):Z(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function vs(e){let{source:t,locator:n,index:r}=e,o=ks(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?Z(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?Z(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),Ae(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):Z(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Is(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ks(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return Z(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return Z(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 Z(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),Ae(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ks(e,t){let n=je(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=xe(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 ut from"@babel/types";function Rs(e){let t=je(e.source,"value");if(!t.ok)return t.result;let n=xe(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return Z(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ut.isSpreadElement(a)||ut.isObjectProperty(a)&&a.computed))return Z(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ut.isObjectProperty(a)&&Rk(a.key)===e.name);if(o.length>1)return Z(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ut.unaryExpression("void",ut.numericLiteral(0)):zn(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ut.objectProperty(Gc(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return Ae(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Rk(e){return ut.isIdentifier(e)?e.name:ut.isStringLiteral(e)?e.value:ut.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as Ck,isSiteEditRuntimeVoidElementTag as Nk}from"@vcp-dev/contracts/site-edit-runtime-capability";function Hr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function _k(e,t,n){let r=Hr(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(v=>({kind:v.kind,message:v.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&Nk(u),g=d||Ck(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(v=>v.editable);f&&!s.some(v=>v.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(v=>v.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||p);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function Cs(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,_k(r,e,t));return n}function sl(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Pk(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:rm(r),version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:nm(e.route.source,o),valueRaw:s?nm(e.route.source,s):null,attrRange:rm(o),diagnostics:[]}}function om(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 Pk(e,t){let n=un({source:e,profile:hr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=xe(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Ak(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function im(e){let t=un({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 nm(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function rm(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 Ak(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function sm(){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 Tk}from"node:crypto";import Ns from"node:fs/promises";import al from"node:path";import{setTimeout as wk}from"node:timers/promises";var Ok={async mkdir(e,t){await Ns.mkdir(e,t)},async writeFile(e,t,n){await Ns.writeFile(e,t,n)},async rename(e,t){await Ns.rename(e,t)},async rm(e,t){await Ns.rm(e,t)}},Fk=new Set(["EACCES","EBUSY","EPERM"]),Lk=[10,20,40,80,160];async function Dk(e,t,n){for(let r of Lk)try{await e.rename(t,n);return}catch(o){if(!Mk(o))throw o;await wk(r)}await e.rename(t,n)}function Mk(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Fk.has(e.code)}async function _s(e,t,n=Ok){let r=al.dirname(e),o=al.basename(e),i=al.join(r,`.${o}.${process.pid}.${Tk()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Dk(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import cl from"@babel/traverse";import*as k from"@babel/types";import*as Ne from"@babel/types";function mn(e,t={}){if(Ne.isTSAsExpression(e)||Ne.isTSSatisfiesExpression(e)||Ne.isTSNonNullExpression(e)||Ne.isTypeCastExpression(e)||Ne.isParenthesizedExpression(e))return mn(e.expression,t);if(Ne.isStringLiteral(e))return{status:"resolved",value:e.value};if(Ne.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Ne.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Ne.isNullLiteral(e))return{status:"resolved",value:null};if(Ne.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(Ne.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Ne.isUnaryExpression(e)&&e.operator==="void"&&Ne.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Ne.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Ne.isSpreadElement(r))return{status:"unresolved"};let o=mn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Ne.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Ne.isObjectProperty(r)||r.computed||!Ne.isExpression(r.value))return{status:"unresolved"};let o=Bk(r.key);if(o===null)return{status:"unresolved"};let i=mn(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 Ne.isMemberExpression(e)||Ne.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Bk(e){return Ne.isIdentifier(e)?e.name:Ne.isStringLiteral(e)?e.value:Ne.isNumericLiteral(e)?String(e.value):null}var jk=typeof cl=="function"?cl:cl.default;function yt(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 $k(e){return/^[A-Z]/.test(e)}function fl(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 Gr(e){return k.isJSXFragment(e)}function cm(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?lm(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function lm(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${lm(e.object)}.${e.property.name}`:e.property.name}function Vk(e){return e.split(".")[0]??e}function Uk(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 Kk(){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 Jk(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 wn(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)?wn(n.value,t):k.isRestElement(n)&&wn(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?wn(n.argument,t):wn(n,t));return t}return k.isAssignmentPattern(e)?(wn(e.left,t),t):(k.isRestElement(e)&&wn(e.argument,t),t)}function en(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function $o(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 Xk(e,t,n){e.set(t,{resolved:!0,value:n})}function ml(e,t){e.set(t,{resolved:!1})}function um(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 tt(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return tt(e.expression,t,n);if(k.isLogicalExpression(e))return Ps([tt(e.left,t,n),tt(e.right,t,n)]);if(k.isBinaryExpression(e))return Ps([k.isExpression(e.left)?tt(e.left,t,n):null,k.isExpression(e.right)?tt(e.right,t,n):null]);if(k.isConditionalExpression(e))return Ps([tt(e.consequent,t,n),tt(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return Ps(e.expressions.filter(k.isExpression).map(i=>tt(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=Gn(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:en(e,t),base:o.name,path:r}:null}function Ps(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 Gn(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=$o(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=Gn(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=$o(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Gn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=tt(e,"",t);if(!n)return;let r=$o(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=um(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return pm(e,t)??void 0}function dm(e,t,n){let r=tt(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:en(e,n),source:null}:null;let o=$o(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?um(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 ll(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Kk(),parentStack:[],valueScopes:i,importMap:o}}function dl(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of wn(o.id))ml(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=Gn(o.init,t);i!==void 0&&Xk(n,o.id.name,i)}}function zk(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 Hk(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:yt(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:yt(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:yt(i),editable:!0,source:null}):r.push({index:o++,value:en(s,n),sourceRange:yt(i),editable:!0,source:tt(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=dm(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:yt(i),editable:!0,source:s.source})}return r}function Wk(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=Yk(i.name);if(!s)continue;let a=en(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:yt(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:yt(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=Gn(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?pm(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:yt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=dm(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:rR(c),sourceRange:yt(i),source:tt(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=Zk(i.value.expression,t),d=tt(i.value.expression,n,t),f=l?.value??en(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:yt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function Gk(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:en(r.argument,n),sourceRange:yt(r),order:o,source:tt(r.argument,n,t)}])}function Yk(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Zk(e,t){return mn(e,{resolveIdentifier(n){let r=$o(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=Gn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function pm(e,t){let n=Wr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Wr(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=Gn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=Wr(e.consequent,t),r=Wr(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Gn(e.left,t);return n===!1||n===null?[]:Wr(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=Wr(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=qk(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=Qk(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=Wr(o,t);if(!i)return null;r.push(...i)}return r}return null}function Qk(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function qk(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function eR(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 tR(e,t){for(let n of t){let r=eR(e,n);if(r)return r}return null}function nR(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function rR(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function oR(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 ul(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function iR(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function sR(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function am(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:en(e,n),collectionSource:tt(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 On(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(fl(e))return Fs(e.children,t,n);let r=ws(e,t,n);return r?[r]:[]}return Gr(e)?Os(e,t,n):k.isParenthesizedExpression(e)?On(e.expression,t,n):k.isExpression(e)?Ls(e,t,n):[]}function As(e,t,n){let r=new Map;for(let o of e.params)for(let i of wn(o))ml(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return On(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return fm(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function fm(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){dl([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...On(s.init,t,n))}continue}r.push(...pl(o,t,n))}return r}function pl(e,t,n){if(k.isReturnStatement(e))return e.argument?On(e.argument,t,n):[];if(k.isBlockStatement(e))return Rr(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Rr(e.consequent.body,t,n):pl(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Rr(e.alternate.body,t,n):pl(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Rr(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Rr(e.block.body,t,n);return e.handler&&r.push(...Rr(e.handler.body.body,t,n)),e.finalizer&&r.push(...Rr(e.finalizer.body,t,n)),r}return[]}function Rr(e,t,n){let r=new Map;t.valueScopes.push(r);try{return fm(e,t,n)}finally{t.valueScopes.pop()}}function Ts(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:yt(r),sourceCandidates:i&&i.length>0?i:void 0})}function aR(e,t,n,r){let o=tR(e.openingElement,["items","dataSource","data"]),i={key:t,tag:cm(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=nR(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(iR(a)&&ul(c)){let l=As(c,n,r),u=am(o,c,r,n);Ts(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(sR(a)){let l=ul(c)?As(c,n,r):On(c,n,r);Ts(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!ul(s.expression))continue;let a=As(s.expression,n,r),c=am(o,s.expression,r,n);Ts(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ws(e,t,n){let r=cm(e.openingElement);if(r==="Fragment"||fl(e))return Fs(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=$k(r),a;if(s){let v=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${v}`}else{let v=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${v}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Lo(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=Hk(e.children,t,n),p=Wk(e.openingElement,t,n),h=Gk(e.openingElement,t,n),y,x,E=!1;if(s){let v=t.importMap.get(r)??t.importMap.get(Vk(r));v&&(y=v.specifier,x=v.exportName,E=yr(v.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:yt(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:f,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),aR(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),cR(e.children,t,n),t.parentStack.pop()),u}function Os(e,t,n){return Fs(e.children,t,n)}function Fs(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(fl(o))r.push(...Fs(o.children,t,n));else{let i=ws(o,t,n);i&&r.push(i)}else Gr(o)?r.push(...Os(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...Ls(o.expression,t,n));return r}function cR(e,t,n){for(let r of e)k.isJSXElement(r)?ws(r,t,n):Gr(r)?Os(r,t,n):k.isJSXExpressionContainer(r)&&Ls(r.expression,t,n)}function lR(e){return e==="&&"||e==="||"||e==="??"}function Ls(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=oR(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:en(r.collection,n),collectionSource:tt(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:yt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...As(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:en(e.test,n),conditionSource:tt(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:yt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...On(e.consequent,t,n)),s.childKeys.push(...On(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&lR(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:en(e.left,n),conditionSource:tt(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:yt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...On(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return Ls(e.expression,t,n);if(k.isJSXElement(e)){let o=ws(e,t,n);return o?[o]:[]}return Gr(e)?Os(e,t,n):[]}function uR(e){let t=e.argument;return t&&(k.isExpression(t)||Gr(t))?t:null}function Vo(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=uR(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(...Vo(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Vo(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(...Vo(o.consequent,i))}}return n}function Ds(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function mm(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!k.traverseFast(r,f=>{if(k.isJSXElement(f)||k.isJSXFragment(f))return k.traverseFast.stop}))return{graph:Ds(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=Jk(r);jk(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=Uk(f);if(!g)return;let p=f.node,h=[];if(k.isArrowFunctionExpression(p))k.isExpression(p.body)||Gr(p.body)?h=[{argument:p.body,statement:k.returnStatement(k.isExpression(p.body)?p.body:null)}]:k.isBlockStatement(p.body)&&(h=Vo(p.body.body));else{let _=p.body;k.isBlockStatement(_)&&(h=Vo(_.body))}if(h.length===0){f.skip();return}let y=new Map;dl(zk(r.program.body),ll(t,g,s,a,u,[y]),y);let x=new Map;for(let _ of p.params)for(let P of wn(_))ml(x,P);let E=k.isBlockStatement(p.body)?p.body.body:[],b=h[0]?.statement??null;for(let _ of E){if(b&&_===b)break;k.isVariableDeclaration(_)&&dl([_],ll(t,g,s,a,u,[y,x]),x)}let v=ll(t,g,s,a,u,[y,x]);for(let _ of h){let P=On(_.argument,v,n);for(let R of P)c.includes(R)||c.push(R);if(_.condition){let R={kind:"conditional-branch",conditionExpression:en(_.condition,n),conditionSource:tt(_.condition,n,v)};Ts(v,"conditional-region","",_.statement,P,[R])}}f.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 gl(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ms(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function gm(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 Bs(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Ke,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(E)||(f.add(E),d.push(x))},p=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],h=new Set;for(;p.length>0;){let x=p.shift(),{file:E,source:b,depth:v,diagnosticEntryFile:_,importStack:P}=x;if(h.has(E))continue;h.add(E),c.set(E,b);let R=o.validationOnly&&v<i?o.validatedImports?.(E,b):void 0,N,A;if(R)N=Ds(E),A=R;else{let z=a(E,b);if(!z.ok){g(Ms(z.diagnostic,_,P));continue}u.set(E,z.module);let Q=o.validationOnly&&v<i?{graph:Ds(E),localImports:z.module.imports.map(ke=>ke.specifier)}:mm(z.module);N=Q.graph,A=Q.localImports}let L=[...new Set([...N.elements.values()].map(z=>z.importedFrom).filter(z=>typeof z=="string"&&Rt(z)))],$=L.length?await gm(L,z=>Zi(E,z,r)):[],U=new Map(L.map((z,Q)=>[z,$[Q]]));for(let z of N.elements.values())if(z.importedFrom&&Rt(z.importedFrom)){let Q=z.importedFrom,ke=U.get(Q);ke.ok?(z.importedFrom=ke.path,_n(ke.path)&&(z.isPublicUiComponent=!0)):yr(Q,E)||g(Ms(ke.diagnostic,_,gl(P,E,Q,ke.diagnostic.path)))}if(l.set(E,N),v>=i)continue;let de=await gm(A,async z=>{if(Yp(z))return null;let Q=U.get(z)??await Zi(E,z,r);if(!Q.ok)return yr(z,E)?null:{diagnostic:Ms(Q.diagnostic,_,gl(P,E,z,Q.diagnostic.path))};let ke=Q.path;if(h.has(ke)||_n(ke))return null;let ct=gl(P,E,z,ke);try{let lt=await n(ke);return{entry:{file:ke,source:lt,depth:v+1,diagnosticEntryFile:_,importStack:ct}}}catch(lt){return{diagnostic:Ms({path:ke,code:"import-read-failed",message:`Failed to read imported file: ${ke}`,details:{fromFile:E,specifier:z,reason:lt instanceof Error?lt.message:String(lt)}},_,ct)}}});for(let z of de)z&&"entry"in z?p.push(z.entry):z&&g(z.diagnostic)}let y=dR(e,l,s,(o.additionalEntries??[]).map(x=>x.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function dR(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 f=s.get(u)??[];s.set(u,[...f,...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 hm(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 $R}from"@vcp-dev/contracts";import{createHash as pR,randomUUID as Rl}from"node:crypto";import He from"node:fs/promises";import Ge from"node:path";var Cm=new WeakMap;function Yr(e){return Cm.get(e)?.()??e.readIndex()}var Xt=1,yl=1,fR=2,mR="index.json",gR="recovery.json",hR="transaction-journal.json",yR="document-version.json",Vs={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},fe={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"},ge=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Fn(){return{entries:new Map,blobSizes:new Map}}function js(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Nm(n,r,t);return n}function Nm(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 _m(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 Pm(e,t={}){let n=FR(e),r=BR(t.limits),o=hl(n),i=LR(n),s=await Ct(i),a=await Ct(o)||s;a||(await CR(n),await NR(n)),a||await jR(n);let c=Fn(),l=await Ks(n,c),u=new Set(a?(await Ws(n)).map(E=>E.stageId):[]);a||await Sm(n,l.entryIds,c);let d=l.digest,f=js(l.entryIds,c),g=async E=>{let{index:b,sizeBytes:v}=await zo(n);if(Dm(b,E),b.digest!==d){let _=Fn();await Om(n,b.entryIds,_,v),f=js(b.entryIds,_),d=b.digest}return{...Gs(b),totalBytes:f.objectBytes+v}},p=async E=>{Cl(E),await g(),await bm(n,f,[E.entryId],E.blobIds,E.stageId),await Us(n,E.stageId)},h=async(E,b)=>{let v=await g(b);Tm(E,v.entryIds.length);let _=Fn();for(let P of v.entryIds.slice(Math.min(v.cursor,E)+1,Math.max(v.cursor,E)+1))await Ko(n,P,_);return v},y=async()=>{if(await Ct(o)||s)throw new ge(fe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return km(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new ge(fe.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await km(n);E<=b||await Uo($m(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let v=await ER(E,r),_={schemaVersion:yl,stageId:Rl(),entryId:v.entryId,blobIds:v.blobs.map(P=>P.digest)};try{await SR(n,v),await IR(n,_,b.durableManifest!==!1)}catch(P){try{await p(_)}catch(R){throw new ge(fe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw P}return{stageId:_.stageId,entryId:_.entryId,blobIds:_.blobIds}},async discardStage(E){await y(),El(E);let b=await xl(n,E);b&&await p(b)},async previewStagedAppend(E,b){await y();let v=await g(b);return(await ym(n,r,E,v,f)).transition},async previewCursor(E,b){await y();let v=await h(E,b);return Am(v,v.entryIds,E)},async publishStagedAppend(E,b,v){if(await y(),Xs(E,"entryId"),v){El(v);let A=await xl(n,v);if(!A||A.entryId!==E)throw new ge(fe.INVALID_SCHEMA,"history stage does not match the published entry")}let _=await g(b),P=f,R=await ym(n,r,E,_,P),N=await Im({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>vm(n,R.usage),afterWrite:async()=>{v?await Us(n,v):await RR(n,E),await bm(n,R.usage,[...P.entries.keys()].filter(A=>!R.usage.entries.has(A)),[...P.blobs.keys()].filter(A=>!R.usage.blobs.has(A)))}});return f=R.usage,d=N.digest,N},async append(E){await y();let b=await g(),v=await x.stageAppend(E);try{return await x.publishStagedAppend(v.entryId,b.digest,v.stageId)}catch(_){throw await x.discardStage(v.stageId),_}},async readEntry(E){return Xs(E,"entryId"),Ko(n,E)},async readBlob(E){Xs(E,"blobId");let b=await Um(n,E),v=await Jo(b,fe.NOT_FOUND,"blob");return jm(v,E,b),v},async readIndex(){let E=Fn(),b=await Ks(n,E);return f=js(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await Js(n);return{canUndo:E.undoIds.length>0,canRedo:E.redoIds.length>0,undoDepth:E.undoIds.length,redoDepth:E.redoIds.length,cursor:E.cursor,recoveryRequired:await Ct(o)||await Ct(i)}},async readUndoRedoIds(){let E=await Js(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await y();let v=await h(E,b),_=await Im({rootDir:n,previousDigest:v.digest,entryIds:v.entryIds,cursor:E,readback:async()=>vm(n,f)});return d=_.digest,_},async markRecoveryRequired(E){await Ct(o)||await Uo(hl(n),{schemaVersion:Xt,reason:DR(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await He.rm(hl(n),{force:!0})},async readTransactionJournal(){return await Ct(i)?$s(i):null},async writeTransactionJournal(E){await y(),Vm(E);try{await Uo(i,E)}catch(v){let _=await $s(i).catch(()=>null);if(_&&Buffer.from(Nt(_)).equals(Buffer.from(Nt(E))))return;throw _?new ge(fe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:v}):v}let b=await $s(i);if(!Buffer.from(Nt(b)).equals(Buffer.from(Nt(E))))throw new ge(fe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await Ct(i)?await $s(i):null;if(b&&b.transactionId!==E)throw new ge(fe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await He.rm(i,{force:!0})}catch(v){if(!await Ct(i))return;throw v}if(await Ct(i))throw new ge(fe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let v of u)await Us(n,v),u.delete(v);await _R(n);let E=Fn(),b=await Ks(n,E);await Sm(n,b.entryIds,E),f=js(b.entryIds,E),d=b.digest}};return Cm.set(x,()=>Js(n)),x}async function ym(e,t,n,r,o){Xs(n,"entryId");let i=Fn(),s=await Ko(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))_m(a,u);Nm(a,s.id,i),c.push(s.id);let l=vR(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Am(r,l.entryIds,l.cursor)}}function Am(e,t,n){return Tm(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:xR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function xR(e,t){return Yn(Nt({schemaVersion:Xt,entryIds:e,cursor:t}))}function Tm(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ge(fe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function bR(e){if(!tn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ot(e.expectedIndexDigest)||!Ot(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ot(n)?!1:t===-1?n===null:Ot(n)}async function ER(e,t){if(!e.kind.trim())throw new ge(fe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ge(fe.INVALID_JSON,"history blob name must not be empty");let l=OR(c.data),u=Yn(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:Xt,kind:e.kind,manifest:e.manifest,blobs:r},i=Nt({...o}),s=Yn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ge(fe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function SR(e,t){let n=Al(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=>xm(Tl(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Ol(e,c.digest))),xm(n,Nt(r),{kind:"entry",digest:t.entryId},wl(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function xm(e,t,n,r){let o=await Il(e)??(r?await Il(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ge(n.kind==="blob"?fe.BLOB_CORRUPT:fe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Mm(e,t)}function vR(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Nt(Lm(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ge(fe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");_m(n,r.shift()),o-=1}}async function IR(e,t,n){Cl(t);let r=Pl(e,t.stageId);if(n){await Uo(r,t);return}await wR(r,t)}async function xl(e,t){let n=await Il(Pl(e,t));if(n===null)return null;let r=Ho(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Cl(r);if(o.stageId!==t)throw new ge(fe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ws(e){let t=[];for(let n of await Hs(_l(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);El(r);let o=await xl(e,r);o&&t.push(o)}return t}async function bm(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 Ws(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 Em(Al(e,a),wl(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Em(Tl(e,a),Ol(e,a));await kl(Wo(e)),await kl(Go(e))}async function Us(e,t){await bl(Pl(e,t)),await kR(e)}async function kR(e){try{await He.rmdir(_l(e))}catch(t){if(Yo(t)||tn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function RR(e,t){for(let n of await Ws(e))n.entryId===t&&await Us(e,n.stageId)}async function bl(e){if(await He.rm(e,{force:!0}),await Ct(e))throw new ge(fe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Em(e,t){await bl(e),await bl(t)}function Cl(e){if(!tn(e)||e.schemaVersion!==yl||typeof e.stageId!="string"||!wm(e.stageId)||!Ot(e.entryId))throw new ge(fe.INVALID_SCHEMA,"history stage schema is invalid");let t=Bm(e.blobIds,"history stage blobIds");return{schemaVersion:yl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function El(e){if(!wm(e))throw new ge(fe.INVALID_PATH,"history stageId must be a UUID")}function wm(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 Sm(e,t,n=Fn()){let r=new Set(t),o=new Set;for(let l of t){let u=await Ko(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ws(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Wo(e),s=await Hs(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Rm(l.slice(0,-5));u&&!r.has(u)&&await zs(Ge.join(i,l))}let a=Go(e),c=await Hs(a);for(let l of c){let u=Rm(l);u&&!o.has(u)&&await zs(Ge.join(a,l))}}async function Ks(e,t=Fn()){let{index:n,sizeBytes:r}=await zo(e),{totalBytes:o}=await Om(e,n.entryIds,t,r);return{...Gs(n),totalBytes:o}}async function vm(e,t){let{index:n,sizeBytes:r}=await zo(e);return{...Gs(n),totalBytes:t.objectBytes+r}}async function zo(e){let t=Nl(e),n=await Jo(t,fe.NOT_FOUND,"index"),r=Ho(Buffer.from(n).toString("utf8"),"index");return{index:PR(r),sizeBytes:n.byteLength}}async function Js(e){return Gs((await zo(e)).index)}function Gs(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:Xt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Om(e,t,n,r){let o=0,i=new Set;o+=r??(await zo(e)).sizeBytes;for(let s of new Set(t)){let a=await Ko(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 Ko(e,t,n=Fn()){let r=n.entries.get(t);if(r)return r.entry;let o=await MR(e,t),i=await Jo(o,fe.NOT_FOUND,"entry"),s=Ho(Buffer.from(i).toString("utf8"),`entry ${t}`),a=AR(s);if(a.id!==t)throw new ge(fe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Yn(Nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ge(fe.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 f=await Um(e,d),g=await Jo(f,fe.NOT_FOUND,"blob");return jm(g,d,f),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),f=[],g=0,p=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(E){f.push({index:x,error:E})}}}),h=await Promise.allSettled(p),y=f.sort((x,E)=>x.index-E.index)[0];if(y)throw y.error;for(let x of h)if(x.status==="rejected")throw x.reason;for(let x=0;x<l.length;x++)n.blobSizes.set(l[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Fm(e,t,n){await Uo(Nl(e),Lm(t,n))}function Lm(e,t){return{schemaVersion:Xt,digest:Yn(Nt({schemaVersion:Xt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Dm(e,t){if(t!==void 0&&e.digest!==t)throw new ge(fe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Im(e){Dm(await Js(e.rootDir),e.previousDigest);let t=Yn(Nt({schemaVersion:Xt,entryIds:e.entryIds,cursor:e.cursor}));try{await Fm(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ge(fe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ks(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ge(fe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function CR(e){await He.mkdir(e,{recursive:!0}),await He.mkdir(Wo(e),{recursive:!0}),await He.mkdir(Go(e),{recursive:!0}),await He.mkdir(Xo(e),{recursive:!0})}async function NR(e){await He.rm(Xo(e),{recursive:!0,force:!0}),await He.mkdir(Xo(e),{recursive:!0})}async function _R(e){let t=Xo(e);await He.mkdir(t,{recursive:!0});for(let n of await Hs(t))n!=="stages"&&await He.rm(Ge.join(t,n),{recursive:!0,force:!0})}function PR(e){if(!tn(e))throw new ge(fe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Xt)throw new ge(fe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Bm(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ge(fe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ot(o))throw new ge(fe.INDEX_CORRUPT,"index digest is invalid");let i=Yn(Nt({schemaVersion:Xt,entryIds:t,cursor:r}));if(o!==i)throw new ge(fe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Xt,digest:o,entryIds:t,cursor:r}}function AR(e){if(!tn(e))throw new ge(fe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Xt)throw new ge(fe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ot(t))throw new ge(fe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ge(fe.ENTRY_CORRUPT,"entry kind is invalid");let r=vl(e.manifest,"entry.manifest"),o=TR(e.blobs);return{id:t,schemaVersion:Xt,kind:n,manifest:r,blobs:o}}function TR(e){if(!Array.isArray(e))throw new ge(fe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!tn(t))throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ot(o))throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Uo(e,t){await Mm(e,Nt(t))}async function wR(e,t){let n=Ge.dirname(e),r=Ge.basename(e),o=Ge.join(n,`.${r}.${process.pid}.${Rl()}.tmp`);await He.mkdir(n,{recursive:!0});try{await He.writeFile(o,Nt(t),{flag:"wx"}),await He.rename(o,e)}finally{await zs(o)}}async function Mm(e,t){let n=Ge.dirname(e),r=Ge.basename(e),o=Ge.join(n,`.${r}.${process.pid}.${Rl()}.tmp`);await He.mkdir(n,{recursive:!0});try{let i=await He.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await He.rename(o,e),await kl(n)}finally{await zs(o)}}function Nt(e){return Buffer.from(JSON.stringify(Sl(e)),"utf8")}function Sl(e){if(Array.isArray(e))return e.map(t=>Sl(t));if(tn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Sl(e[n]);return t}return e}function Ho(e,t){try{return JSON.parse(e)}catch(n){throw new ge(fe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function vl(e,t){if(e===null)return null;switch(typeof e){case"boolean":case"number":case"string":return e;case"object":if(Array.isArray(e))return e.map(n=>vl(n,t));if(tn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=vl(o,t);return n}break}throw new ge(fe.INVALID_JSON,`${t} must be JSON-serializable`)}function Bm(e,t){if(!Array.isArray(e))throw new ge(fe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ot(n))throw new ge(fe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Xs(e,t){if(!Ot(e))throw new ge(fe.INVALID_PATH,`${t} must be a sha256 digest`)}function Ot(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Yn(e){return`sha256:${pR("sha256").update(e).digest("hex")}`}function OR(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Jo(e,t,n){try{return await He.readFile(e)}catch(r){throw new ge(t,`${n} not found: ${e}`,{cause:r})}}async function Il(e){try{return await He.readFile(e)}catch(t){if(Yo(t))return null;throw t}}function jm(e,t,n){if(Yn(e)!==t)throw new ge(fe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Ct(e){try{return await He.access(e),!0}catch(t){if(Yo(t))return!1;throw t}}async function zs(e){try{await He.rm(e,{force:!0,recursive:!0})}catch{}}async function kl(e){try{let t=await He.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Hs(e){try{return await He.readdir(e)}catch(t){if(Yo(t))return[];throw t}}function FR(e){if(typeof e!="string"||e.trim().length===0)throw new ge(fe.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ge.resolve(e)}function Nl(e){return Ge.join(e,mR)}function hl(e){return Ge.join(e,gR)}function LR(e){return Ge.join(e,hR)}function $m(e){return Ge.join(e,yR)}async function km(e){try{let t=await He.readFile($m(e),"utf8"),n=Ho(t,"document version");if(!tn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ge(fe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Yo(t))return 0;throw t}}async function $s(e){let t=await Jo(e,fe.RECOVERY_PENDING,"transaction journal"),n=Ho(Buffer.from(t).toString("utf8"),"transaction journal");return Vm(n),n}function Vm(e){if(!tn(e)||e.schemaVersion!==fR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!bR(e.historyTransition)||!Array.isArray(e.files))throw new ge(fe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!tn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ot(t.preDigest)||t.postDigest!==null&&!Ot(t.postDigest))throw new ge(fe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function DR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Wo(e){return Ge.join(e,"entries")}function Go(e){return Ge.join(e,"blobs")}function Xo(e){return Ge.join(e,"tmp")}function _l(e){return Ge.join(Xo(e),"stages")}function Pl(e,t){return Ge.join(_l(e),`${t}.json`)}function Al(e,t){return Ge.join(Wo(e),`${Jm(t)}.json`)}function Tl(e,t){return Ge.join(Go(e),Jm(t))}function wl(e,t){return Ge.join(Wo(e),`${t}.json`)}function Ol(e,t){return Ge.join(Go(e),t)}async function MR(e,t){return Km(Al(e,t),wl(e,t))}async function Um(e,t){return Km(Tl(e,t),Ol(e,t))}async function Km(e,t){return await Ct(e)?e:await Ct(t)?t:e}function Jm(e){return e.slice(7)}function Rm(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ot(t)?t:null}function tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function BR(e){return{maxEntries:e?.maxEntries??Vs.maxEntries,maxSessionBytes:e?.maxSessionBytes??Vs.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Vs.maxEntryBytes}}async function jR(e){let t=Nl(e);await Ct(t)||await Fm(e,[],-1)}var VR={affectedCompositions:[]};function Gm(e){let t=null,n=new WeakMap;async function r(){return t??=UR(e),t}async function o(i){if(!i)return null;let s=Fl(i);return s?KR(e,s):i}return{async prepareAppend(i){let s=await Yr(e),a=await e.stageAppend(Hm(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 Yr(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 Yr(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);Xm(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,Zr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Fl(c.at(-1))!==Fl(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Xm(l,i.historyTransition),Object.assign(a,Zr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await Yr(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,Zr(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Hm(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,Zr(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,Zr(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 Xm(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 Fl(e){return typeof e=="string"?e:e?.historyId}async function UR(e){let t=await Yr(e);return Zr(t)}function Zr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function KR(e,t){let n=await e.readEntry(t),r=JR(n),o=r.provenance??VR;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 zm(e,n,r.preSnapshots),postSnapshots:await zm(e,n,r.postSnapshots)}}async function zm(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(HR(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Hm(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=XR(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 JR(e){if(!Zm(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:Ym(t.provenance)}:{},preSnapshots:Wm(t.preSnapshots,"preSnapshots"),postSnapshots:Wm(t.postSnapshots,"postSnapshots")}}function XR(e){if(e.provenance!==void 0)return Ym(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Ym(e){let t=$R.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 Wm(e,t){return e.map((n,r)=>{if(!Zm(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&&!zR(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 zR(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function HR(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Zm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as WR}from"@vcp-dev/contracts";var Qm={schema_version:1,policy_version:"starter-capabilities-v1",source:{starter_package_path:"templates/next-starter/package.json",components_catalog_path:"templates/next-starter/components.catalog.json",package_name:"vcp-next-starter",package_version:"0.0.0"},runtime_dependencies:[{name:"@gsap/react",version:"2.1.2"},{name:"@hookform/resolvers",version:"3.10.0"},{name:"@opennextjs/cloudflare",version:"1.19.11"},{name:"@radix-ui/react-accordion",version:"1.2.12"},{name:"@radix-ui/react-alert-dialog",version:"1.1.15"},{name:"@radix-ui/react-aspect-ratio",version:"1.1.8"},{name:"@radix-ui/react-avatar",version:"1.1.11"},{name:"@radix-ui/react-checkbox",version:"1.3.3"},{name:"@radix-ui/react-collapsible",version:"1.1.12"},{name:"@radix-ui/react-context-menu",version:"2.2.16"},{name:"@radix-ui/react-dialog",version:"1.1.15"},{name:"@radix-ui/react-dropdown-menu",version:"2.1.16"},{name:"@radix-ui/react-hover-card",version:"1.1.15"},{name:"@radix-ui/react-label",version:"2.1.8"},{name:"@radix-ui/react-menubar",version:"1.1.16"},{name:"@radix-ui/react-navigation-menu",version:"1.2.14"},{name:"@radix-ui/react-popover",version:"1.1.15"},{name:"@radix-ui/react-progress",version:"1.1.8"},{name:"@radix-ui/react-radio-group",version:"1.3.8"},{name:"@radix-ui/react-scroll-area",version:"1.2.10"},{name:"@radix-ui/react-select",version:"2.2.6"},{name:"@radix-ui/react-separator",version:"1.1.8"},{name:"@radix-ui/react-slider",version:"1.3.6"},{name:"@radix-ui/react-slot",version:"1.2.3"},{name:"@radix-ui/react-switch",version:"1.2.6"},{name:"@radix-ui/react-tabs",version:"1.1.13"},{name:"@radix-ui/react-toggle",version:"1.1.10"},{name:"@radix-ui/react-toggle-group",version:"1.1.11"},{name:"@radix-ui/react-tooltip",version:"1.2.8"},{name:"class-variance-authority",version:"0.7.1"},{name:"clsx",version:"2.1.1"},{name:"cmdk",version:"1.1.1"},{name:"date-fns",version:"4.3.0"},{name:"embla-carousel-react",version:"8.6.0"},{name:"gsap",version:"3.15.0"},{name:"i18next",version:"26.3.0"},{name:"input-otp",version:"1.4.2"},{name:"lucide-react",version:"0.525.0"},{name:"motion",version:"12.40.0"},{name:"next",version:"16.3.4"},{name:"react",version:"19.2.6"},{name:"react-day-picker",version:"9.14.0"},{name:"react-dom",version:"19.2.6"},{name:"react-hook-form",version:"7.76.1"},{name:"react-i18next",version:"17.0.8"},{name:"recharts",version:"2.15.4"},{name:"sonner",version:"2.0.7"},{name:"tailwind-merge",version:"3.6.0"},{name:"vaul",version:"1.1.2"},{name:"zod",version:"3.25.76"}],catalog_dependencies:["@hookform/resolvers","@radix-ui/react-accordion","@radix-ui/react-alert-dialog","@radix-ui/react-aspect-ratio","@radix-ui/react-avatar","@radix-ui/react-checkbox","@radix-ui/react-collapsible","@radix-ui/react-context-menu","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-hover-card","@radix-ui/react-label","@radix-ui/react-menubar","@radix-ui/react-navigation-menu","@radix-ui/react-popover","@radix-ui/react-progress","@radix-ui/react-radio-group","@radix-ui/react-scroll-area","@radix-ui/react-select","@radix-ui/react-separator","@radix-ui/react-slider","@radix-ui/react-slot","@radix-ui/react-switch","@radix-ui/react-tabs","@radix-ui/react-toggle","@radix-ui/react-toggle-group","@radix-ui/react-tooltip","class-variance-authority","clsx","cmdk","date-fns","embla-carousel-react","input-otp","lucide-react","motion","react-day-picker","react-hook-form","recharts","sonner","tailwind-merge","vaul","zod"],public_paths:["components.json","components/site/generated/*","components/ui/*","components/ui/accordion.tsx","components/ui/alert-dialog.tsx","components/ui/alert.tsx","components/ui/aspect-ratio.tsx","components/ui/avatar.tsx","components/ui/badge.tsx","components/ui/border-beam.tsx","components/ui/breadcrumb.tsx","components/ui/button-group.tsx","components/ui/button.tsx","components/ui/calendar.tsx","components/ui/callout.tsx","components/ui/card.tsx","components/ui/carousel.tsx","components/ui/chart.tsx","components/ui/checkbox.tsx","components/ui/code-block.tsx","components/ui/collapsible.tsx","components/ui/command.tsx","components/ui/composite-carousel.tsx","components/ui/context-menu.tsx","components/ui/dialog.tsx","components/ui/drawer.tsx","components/ui/dropdown-menu.tsx","components/ui/empty.tsx","components/ui/field.tsx","components/ui/form.tsx","components/ui/hover-card.tsx","components/ui/input-group.tsx","components/ui/input-otp.tsx","components/ui/input.tsx","components/ui/item.tsx","components/ui/kbd.tsx","components/ui/label.tsx","components/ui/magic-card.tsx","components/ui/marquee.tsx","components/ui/menubar.tsx","components/ui/multi-step-form.tsx","components/ui/navigation-menu.tsx","components/ui/number-ticker.tsx","components/ui/pagination.tsx","components/ui/popover.tsx","components/ui/progress.tsx","components/ui/radio-group.tsx","components/ui/safe-image.tsx","components/ui/scroll-area.tsx","components/ui/scroll-choreographer.tsx","components/ui/select.tsx","components/ui/separator.tsx","components/ui/sheet.tsx","components/ui/site-footer-shell.tsx","components/ui/site-header.tsx","components/ui/skeleton.tsx","components/ui/slider.tsx","components/ui/sonner.tsx","components/ui/spinner.tsx","components/ui/stepper.tsx","components/ui/switch.tsx","components/ui/table.tsx","components/ui/tabs.tsx","components/ui/textarea.tsx","components/ui/toggle-group.tsx","components/ui/toggle.tsx","components/ui/tooltip.tsx","components/ui/video-frame.tsx","lib/cms","lib/utils.ts#cn"],generated_sections_path:"components/site/generated/*",ui_baseline:{kit:"shadcn-style",components_config:"components.json",class_name_helper:"lib/utils.ts#cn"},host_contract_digest:"03208e0d83ae2140368f162b6051dd45d4d6ac97f3652958b3ba24a6273d6eca"};function Ll(){let e=WR.safeParse(Qm);return e.success?e.data:null}import{randomBytes as lC}from"node:crypto";import Zs from"node:path";import{parse as lg}from"@babel/parser";import uC from"@babel/traverse";import*as ug from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Ml,PageResourceArtifactSchema as dC,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as pC,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as fC,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as mC,parseComponentI18nResourcesJson as gC}from"@vcp-dev/contracts";var eg={colorMixPolicy:"always",includeExtendedColorFunctions:!0},tg=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ng=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,GR=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,YR=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,ZR=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,QR=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,qR=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,eC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tC=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,nC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,rC=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,oC=/\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,iC=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,sC=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Zo(e,t){let n=Ys([...zt(e,GR),...zt(e,YR),...zt(e,ZR),...zt(e,t.includeRgbBackgroundImage?QR:qR),...t.includeExtendedColorFunctions?[...zt(e,eC),...zt(e,tC)]:[]]),r=Ys([...zt(e,nC),...zt(e,rC)]).filter(o=>t.colorMixPolicy==="always"||tg.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...zt(e,oC).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...zt(e,sC).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Ys(zt(e,ng)),hardCodedSurfaceOccurrences:cC(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Ys(zt(e,iC)):[]}}function zt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var qm=160,aC=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function cC(e){let t=new RegExp(ng.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,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>qm?`${g.slice(0,qm-1)}\u2026`:g})}return o}function Ys(e){return[...new Set(e)]}var Bl="{{$INSTANCE}}",hC=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,yC=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,jl="components/site/generated",xC=/\.(?:tsx?|json)$/,bC=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,EC=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],SC=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Dl=uC,vC=typeof Dl=="function"?Dl:Dl.default;async function $l(e){let t=dC.safeParse(e.artifact);if(!t.success)return Je("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>lC(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=TC(r());if(!i)return Je("Random instance suffix must be 8 lowercase hex chars.");let s=`${wC(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let v=b.final_route.slice(1);a.set(b.template_page_id,b.final_route),c.set(b.template_page_id,b.title),l.push({template_page_id:b.template_page_id,title:b.title,final_route:b.final_route,route_file_path:`app/${v}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,p=new Map,h=[],y=new Set(n.pages.flatMap(b=>b.components.map(v=>v.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let v=rg({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!v.ok)return v;for(let _ of v.files){let P=ig(_,d,u);if(P)return P}f.add(v.entry),p.set(v.entry,v.entryExport),g.set(b.component_id,v.entry)}for(let[b,v]of n.pages.entries()){let _=l[b],P=rg({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:_.route_file_path,pageTitle:_.title});if(!P.ok)return P;for(let R of P.files){let N=ig(R,d,u);if(N)return N}f.add(P.entry),p.set(P.entry,P.entryExport),h.push({entry:P.entry,declaredComponentIds:new Set(v.components.map(R=>R.component_id))})}let x=kC(u,f,s,g,h,p);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?$l({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${b.file}`,path:b.file};let E=RC(u);return E||(u.sort((b,v)=>b.file.localeCompare(v.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function rg(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:og(o.pathTemplate,e.packageInstanceId);if(!s)return Je("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=IC(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?NC(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??og(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Je("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function IC(e,t,n,r){let o,i=e.replace(hC,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Je(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(yC,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Je(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Bl,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Je("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function og(e,t){let n=`${jl}/${t}`;if(e.split(Bl).length>2)return null;let o=e.replace(Bl,t),i=`${jl}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Zs.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!xC.test(a)||bC.test(a)?null:a}function ig(e,t,n){return t.has(e.file)?Je(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function kC(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${jl}/${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 Je("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Ml)&&!gC(g.content).success)return Je("Materialization component i18n resources are invalid.",g.file);continue}try{let h=lg(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,h);for(let x of h.program.body)if((x.type==="ImportDeclaration"||x.type==="ExportAllDeclaration"||x.type==="ExportNamedDeclaration"&&x.source)&&x.source){let E=x.source.value,b=PC(g.file,E,s,a);if(!b.allowed)return Je(`Materialization import is outside the controlled package: ${E}`,g.file);b.internalPath&&c.get(g.file).add(b.internalPath)}let y;if(vC(h,{Identifier(x){x.isReferencedIdentifier()&&SC.has(x.node.name)&&(y??=x.node.name,x.stop())},JSXAttribute(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name==="style"&&(y??="inline style",x.stop())},JSXOpeningElement(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name.toLowerCase()==="style"&&(y??="style element",x.stop())}}),y)return Je(`Materialization source uses forbidden capability: ${y}`,g.file)}catch{return Je("Materialization source must parse as TS/TSX.",g.file)}let p=Zo(g.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(p.hardCodedSurfaceHits.length>0||p.rawColorHits.length>0||p.privateTokenHits.length>0)return Je("Materialization source violates the public theme token policy.",g.file)}if([...t].some(g=>!s.has(g)))return Je("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Je("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let h=l.get(g);if(!h||!CC(h,p))return Je("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,p])=>[p,g]));for(let g of o){let p=cg(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!p.has(y))return Je(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of p){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return Je(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of cg(g,c))d.add(p);if(d.size!==e.length)return Je("Every materialization file must be reachable from a package entry.");let f=AC(e,l,c);return f||{ok:!0}}function RC(e){if(e.length>pC)return Je("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>fC)return Je("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>mC?Je("Page resource exceeds the aggregate content byte limit."):null}function CC(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 NC(e,t,n){let r;try{r=lg(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Je("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=sg(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&_C(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=sg(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 sg(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&ug.isExpression(t)?t:null}function _C(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function PC(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=ag(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:EC.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Zs.posix.normalize(Zs.posix.join(Zs.posix.dirname(e),t)),i=ag(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function ag(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 AC(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Ml))continue;let i=o.file.slice(0,-Ml.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Je("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 Je("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function cg(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 TC(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function wC(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Je(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as KC}from"node:crypto";import Dn from"node:path";import{parse as JC}from"@babel/parser";import XC from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Qs,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as fg,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as zC,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as HC,SiteEditMaterializationSchema as WC,parseComponentI18nResourcesJson as GC}from"@vcp-dev/contracts";import{parse as OC}from"@babel/parser";import FC from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as LC,FormDefinitionIdSchema as DC}from"@vcp-dev/contracts";var MC=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],BC=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),dg=new Set(["require","module","exports","__dirname","__filename"]),Vl=FC,jC=typeof Vl=="function"?Vl:Vl.default;function Kl(e,t={}){let n=[],r=$C(t.hostCapabilities),o=Zo(e,t.style??eg),i;try{i=OC(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&UC(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return jC(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){l(Ul(u.node))},OptionalMemberExpression(u){l(Ul(u.node))},Identifier(u){u.isReferencedIdentifier()&&l(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&DC.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&MC.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?VC(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),c(u)}}function c(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function l(u){if(!(!u||!BC.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:dg.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:dg.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function $C(e){if(e==null)return null;let t=LC.safeParse(e);return t.success?t.data:null}function VC(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):pg(n)===pg(o)})}function pg(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function UC(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function Ul(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?Ul(e.object):null}var bg="components/site/generated",mg="{{$INSTANCE}}",qs=5,YC=/^[a-z][a-z0-9-]{0,48}$/,ZC=/^[a-f0-9]{8}$/,gg=/\.tsx?$/,QC=/\.json$/,qC=/\.(?:tsx?|json)$/,eN=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Jl=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Xl=XC,tN=typeof Xl=="function"?Xl:Xl.default;function nN(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>fg)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=hN(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=WC.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=fN(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${bg}.`,path:e.generatedRoot}};if(!Eg(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=yg(r.data.files),s=yg(e.controlledFiles);if(!yN(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>fg)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>zC)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>HC?{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 rN(e){let t=nN(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Eg(e.manifest.instanceBaseName),o=Math.max(1,Math.min(qs,e.maxAttempts??qs));for(let i=0;i<o;i+=1){let s=mN(e.instanceNameGenerator?.()??KC(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=vg(n,a),l=oN({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await sN(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function zl(e){let t=Math.max(1,Math.min(qs,e.maxAttempts??qs));for(let n=0;n<t;n+=1){let r=await rN({...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 oN(e){let t=iN(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Qo({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Qo({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=Hl({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function iN(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function sN(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Qo(e){if(e.pathTemplate.split(mg).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(mg,e.instanceName),n=gN(t);return n?vg(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||!qC.test(n)||eN.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 Hl(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(g=>g.path)),c=new Map,l=new Map(t.map(g=>[g.path,new Set])),u=new Map;for(let g of t){if(QC.test(g.path)){if(g.path.endsWith(Qs)){let x=GC(g.content);if(!x.success)return Ln("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Ln("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=JC(g.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:g.path}}}let h=Kl(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!0,rejectStyleElements:!0,themeStyleMode:"reject",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0}}),y=aN(h.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!gg.test(g.path))continue;let p=c.get(g.path),h=null;if(tN(p,{ImportDeclaration(y){let x=hg({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:g.path},y.stop();else if(!x.internalPath&&!cN(y.node.source.value,i,s))h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:g.path},y.stop();else if(x.internalPath&&(l.get(g.path).add(x.internalPath),x.internalPath.endsWith(Qs))){let E=uN({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:p});E.ok?u.get(x.internalPath).add(g.path):(h??=E.error,y.stop())}},ExportAllDeclaration(y){h??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:g.path},y.stop()},ExportNamedDeclaration(y){if(y.node.source){let x=hg({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},y.stop()):x.internalPath&&l.get(g.path).add(x.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:g.path},y.stop();return}y.node.callee.type==="Identifier"&&y.node.callee.name==="require"&&(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:g.path},y.stop())},NewExpression(y){y.node.callee.type==="Identifier"&&y.node.callee.name==="Function"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:g.path},y.stop())},MetaProperty(y){y.node.meta.type==="Identifier"&&y.node.meta.name==="import"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let x=xg(y.node);x&&Jl.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=xg(y.node);x&&Jl.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&Jl.has(y.node.name)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name==="style"&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:g.path},y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())}}),h)return{ok:!1,error:h}}if(r.length===0)return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let g of r){if(d.has(g.path))return Ln("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!gg.test(g.path))return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!dN(p,g.export))return Ln("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",g.path)}for(let[g,p]of u)if(p.size!==1)return Ln("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",g);let f=new Set;for(let g of r)for(let p of pN(g.path,l))f.add(p);return f.size!==t.length?Ln("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function aN(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function hg(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Dn.posix.normalize(Dn.posix.join(Dn.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 cN(e,t,n){if(n===null)return!0;let r=lN(e);return r===null||t.has(r)&&n.has(r)}function lN(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function uN(e){let t=Dn.posix.dirname(e.importer),n=Dn.posix.dirname(e.imported),r=Dn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Dn.posix.basename(e.imported).slice(0,-Qs.length),i=`./${r}${Qs}`;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 dN(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))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 pN(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 Ln(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function fN(e){let t=Sg(e);return t===bg?t:null}function mN(e){let t=e.trim().toLowerCase();return ZC.test(t)?t:null}function Eg(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 YC.test(t)?t:null}function Sg(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Dn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function gN(e){let t=Sg(e);return!t||t!==e?null:t}function vg(...e){return Dn.posix.join(...e)}function yg(e){return new Set(e.map(t=>t.pathTemplate))}function hN(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 yN(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function xg(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 hu}from"node:crypto";import lu from"@babel/traverse";function Wl(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 TN}from"node:crypto";import _g from"node:path";import*as to from"@babel/parser";import ql from"@babel/traverse";import eu from"@babel/generator";import*as ae from"@babel/types";import Gl from"@babel/generator";import{parse as xN}from"@babel/parser";import Yl from"@babel/traverse";import*as Ie from"@babel/types";import{PortableInvocationBindingSchema as bN}from"@vcp-dev/contracts";var Zl=typeof Gl=="function"?Gl:Gl.default,Ig=typeof Yl=="function"?Yl:Yl.default,Rg=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),EN=new Set(["sourceOrder","source_order","originalOrder","original_order"]),SN=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),vN=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,IN=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function qr(e){if(!Ng(e)||!Array.isArray(e.bindings))return Zn("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=NN(e);if(!t||!IN.test(t))return Zn("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Cg(e.targetBlockId);if(!n.ok)return n;let r=_N(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!vN.test(o))return Zn("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,c=!1,l=0;for(let[d,f]of e.bindings.entries()){let g=bN.safeParse(f);if(!g.success)return Zn("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${d}`);let p=g.data;if(a.has(p.propName))return Zn("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),EN.has(p.propName))return Zn("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(Rg.has(p.propName)&&p.value.kind!=="target-block-id")return Zn("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${d}`);if(p.value.kind==="target-block-id"&&(l+=1,l>1))return Zn("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${d}`);p.value.kind==="route-search-params"&&(c=!0),s.push(p),i.push(Ie.jsxAttribute(Ie.jsxIdentifier(p.propName),Ie.jsxExpressionContainer(RN(p.value,n.value,o))))}let u=Ie.jsxElement(Ie.jsxOpeningElement(CN(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:Zl(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function kN(e){if(!Ng(e)||e.jsx===void 0==(e.source===void 0))return Qr("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Cg(e.targetBlockId);if(!t.ok)return Qr("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Qr("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r;try{r=xN(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(u){return Qr("BLOCK_METADATA_PARSE_FAILED",u instanceof Error?u.message:String(u),n?"jsx":"source")}let o=[];if(Ig(r,{JSXElement(u){kg(u)||o.push(u.node)},JSXFragment(u){kg(u)||o.push(u.node)}}),o.length!==1)return Qr("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let i=o[0],s=PN(i);if(!s)return Qr("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let a=0,c=0;Ig(r,{JSXAttribute(u){let d=AN(u.node.name);!d||!SN.has(d)||(d==="data-site-block-id"||d==="data-vcp-block-id"||Rg.has(d)?a+=1:c+=1,u.remove())}}),s.openingElement.attributes.push(Ie.jsxAttribute(Ie.jsxIdentifier("data-site-block-id"),Ie.stringLiteral(t.value)),Ie.jsxAttribute(Ie.jsxIdentifier("data-site-block-order"),Ie.jsxExpressionContainer(Ie.numericLiteral(e.targetOrder))));let l=n?Zl(i,{jsescOption:{minimal:!0}}).code:Zl(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:l,jsx:l,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:a,removedSourceOrderCount:c}}}function RN(e,t,n){return e.kind==="route-search-params"?Ie.identifier(n):e.kind==="target-block-id"?Ie.stringLiteral(t):Ql(e.value)}function Ql(e){return e===null?Ie.nullLiteral():typeof e=="string"?Ie.stringLiteral(e):typeof e=="number"?Ie.numericLiteral(e):typeof e=="boolean"?Ie.booleanLiteral(e):Array.isArray(e)?Ie.arrayExpression(e.map(t=>Ql(t))):Ie.objectExpression(Object.entries(e).map(([t,n])=>Ie.objectProperty(Ie.stringLiteral(t),Ql(n))))}function CN(e){let t=e.split("."),n=Ie.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Ie.jsxMemberExpression(n,Ie.jsxIdentifier(r));return n}function NN(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function Cg(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function _N(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function PN(e){if(Ie.isJSXElement(e))return e;let t=e.children.filter(Ie.isJSXElement),n=e.children.some(r=>Ie.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function kg(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function AN(e){return Ie.isJSXIdentifier(e)?e.name:null}function Ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zn(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Qr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var nu=typeof eu=="function"?eu:eu.default,wN=typeof ql=="function"?ql:ql.default;function ni(e){let t=Fg(e);if(t)return{ok:!1,error:t};let n=e.projection,r=cu(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=LN(n,o),s=XN(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=ON(e);if(i){let p=ru(e);return p.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:p.locator,sourceHash:p.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:p.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(ea(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return qo("Route page composition does not expose a verifiable container boundary.");let d=ti(l),f=Ag(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?ti(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return qo("Route page composition placement does not expose a verifiable anchor boundary.");let p=Ag(e.source,g,o.anchorSourceHash,"Route page composition anchor");if(!p.ok)return p.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:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}}}}}function su(e){let t=Ke(e.entryFile,e.source);if(!t.ok)return Qn("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=nn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return Qn("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(l=>{if(l.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return l.anchorSourceRange&&ea(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+wg(f,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return Qn("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Qn("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=ni({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let l=ri({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=Kt({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=Lg({source:s,step:i.plan.serverParamsStep});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=Jt({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return c.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:c.source}}:Qn("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function wg(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+wg(r,t),0)}function Qn(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function ON(e){let t=jN(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 ri(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Cr(e.source,"Root expression rewrite requires an exact expression locator.");let t=_o(e.source,"value");if(!t.ok)return Cr(e.source,t.diagnostic.message);let n=xe(t.ast,e.locator);if(!n.ok)return Cr(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Cr(e.source,"Resolved value locator does not point to an expression.");let o=eo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Cr(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ae.nullLiteral()),{ok:!0,source:nu(t.ast,{}).code};let i;try{i=to.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Cr(e.source,s instanceof Error?s.message:String(s))}return!ae.isJSXElement(i)&&!ae.isJSXFragment(i)?Cr(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(FN(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:nu(t.ast,{}).code})}function FN(e,t,n,r){if(ae.isNullLiteral(e)||r)return t;let o=ae.isJSXFragment(e)?[...e.children]:[ae.isJSXElement(e)?e:ae.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ae.jsxFragment(ae.jsxOpeningFragment(),ae.jsxClosingFragment(),s)}function Cr(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function au(e){let t=Fg(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Vg(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(DN(n,o)){let h=ru(e);return h.ok?e.operation==="remove-node"&&!Pg(n,o.placementUnitKey)?qo("The last editable page unit cannot be deleted."):e.operation==="move-node"?qo("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=ti(o.sourceRange),a=pn(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?[]:[ei(a.diagnostic)]}};if(eo(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=ru(e);return h.ok?Pg(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}}}:qo("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||!BN(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=cu(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 f=ti(d),g=pn(e.source,f);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?[]:[ei(g.diagnostic)]}};if(eo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Tg("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 x=ti(h),E=pn(e.source,x);return!E.ok||!E.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:E.ok===!1?E.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:E.ok?[]:[ei(E.diagnostic)]}}:eo(e.source,E.match.node.start??null,E.match.node.end??null)!==y?Tg("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:f,anchorLocator:x,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:f,placement:u.relation}}}}function Pg(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function LN(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ea(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 DN(e,t){return e.container.kind!=="jsx-container"&&ea(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ru(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=pn(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?[]:[ei(r.diagnostic)]}}}:eo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Og("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Ag(e,t,n,r){let o=pn(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?[]:[ei(o.diagnostic)]}}}:eo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Og(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Og(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function qo(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Tg(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ei(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Fg(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&&!MN(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 MN(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function BN(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function jN(e,t){let n=_g.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=_g.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ti(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function eo(e,t,n){return t==null||n==null?null:`sha256:${TN("sha256").update(e.slice(t,n)).digest("hex")}`}function ea(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}function Lg(e){let t;try{t=to.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=$N(t,e.step);return n.ok?{ok:!0,source:nu(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function $N(e,t){let n=jg(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=iu(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:Mg(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Dg(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?ou():VN()),{ok:!0};let i=n.node.params[0],s=iu(i);return s?(UN(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function VN(){return ae.objectPattern([ae.objectProperty(ae.identifier("searchParams"),ae.identifier("searchParams"),!1,!0)])}function ou(){let t=to.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ae.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ae.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ae.cloneNode(n,!0)}function UN(e,t){let n=ae.objectProperty(ae.identifier("searchParams"),ae.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ae.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Bg(e);if(!o){e.typeAnnotation=ou().typeAnnotation;return}if(!ae.isTSTypeLiteral(o.typeAnnotation))return;let i=ou().typeAnnotation;if(!i||!ae.isTSTypeAnnotation(i)||!ae.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!KN(o.typeAnnotation)&&o.typeAnnotation.members.push(ae.cloneNode(s,!0))}function KN(e){return e.members.some(t=>!("key"in t)||!t.key?!1:$g(t.key)==="searchParams")}function JN(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function XN(e){if(!e.invocation)return{ok:!0};let t=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return tu(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=zN(e.source,e.entryFile);if(!r.ok)return tu(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return tu(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function tu(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function zN(e,t){let n;try{n=to.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=jg(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Dg(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Dg(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=iu(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Mg(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!HN(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function iu(e){return!e||ae.isTSParameterProperty(e)?null:ae.isObjectPattern(e)?e:ae.isAssignmentPattern(e)&&ae.isObjectPattern(e.left)?e.left:null}function Mg(e){for(let t of e.properties)if(!(!ae.isObjectProperty(t)||t.computed||$g(t.key)!=="searchParams"))return ae.isIdentifier(t.value)?t.value.name:ae.isAssignmentPattern(t.value)&&ae.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function HN(e){let t=Bg(e);return t?ae.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Bg(e){return e.typeAnnotation&&ae.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function jg(e){let t=null;return wN(e,{ExportDefaultDeclaration(n){if(t)return;let r=JN(n,n.get("declaration"));r&&(t=r)}}),t}function $g(e){return ae.isIdentifier(e)?e.name:ae.isStringLiteral(e)?e.value:null}var WN=typeof lu=="function"?lu:lu.default;function nn(e){if(!e.ast)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=n_(e.ast);if(!t)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=o_(t);if(!n.ok)return rn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=s_(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(c_(r,t))return rn(e,[nt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return du(e,t,"virtual-route-root",r);if(a_(r)){let o=p_({input:e,source:e.source,expression:r});return uu(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ue(r)&&!ii(r)){let o=mu(r),i=Jg({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return uu(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=u_(r);if(!o.ok)return rn(e,[o.diagnostic]);let i=no(o.path);if(i.unsupported)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(l_(e.source,r,i.members))return du(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ue(r);if(i.members.length===0&&s)return du(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=Jg({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return uu(e,t,l,{kind:a,sourceKind:c},r)}return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function cu(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:nt("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:nt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Vg(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:nt("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:nt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Xg(e){return e.ok?GN(e.projection):YN(e.projection)}function GN(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)=>zg(e,u,h,y,e.container.placementKey)),f=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>QN(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,f);let p=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:p,businessMemberKeys:f.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:ZN(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function YN(e){let t=e.diagnostics.map(qN);return{status:"unsupported",version:e.version,composition:e.composition,reason:e_(e.diagnostics),diagnostics:t}}function ZN(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 zg(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)=>zg(e,t,a,c,i))]}function QN(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function qN(e){return{code:t_(e),message:e.message}}function e_(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 t_(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 n_(e){let t=null;return WN(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=r_(o.path);i&&(t=i,n.stop())}}),t}function r_(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 o_(e){let t=e.get("body");if(!t.isBlockStatement()){let s=oi(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:nt("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:nt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:nt("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(!i_(s))return{ok:!1,diagnostic:nt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Hg(s)||Wg(s))return{ok:!1,diagnostic:nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=oi(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:nt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function i_(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(Hg(o)||Wg(o))return null;return r}function Hg(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function Wg(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function s_(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=oi(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 a_(e){return e.isConditionalExpression()?Ug(oi(e.get("consequent")))&&Ug(oi(e.get("alternate"))):!1}function Ug(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function oi(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 c_(e,t){if(e.isIdentifier())return Kg(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Kg(n.node.name,t)}return!1}function Kg(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 l_(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&fu(t)}function fu(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(!fu(t))return!1;continue}if(t.isJSXElement()&&!fu(t))return!1}return!0}function u_(e){return{ok:!0,path:e}}function no(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:gu(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Ht(r.node.loc),businessMemberCount:0,parentSourceRange:Ht(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=no(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=ii(o)?no(o):null;n||=i?.unsupported??!1,t.push({...mu(o,i?.members),sourceRange:Ht(r.node.loc),parentSourceRange:Ht(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:gu(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Ht(r.node.loc),businessMemberCount:1,parentSourceRange:Ht(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ue(r)){let o=no(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=ii(r)?no(r):null;n||=o?.unsupported??!1,t.push({...mu(r,o?.members),parentSourceRange:Ht(e.node.loc)})}}return{members:t,unsupported:n}}function mu(e,t){let n=e.isJSXElement()&&ii(e)?t??no(e).members:[],r=e.isJSXElement()&&!ii(e)&&!Ue(e);return{memberKey:gu(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Ht(e.node.loc),businessMemberCount:r?1:Gg(n),parentSourceRange:Ht(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:d_(e)}}function ii(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function d_(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 Gg(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ta(e){return e.length===0?0:Math.max(1,Gg(e))}function Jg(e){let t=Ht(e.containerPath.node.loc),n=yu(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Wt(e.input,e.containerKind,e.sourceKind,t),o=Wt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:ta(e.members)<=1,memberCount:ta(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function p_(e){let t=Ht(e.expression.node.loc),n=yu(e.source,e.expression.node.start,e.expression.node.end),r=Wt(e.input,"virtual-route-root","atomic-expression",t),o=Wt(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:Wt(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 Yg(e,t){let n=Ht(t.node.loc),r=yu(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function uu(e,t,n,r,o){let i=Yg(e,o);if(!i)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=f_(e,n,s),c=Wl(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qg(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 f_(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,p,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:ta(p)<=1,memberCount:ta(p),sourceRange:f,sourceHash:f?pu(e.source,f):null,relation:l,containerSourceRange:h,containerSourceHash:h?pu(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?pu(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>Wt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Wt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Wt(e,i,"placement-unit",l.sourceRange);r.push(o("before",Wt(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Wt(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function du(e,t,n,r){let o=Yg(e,r);if(!o)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Wt(e,n,"empty-container",void 0),s=Wt(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=Wl([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Qg(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 rn(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 nt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Wt(e,t,n,r){return Zg([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function gu(e,t,n){return Zg(["member",e,String(t??-1),String(n??-1)])}function Zg(e){return`pc_${hu("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function yu(e,t,n){return t==null||n==null?null:`sha256:${hu("sha256").update(e.slice(t,n)).digest("hex")}`}function pu(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:${hu("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Ht(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Qg(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{createHash as k_}from"node:crypto";import xu from"@babel/traverse";import*as We from"@babel/types";var g_=typeof xu=="function"?xu:xu.default;function Nr(e){let t=h_(e.module,e.exportName);if(!t)return na("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file);let n=x_(e.module.ast,t.node);if(!n)return na("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=b_(n);if(!r)return na("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file);let o=[];return ra(r,o)?{ok:!0,componentName:t.name,roots:o}:na("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function h_(e,t){let n=r=>y_(e,r);for(let r of e.ast.program.body){if(We.isExportDefaultDeclaration(r)&&t==="default"){let o=r.declaration;if(eh(o))return{node:o,name:S_(o)??"default"};if(We.isIdentifier(o))return n(o.name)}if(!(!We.isExportNamedDeclaration(r)||r.source)){if(r.declaration){let o=E_(r.declaration,t);if(o)return n(o)}for(let o of r.specifiers)if(We.isExportSpecifier(o)&&qg(o.exported)===t)return n(qg(o.local))}}return null}function y_(e,t){for(let n of e.ast.program.body){let r=We.isExportNamedDeclaration(n)?n.declaration:n;if(We.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(We.isVariableDeclaration(r)){for(let o of r.declarations)if(We.isIdentifier(o.id)&&o.id.name===t&&eh(o.init))return{node:o.init,name:t}}}return null}function x_(e,t){let n=null;return g_(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function b_(e){let t=e.get("body");if(!t.isBlockStatement())return t;let n=t.get("body"),r=n.at(-1);return!r?.isReturnStatement()||!r.get("argument").node||!n.slice(0,-1).every(o=>o.isVariableDeclaration())?null:r.get("argument")}function ra(e,t){if(e.isJSXFragment()||e.isJSXElement()&&Ue(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!ra(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||ra(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?ra(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function E_(e,t){return We.isFunctionDeclaration(e)?e.id?.name===t?t:null:We.isVariableDeclaration(e)&&e.declarations.some(n=>We.isIdentifier(n.id)&&n.id.name===t)?t:null}function eh(e){return We.isFunctionDeclaration(e)||We.isFunctionExpression(e)||We.isArrowFunctionExpression(e)}function S_(e){return"id"in e&&e.id&&We.isIdentifier(e.id)?e.id.name:null}function qg(e){return We.isIdentifier(e)?e.name:e.value}function na(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}function oa(e,t){return JSON.stringify([t,e])}function th(e,t){let n=new Map,r=[],o=new Map,i=(u,d)=>JSON.stringify([u,d.loc?.start.line,d.loc?.start.column,d.loc?.end.line,d.loc?.end.column]);for(let u of e.graph.elements.values()){let d=u.sourceRange;o.set(JSON.stringify([u.sourceFile,d.startLine,d.startColumn,d.endLine,d.endColumn]),u)}let s=u=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:u}),a=(u,d,f,g,p)=>{if(u.isJSXElement()){if(Ue(u)){for(let x of u.get("children"))a(x,d,f,g,p);return}let h=o.get(i(d,u.node));if(!h)return;let y=h.identity.key;if(t.has(y)){p||s(d);let x=n.get(y)??[];x.push(oa(y,f)),n.set(y,x)}if(h.boundaryKind==="component-boundary"&&!h.isPublicUiComponent){let x=e.parsedModules.get(h.importedFrom??d);if(!x)return;let E=h.importedFrom?h.exportName??h.tag:h.tag,b=Nr({module:x,exportName:E});if(!b.ok){[...t].some(P=>e.graph.elements.get(P)?.sourceFile===x.file)&&b.diagnostic.code!=="component-export-unresolved"&&s(x.file);return}let v=`${x.file}#${b.componentName}`;if(g.has(v)){s(x.file);return}let _=new Set(g).add(v);for(let P of b.roots)a(P,x.file,[...f,y],_,p);return}for(let x of u.get("children"))a(x,d,f,g,p);return}if(u.isJSXFragment()){for(let h of u.get("children"))a(h,d,f,g,p);return}if(u.isJSXExpressionContainer()){a(u.get("expression"),d,f,g,p);return}if(u.isParenthesizedExpression()||u.isTSAsExpression()||u.isTSNonNullExpression()||u.isTSTypeAssertion()){a(u.get("expression"),d,f,g,p);return}u.traverse({JSXElement(h){a(h,d,f,g,!1),h.skip()}})},c=e.parsedModules.get(e.entryFile);if(!c)return{occurrences:n,diagnostics:r};let l=Nr({module:c,exportName:"default"});if(!l.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let u of l.roots)a(u,c.file,[],new Set,!0);return{occurrences:n,diagnostics:r}}function nh(e){let t=[],n=[];return rh(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function rh(e,t,n,r,o,i,s,a,c){if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let l=t.parsedModules.get(e.importedFrom??e.sourceFile);if(!l){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.importedFrom??e.sourceFile,structuralPath:e.identity.structuralPath});return}let u=Nr({module:l,exportName:e.importedFrom?e.exportName??e.tag:e.tag});if(!u.ok){c.push({...u.diagnostic,structuralPath:e.identity.structuralPath});return}let d=`${l.file}#${u.componentName}`;if(s.has(d)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(u.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:l.file,structuralPath:e.identity.structuralPath});return}let f=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange}}],g=u.roots.length>1?{kind:"component-definition",key:d}:r,p=new Set(s);p.add(d);for(let h of u.roots){let y=I_(h),x=y?v_(t.graph,l.file,y):[];if(x.length!==1){c.push({code:x.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:l.file,structuralPath:e.identity.structuralPath});continue}rh(x[0],t,f,g,u.roots.length>1?x[0]:o,u.roots.length>1?f:i,p,a,c)}}function v_(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function I_(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function ia(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!ih(e.projection.composition,e.composition)||e.graph.composition&&!ih(e.graph.composition,e.composition))return{roots:[],diagnostics:[si("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[si("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(si("route-member-not-addressable",e.entryFile));continue}let s=C_(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(si(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=nh({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...c.diagnostics);for(let l of c.roots){let u=l.ownerMember;n.push({...l,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=th(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=oa(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(si("render-occurrence-unproven",i.element.sourceFile))}return{roots:R_(n,e.composition,o.occurrences),diagnostics:t}}function R_(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],c=i.callChain.map(l=>l.callLocator.key);return{rootKey:k_("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(oa(s.identity.key,c)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(l=>l.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=oh(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(oh(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function oh(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function C_(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function ih(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function si(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as N_,SiteEditPageBlockDescriptorSchema as __,SiteEditSourcePathSchema as ah}from"@vcp-dev/contracts";function sa(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}),sh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function sh(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}),sh(s,t,n,r,o))}}function ai(e){let t=[],n={...e.graph,composition:e.composition},r=Cs(sa(n),n),o=[],i=new Map;for(let a of e.roots){let c=e.graph.elements.get(a.rootRef.key),l=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=T_(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!ah.safeParse(a.sourceFile).success||!d||!f||!ah.safeParse(d).success){t.push(bu("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(bu("block-key-ambiguous",a.sourceFile));continue}let g=ve(u.source),p=__.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:g},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:w_(a,e),capabilities:P_(c,r),...A_(c,r)});if(!p.success){t.push(bu("page-block-descriptor-invalid",a.sourceFile));continue}let h=p.data;o.push(h),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:h,root:a,ownerFile:d,ownerSourceHash:ve(f.source),ownerSourceContent:f.source,sourceHash:g,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName},rootLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName}})}let s=N_.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function P_(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function A_(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function T_(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function w_(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function bu(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Eu from"@babel/traverse";import{BlockRenderRefSchema as O_,SiteEditPageBlockPositionSchema as F_,SiteEditPageBlockTargetSchema as L_}from"@vcp-dev/contracts";var D_=typeof Eu=="function"?Eu:Eu.default;function ro(e,t,n,r){if(!L_.safeParse(t).success)return _t("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return _t("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return _t("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!O_.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?_t("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:_t("INVALID_TARGET","The page block target was not found.")}function aa(e,t){if(!F_.safeParse(t).success)return _t("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return _t("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return _t("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return _t("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return _t("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=ch(n);if(!i)return _t("INVALID_TARGET","The operation owner call site is unavailable.");let s=lh(n,i);if(s===void 0)return _t("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!M_(lh(u,ch(u)),s))return _t("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return _t("INVALID_TARGET","Anchor order is ambiguous.");let c=t.placement==="before"?o[a-1]:n,l=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:c?.blockKey??null,afterBlockKey:l?.blockKey??null}}}function ch(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function lh(e,t){if(!t)return;let n=Ke(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(D_(n.module.ast,{JSXElement(i){let s=Su(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=Su(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Su(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function M_(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function Su(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function _t(e,t){return{ok:!1,code:e,message:t}}import ph from"node:path";import{SiteEditSourcePathSchema as W_}from"@vcp-dev/contracts";import ca from"node:path";import vu from"@babel/traverse";import*as qn from"@babel/types";import{SiteEditSourcePathSchema as uh,SiteEditPageBlockTargetSchema as B_}from"@vcp-dev/contracts";var j_=typeof vu=="function"?vu:vu.default;function dh(e){if(!e.operationId)return Ze("INVALID_PARAMS","An operationId is required.");if(!B_.safeParse(e.target).success)return Ze("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return Ze("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return Ze("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return Ze("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return Ze("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!uh.safeParse(t).success)return Ze("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return Ze("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ve(n)!==e.binding.ownerSourceHash)return Ze("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ve(r)!==e.binding.descriptor.source.contentHash)return Ze("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return Ze("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let l=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(l!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(l??""))return Ze("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return Ze("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=V_(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?Jr({source:n,locator:$_(e.binding),node:{jsx:i.value.jsx}}):Kt({source:n,locator:Iu(o.parentLocator),anchorLocator:Iu(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return Ze("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=Jt({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return Ze("UNSUPPORTED_OPERATION",l.diagnostic.message);a=l.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function $_(e){return Iu(e.ownerLocator)}function Iu(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function V_(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:Ze("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return Ze("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=U_(t,e.component.source,r);if(!o)return Ze("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Ke(t,n);if(!i.ok)return Ze("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=K_(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??X_(z_(e.component.exportName,o),J_(i.module.ast)),c=H_(e.props??{});if(!c.ok)return c;let l=`<${a}${c.value?` ${c.value}`:""} />`;if(s)return{ok:!0,value:{jsx:l}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:l,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function U_(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?ca.posix.normalize(ca.posix.join(ca.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>uh.safeParse(i).success&&n.has(i))??null:null}function K_(e,t,n){for(let r of e)if(!(!qn.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&qn.isImportDefaultSpecifier(o)||n!=="default"&&qn.isImportSpecifier(o)&&(qn.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function J_(e){let t=new Set;return j_(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function X_(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function z_(e,t){let r=(e==="default"?ca.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function H_(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return Ze("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return Ze("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return Ze("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function Ze(e,t){return{ok:!1,code:e,message:t}}function fh(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return la("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&W_.safeParse(i.path).success))return la("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return la("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return la("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=Y_(t,e.materialization.entry.path),r=dh({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:G_(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function G_(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function Y_(e,t){let n=ph.posix.relative(ph.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function la(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as aP}from"@vcp-dev/contracts";import UV from"node:fs";import JV from"node:path";var Z_=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ci(e){let t=e.map(r=>sP(r.path)),n=Q_(t);return n?t.filter(r=>eP(n,r)).map(r=>({routeId:tP(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function ku(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=iP(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function Q_(e){return e.some(r=>r.startsWith("app/")&&!q_(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function q_(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function eP(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return Z_.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function tP(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(rP).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function nP(e){return e.startsWith("(")&&e.endsWith(")")}function rP(e){return!e||e.startsWith("@")||e.startsWith("_")||nP(e)?null:oP(e)}function oP(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function iP(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function sP(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var li=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Pt(e,t={}){throw new li("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Ru(e){return aP.safeParse(e).success||Pt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function mh(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Pt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Pt("invalid-template-key",{path:e})}return Ru(t)!==e&&Pt("noncanonical-template-key",{path:e}),t}function cP(e){let t=ku(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("(")||lP(r)&&!gh(r)))&&Pt("invalid-public-route",{routeId:e}),t}function lP(e){return e.includes("[")||e.includes("]")}function gh(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function hh(e){return e.some(gh)}function yh(e,t,n="app"){n!=="app"&&n!=="src/app"&&Pt("invalid-app-root");let r=cP(e),o=Ru(t),i=hh(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))&&Pt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function xh(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function bh(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===".")&&Pt("invalid-file-path",{path:i}),n.has(i)&&Pt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function da(e){let t=bh(e.files),n=ci([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new li("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(!xh(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Pt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=hh(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=mh(u),g=d.length?`/${d.join("/")}`:"/";yh(g,f,a).templateEntryFile!==i&&Pt("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&Pt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>ua(i.routeId,s.routeId)||ua(i.templateId,s.templateId))}function pa(e){let t=bh(e.files),n=da({files:t}),r=ci([...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)=>ua(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:ua(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function uP(e){let t=ku(e.selector.routeId),n=pa({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Pt("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||Pt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function ua(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as TP}from"@vcp-dev/contracts";import{parse as IP}from"@babel/parser";import{parse as qV}from"@babel/parser";import{FormBlockIdSchema as tU,FormSpecV1Schema as nU}from"@vcp-dev/contracts";var ui="components/site/generated/forms",rU=`${ui}/vcp-form-runtime.tsx`,fa="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",oU=new RegExp(`^${ui}/form-(${fa})\\.spec\\.ts$`),iU=new RegExp(`^${ui}/form-(${fa})\\.tsx$`),sU=new RegExp(`^@/${ui}/form-(${fa})$`),aU=new RegExp(`(?:^|/)${ui}/form-(${fa})(?:\\.tsx?)?$`);var cU=Symbol("invalid-literal");import{createHash as dU}from"node:crypto";import{posix as fU}from"node:path";import{parse as gU}from"@babel/parser";import{FormSpecV1Schema as yU}from"@vcp-dev/contracts";var xU=Symbol("dynamic");import{parse as dP}from"@babel/parser";function ma(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var pP=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Eh(e){let t=pP.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 fP(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Sh(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function mP(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Cu(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(Cu);if(t?.type==="ObjectExpression"){let n={};for(let r of ma(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Sh(r.key);if(!o)throw new Error("unsupported object key");n[o]=Cu(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Nu(e,t){let n=[],r=Eh(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=dP(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 ma(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of ma(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=mP(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 ma(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Sh(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=fP(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=Cu(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 gP}from"@babel/parser";var vh=["page","anchor","external","email","phone","group","file"],hP=["link","cta"],kh=["description","badge","iconKey"],_u=["label","targetType","href","role","openInNewTab","nofollow","children",...kh],yP=new Set(_u);function pi(e){return Array.isArray(e)?e:[]}function di(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}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 Ih(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Pu(e){let t=[],n;try{n=gP(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 pi(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of pi(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 pi(r.elements).forEach((i,s)=>{let a=Rh(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Rh(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 pi(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=xP(l.key);u&&(r[u]=l.value)}let o=di(r.label),i=di(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!vh.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${vh.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 kh){if(r[l]===void 0)continue;let u=di(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))yP.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 ${_u.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=[];pi(r.children.elements).forEach((u,d)=>{let f=Rh(u,`${t}.children[${d}]`,n);f&&l.push(f)}),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=di(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=di(r.role);if(c!==void 0&&(hP.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ih(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=Ih(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 bP}from"@babel/parser";function fi(e){return Array.isArray(e)?e:[]}function Ch(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function EP(e){let t;try{t=bP(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of fi(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of fi(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=Ch(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 Au(e,t){let n=Nh(t);if(!n)return{status:"unsupported",source:e};let r=EP(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Pu(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=fi(l.elements);for(let[d,f]of u.entries()){if(vP(f,n)){let p=u[d+1],h=u[d-1],y=f.start,x=f.end;if(typeof y!="number"||typeof x!="number")continue;if(p&&typeof p.start=="number")s.push({start:y,end:p.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:x});else{let E=/^\s*,/.exec(e.slice(x));s.push({start:y,end:E?x+E[0].length:x})}continue}let g=SP(f);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 SP(e){if(e.type==="ObjectExpression")for(let t of fi(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Ch(t.value)}}function Nh(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function vP(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of fi(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"&&Nh(n??"")===t}import{estimateNavLabelWidth as _U}from"@vcp-dev/contracts";import{parse as TU}from"@babel/parser";function Mn(e,t){let n;try{n=IP(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(N){let A=N.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:N instanceof Error?N.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:A?.line??1}]}}let r=n.program,o=Ft(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=N=>{if(N?.type==="FunctionDeclaration"){let A=N.id;A?.type==="Identifier"&&typeof A.name=="string"&&s.set(A.name,N);return}if(N?.type==="VariableDeclaration")for(let A of Ft(N.declarations)){let L=A.id,$=A.init;L?.type==="Identifier"&&typeof L.name=="string"&&$&&(er($)?s.set(L.name,$):$.type==="Identifier"&&typeof $.name=="string"&&a.set(L.name,$.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let A=N.source?.value;if(typeof A!="string")continue;for(let L of Ft(N.specifiers)){let $=L.local;if(!($?.type!=="Identifier"||typeof $.name!="string")){if(L.type==="ImportDefaultSpecifier")i.set($.name,{source:A,exportName:"default"});else if(L.type==="ImportNamespaceSpecifier")i.set($.name,{source:A,exportName:"*"});else if(L.type==="ImportSpecifier"){let U=L.imported,de=U?.type==="Identifier"&&typeof U.name=="string"?U.name:U?.type==="StringLiteral"&&typeof U.value=="string"?U.value:"";de&&i.set($.name,{source:A,exportName:de})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let $=N.declaration;$&&er($)?c.set("default",$):$?.type==="Identifier"&&typeof $.name=="string"&&c.set("default",$.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let A=N.declaration;if(A?.type==="FunctionDeclaration"){let $=A.id;$?.type==="Identifier"&&typeof $.name=="string"&&c.set($.name,$.name)}else if(A?.type==="VariableDeclaration")for(let $ of Ft(A.declarations)){let U=$.id;U?.type==="Identifier"&&typeof U.name=="string"&&c.set(U.name,U.name)}let L=N.source?.value;for(let $ of Ft(N.specifiers)){let U=Ah($.local),de=Ah($.exported);if(!(!U||!de))if(typeof L=="string"){let z=`#re-export:${de}`;i.set(z,{source:L,exportName:U}),c.set(de,z)}else c.set(de,U)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,h=[],y=new Map,x=!1,E=[],b=new Map,v=new Map,_=(N,A="rendered")=>{let L=Ph(N,i);if(!L)return!1;let $=`${L.source}\0${L.exportName}`;if(A==="uncertain")return!f.has($)&&!p.has($)&&(p.add($),g.push({source:L.source,export_name:L.exportName})),!0;if(!f.has($)&&(f.add($),d.push({source:L.source,export_name:L.exportName}),p.delete($))){let U=g.findIndex(de=>de.source===L.source&&de.export_name===L.exportName);U>=0&&g.splice(U,1)}return!0},P=(N,A="rendered",L=[])=>{let $=`${A}\0${wu(L)}`,U=b.get(N)??new Set,de=v.get(N)??new Set;if(U.has($)||de.has(A))return;U.add($),b.set(N,U),de.add(A),v.set(N,de);let z=new Map(s),Q=new Map,ke=[],ct=(he,Qe=!1)=>{if(ga(he)){if(!Qe&&er(he)){if(he.type==="FunctionDeclaration"){let Pe=he.id;Pe?.type==="Identifier"&&typeof Pe.name=="string"&&z.set(Pe.name,he)}return}if(he.type==="VariableDeclarator"){let Pe=he.id,ce=he.init;Pe?.type==="Identifier"&&typeof Pe.name=="string"&&ce&&(er(ce)?z.set(Pe.name,ce):Q.set(Pe.name,ce))}else if(he.type==="ReturnStatement"){let Pe=he.argument;Pe&&ke.push(Pe)}if(he.type==="CallExpression"){let Pe=he.callee;if(Pe?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:he.loc?.start.line??1}),mi(Pe)==="cms.forms.getConfig"){let ce=Ft(he.arguments)[0];ce?.type==="StringLiteral"&&typeof ce.value=="string"&&ce.value.trim()?A==="rendered"?u.add(ce.value.trim()):E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:he.loc?.start.line??1}):E.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:he.loc?.start.line??1})}}for(let[Pe,ce]of Object.entries(he))if(Pe!=="loc")if(Array.isArray(ce))for(let $e of ce)ct($e);else ct(ce)}};ct(N,!0);let lt=new Set,Ro=new Set,Qt=(he,Qe=A,Pe=L)=>{if(!(!ga(he)||er(he))){if(he.type==="Identifier"&&typeof he.name=="string"){let ce=Q.get(he.name),$e=`${Qe}\0${he.name}\0${wu(Pe)}`;ce&&!lt.has($e)&&!Ro.has(he.name)?(lt.add($e),Ro.add(he.name),Qt(ce,Qe,Pe),Ro.delete(he.name)):_(he.name,Qe);return}if(he.type==="CallExpression"){let ce=he.callee,$e=Ft(he.arguments),mt=mi(ce),qt=ce?.type==="Identifier"&&typeof ce.name=="string"?i.get(ce.name):void 0;if(Qe==="rendered"&&(mt==="createElement"||mt.endsWith(".createElement")||qt?.source==="react"&&qt.exportName==="createElement")&&$e[0]?.type==="StringLiteral"&&$e[0].value==="form"&&(x=!0),ce?.type==="Identifier"&&typeof ce.name=="string"){let gt=z.get(ce.name);if(gt){P(gt,Qe,Pe);return}}if(ce&&er(ce)){P(ce,Qe,Pe);return}if(CP(ce)){for(let gt of $e)if(er(gt))P(gt,Qe,Pe);else if(gt.type==="Identifier"&&typeof gt.name=="string"){let $r=z.get(gt.name);$r&&P($r,Qe,Pe)}return}for(let gt of $e)NP(gt)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:gt.loc?.start.line??1});return}if(he.type==="JSXElement"){let ce=he.openingElement,$e=ce?_h(Pe,kP(ce)):Pe;Qt(ce,Qe,$e);for(let mt of Ft(he.children))Qt(mt,Qe,$e);return}if(he.type==="JSXOpeningElement"){let ce=ha(he.name);Qe==="rendered"&&ce==="form"&&(x=!0);let $e=ce?Ph(ce,i):void 0;if(Qe==="rendered"&&$e&&typeof he.start=="number"){let mt=`${$e.source}\0${$e.exportName}\0${he.start}`,qt=y.get(mt);if(!qt){let gt=_P(he).get("formBlockId");qt={source:$e.source,export_name:$e.exportName,start_offset:he.start,...typeof gt=="string"?{static_form_block_id:gt}:{}},y.set(mt,qt),h.push(qt)}Pe.length>0&&(qt.static_render_blockers=_h(qt.static_render_blockers??[],Pe))}if(ce&&!_(ce,Qe)){let mt=z.get(ce);mt?P(mt,Qe,Pe):Q.has(ce)?Qt(Q.get(ce),Qe,Pe):RP(ce)||/^[A-Z]/.test(ce)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ce} from a static import.`,file_path:t.filePath??"",line:he.loc?.start.line??1})}for(let mt of Ft(he.attributes))Qt(mt,"uncertain",Pe);return}if(he.type==="JSXAttribute"){let ce=he.value,$e=ce?.type==="JSXExpressionContainer"?ce.expression:ce;$e&&er($e)?P($e,"uncertain",Pe):Qt($e,"uncertain",Pe);return}for(let[ce,$e]of Object.entries(he))if(!(ce==="loc"||ce==="closingElement"))if(Array.isArray($e))for(let mt of $e)Qt(mt,Qe,Pe);else Qt($e,Qe,Pe)}},Co=N.body;Co&&Co.type!=="BlockStatement"&&ke.push(Co);for(let he of ke)Qt(he);de.delete(A)},R=c.get(t.exportName);if(typeof R=="string"){let N=R,A=new Set;for(;a.has(N)&&!A.has(N);)A.add(N),N=a.get(N);if(!_(N)){let L=s.get(N);L?P(L):E.push(Th(t))}}else R?P(R):E.push(Th(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:h,renders_native_form:x,diagnostics:E}}function wu(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function _h(e,t){return[...new Map([...e,...t].map(r=>[wu([r]),r])).values()]}function kP(e){let t=new Map;for(let a of Ft(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=wh(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=ha(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:AP(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Tu(t.get(a));(c===!0||(a==="aria-hidden"?c==="true":typeof c=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let l of Ft(i.properties)){let u=l.key,d=!l.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;l.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,Tu(l.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let c=a.get("opacity");(c===0||typeof c=="string"&&c.trim()==="0")&&o("style.opacity=0")}let s=Tu(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),l={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(l))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function Tu(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&Ft(e.expressions).length===0)return Ft(e.quasis)[0]?.value?.cooked}}function Ph(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function RP(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function er(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function CP(e){let t=mi(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function NP(e){let t=!1;return Ou(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&mi(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Ah(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Th(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function mi(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=mi(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function _P(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=wh(o.name);i&&t.set(i,PP(o.value))}return t}function PP(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function wh(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function AP(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Ou(e,t){if(ga(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)Ou(o,t);continue}Ou(r,t)}}}function ga(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ha(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=ha(t.object),r=ha(t.property);return n&&r?`${n}.${r}`:r||n}return""}function Ft(e){return Array.isArray(e)?e.filter(t=>ga(t)):[]}var wP="components/site/generated/",gi=[".tsx",".ts",".jsx",".js"];function Oh(e){if(e.expectedUrlPath===TP)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(ci(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let x=h.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Nu(y,x);return E.found&&E.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=da({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=OP(e.files);if(!i.ok)return i.error;let s=i.graph,a=MP(o,s),c=BP(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),f=u.map(h=>({operation:"delete",file:h})),g=[],p=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let x=Au(y,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:h,content:x.source}),g.push(h)):x.status==="unsupported"&&p.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&p.push(`preserved_link:${h}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:p}}function OP(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")||!FP(r))continue;let s=Ke(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(LP(c))continue;let l=Nn(r,c),u=DP(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 FP(e){let t=e.toLowerCase();return gi.some(n=>t.endsWith(n))}function LP(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!gi.some(n=>e.endsWith(n)))}function DP(e,t){let n=e.replace(/\\/g,"/");return(gi.some(o=>n.endsWith(o))?[n]:[...gi.map(o=>`${n}${o}`),...gi.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function MP(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(wP)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function BP(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 Fy from"@babel/parser";import*as _e from"@babel/types";import*as Fa from"node:path";import*as Fe from"@babel/types";function Fh(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 gn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return _r(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Fe.isObjectPattern(n)||Fe.isArrayPattern(n))return _r(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($P(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function _r(e,t,n=!1){return Fe.isIdentifier(e)?e.name===t&&n:Fe.isObjectPattern(e)?e.properties.some(r=>Fe.isObjectProperty(r)?_r(r.value,t,n):_r(r.argument,t,n)):Fe.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Fe.isRestElement(r)?r.argument:r;return _r(o,t,n)}):Fe.isAssignmentPattern(e)?_r(e.left,t,!0):Fe.isRestElement(e)?_r(e.argument,t,n):!1}function oo(e,t){if(e.path.isObjectPattern()){if(t){let r=on(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:gn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:gn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Lh(r),i=!1,s=o?o.initBinding&&Fu(o.initBinding)?(i=gn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=oo(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=on(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||gn(e)}}}}let n=KP(e);if(n){let r=jP(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||gn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=VP(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:gn(e)}}let i=hi(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:gn(e)}:null}if(Fu(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:gn(e)}}return null}function jP(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=Lh(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Fu(i)?(a=gn(i),[...s]):(()=>{let u=oo(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=on(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||gn(t)}:null}function Lh(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=JP(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Fu(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function $P(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function VP(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=on(i.node,t);if(a)return a}return null}function Dh(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=ya(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=hi(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=UP(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=hi(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 ya(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=hi(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&on(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=ya(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=ya(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=ya(r,t);if(o)return o}}return null}function on(e,t,n=[]){if(Fe.isIdentifier(e))return e.name===t?n:null;if(Fe.isObjectPattern(e)){for(let r of e.properties)if(Fe.isObjectProperty(r)){let o=hi(r);if(!o)continue;let i=on(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Fe.isRestElement(r)){let o=on(r.argument,t,n);if(o)return o}}if(Fe.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Fe.isRestElement(o)?o.argument:o,s=on(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Fe.isAssignmentPattern(e)?on(e.left,t,n):null}function UP(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function KP(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 hi(e){return e.computed?null:Fe.isIdentifier(e.key)?e.key.name:Fe.isStringLiteral(e.key)?e.key.value:null}function JP(e){let t=[],n=e;for(;Fe.isMemberExpression(n);){if(n.computed)if(Fe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Fe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Fe.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Fe.isIdentifier(n)?{base:n.name,path:t}:null}import*as Uh from"@babel/parser";import Mu from"@babel/traverse";import*as io from"@babel/types";import*as Ee from"@babel/types";var Mh=new WeakMap;function Ea(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?xa(n,t):null}if(e.isMemberExpression()){let n=YP(e.node),r=XP(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?xa(o,[...r,...t]):null}return e.isAwaitExpression()||Du(e.node)?tr(QP(e.node),t,"awaited or fetched expression"):null}function XP(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?t:null}function xa(e,t=[],n){let r=zP(e,t);if(r)return r;let o=HP(e,t,n);if(o)return o;let i=WP(e,t,n);return i||null}function xi(e){return e?.kind==="api-source"}function zP(e,t){if(e.path.isVariableDeclarator()&&Ee.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Lu(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return tr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ee.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Ee.isObjectProperty(c)&&$h(c)==="data"&&yi(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Lu(a.node))return tr(e.identifier.name,t,"query hook data binding")}let n=GP(e);if(!n||$h(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()||!Lu(i.node)?null:tr(e.identifier.name,t,"query hook data binding")}function HP(e,t,n){if(e.path.isVariableDeclarator()&&Ee.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!jh(c.node))return null;let[l,u]=e.path.node.id.elements;return!Ee.isIdentifier(l)||l.name!==e.identifier.name||!Ee.isIdentifier(u)?null:Bh(e,u.name,n)?tr(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()||!jh(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Ee.isIdentifier(a)&&Bh(e,a.name,n)?tr(e.identifier.name,t,"state setter is updated by API data"):null}function WP(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()?tr(e.identifier.name,t,"awaited binding result"):Du(o.node,n)?tr(e.identifier.name,t,"fetch-backed binding result"):null:null}function GP(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 yi(e,t){return Ee.isIdentifier(e)?e.name===t:Ee.isAssignmentPattern(e)?yi(e.left,t):Ee.isObjectPattern(e)?e.properties.some(n=>Ee.isObjectProperty(n)?yi(n.value,t):yi(n.argument,t)):Ee.isArrayPattern(e)?e.elements.some(n=>!!n&&yi(Ee.isRestElement(n)?n.argument:n,t)):!1}function Bh(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Mh.get(n);c||(c=new WeakMap,Mh.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){Du(c.node)&&(r=!0),(ZP(c.node.callee,t)||c.node.arguments.some(l=>Ee.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Lu(e){let t=Sa(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function jh(e){return Sa(e.callee)==="useState"}function Du(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=ba(e,o=>Ee.isCallExpression(o)&&Sa(o.callee)==="fetch");return t?.set(e,r),r}function YP(e){let t=e;for(;Ee.isMemberExpression(t);)t=t.object;return Ee.isIdentifier(t)?t.name:null}function $h(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function Sa(e){return Ee.isIdentifier(e)?e.name:Ee.isMemberExpression(e)&&Ee.isIdentifier(e.property)?e.property.name:null}function ZP(e,t){return ba(e,n=>Ee.isIdentifier(n)&&n.name===t)}function ba(e,t){if(t(e))return!0;let n=Ee.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(Ee.isNode(i)&&ba(i,t))return!0;continue}if(Ee.isNode(o)&&ba(o,t))return!0}return!1}function QP(e){return Ee.isIdentifier(e)?e.name:Ee.isCallExpression(e)?Sa(e.callee)??"api":Ee.isAwaitExpression(e)?"awaited-api":"api"}function tr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:qP(e,t),reason:n}}function qP(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Kh=typeof Mu=="function"?Mu:Mu.default;function Jh(e,t){let n=zh(e);if(!n)return{allowed:!0};let r=!1;return Kh(n,{CallExpression(o){if(!Hh(o.node,t.sourceRange)||!eA(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||xi(Ea(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Xh(e,t){let n=zh(e);if(!n)return{allowed:!0};let r=!1;return Kh(n,{JSXExpressionContainer(o){Hh(o.node,t.sourceRange)&&(io.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 zh(e){try{return Uh.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function eA(e){let t=e.callee;return io.isMemberExpression(t)&&io.isIdentifier(t.property)&&t.property.name==="map"}function Hh(e,t){let n=e.loc;return n?Vh({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Vh({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Vh(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 q from"@babel/types";import*as Wh from"@babel/parser";import Bu from"@babel/traverse";import*as Xe from"@babel/types";import*as so from"node:path";var sn=typeof Bu=="function"?Bu:Bu.default;function it(e){try{return Wh.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ju(e){return e.computed?Xe.isStringLiteral(e.key)||Xe.isNumericLiteral(e.key)?String(e.key.value):null:tA(e.key)}function tA(e){return Xe.isIdentifier(e)?e.name:Xe.isStringLiteral(e)||Xe.isNumericLiteral(e)?String(e.value):null}function Pr(e){return Xe.isParenthesizedExpression(e)||Xe.isTSAsExpression(e)||Xe.isTSSatisfiesExpression(e)||Xe.isTSNonNullExpression(e)||Xe.isTSTypeAssertion(e)?Pr(e.expression):Xe.isExpression(e)?e:null}function $u(e){if(Xe.isIdentifier(e))return[e.name];if((Xe.isMemberExpression(e)||Xe.isOptionalMemberExpression(e))&&!e.computed&&Xe.isIdentifier(e.property)){let t=Pr(e.object),n=t?$u(t):null;return n?[...n,e.property.name]:null}return null}function Ar(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?so.normalize(so.join(so.dirname(e),t)).replace(/\\/g,"/"):t}function Lt(e,t){return va(e)===va(t)}function va(e){let t=ao(e);return t.endsWith("/index")?t.slice(0,-6):t}function ao(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Zh(e,t,n){let r=ty(e,t);if(ny(e,r),ry(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 sn(e,{JSXElement(s){ay(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Ia(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 Qh(e,t){let n=new Map,r=i=>{let s=co(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 nA(i,n))o=r(s)||o}return[...n.values()]}function nA(e,t){let n=[],r=rA(e,t);for(let o of e.ast.program.body){if(q.isExportDefaultDeclaration(o)&&q.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=bi(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(q.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Ar(e.file,o.source.value);for(let s of o.specifiers){if(q.isExportNamespaceSpecifier(s)){let l=nr(s.exported);for(let u of t.values())Lt(u.file,i)&&n.push({file:e.file,namespace:Vu(l,u.namespace),exportName:u.exportName});continue}if(!q.isExportSpecifier(s))continue;let a=nr(s.local),c=[...t.values()].filter(l=>Lt(l.file,i)&&Tr(l.namespace,a));if(c.length>0){let l=nr(s.exported);for(let u of c){let d=bi(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(co({file:i,exportName:a}))&&n.push({file:e.file,exportName:nr(s.exported)})}continue}if(q.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!q.isExportSpecifier(i))continue;let s=nr(i.local),a=r.get(s)??[];if(a.length>0){let c=nr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=bi(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(q.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Ar(e.file,o.source.value),s=o.exported;if(s){let a=nr(s);for(let c of t.values())Lt(c.file,i)&&n.push({file:e.file,namespace:Vu(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Lt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Vu(e,t){return t?`${e}.${t}`:e}function Tr(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function bi(e,t,n){return!Tr(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function rA(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(!q.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Ar(e.file,i.source.value);for(let a of i.specifiers){if(q.isImportDefaultSpecifier(a)){let c=t.get(co({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Lt(u.file,s)&&Tr(u.namespace,"default"));for(let u of l){let d=bi(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(q.isImportSpecifier(a)){let c=nr(a.imported),l=[...t.values()].filter(d=>Lt(d.file,s)&&Tr(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(co({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(q.isImportNamespaceSpecifier(a))for(let c of t.values())Lt(c.file,s)&&r(a.local.name,{...c,namespace:Vu(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(q.isVariableDeclaration(i))for(let s of i.declarations){if(!q.isIdentifier(s.id)||!s.init)continue;let a=Pr(s.init);if(!a||!q.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(co));for(let d of c){let f=bi(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=co(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function co(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${va(e.file)}#${t}`}function nr(e){return q.isIdentifier(e)?e.name:e.value}function qh(e,t){for(let n of e.program.body){if(q.isExportDefaultDeclaration(n)){let o=n.declaration;if((q.isFunctionDeclaration(o)||q.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(q.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!q.isExportNamedDeclaration(n))continue;let r=n.declaration;if((q.isFunctionDeclaration(r)||q.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(q.isVariableDeclaration(r)){for(let o of r.declarations)if(q.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!q.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:q.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Ku(e){let t=oA(e),n=[],r=ry(e.ast,t);return sn(e.ast,{JSXElement(o){Lt(e.file,e.sourceFile)&&Ia(o)===e.sourceComponent||ay(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function ey(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function ty(e,t){let n=ey();return sn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function oA(e){let t=ey();return Lt(e.file,e.sourceFile)&&iA(t,ty(e.ast,e.sourceComponent)),sn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Ar(e.file,o),s=e.componentIdentities.filter(a=>Lt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(q.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),q.isImportDefaultSpecifier(a)){let l=s.filter(u=>Tr(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=Yh(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(q.isImportSpecifier(a)){let l=q.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Tr(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=Yh(f,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(q.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)}}}}}),ny(e.ast,t),t}function iA(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 ny(e,t){sn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Pr(n.node.init);if(r){if(q.isIdentifier(n.node.id)){let o=wr(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Uu(t,i,o);return}if(q.isObjectPattern(n.node.id)){let o=wr(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&sy(n.node.id,o.namespaceMembers,t,n)}}}})}function ry(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return sn(e,{ReferencedIdentifier(r){if(n){r.stop();return}sA(r)||!r.isIdentifier()||!oy(r,t)||aA(r,t)||cA(r)||(n=!0,r.stop())}}),n}function sA(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 oy(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)&&wr(r.node,t,r)?r:null}function aA(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Gh(e,r))return!1;let o=oy(e,t);if(!o)return!1;if(Pr(r.node)===o.node)return!!wr(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Gh(e,a)&&!!wr(a.node,t,a)}function cA(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Gh(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function wr(e,t,n){let r=Pr(e);if(!r)return null;if(q.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(q.isObjectExpression(r))return lA(r,t,n);let o=$u(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?iy(s,o.slice(1).join(".")):null}function lA(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!q.isObjectProperty(i))continue;let s=ju(i);if(!s||!q.isExpression(i.value)){q.isExpression(i.value)&&(o||=wr(i.value,t,n)!==null);continue}let a=wr(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 iy(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 Uu(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 sy(e,t,n,r){for(let o of e.properties){if(q.isRestElement(o)){if(q.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Uu(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!q.isObjectProperty(o))continue;let i=ju(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=iy(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=q.isAssignmentPattern(o.value)?o.value.left:o.value;if(q.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Uu(n,c,s);continue}if(q.isObjectPattern(a)&&s.namespaceMembers.size>0){sy(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Yh(e,t){if(!Tr(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 ay(e,t){let n=e.node.openingElement.name;if(q.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=cy(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 cy(e){if(q.isJSXIdentifier(e))return[e.name];if(q.isJSXMemberExpression(e)){let t=cy(e.object);return t?[...t,e.property.name]:null}return null}function Ia(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()&&q.isIdentifier(n.node.id))return n.node.id.name}return null}function ly(e,t){let n=it(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Ku({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 Oe(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 Te(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function hn(e,t){let n=Te(e);return!!(n&&Dt(t,n))}function Dt(e,t){return t.start>=e.start&&t.end<=e.end}function Gt(e,t){let n=xe(e,Oe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ka(e,t)}function lo(e,t){let n=Te(t);return n?e.slice(n.start,n.end):""}function uy(e,t){return e.start===t.start&&e.end===t.end}function ka(e,t){let n=null;return sn(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 Ra(e,t){return Ju(e,t).length>0}function Ca(e,t){let n=Te(e.node),r=Te(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()&&!uA(o,n,r)))return!0;o=o.parentPath}return!1}function uA(e,t,n){let r=Te(e.node.consequent);if(r&&Dt(r,t)&&!Dt(r,n))return!1;let o=e.node.alternate?Te(e.node.alternate):null;return!(o&&Dt(o,t)&&!Dt(o,n))}function Ju(e,t){let n=Te(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=Te(o.node.consequent),a=Te(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()&&Xu(o.node.operator)){let s=Te(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 Xu(e){return e==="&&"||e==="||"||e==="??"}function dy(e,t){let n=Te(e.consequent);if(n&&Dt(n,t))return n;let r=Te(e.alternate);return r&&Dt(r,t)?r:null}function py(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=>ao(a.file)));if(!t.has(ao(e.sourceFile))||!t.has(ao(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(ao(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=qh(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=it(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=Qh(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Ku({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!Lt(s.file,e.targetFile)||Ia(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 hA}from"@vcp-dev/contracts";function Na(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 Ei();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Ei();let u=dA(a,l,o?.instanceCount);if(!u)return Ei();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"?Ei():{ok:!0,target:{kind:"jsx-attribute"}}}function Ei(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function dA(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 yn from"@babel/types";import{SiteEditSetPropsParamsSchema as pA}from"@vcp-dev/contracts";function fy(e){let t=e.changes??(e.change?[e.change]:[]);if(!pA.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Si("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Si("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=je(e.source,"value");if(!o.ok)return Si("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=xe(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Si("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?fA(r):mA(c.match.path.node,r.name);if(!l)return Si("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 fA(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function mA(e,t){let n=e.properties.filter(i=>yn.isObjectProperty(i)&&gA(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!yn.isExpression(r.value))return null;let o=mn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function gA(e){return yn.isIdentifier(e)?e.name:yn.isStringLiteral(e)?e.value:yn.isNumericLiteral(e)?String(e.value):null}function Si(e,t){return{ok:!1,errorCode:e,reason:t}}function my(e){if(e.change.name!=="className"&&e.change.name!=="class")return vi("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return vi("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return vi("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return vi("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 vi("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 vi(e,t){return{ok:!1,errorCode:e,reason:t}}async function hy(e){let t=hA.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return rr("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 rr("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 yA(e,r);if(o){if(!o.ok)return rr("owner-plan-failed",o.reason);gy(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return rr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return rr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(EA(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=Na({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return rr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){zu(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=fy({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return rr("repeat-target-failed",l.reason);gy(n,l.steps);continue}zu(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:xA(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),bA(n)?rr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function yA(e,t){return t.name!=="className"&&t.name!=="class"?null:my({node:e.node,change:t,classNameSource:e.classNameSource})}function xA(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 bA(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 gy(e,t){for(let n of t)zu(e,{...n,order:e.length})}function zu(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 EA(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Hu(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Hu(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)=>Hu(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=>Hu(n[i],r[i]))}return!1}function rr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as po from"@babel/types";import*as oe from"@babel/types";function Wu(e,t,n){let r=Gt(t,n);return r?xn(e,r):null}function xn(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(!oe.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=lo(e,u.node),f=r.node.params.map(h=>lo(e,h)),g=Te(i.node),p=Te(r.node);return!d||f.some(h=>h.length===0)||!g||!p?null:{callStart:g.start,callEnd:g.end,callbackStart:p.start,callbackEnd:p.end,collectionExpression:d,callbackParams:f,mapOperator:oe.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:_a(u.node),callbackPath:r,collectionPath:u}}function Ii(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function SA(e,t){let n=Te(e.node);return n?vA(t).some(r=>{let o=Te(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function vA(e){let t=e.callbackPath.node.body;return oe.isBlockStatement(t)?or(t.body):ir(t)}function or(e){let t=[];for(let n of e){if(oe.isReturnStatement(n)){n.argument&&t.push(...ir(n.argument));continue}if(oe.isBlockStatement(n)){t.push(...or(n.body));continue}if(oe.isIfStatement(n)){let r=oe.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...or(r)),n.alternate){let o=oe.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...or(o))}continue}if(oe.isSwitchStatement(n)){for(let r of n.cases)t.push(...or(r.consequent));continue}oe.isTryStatement(n)&&(t.push(...or(n.block.body)),n.handler&&t.push(...or(n.handler.body.body)),n.finalizer&&t.push(...or(n.finalizer.body)))}return t}function ir(e){return oe.isJSXElement(e)?IA(e)?yy(e.children):[e]:oe.isJSXFragment(e)?yy(e.children):oe.isParenthesizedExpression(e)||oe.isTSAsExpression(e)||oe.isTSSatisfiesExpression(e)||oe.isTSNonNullExpression(e)||oe.isTSTypeAssertion(e)?ir(e.expression):oe.isConditionalExpression(e)?[...ir(e.consequent),...ir(e.alternate)]:oe.isLogicalExpression(e)&&Xu(e.operator)?ir(e.right):[]}function yy(e){return e.flatMap(t=>oe.isJSXElement(t)||oe.isJSXFragment(t)?ir(t):oe.isJSXExpressionContainer(t)&&(oe.isJSXElement(t.expression)||oe.isJSXFragment(t.expression)||oe.isConditionalExpression(t.expression)||oe.isLogicalExpression(t.expression))?ir(t.expression):[])}function IA(e){let t=e.openingElement.name;return oe.isJSXIdentifier(t)?t.name==="Fragment":oe.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function xy(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function _a(e){return!(oe.isIdentifier(e)||oe.isThisExpression(e)||oe.isMemberExpression(e)||oe.isOptionalMemberExpression(e)||oe.isCallExpression(e)||oe.isOptionalCallExpression(e))}function by(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(oe.isMemberExpression(n)||oe.isOptionalMemberExpression(n))&&oe.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function uo(e,t){let n=it(e);if(!n)return t.isRepeatItemRoot===!0;let r=xe(n,Oe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ka(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=xn(e,o);return i?SA(o,i):t.isRepeatItemRoot===!0}function Ey(e,t){let n=it(e);if(!n)return!1;let r=xe(n,Oe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ka(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(oe.isMemberExpression(s)||oe.isOptionalMemberExpression(s))&&oe.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as De from"@babel/types";function Gu(e){if(De.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(De.isJSXMemberExpression(e)){let t=e;for(;De.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function kA(e,t){let n=Te(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||hn(a.path.node,n)||sr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Gu(i.node.name);s&&o(s,i)}}),[...r].sort()}function Yu(e,t,n){let r=it(e);if(!r)return{ok:!0};let o=xe(r,Oe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=xe(r,Oe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Mo(o.match.path,i.match.path);if(Ra(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=kA(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function vy(e){let t=e;for(;De.isTSQualifiedName(t);)t=t.left;return De.isIdentifier(t)?t.name:null}function ki(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Pa(e){let t=[],n=r=>{if(r){if(De.isIdentifier(r)){t.push(r.name);return}if(De.isObjectPattern(r)){for(let o of r.properties){if(De.isRestElement(o)){n(o.argument);continue}De.isObjectProperty(o)&&n(o.value)}return}if(De.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(De.isAssignmentPattern(r)){n(r.left);return}if(De.isRestElement(r)){n(r.argument);return}De.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Zu(e,t){let n=Te(e.node),r=Te(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=Sy(e),i=Sy(t);if(!o||!i||!uy(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=dy(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=Te(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())&&by(s)){let a=Te(s.node.body)??Te(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 Sy(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Te(t.node.argument):null;if(t.isArrowFunctionExpression()&&(De.isJSXElement(t.node.body)||De.isJSXFragment(t.node.body)||De.isConditionalExpression(t.node.body)||De.isLogicalExpression(t.node.body)))return Te(t.node.body);t=t.parentPath}return null}function sr(e,t,n){return n.scope.getBinding(t)===e}function Qu(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Ra(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Te(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Pa(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||hn(u.path.node,o)||i.has(u.path.node)||sr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Gu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function qu(e,t,n){let r=Te(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Pa(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ki(e,s=>{let a=s.scope.getBinding(s.node.name);!a||hn(a.path.node,r)||o.has(a.path.node)||sr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Iy(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Pa(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)||sr(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(po.isIdentifier(l))o(l.name,c);else{let u=vy(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function ed(e,t){let n=Te(e.node),r=new Set;return ki(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&hn(i.path.node,n)||sr(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 ky(e){let t=[];for(let n of e.callbackPath.node.params){if(po.isIdentifier(n)){t.push(n.name);continue}if(po.isRestElement(n)&&po.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 Ry(e,t){return{...e,callbackParams:t}}function td(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ri(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 Cy(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 Or(e){return{file:e.file,component:e.component}}function RA(e){return e.target.kind==="node"?e.target.key:null}function CA(e){return"kind"in e&&e.kind==="page-composition"}function wa(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Aa(e){return!CA(e)&&!wa(e)}function sd(e,t){let n=Fa.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Fa.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function nd(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=pn(n,Oe(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function cd(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 NA(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function _A(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 rd(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function PA(e){let t=Zh(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Zu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=AA({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Ly(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?_a(o):!0}}}function AA(e){let t=Te(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||hn(a.path.node,t))return;let c=OA(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=LA(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=TA(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=ed(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}sr(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:DA(e.source,t,[...n.values()])}}function TA(e,t){if(t.length===0)return e;let n=Ly(e);if(!n)return null;let r=_a(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=wA(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function wA(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function OA(e,t,n){let r=FA(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=oo(t,o);if(!i)return null;let s=r?.range??Te(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function FA(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!hn(n.node,t)||n.node.computed||!_e.isIdentifier(n.node.property))return null;let r=Te(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function LA(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()&&_e.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=lo(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 DA(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 Ly(e){try{let n=Fy.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=_e.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&_e.isExpression(r)?r:null}catch{return null}}function MA(e){let t=Te(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||hn(s.path.node,t))return;let a=Ny(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Ny(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!BA(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 ki(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 BA(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 Ny(e,t,n){let r=jA(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Ar(t,i),a=i.startsWith(".")?sd(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=_e.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 jA(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function _y(e,t,n,r){let o=Ju(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=lo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=$A(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${UA(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function $A(e,t){return VA(e.node)?t:`(${t})`}function VA(e){return _e.isIdentifier(e)||_e.isThisExpression(e)||_e.isSuper(e)||_e.isMemberExpression(e)||_e.isOptionalMemberExpression(e)||_e.isCallExpression(e)||_e.isOptionalCallExpression(e)||_e.isBooleanLiteral(e)||_e.isNumericLiteral(e)||_e.isStringLiteral(e)||_e.isNullLiteral(e)||_e.isUnaryExpression(e)}function UA(e){return e.trim().startsWith("<")?e:`(${e})`}var KA={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 Ta(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=KA[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 JA(e,t){for(let n of e.program.body){if(!_e.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>_e.isImportDefaultSpecifier(o));if(r&&_e.isImportDefaultSpecifier(r))return r.local.name}return null}function XA(e,t,n){for(let r of e.program.body){if(!_e.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>_e.isImportSpecifier(i)&&(_e.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&_e.isImportSpecifier(o))return o.local.name}return null}function Py(e){let t=new Set;return sn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Ay(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function zA(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=cd(e),o=it(t);if(n.exportName!=="default"){let a=o?XA(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Ay(r,Py(o)):r;return{localName:c,importStep:od(e,c)}}if(!o)return{localName:r,importStep:od(e,r)};let i=JA(o,n.source);if(i)return{localName:i};let s=Ay(r,Py(o));return{localName:s,importStep:od(e,s)}}function HA(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??cd(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 WA(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?GA(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function GA(e){return Object.fromEntries(Object.entries(e).filter(t=>ad(t[1])))}function ad(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ad):typeof e=="object"?Object.values(e).every(ad):!1}function od(e,t=cd(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 Ty(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 YA(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function fo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function ld(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Ci(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:ld(e,t.slice(0,n)),index:r.index}}return null}function id(e,t){return e.locator?e.collectionPathMap?.[t]?ld(e.locator,e.collectionPathMap[t]):Ci(e.locator)?QA(e.locator,qA(t,e.collectionIndexMap)):null:null}function ZA(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:Dy(o,t)}function Dy(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Dy(r,t);return o===void 0?void 0:{[n.name]:o}}function QA(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},ld(e,i)}return null}function qA(e,t){return t?.[e]??e}function wy(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 eT(e,t){return tT(e.root,t.root)&&rT(e.path??[],t.path??[])}function tT(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&&nT(e.sourceRange,t.sourceRange)}}function nT(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function rT(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 Oa=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:fo(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:fo(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:fo(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:fo(t.kind,t.params.kind)};let r=t;if(wa(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Aa(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Ty(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:fo(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:fo(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=RA(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):Oy(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 Oy(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:Oe(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?hy({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 p=id(u,i.instanceIndex);if(!p)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=p}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:Oe(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=id(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:Oe(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=it(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=xe(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!NA(a.match.path))return{ok:!0,value:r};let c=_A(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=id(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=it(this.graph.getFileContent(t));if(!o)return!1;let i=xe(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 f=Ci(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ri(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:Oe(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||ly(n,t)>1)return null;let r=sd(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(!Aa(n.params.position))return wa(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{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=Ri(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 f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=Jh(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 p=Ta(r,n.params.node);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let h=[],y=0,x=n.params.node.kind==="component-call"?zA(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Oe(r),node:{jsx:HA(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Oe(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Aa(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:WA(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(!Aa(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=Ci(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=ZA(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"?wy(0,a.collectionIndexMap):wy(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=Ri(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 uo(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:")||Ey(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&&uo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=it(c);if(!l)return null;let u=Gt(l,r),d=Gt(l,o);if(!u||!d)return null;let f=xn(c,u),g=xn(c,d);if(!Ii(f,g))return null;if(a&&(s==="before"||s==="after")){let h=Gt(l,a),y=h?xn(c,h):null;if(!Ii(f,y))return null}if(Ca(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=Yu(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Oe(r),targetParentLocator:Oe(o),placement:s,anchorLocator:a?Oe(a):void 0,selectionContext:Or(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:p.reason??`Cannot move node because it depends on bindings outside the target scope: ${p.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&uo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=it(c);if(!l)return null;let u=Gt(l,r),d=Gt(l,o);if(!u||!d)return null;let f=xn(c,u);if(!f)return null;let g=xn(c,d);if(Ii(f,g))return null;if(g&&!xy(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let b=Wu(c,l,a);if(g&&!Ii(g,b)||!g&&b)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 b=Ta(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let p=nd(this.graph,r);if(!p)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ca(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=_y(c,u,d,p);for(let b of h.conditionPaths){let v=qu(b,d,f);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${v.bindingNames.join(", ")}`}}let y=Qu(u,d,f,{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 x=Iy(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=f;if(r.component!==o.component){let b=PA({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=ed(f.collectionPath,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${b.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Oe(r),targetParentLocator:Oe(o),placement:s,anchorLocator:a?Oe(a):void 0,repeatExpression:td(E,h.sourceJsx),selectionContext:Or(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&uo(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=it(c),d=it(l);if(!u||!d)return null;let f=py({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=Gt(u,r),p=Gt(d,o);if(!g||!p)return null;let h=Zu(f.callSitePath,p);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=xn(c,g);if(!y)return null;if(xn(l,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Wu(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 A=Ta(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let E=nd(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Ca(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=_y(c,g,p,E);for(let A of b.conditionPaths){let L=qu(A,p,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 v=Qu(g,p,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let _=MA({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!_.ok)return{ok:!1,errorCode:"unsupported-operation",reason:_.reason};let P=ky(y);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let R=Ry(y,P.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Oe(r),removeWhitespace:!0}];for(let A of _.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Oe(o),expression:td(R,b.sourceJsx),placement:s,anchorLocator:a?Oe(a):void 0,selectionContext:Or(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(wa(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let b=n.params.target,v=this.graph.getNode(b.anchorKey);if(!v||r.file!==v.file||r.component!==v.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let _=this.graph.getFileVersion(r.file);if(n.documentVersion!==_)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${_})`};let P=this.graph.getFileContent(r.file),R=it(P),N=R?Gt(R,r):null,A=R?Gt(R,v):null,L=N?.parentPath,$=A?.parentPath;if(!N||!A||!L||!$||L.node!==$.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Ue(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let U=L.node.loc;return U?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Oe(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:U.start.line,startColumn:U.start.column,endLine:U.end.line,endColumn:U.end.column}},placement:b.relation,anchorLocator:Oe(v),selectionContext:Or(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Ty(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(YA(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 b=n.params.target.relation,v=i.anchorNode&&(b==="before"||b==="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:b,anchorSourceId:v?.kind==="external-entry"?v.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,f=this.graph.getTextProvenance?.(r.key,0)??null,g=Ri(r,c,f);if(g&&!rd(g)&&!Cy(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=c,v=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&v?.kind==="value-binding"&&b.locator&&v.locator){let _=Ci(b.locator),P=Ci(v.locator);if(_&&P&&b.file===v.file&&eT(_.locator,P.locator)){let R=_.index,N=P.index,A=u==="before"?N-(R<N?1:0):N+(R<N?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:_.locator,fromIndex:R,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&uo(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),h=rd(g)?g:p;if(h&&rd(h)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let v=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(v)return v;let _=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return _||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};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 b=Ta(s,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Yu(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=[{order:0,file:r.file,type:"move-node",locator:Oe(r),targetParentLocator:Oe(s),placement:u,anchorLocator:d?Oe(d):void 0,selectionContext:Or(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=nd(this.graph,r)??`<${r.component} />`,f=Xh(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Oe(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:sd(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:p}]:[{kind:"named",imported:r.exportName,local:p===r.exportName?void 0:p}]};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:Oe(o),node:{jsx:d},placement:s,anchorLocator:a?Oe(a):void 0,selectionContext:Or(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Oe(o),node:{jsx:d},placement:s,anchorLocator:a?Oe(a):void 0,selectionContext:Or(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:ve(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function Oy(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 md from"@babel/generator";import{parse as xT}from"@babel/parser";import*as T from"@babel/types";import*as En from"@babel/types";import ud from"@babel/generator";import*as Le from"@babel/types";var oT=typeof ud=="function"?ud:ud.default,iT=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,sT=/^((?:https?:)?\/\/)[^/@\s]+@/i,aT=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function By(e,t){let n=bn(e.callee);if(!n)return null;if(n==="fetch")return dd(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(My(r))return dd(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(My(r))return dd(e.arguments[0],r,t,["ky client contract"])}return null}function dd(e,t,n,r){if(!e||Le.isSpreadElement(e)||Le.isJSXNamespacedName(e))return dT(t,n,r,"missing url argument");let o=Ni(e);return{sourceKind:uT(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 Ni(e){if(Le.isStringLiteral(e))return La(e.value);if(Le.isTemplateLiteral(e))return La(cT(e));if(Le.isBinaryExpression(e)&&e.operator==="+"){let t=Ni(e.left),n=Ni(e.right);return!t&&!n?void 0:La(`${t??pd(e.left)}${n??pd(e.right)}`)}if(Le.isMemberExpression(e)){let t=jy(e);if(t)return`env:${t}`}if(!(Le.isCallExpression(e)&&bn(e.callee)==="new URL")){if(Le.isNewExpression(e)&&Le.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Le.isSpreadElement(t)?Ni(t):void 0,o=n&&!Le.isSpreadElement(n)?Ni(n):void 0;return o&&r?La(`${o} + ${r}`):r??o}if(Le.isIdentifier(e))return`:${e.name}`}}function cT(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+=pd(r))}return t}function pd(e){if(Le.isIdentifier(e))return`:${e.name}`;if(Le.isMemberExpression(e)){let t=jy(e);if(t)return`env:${t}`}return`:${lT(e)}`}function lT(e){return oT(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function La(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(sT,"$1<redacted>@").replace(aT,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?iT.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function uT(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 dT(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function My(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function jy(e){return!Le.isMemberExpression(e.object)||!Le.isIdentifier(e.object.object,{name:"process"})||!pT(e.object.property,"env")?null:Le.isIdentifier(e.property)?e.property.name:Le.isStringLiteral(e.property)?e.property.value:null}function pT(e,t){return Le.isIdentifier(e)&&e.name===t}function bn(e){if(Le.isIdentifier(e))return e.name;if(Le.isMemberExpression(e)){let t=bn(e.object),n=Le.isIdentifier(e.property)?e.property.name:Le.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var fT=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),mT=new Set(["getConfig","submit"]);function $y(e,t){let n=gT(bn(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!fT.has(i))return null;let s=fd(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(!mT.has(i))return null;let s=fd(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=fd(e,0)??hT(e,0,"path")??"/cms/:path",s=yT(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 gT(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 Vy(e,t){let n=bn(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 Uy(e){let t=bn(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function fd(e,t){let n=e.arguments[t];return En.isStringLiteral(n)?n.value:null}function hT(e,t,n){let r=e.arguments[t];if(!En.isObjectExpression(r))return null;for(let o of r.properties)if(En.isObjectProperty(o)&&!o.computed&&(En.isIdentifier(o.key)&&o.key.name===n||En.isStringLiteral(o.key)&&o.key.value===n)&&En.isStringLiteral(o.value))return o.value.value;return null}function yT(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Ky(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 f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,p=g.get(a)??new Map,h=p.get(c)??new Map;return h.set(l,f),p.set(c,h),g.set(a,p),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}var P1=typeof md=="function"?md:md.default,Qy=new WeakMap;function qy(e){let t=new Map;return Qy.set(t,new Map([...e].map(n=>[n.file,n]))),t}var bT={maxFunctionDepth:8,maxImportDepth:6},ET=new Set(["src","href","alt","poster","content","title","aria-label"]),Jy=new WeakMap;function ST(e,t,n){let r=Jy.get(t.fileCache);r||(r=new WeakMap,Jy.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 f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let p=g.get(d.tag)??[];p.push(f),g.set(d.tag,p)}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 ex(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&zy(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=xd(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...bT,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:gx(n,e.element.componentName)};await tx(e.element.componentName,e.graph,r);let o=[];o.push(...await RT(e.element,e.graph,r),...await CT(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await NT(s,e.element,e.graph,r);a&&o.push(Ba(a,"text","children"))}for(let s of e.element.attributes??[]){let a=zy(s,e.element);if(!a)continue;let c=await ix(s.source,e.element,e.graph,r);c&&o.push(Ba(c,a,s.name))}let i=UT(o).sort(fx);return{hasDynamicData:i.length>0,bindings:i}}async function tx(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 ST(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 vT(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 ox(l.sourceFile,n);if(!d)continue;let f=$a(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=gx(d,l.componentName),await tx(l.componentName,t,f);let g=await IT(l,f);for(let[p,h]of g){if(!h)continue;let y=a.get(p)??[];y.push(h),a.set(p,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=dx(u);d.length===1&&c.set(l,d[0])}kT(o,c,n)}var Xy=new WeakMap;function vT(e,t,n,r){let o=Xy.get(r.fileCache);return o||(o=Ky(),Xy.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>nx(e,t,n,r))}async function nx(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 ox(e,r))?.imports.get(t);if(!s||!Rt(s.source))return!1;let a=await xx(e,s.source,r.exists);return a?a===n?!0:nx(a,s.importedName,n,r,o):!1}async function IT(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(rx(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!T.isJSXAttribute(i)||!T.isJSXIdentifier(i.name)||!T.isJSXExpressionContainer(i.value)||!T.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 et(s,t);a&&o.set(i,a)}return o}function rx(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function ox(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 xd(e,r,t.fileCache)}function kT(e,t,n){if(T.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,yd(Object.fromEntries(t),n.file));return}if(T.isObjectPattern(e))for(let r of e.properties){if(!T.isObjectProperty(r)||r.computed||!T.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=T.isAssignmentPattern(r.value)?r.value.left:r.value;T.isIdentifier(i)&&n.paramSources.set(i.name,dt(o))}}function zy(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":ET.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function RT(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 ja(i.collectionSource,n);s&&r.push(Ba(Fr(s),"repeat-region",i.collectionExpression))}return r}async function CT(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 ja(i.conditionSource,n);s&&r.push(Ba(Fr(s),"conditional-region",i.conditionExpression))}return r}async function NT(e,t,n,r){return ix(e.source,t,n,r)}async function ix(e,t,n,r){let o=await _T(e,t,n,r);return o||ja(e,r)}async function _T(e,t,n,r){if(!e)return null;let o=PT(e.base,t,n);if(!o)return null;let i=await ja(o.collectionSource,r);return i?Ti(i,e.path,!0):null}function PT(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 ja(e,t){if(!e)return null;let n=await sx(e.base,t);return n?Ti(n,e.path,!1):null}async function sx(e,t){let n=t.paramSources.get(e);if(n)return dt(n);if(t.variableCache.has(e))return KT(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await AT(e,t);if(r)return t.variableCache.set(e,dt(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await et(o,t);return t.variableCache.set(e,s?dt(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await hx(i,t);if(s){let a=$a(s,t,{importDepth:t.importDepth+1}),c=yx(i,s);if(c){let d=(await Lr(c,[],a)).returnSource;return t.variableCache.set(e,d?dt(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await et(l,a);return t.variableCache.set(e,u?dt(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function AT(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 et(o,t);if(i)return i}return null}async function et(e,t){if(T.isIdentifier(e))return sx(e.name,t);if(T.isMemberExpression(e)||T.isOptionalMemberExpression(e)){let n=T.isMemberExpression(e)?Vy(e,{file:t.file}):null;if(n)return ux(n);let r=await TT(e,t);if(!r)return null;let o=$T(e);return Ti(r,o,!1)}if(T.isAwaitExpression(e))return T.isExpression(e.argument)?et(e.argument,t):null;if(T.isCallExpression(e))return ax(e,t);if(T.isObjectExpression(e)){let n=await cx(e,t);return Object.keys(n).length>0?yd(n,t.file):null}if(T.isConditionalExpression(e)){let n=await et(e.consequent,t),r=await et(e.alternate,t);return Ai(Wy(n,r))}if(T.isLogicalExpression(e)){let n=await et(e.left,t),r=await et(e.right,t);return Ai(Wy(n,r))}return T.isTSAsExpression(e)||T.isTSSatisfiesExpression(e)||T.isTSNonNullExpression(e)||T.isTypeCastExpression(e)||T.isParenthesizedExpression(e)?et(e.expression,t):null}async function TT(e,t){let n=e;for(;T.isMemberExpression(n)||T.isOptionalMemberExpression(n);)n=n.object;return T.isExpression(n)?et(n,t):null}async function ax(e,t){let n=$y(e,{file:t.file,imports:t.analysis.imports});if(n)return ux(n);if(Uy(e)){let d=e.arguments[0];if(d&&T.isExpression(d))return Ai(await et(d,t))}let r=await wT(e,t);if(r)return r;let o=By(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 LT(e,t);if(i)return i;let s=await DT(e,t);if(s)return s;let a=await MT(e,t);if(a)return a;let c=await BT(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(T.isExpression(d)){let f=await et(d,t);f&&l.push(f)}let u=dx(l);return u.length===1?Ai(u[0]):null}async function wT(e,t){let n=bn(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=FT(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(T.isIdentifier(s)){let a=await Pi(s.name,t);if(a)return(await Lr(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!T.isObjectExpression(r))return Da(t.file,`${n} without static options`);let o=OT(r,"queryFn");if(!o)return Da(t.file,`${n} without queryFn`);if(T.isIdentifier(o)){let i=await Pi(o.name,t);return i?(await Lr(i.node,[],i.context)).returnSource:Da(t.file,`${n} queryFn unresolved`)}return T.isArrowFunctionExpression(o)||T.isFunctionExpression(o)?(await Lr(o,[],t)).returnSource:T.isCallExpression(o)?ax(o,t):null}function OT(e,t){for(let n of e.properties){if(!T.isObjectProperty(n)||!T.isExpression(n.value))continue;if(lx(n)===t)return n.value}return null}function FT(e,t,n){return T.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 LT(e,t){if(!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=T.isExpression(e.callee.object)?await et(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Fr(r);let o=e.arguments[0];if(T.isIdentifier(o)){let i=await Pi(o.name,t);if(!i)return Fr(r);let s=await Lr(i.node,[r],i.context);return{...Fr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(T.isArrowFunctionExpression(o)||T.isFunctionExpression(o)){let i=await Lr(o,[r],t);return{...Fr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Fr(r)}async function DT(e,t){return!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property,{name:"json"})||!T.isExpression(e.callee.object)?null:et(e.callee.object,t)}async function MT(e,t){return!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property,{name:"then"})||!T.isExpression(e.callee.object)?null:Ai(await et(e.callee.object,t))}async function BT(e,t){if(!T.isIdentifier(e.callee))return null;let n=await Pi(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!T.isExpression(i)){r.push(Da(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await et(i,t);r.push(s)}return(await Lr(n.node,r,n.context)).returnSource}async function Pi(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 hx(r,t);if(!o)return null;let i=$a(o,t,{importDepth:t.importDepth+1}),s=yx(r,o);return s?{node:s,context:i}:Pi(r.importedName,i)}async function Lr(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=$a(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&gd(c,VT(u),r)});let o=jT(e),i=null,s,a=!1;for(let c of o){if(T.isObjectExpression(c)){s={...s??{},...await cx(c,r)},i=i??yd(s,n.file);continue}let l=await et(c,r);if(l){if(!i){i=l;continue}let u=hd(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function gd(e,t,n){if(T.isIdentifier(e)){n.paramSources.set(e.name,dt(t));return}if(T.isAssignmentPattern(e)){gd(e.left,t,n);return}if(T.isObjectPattern(e))for(let r of e.properties){if(!T.isObjectProperty(r)||r.computed||!T.isIdentifier(r.key))continue;let o=Ti(t,[{kind:"property",name:r.key.name}],!0),i=T.isAssignmentPattern(r.value)?r.value.left:r.value;gd(i,o,n)}}function jT(e){if(T.isArrowFunctionExpression(e)&&T.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!T.isBlockStatement(n))return t;let r=o=>{if(T.isFunction(o)&&o!==e)return;if(T.isReturnStatement(o)){o.argument&&T.isExpression(o.argument)&&t.push(o.argument);return}let i=T.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)T.isNode(c)&&r(c);else T.isNode(a)&&r(a)}};return r(n),t}async function cx(e,t){let n={};for(let r of e.properties){if(!T.isObjectProperty(r))continue;let o=lx(r);if(!o||!T.isExpression(r.value))continue;let i=await et(r.value,t);i&&(n[o]=i)}return n}function lx(e){return T.isIdentifier(e.key)&&!e.computed?e.key.name:T.isStringLiteral(e.key)?e.key.value:null}function $T(e){let t=[],n=e;for(;T.isMemberExpression(n)||T.isOptionalMemberExpression(n);){let r=n.property;n.computed?T.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):T.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):T.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return T.isIdentifier(n),t}function Ti(e,t,n){if(t.length===0)return dt(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Ti(e.fieldMap[r.name],t.slice(1),n);let o=dt(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=_i(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=_i(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=_i(o.fieldPath,i.join(".")),o):(o.valuePath=_i(o.valuePath,Hy(t)),o)}return o.valuePath=_i(o.valuePath,Hy(t)),o}function Hy(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function _i(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function ux(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 Fr(e){let t=dt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function VT(e){let t=dt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function Ai(e){return e?{...dt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function Wy(e,t){return e?t?hd(e,t):dt(e):t?dt(t):null}function hd(e,t){if(Ma(e)!==Ma(t))return null;let n=mx(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function dx(e){let t=new Map;for(let n of e){let r=Ma(n),o=t.get(r);t.set(r,o?hd(o,n):dt(n))}return[...t.values()]}function Ma(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Ma(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 yd(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 Da(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Ba(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 px(e){let t=[...e].sort(fx),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 UT(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 fx(e,t){return Gy(e.targetKind)-Gy(t.targetKind)||mx(e.confidence,t.confidence)||Yy(e.sourceKind)-Yy(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function Gy(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function Yy(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function mx(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function xd(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=Qy.get(n)?.get(e),i=o?.source===t?o.ast:xT(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=[];T.traverse(i,{enter(d){switch(T.isFunction(d)&&a.push(d),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=rx({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)T.isImportSpecifier(g)&&T.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:T.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):T.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,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 f=a.at(-1),g=f&&(T.isFunctionDeclaration(f)||T.isFunctionExpression(f)||T.isArrowFunctionExpression(f))?f:null,p=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,p);for(let h of mo(d.id))p.set(h,T.isExpression(d.init)?d.init:null);if(T.isArrayPattern(d.id)&&T.isCallExpression(d.init)&&bn(d.init.callee)==="useState"){let[h,y]=d.id.elements;T.isIdentifier(h)&&T.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}T.isIdentifier(d.id)&&Zy(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let p of d.specifiers){if(!T.isExportSpecifier(p))continue;let h=T.isIdentifier(p.exported)?p.exported.name:p.exported.value,y=p.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(T.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),T.isVariableDeclaration(f))for(let p of f.declarations)T.isIdentifier(p.id)&&Zy(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((T.isFunctionDeclaration(f)||T.isFunctionExpression(f)||T.isArrowFunctionExpression(f))&&s.functions.set("default",f),T.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){T.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=T.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&T.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)T.isIdentifier(p)&&p.name!==f&&l.has(p.name)&&g.add(p.name);for(let p of g)u(p,d)}return n.set(e,s),s}function mo(e){return!e||T.isVoidPattern(e)?[]:T.isIdentifier(e)?[e.name]:T.isObjectPattern(e)?e.properties.flatMap(t=>T.isObjectProperty(t)?mo(t.value):mo(t.argument)):T.isArrayPattern(e)?e.elements.flatMap(t=>t?mo(T.isRestElement(t)?t.argument:t):[]):T.isAssignmentPattern(e)?mo(e.left):T.isRestElement(e)?mo(e.argument):[]}function Zy(e){return T.isFunctionExpression(e)||T.isArrowFunctionExpression(e)}function gx(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function hx(e,t){let n=await xx(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return xd(n,r,t.fileCache)}function yx(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function xx(e,t,n){return Rt(t)?mr(e,t,n):null}function $a(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 KT(e){return e?dt(e):null}function dt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,dt(n)]))}:{}}}import*as Ed from"@babel/parser";import bd from"@babel/traverse";import*as ie from"@babel/types";import{classifySiteEditPropertyName as JT}from"@vcp-dev/contracts";var Sd=typeof bd=="function"?bd:bd.default;function vd(e){let t=JT(e.propertyName);if(t.owner!=="generic")return Mt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Mt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Mt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Mt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Ed.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Mt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=XT(r,e.element.sourceRange);if(!o)return Mt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ie.isIdentifier(o.callback.params[0]))return Mt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=zT(r,o.collection,e.file,e.sources);if(!i)return Mt("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,x]of s.elements.entries()){if(!x||!ie.isObjectExpression(x)||!kx(x))return Mt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:y}];l.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Mt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Mt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ie.isObjectExpression(g))return Mt("unsafe-collection","Selected repeat item is not an object");let p=QT(e.element,e.propertyName),h=YT(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,x)=>x),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:ZT(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:Mt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function XT(e,t){let n=[];return Sd(e,{CallExpression(r){let o=bx(r.node);o&&Sx(o.callback,t)&&n.push({...o,span:Ex(r.node)})},OptionalCallExpression(r){let o=bx(r.node);o&&Sx(o.callback,t)&&n.push({...o,span:Ex(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function bx(e){let t=e.callee;if(!ie.isMemberExpression(t)&&!ie.isOptionalMemberExpression(t)||t.computed||!ie.isIdentifier(t.property)||t.property.name!=="map"||!ie.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ie.isExpression(n)||!ie.isArrowFunctionExpression(n)&&!ie.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function zT(e,t,n,r){let o=wi(t);if(o&&ie.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Cx(o)}},sourceFile:n};if(!ie.isIdentifier(t))return null;let i=[];if(Sd(e,{VariableDeclarator(s){ie.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=wi(i[0].init);return!s||!ie.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return HT(e,t.name,n,r)}function HT(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ie.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ie.isStringLiteral(o.source)||!ie.isImportSpecifier(i))continue;let s=GT(n,o.source.value,r);if(!s)return null;let a=ie.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Ed.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=WT(l,a),d=u?wi(u):null;return!d||!ie.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function WT(e,t){let n=null;return Sd(e,{VariableDeclarator(r){n||!ie.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ie.isExpression(r.node.init)||(n=r.node.init)}}),n}function GT(e,t,n){let r=Nn(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 wi(e){return ie.isParenthesizedExpression(e)?wi(e.expression):ie.isTSAsExpression(e)?Ix(e.typeAnnotation)?wi(e.expression):null:ie.isTSSatisfiesExpression(e)?null:e}function Ix(e){return ie.isTSTypeReference(e)&&ie.isIdentifier(e.typeName)&&e.typeName.name==="const"}function kx(e){return e.properties.every(t=>!ie.isObjectProperty(t)||t.computed||!ie.isExpression(t.value)?!1:Va(t.value))}function Va(e){if(ie.isTSAsExpression(e)&&Ix(e.typeAnnotation))return Va(e.expression);if(ie.isTSSatisfiesExpression(e))return!1;if(ie.isArrayExpression(e))return e.elements.every(n=>!n||ie.isSpreadElement(n)||!ie.isExpression(n)?!1:Va(n));if(ie.isObjectExpression(e))return kx(e);let t=mn(e);return t.status==="resolved"||t.status==="undefined"}function YT(e,t){let n=e.properties.filter(o=>ie.isObjectProperty(o)&&Rx(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ie.isExpression(r.value)?Va(r.value)?"static":ie.isIdentifier(r.value)||ie.isMemberExpression(r.value)?"binding":null:null:"missing"}function ZT(e,t){let n=e.properties.filter(o=>ie.isObjectProperty(o)&&Rx(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ie.isExpression(r.value)?{status:"undefined"}:mn(r.value)}function QT(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function Rx(e){return ie.isIdentifier(e)?e.name:ie.isStringLiteral(e)?e.value:ie.isNumericLiteral(e)?String(e.value):null}function Cx(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 Ex(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function Sx(e,t){let n=Cx(e);return vx(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&vx(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function vx(e,t,n,r){return e===n?t-r:e-n}function Mt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as Dw}from"@vcp-dev/contracts";import*as le from"@babel/types";import Mi from"node:path";import*as W from"@babel/types";import*as wx from"@babel/parser";import Id from"@babel/traverse";import*as me from"@babel/types";function Ka(e,t){let n=[],r=e;for(;me.isMemberExpression(r);){if(r.computed)if(me.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(me.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!me.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!me.isIdentifier(r)||r.name!==t?null:n}function Nx(e){if(me.isIdentifier(e))return{base:e.name,path:[]};if(!me.isMemberExpression(e))return null;let t=[],n=e;for(;me.isMemberExpression(n);){if(n.computed)if(me.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(me.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!me.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return me.isIdentifier(n)?{base:n.name,path:t}:null}function xt(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 Sn=Symbol("not-closed-literal");function Ua(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:Sn;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Ua(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||me.isSpreadElement(n))return Sn;let r=Ua(n);if(r===Sn)return Sn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!me.isObjectProperty(n)||n.computed||n.shorthand||!me.isExpression(n.value))return Sn;let r=me.isIdentifier(n.key)?n.key.name:me.isStringLiteral(n.key)?n.key.value:null;if(!r)return Sn;let o=Ua(n.value);if(o===Sn)return Sn;t[r]=o}return t}default:return Sn}}function _x(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Ua(i);if(f!==Sn)return f;if(!me.isTemplateLiteral(i)){if(me.isTSAsExpression(i)||me.isTSSatisfiesExpression(i)||me.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(me.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return p?.kind==="static"?p.value:void 0}if(me.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||me.isSpreadElement(p))return;let h=await r(p,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(me.isObjectExpression(i)){let g={};for(let p of i.properties){if(!me.isObjectProperty(p)||p.computed)return;let h=null;if(me.isIdentifier(p.key)?h=p.key.name:me.isStringLiteral(p.key)&&(h=p.key.value),!h)return;if(p.shorthand){if(!me.isIdentifier(p.value))return;let x=await r(p.value,s,a,c,l,u,d);if(x===void 0)return;g[h]=x;continue}if(!me.isExpression(p.value))return;let y=await r(p.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(me.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let p=s.getBinding(g.base);if(!p)return;let h=await t({currentFile:a,binding:p,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:xt(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!me.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(me.isIdentifier(i))return{base:i.name,path:[]};if(!me.isMemberExpression(i))return null;let f=[],g=i;for(;me.isMemberExpression(g);){if(g.computed){let p=g.property;if(me.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(me.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let h=me.isExpression(p)?await n(p,s,a,c,l,u,d):void 0;if(typeof h=="string")f.unshift({kind:"property",name:h});else if(Number.isInteger(h))f.unshift({kind:"index",index:h});else return null}}else{if(!me.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return me.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var Ox=typeof Id=="function"?Id:Id.default,Px=new WeakMap;function Fx(e){try{return wx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ja(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Fx(n);return e.set(t,{source:n,ast:o}),o}function Xa(e,t){return kd(Oi(e).expressionRanges,t,!1)}function Lx(e,t){return Oi(e).exactExpressions.get(Dx(t))??null}function za(e,t){return kd(Oi(e).jsxRanges,t,!0)}function Oi(e){let t=Px.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return Ox(e,{Expression(r){let o=r;n.expressions.push(o);let i=Ax(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=Dx(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=Ax(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(Tx),n.jsxRanges.sort(Tx),Px.set(e,n),n}function Ax(e,t){let n=Fi(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Dx(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function Tx(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function kd(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 Fi(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 go(e,t){if(t)return Rd(e,t);let n=Nx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Rd(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Li(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Oi(e).expressions){if(Rd(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Mx(e,t,n,r){return kd(Oi(e).expressionRanges,r,!0,o=>Rd(o.node,t)===n)}function ho(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Di(e){let t=null;if(Ox(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function an(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Fx(o),s={source:o,ast:i};return n.set(e,s),s}function qT(e){return W.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:W.isMemberExpression(e.callee)&&W.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function ew(e){if(!W.isNewExpression(e)||!W.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!W.isIdentifier(e.arguments[0])||!W.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!W.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!W.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(W.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(W.isIfStatement(i)&&W.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=W.isIfStatement(i)?i.test:null,c=a&&W.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=W.isIfStatement(i)?W.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=W.isReturnStatement(s)?s.argument:null;return!a||!W.isLogicalExpression(a,{operator:"&&"})||!W.isBinaryExpression(a.left,{operator:"==="})||!W.isUnaryExpression(a.left.left,{operator:"typeof"})||!W.isIdentifier(a.left.left.argument,{name:r.name})||!W.isStringLiteral(a.left.right,{value:"string"})||!W.isUnaryExpression(c,{operator:"!"})||!W.isBinaryExpression(c.argument,{operator:"in"})||!W.isIdentifier(c.argument.left,{name:r.name})||!W.isIdentifier(c.argument.right,{name:n.name})||!W.isReturnStatement(l)||!W.isIfStatement(i)||i.alternate||!W.isCallExpression(u)||!W.isMemberExpression(u.callee)||!W.isIdentifier(u.callee.object,{name:"Reflect"})||!W.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!W.isIdentifier(u.arguments[0],{name:n.name})||!W.isIdentifier(u.arguments[1],{name:r.name})||!W.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function tw(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()||!W.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 Bx(e,t){let n=tw(e.path);if(!n)return null;let r=oo(e,t);return r?{...n,...r}:null}function jx(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Cd(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 Nd(e,t){for(let n of e.program.body){if(t==="default"&&W.isExportDefaultDeclaration(n))return W.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(W.isFunctionDeclaration(n.declaration)||W.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(W.isExportNamedDeclaration(n)){if(n.declaration){if(W.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(W.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((W.isFunctionDeclaration(n.declaration)||W.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((W.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&W.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 $x(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=`${h}::${y.kind}::${y.identifier.name}`;if(v.has(_))return null;v.add(_);try{let P=await a({currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v});if(P)return P;if(y.path.isImportSpecifier()||y.path.isImportDefaultSpecifier())return await f({currentFile:h,binding:y,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:b,visited:v});if(y.kind==="param")return null;if(y.path.isVariableDeclarator()){let R=y.path.node.init;if(!R||!W.isExpression(R))return null;let N=ew(R);if(N&&!y.path.scope.getBinding("Proxy")&&!y.path.scope.getBinding("Reflect")){let $=y.path.scope.getBinding(N),U=$?await s({...p,binding:$}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let A=y.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let $=await t({currentFile:h,expressionPath:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if($)return $;if(A.isCallExpression()){let U=await n({currentFile:h,callPath:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(U)return U}}let L=await r(R,y.path.scope,h,x,E,b,v);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 R=y.path.parentPath.node.declaration;if(!W.isExpression(R))return null;let N=await r(R,y.path.scope,h,x,E,b,v);return N===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:N,sourceKind:"binding"}}return null}finally{v.delete(_)}}async function a(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p;if(!y.path.isVariableDeclarator()||!y.path.get("id").isArrayPattern())return null;let _=y.path,P=_.node.init;if(!P||!W.isCallExpression(P))return null;let R=qT(P);if(!R||!W.isArrayPattern(_.node.id)||_.node.id.elements.findIndex(U=>W.isIdentifier(U)&&U.name===y.identifier.name)!==0)return null;let A=R==="useReducer"?1:0,L=P.arguments[A];if(!L||!W.isExpression(L))return null;let $=await r(L,_.scope,h,x,E,b,v);return $===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:y.identifier.name,hook:R},value:$,sourceKind:"binding"}}async function c(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let y=Bx(h,p.sourceInfo);if(!y)return null;let x=[...p.graph.elements.values()].filter(b=>jx(b,p.currentFile,y.componentName,y.exportName));if(!x.length)return null;let E=[];for(let b of x){if(b.sourceFile!==x[0].sourceFile||b.componentName!==x[0].componentName||b.attributeSpreads?.length)return null;let v=await an(b.sourceFile,p.readFile,p.fileCache),_=v.ast?za(v.ast,b.sourceRange):null;if(!_)return null;let P=_.parentPath;for(;P&&!P.isFunction();){if(P.isJSXElement()){let de=P.node.openingElement.name;if(!W.isJSXIdentifier(de)||!/^[a-z]/.test(de.name))return null}else if(!P.isJSXFragment()&&!P.isReturnStatement()&&!P.isBlockStatement())return null;P=P.parentPath}if(!P)return null;let R=_.get("openingElement").get("attributes").filter(de=>de.isJSXAttribute()&&W.isJSXIdentifier(de.node.name,{name:y.propName}));if(R.length!==1)return null;let N=R[0];if(!N?.isJSXAttribute())return null;let A=N.get("value"),L=A.isJSXExpressionContainer()?A.get("expression"):A;if(!L.isExpression())return null;let $=await r(L.node,L.scope,b.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),U=$===void 0?void 0:xt($,y.remainingPath);if(U===void 0)return null;E.push(U)}return E}async function l(p){let h=Bx(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let y=[...p.graph.elements.values()].filter(R=>jx(R,p.currentFile,h.componentName,h.exportName));if(y.length!==1)return null;let x=y[0],E=x.attributes?.find(R=>R.name===h.propName);if(E&&!E.source){let R=await u({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(R)return Cd(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile})}if(!E?.source){let R=await d({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(R)return Cd(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile});let N=Dh(p.binding,h.componentName,h.propName);if(!N||N.propName!==h.propName)return null;let A=await r(N.expressionPath.node,N.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(A===void 0)return null;let L=h.remainingPath;return L.length>0&&xt(A,L)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.propName},path:L,sourceKind:"binding",semanticKind:"component-prop",displayExpression:N.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:N.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let b=await an(x.sourceFile,p.readFile,p.fileCache);if(!b.ast)return null;let v=Mx(b.ast,b.source,E.source.expression,E.sourceRange)??Li(b.ast,b.source,E.source.expression);if(!v)return null;let _={...E.source,expression:ho(E.source.expression,h.remainingPath),path:[...E.source.path,...h.remainingPath]},P=await o({currentFile:x.sourceFile,expressionPath:v,sourceInfo:_,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});return P?Cd(P.kind==="external"?P:{...P,displayExpression:_.expression},{componentName:h.componentName,propName:h.propName,file:x.sourceFile}):null}async function u(p){let h=await an(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let y=za(h.ast,p.caller.sourceRange);if(!y)return null;let x=y.get("openingElement").get("attributes").find(_=>_.isJSXAttribute()&&_.node.name.type==="JSXIdentifier"&&_.node.name.name===p.propName);if(!x?.isJSXAttribute())return null;let E=x.get("value"),b=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!b?.isExpression())return null;let v=Fi(b.node);return v?{kind:"value",file:p.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:p.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:p.propName,editMode:"upstream",diagnostics:[]}:null}async function d(p){let h=await an(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let y=za(h.ast,p.caller.sourceRange);if(!y)return null;let x=y.get("openingElement");for(let E of x.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let b=E.get("argument");if(!b.isExpression())continue;let v=await i({expression:b.node,scope:b.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let _=[{kind:"property",name:p.propName},...p.remainingPath],P={...v,expression:ho(v.expression,_),path:[...v.path,..._]},R=await o({currentFile:p.caller.sourceFile,expressionPath:b,sourceInfo:P,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(R)return R.kind==="external"?R:{...R,displayExpression:P.expression}}return null}async function f(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=y.path.parentPath;if(!_||!_.isImportDeclaration())return null;let P=_.node.source.value;if(typeof P!="string")return null;let R=await mr(h,P,E);if(!R)return null;if(y.path.isImportDefaultSpecifier()){let de=await an(R,x,b),z=de.ast?Nd(de.ast,"default"):null,Q=await g({file:R,exportName:"default",readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return!Q||Q.kind!=="static"?null:{kind:"static",file:z?.kind==="default-expression"?Q.file:R,root:z?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!y.path.isImportSpecifier())return null;let N=y.path.node.imported,A=W.isIdentifier(N)?N.name:N.value,L=await an(R,x,b),$=L.ast?Nd(L.ast,A):null,U=await g({file:R,exportName:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return U?U.kind==="external"?U:{kind:"static",file:$?.kind==="re-export"?U.file:R,root:$?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==$?.name?U.root:{kind:"named-export",name:A},value:U.value,sourceKind:"imported-binding"}:null}async function g(p){let{file:h,exportName:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=`export::${h}::${y}`;if(!v.has(_)){v.add(_);try{let P=await an(h,x,b);if(!P.ast)return;let R=Nd(P.ast,y);if(!R)return;if(R.kind==="default-expression"){let $=R.expression;if(!$||!W.isIdentifier($))return;let U=Di(P.ast).getBinding($.name);return U?await s({currentFile:h,binding:U,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v})??void 0:void 0}if(R.kind==="re-export"){if(!R.source||!R.name)return;let $=await mr(h,R.source,E);return $?g({...p,file:$,exportName:R.name}):void 0}let N=R.name;if(!N)return;let A=Di(P.ast).getBinding(N);return A?await s({currentFile:h,binding:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v})??void 0:void 0}finally{v.delete(_)}}}return{resolveExportValue:g,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as ne from"@babel/types";function Pd(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=on(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!nw(s,r)?null:{callPath:s,basePath:i}}function nw(e,t){let n=e.node.callee;return!ne.isMemberExpression(n)||!ne.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Jx(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ea(r,t)}function Vx(e,t){return e?ne.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Ux(e,t,n,r,o){let i=ne.isExpression(e.body)?e.body:e.body.body.find(a=>ne.isReturnStatement(a))?.argument;if(!i||!ne.isExpression(i))return;let s=_d(i,t,n,r,o);return typeof s=="number"?s:void 0}function _d(e,t,n,r,o){if(ne.isNumericLiteral(e)||ne.isStringLiteral(e)||ne.isBooleanLiteral(e))return e.value;if(ne.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(ne.isMemberExpression(e)){let i=Ka(e,t);if(i)return xt(r,i);let s=Ka(e,n);return s?xt(o,s):void 0}if(ne.isBinaryExpression(e)&&e.operator==="-"){let i=ne.isExpression(e.left)?_d(e.left,t,n,r,o):void 0,s=ne.isExpression(e.right)?_d(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function rw(e){if(ne.isExpression(e.body))return e.body;for(let t of e.body.body)if(ne.isReturnStatement(t)&&t.argument&&ne.isExpression(t.argument))return t.argument;return null}function ow(e,t,n){let r=Dr(e,t,n);return typeof r=="boolean"?r:void 0}function Dr(e,t,n){if(ne.isStringLiteral(e)||ne.isNumericLiteral(e)||ne.isBooleanLiteral(e))return e.value;if(ne.isNullLiteral(e))return null;if(ne.isIdentifier(e))return e.name===t?n:void 0;if(ne.isMemberExpression(e)){let r=Ka(e,t);return r?xt(n,r):void 0}if(ne.isUnaryExpression(e)&&e.operator==="!"){let r=Dr(e.argument,t,n);return r===void 0?void 0:!r}if(ne.isLogicalExpression(e)){let r=Dr(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Dr(e.right,t,n);if(e.operator==="||")return r||Dr(e.right,t,n)}if(ne.isBinaryExpression(e)){let r=ne.isExpression(e.left)?Dr(e.left,t,n):void 0,o=ne.isExpression(e.right)?Dr(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 Xx(e){let t=[],n=e;for(;ne.isMemberExpression(n)||ne.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(ne.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(ne.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(ne.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(ne.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return ne.isIdentifier(n)?{base:n.name,segments:t}:null}function zx(e){return e.some(t=>t.kind==="dynamic")}function Kx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function Hx(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 iw(e,t){let n=[],r=[];for(let o of t){let i=xt(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 Wx(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(p){let{currentFile:h,callPath:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=y.node.callee;if(!ne.isMemberExpression(_)||!ne.isIdentifier(_.property)||_.property.name!=="map")return null;let P=y.get("callee");if(!P.isMemberExpression())return null;let R=P.get("object");if(Array.isArray(R)||!R.isExpression())return null;let N=await a({currentFile:h,expressionPath:R,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(p){let{currentFile:h,expressionPath:y,readFile:x,exists:E,fileCache:b,visited:v}=p;if(y.isIdentifier()){let _=y.scope.getBinding(y.node.name);if(!_)return null;let P=await t({currentFile:h,binding:_,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return P?.kind==="static"?P:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let _=y.get("expression");if(!Array.isArray(_)&&_.isExpression())return a({...p,expressionPath:_})}if(y.isArrayExpression()){let _=Fi(y.node);if(!_)return null;let P=await n(y.node,y.scope,h,x,E,b,v);return Array.isArray(P)?{kind:"static",file:h,root:{kind:"expression",sourceRange:_},value:P,sourceKind:"binding"}:null}if(y.isMemberExpression()){let _=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:x,exists:E,fileCache:b,visited:v});if(!_)return null;let P=await o({currentFile:h,expressionPath:y,sourceInfo:_,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(!P||P.kind==="external")return null;let R=await c({currentFile:h,expressionPath:y,provenance:P,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(!R||R.kind!=="static")return null;if(P.collectionPathMap?.length){let A=iw(R.value,P.collectionPathMap);if(A)return{kind:"static",file:P.file,root:P.root,value:A.value,sourceKind:P.sourceKind,collectionPathMap:A.collectionPathMap}}let N=xt(R.value,P.path);return Array.isArray(N)?{kind:"static",file:P.file,root:P.root,value:N,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function c(p){let{provenance:h}=p;if(h.root.kind==="binding"){let b=p.expressionPath.scope.getBinding(h.root.name);if(!b&&h.file!==p.currentFile){let v=await an(h.file,p.readFile,p.fileCache);b=v.ast?Di(v.ast).getBinding(h.root.name):void 0}return b?await t({currentFile:h.file,binding:b,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited}):null}if(h.root.kind!=="expression")return null;let y=await an(h.file,p.readFile,p.fileCache);if(!y.ast)return null;let x=Lx(y.ast,h.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,h.file,p.readFile,p.exists,p.fileCache,p.visited);return E===void 0?null:{kind:"static",file:h.file,root:h.root,value:E,sourceKind:h.sourceKind}}async function l(p){return await u(p)??await d(p)??await f(p)}async function u(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v]=h.node.arguments;if(!ne.isArrowFunctionExpression(v)&&!ne.isFunctionExpression(v))return null;let _=v.params[0];if(!ne.isIdentifier(_))return null;let P=rw(v);if(!P)return null;let R=[],N=[],A=[];for(let[L,$]of b.value.entries()){let U=ow(P,_.name,$);if(typeof U!="boolean")return null;if(U){R.push($),N.push(b.collectionIndexMap?.[L]??L);let de=b.collectionPathMap?.[L];de&&A.push(de)}}return{...b,value:R,pathPrefix:b.pathPrefix,collectionIndexMap:N,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v,_]=h.node.arguments,P=Vx(v,0),R=Vx(_,b.value.length);if(P===null||R===null)return null;let N=Math.max(0,P<0?b.value.length+P:P),A=Math.max(0,R<0?b.value.length+R:R),L=b.value.map((U,de)=>b.collectionIndexMap?.[de]??de).slice(N,A),$=b.collectionPathMap?.slice(N,A);return{...b,value:b.value.slice(N,A),pathPrefix:b.pathPrefix,collectionIndexMap:L,...$?{collectionPathMap:$}:{}}}async function f(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v]=h.node.arguments;if(!ne.isArrowFunctionExpression(v)&&!ne.isFunctionExpression(v))return null;let[_,P]=v.params;if(!ne.isIdentifier(_)||!ne.isIdentifier(P))return null;let R=b.value.map((A,L)=>({value:A,sourceIndex:b.collectionIndexMap?.[L]??L,originalIndex:L})),N=[...R];for(let A of R)for(let L of R)if(Ux(v,_.name,P.name,A.value,L.value)===void 0)return null;return N.sort((A,L)=>{let $=Ux(v,_.name,P.name,A.value,L.value)??0;return $===0?A.originalIndex-L.originalIndex:$}),{...b,value:N.map(A=>A.value),pathPrefix:b.pathPrefix,collectionIndexMap:N.map(A=>A.sourceIndex),...b.collectionPathMap?{collectionPathMap:N.map(A=>b.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let h=null,y=!1,x,E=[];for(let v of p.segments){if(v.kind!=="dynamic")continue;let _=await r({expression:v.expression,scope:p.expressionPath.scope,source:p.fileCache.get(p.currentFile)?.source,currentFile:p.currentFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!_)return null;let P=Pd(p.expressionPath,_.base),R;if(P){y=!0;let N=await s({currentFile:p.currentFile,callPath:P.callPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!N||!Array.isArray(N.value))return null;R=N.value.map((A,L)=>{let $=xt(N.value,[{kind:"index",index:L},...P.basePath,..._.path]);return Kx($)}),x??=N.collectionIndexMap}else{let N=await i({...p,sourceInfo:_});if(!N)return null;R=N.map(Kx)}if(R.some(N=>N===null)||h!==null&&h!==R.length)return null;h=R.length,E.push(R)}if(h===null||h===0)return null;let b=[];for(let v=0;v<h;v+=1){let _=[...p.rootPath],P=0;for(let R of p.segments){if(R.kind==="dynamic"){let N=E[P]?.[v];if(!N)return null;_.push(N),P+=1;continue}_.push({...R})}b.push(_)}return{sourceKind:y||h>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:sw,evaluateStaticExpression:Ha}=_x({resolveBindingTarget:e=>Wa(e)}),{resolveRepeatCollectionTarget:aw,resolveCollectionCallTarget:cw,resolveDynamicMemberPathMap:lw}=Wx({resolveBindingTarget:e=>Wa(e),evaluateStaticExpression:Ha,buildExpressionSourceInfo:vn,resolveSourceInfoProvenance:Yt,resolveComponentPropValues:e=>pw(e)}),{resolveExportValue:uw,resolveComponentPropBinding:dw,resolveComponentPropValues:pw,resolveBindingTarget:Wa}=$x({resolveExternalExpression:Dd,resolveCollectionCallTarget:cw,evaluateStaticExpression:Ha,resolveSourceInfoProvenance:Yt,buildExpressionSourceInfo:vn});function rb(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var Gx=new WeakMap;function fw(e){let t=Gx.get(e);return t||(t=new WeakMap,Gx.set(e,t)),t}function Yx(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 ob(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ja(s,t,n);if(!a)return null;let c=Xa(a,r.sourceRange);if(!c)return null;let l=await vn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await $d({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 f?wd(f,go(c.node,n)):null}let u=new Set,d=await Lw({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?wd(d,l.expression):null}async function yo(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ja(i,t,n);if(!s)return null;let a=e.sourceRange?Xa(s,e.sourceRange):e.expression!==void 0?Li(s,n,e.expression):null;if(!a)return null;let c=Ga(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await vn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Yt({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 pb({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 wd(d,e.expression??go(c.node,n))}async function Ld(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ja(i,t,n);if(!s)return Bt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?mw({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}):gw({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function vn(e){if(le.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!le.isMemberExpression(e.expression))return null;let t=await sw(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:go(e.expression,e.source),base:t.base,path:t.path}:null}function wd(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 mw(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Xa(r,o.sourceRange),u=l?await vn({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 Zx(t,o.value);let f=await $d({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 f?f.kind==="external"?nb(t,f):Fd(t,go(l.node,n),f):hw({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Bt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Yt({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 f=Od(l.node);if(f)return Bt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=Od(g.path.node.init);if(p)return Bt(p.code,p.message)}return g?.path.isVariableDeclarator()&&le.isCallExpression(g.path.node.init)?yw("unsupported-expression",lb(g.path.node.init,e.functionCallContracts)):Bt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?nb(t,d):Fd(t,u.expression,d)}async function gw(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Li(r,n,o.conditionExpression);if(!l)return Bt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Yt({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 Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Fd(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 Zx(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 hw(e){let t=await sb(e);if(t.length===0)return Bt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(xw(e.expression))return ib(t);if(cb(e.expression))return Bt("unsupported-expression","i18n helpers require a static message id string");if(le.isMemberExpression(e.expression)&&e.expression.computed&&!le.isNumericLiteral(e.expression.property)&&!le.isStringLiteral(e.expression.property))return Bt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Bt(n.code,n.message)}function Bt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function yw(e,t){return ib([{code:e,message:t}])}function ib(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function xw(e){return le.isCallExpression(e)||le.isConditionalExpression(e)||le.isLogicalExpression(e)||le.isBinaryExpression(e)}function Bi(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 sb(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Od(t);if(l)return[l];if(le.isCallExpression(t))return[{code:"unsupported-expression",message:lb(t,c)}];if(le.isMemberExpression(t)&&t.computed){let u=t.property;if(!le.isNumericLiteral(u)&&!le.isStringLiteral(u)){if(!le.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Ha(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return le.isBinaryExpression(t)?Bi([...await Ad(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):le.isLogicalExpression(t)?Bi([...await Ad(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"}]):le.isConditionalExpression(t)?Bi([...await Ad(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 Od(e){return cb(e)?Qx("i18n helpers require a static message id string"):Iw(e)?Qx("CMS helpers require static entry id and field path string arguments"):null}async function Ad(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await sb({...t,expression:o}));return r}function bw(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:[Ew(e.sourceType)]}}async function Dd(e){for(let n of Nw){if(!qx(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return tb(eb(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(!qx(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return tb(eb(r),e.externalAdapters)}return null}function Ew(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Sw(e){return{code:"external-source-readonly",message:e}}function Qx(e){return{code:"unsupported-expression",message:e}}function Md(e){return!e||!le.isCallExpression(e)?null:le.isIdentifier(e.callee)?e.callee.name:le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&le.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function qx(e,t){if(!t||t.length===0)return!0;let n=Md(e.node);return n?t.includes(n):!1}function eb(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Bi(e.diagnostics??[])}:{match:e,diagnostics:[]}}function tb(e,t){let n=bw(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:Bi([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function vw(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!le.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!le.isStringLiteral(n)||!le.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 Iw(e){return!!e&&le.isCallExpression(e)&&le.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!le.isStringLiteral(e.arguments[0])||!le.isStringLiteral(e.arguments[1]))}function ab(e){if(!(!e||!le.isCallExpression(e))){if(le.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&le.isStringLiteral(t)?t.value:null}if(le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&le.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!le.isObjectExpression(t))return null;for(let n of t.properties)if(le.isObjectProperty(n)&&!n.computed&&(le.isIdentifier(n.key)&&n.key.name==="id"||le.isStringLiteral(n.key)&&n.key.value==="id")&&le.isStringLiteral(n.value))return n.value.value;return null}}}function cb(e){return ab(e)===null}async function kw(e,t,n){let r=new Set,o=Mi.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Mi.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"]:[Mi.posix.join(i,"locales"),Mi.posix.join(i,"messages")];for(let a of s){let c=Mi.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function Rw(e){let t=ab(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await kw(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Cw(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!le.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!le.isExpression(n))return null;let o=await Ha(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:[Sw("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Nw=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>vw(e)},{helperNames:["apiField"],resolve:e=>Cw(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Rw({currentFile:e,expressionPath:t,exists:n})}];function Bd(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function nb(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 Fd(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=Fw(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 _w=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function jd(e,t){let n=[..._w,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function lb(e,t){let n=e.callee;return le.isIdentifier(n)&&jd(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 $d(e){let t=await Dd(e);if(t)return t;let n=await ub({...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 vn({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 Yt({...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 ww(e)}async function ub(e){let t=await cn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Ga(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Bd(t.provenance)}async function cn(e){let t=Ga(e.expressionPath),n=Tw(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 vn({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 Yt({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 vn({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 Yt({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 cn({...e,expressionPath:r,allowComposed:!0}),a=await cn({...e,expressionPath:o,allowComposed:!1}),c=await cn({...e,expressionPath:i,allowComposed:!1});return Td(s,a,c)}if(t.isCallExpression())return Pw({...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 cn({...e,expressionPath:r,allowComposed:!0}),s=await cn({...e,expressionPath:o,allowComposed:!0});return Td(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 cn({...e,expressionPath:r,allowComposed:!0}),s=await cn({...e,expressionPath:o,allowComposed:!0});return Td(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:cn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ga(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 Pw(e){let t=Md(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:cn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(le.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:cn({...e,expressionPath:o,allowComposed:!1})}}return null}function Td(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Aw(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Aw(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 Tw(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function ww(e){if(!e.expressionPath.isCallExpression())return null;let t=Md(e.expressionPath.node);if(!t)return null;let n=jd(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 db({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?Bd(i):null}async function db(e){let t=await Dd({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 vn({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 Yt({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 $d({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||!le.isCallExpression(t))return null;let n=t.callee;if(!le.isIdentifier(n))return null;let r=jd(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 db({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?Bd(a):null}function Fw(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=ho(t,e.path);return{sourceId:o,displayPath:o}}async function Lw(e){let t=e.segment.source;return t?Yt({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 Yt(e){let t=e.sourceInfo,n=Pd(e.expressionPath,t.base);if(n){let l=await aw({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=Jx(n.callPath,[...n.basePath,...t.path]);return xi(h)?Yx(e.currentFile,h.sourceId,h.displayPath):null}let u=Hx(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return xt(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,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 mr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await uw({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(!f||f.kind==="external")return null;let g=t.path.slice(1);return xt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Fh(r);if(o){let l=o.expressionPath,u=await vn({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 Yt({...e,expressionPath:l,sourceInfo:{...u,expression:ho(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 f=await pb({...e,expressionPath:Ga(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await ub({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 dw({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=xa(r,t.path,fw(e.fileCache));if(xi(s))return Yx(e.currentFile,s.sourceId,s.displayPath);let a=await Wa({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:xt(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 pb(e){let t=Xx(e.expressionPath.node);if(!t||!zx(t.segments))return null;let n=await Yt({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 lw({...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 Wa({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>xt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:go(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function fb(e){let t=Dw(e.propertyName);if(t.owner==="blocked")return ar(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return ar(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 ar("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 Bw(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 ar("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}:ar("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?ar("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):Mw(e,s.attribute)}async function Mw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await yo({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}}:ar("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 yo({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"?ar("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 Bw(e,t){let n=t.source?.expression;if(!n)return;let r=await yo({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:jw(r,e.propertyName)}}function jw(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 ar(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function mb(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(Mr(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=>Kw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>$w({...r,graph:e},n)}function $w(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=Uw(n,r,o,t),a=s?.tag??(Mr(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=Xw(s),u=zw(n,r,o,i,s),d=Vw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:Jw(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:Hw(d),alternativeStrategies:Ww(d)}}function Vw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Vd(e,n)?"instance":!Mr(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function Uw(e,t,n,r){if(Mr(t.tag))return t;let o=Vd(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function Kw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Jw(e,t){return Mr(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Xw(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 zw(e,t,n,r,o){let i=new Set,s=Vd(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&&Mr(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Vd(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Mr(r.tag))return r;n=r.parentKey}return null}function Mr(e){return/^[A-Z]/.test(e)}function Hw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Ww(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function yb(e){let t=e.isRepeat??(e.graph?rO(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=nO(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>Gw({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:oO(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 Gw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=Yw(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:Na({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=Zw(t,n,l,e.isRepeat),d=c?eO(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?qw(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=tO(t,n,r);if(f.length===0&&h.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:p,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function Yw(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 Zw(e,t,n,r){return n?gb(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:gb(Qw(e))}function Qw(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 gb(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function qw(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 eO(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:hb({...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:hb(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function tO(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 nO(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function rO(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 hb(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 oO(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 iO(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var sO=160;function xb(e,t,n,r={}){let o=Hr(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 bb(e,t,n,r,o,i,s,a,c,l,u){let d=Hr(t),f=t.elements.get(e),g=n.nodes.get(e),p=r.get(e);if(!f||!g||!p)throw new Error(`Node not found: ${e}`);let h=kb(f.textSegments,s),y=Rb(e,t,f,p,h),x=h?uO(h):void 0,E=dO(i,h),b=f.textSegments.map(R=>({index:R.index,value:R.value,editable:Cb(R,p,s?.get(R.index)??null),source:o.get(R.index)??null})),v=vb(f,t),_=f.childKeys.map(R=>{let N=t.elements.get(R);return N?{key:R,tag:N.tag,label:N.tag}:null}).filter(R=>R!==null),P=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let N of R.childKeys){if(N===e)continue;let A=t.elements.get(N);A&&P.push({key:N,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:Sb(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:v,children:_,siblings:P}}function Eb(e,t,n,r,o,i,s,a){let c=Hr(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 f=kb(l.textSegments,i),g=aO(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:Sb(l),label:l.tag,capabilities:Rb(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(p=>({code:p.code,message:p.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(p=>{let h=o.get(p.index);return{index:p.index,editable:Cb(p,d,i?.get(p.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:vb(l,t)}}function aO(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 Sb(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:cO(e.sourceRange),structuralPath:e.identity.structuralPath,...lO(e.textSegments)}}function vb(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 cO(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function lO(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,sO)}:{}}function Ib(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 kb(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Rb(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&&Nb(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 Cb(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Nb(n.editMode):!0}function Nb(e){return e==="direct"||e==="proxy"||e==="upstream"}function uO(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 dO(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}:iO(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 Ud=["set-class-name-source","apply-style-draft"];function _b(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Ud,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:Ud,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Ud}}import Pb from"node:path";function Jd(){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 Tb(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=gO(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 Ya(e){let t=()=>pO(e);return e.mutex?e.mutex.runExclusive(t):t()}async function pO(e){let t=await Tb(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=fO(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 Kd({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 Kd({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 Kd({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 Ab("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Ab("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 fO(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 Kd(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:mO(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 Ab(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function mO(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 gO(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)||Pb.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Pb.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 hO=50,yO=8*1024*1024;function Lb(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??hO),s=Math.max(0,t.maxUndoBytes??yO);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let N=[...R.steps].sort((z,Q)=>z.order-Q.order),A=N.filter(z=>z.type!=="invoke-external-adapter");if(A.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(A.map(z=>z.file)),$=await E(L),U=new Map($.map(z=>[z.file,z.exists===!1?"":z.content])),de;for(let z of A){let Q=Fb(z,U.get(z.file)??"");if(!Q.ok)return{ok:!1,errorCode:Q.errorCode,reason:Q.reason};U.set(z.file,Q.source),de=Q.selectionRef??de}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...U].map(([z,Q])=>({operation:"upsert",file:z,content:Q,baseContentHash:$.find(ke=>ke.file===z)?.sha256??null}))},...de?{selectionRef:de}:{}}}async function c(R){let N=[...R.steps].sort((ke,ct)=>ke.order-ct.order),A=N.filter(ke=>ke.type!=="invoke-external-adapter"),L=N.filter(ke=>ke.type==="invoke-external-adapter"),$=new Set(A.map(ke=>ke.file));if(A.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(A.length===0)return y(R,L);let U=await E($),de=new Map;for(let ke of U)de.set(ke.file,ke.exists===!1?"":ke.content);let z;for(let ke of A){let ct=de.get(ke.file)??"",lt=Fb(ke,ct);if(!lt.ok)return{ok:!1,operationId:R.operationId,errorCode:lt.errorCode,reason:lt.reason,rolledBack:!1};de.set(ke.file,lt.source),lt.selectionRef&&(z=lt.selectionRef)}let Q=await v([...de].map(([ke,ct])=>({file:ke,content:ct,exists:!0,version:0,sha256:ve(ct)})),U);return Q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:U,postSnapshots:Q.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Q.snapshots.map(ke=>ke.version)),affectedFiles:[...$],...z?{selectionRef:z}:{}})}async function l(R){let N=new Set(R.edits.map(Q=>Q.file)),A=await E(N),L=x(R,A);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let $=new Map(A.map(Q=>[Q.file,Q])),U=R.edits.find(Q=>Q.operation==="create-only"&&$.get(Q.file)?.exists!==!1);if(U)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${U.file}`,affectedFiles:[U.file],rolledBack:!1};let de=R.edits.map(Q=>Q.operation==="delete"?{file:Q.file,content:"",exists:!1,version:0}:{file:Q.file,content:Q.content,exists:!0,version:0,sha256:ve(Q.content)}),z=await v(de,A,new Set(R.edits.filter(Q=>Q.operation==="create-only").map(Q=>Q.file)));return z.ok===!1?{ok:!1,operationId:R.operationId,errorCode:z.rolledBack?"writeback-failed":"rollback-failed",reason:z.reason,rolledBack:z.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:A,postSnapshots:z.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...z.snapshots.map(Q=>Q.version)),affectedFiles:[...N]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await v(R.preSnapshots,R.postSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:R.preSnapshots.map(A=>A.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await v(R.postSnapshots,R.preSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:R.postSnapshots.map(A=>A.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((R,N)=>R+p(N),0)}function p(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((N,A)=>N+A.file.length+A.content.length,0)}async function y(R,N){let A=[];for(let L of N){let $=L.capability??"write-text",U=o.find(z=>z.sourceType===L.sourceType&&(L.adapterId===void 0||z.adapterId===L.adapterId)&&(z.capabilities===void 0||z.capabilities.includes($)));if(!U)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let de=await U.execute(L);if(!de.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:de.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};A.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:A}}function x(R,N){if(R.conflictPolicy!=="compare-and-swap")return null;let A=new Map(N.map(L=>[L.file,L]));for(let L of R.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 $=A.get(L.file),U=L.baseContentHash;if(U===null){if($?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!U)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if($?.exists===!1||$?.sha256!==U)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let N=[];for(let A of R)N.push(await b(A));return N}async function b(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:A,exists:!0,sha256:ve(L)}}async function v(R,N,A=new Set){let L=[];try{for(let $ of R){if(A.has($.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive($.file,$.content)}else await _($);let U=e.bumpVersion($.file);L.push($.file),$.version=U}}catch($){let U=await P(N.filter(z=>L.includes(z.file)));if(U.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${U.failedFiles.join(", ")}: ${Ob($)}`,rolledBack:!1,instanceConflict:wb($)};let de=wb($);return{ok:!1,reason:`${de?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Ob($)}`,rolledBack:!0,instanceConflict:de}}return{ok:!0,snapshots:R.map(xO)}}async function _(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function P(R){let N=[];for(let A of R)try{await _(A),e.bumpVersion(A.file)}catch{N.push(A.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function wb(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function xO(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function Ob(e){return e instanceof Error?e.message:String(e)}function Fb(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 pt(Jt({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return pt(zr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return pt(vr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return pt(Kt({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return pt(gs({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return pt(jo({source:t,locator:e.locator,next:e.value}));case"update-array-item":return pt(jo({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return pt(Ss({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return pt(hs({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return pt(vs({source:t,locator:e.locator,index:e.index}));case"move-array-item":return pt(Is({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return pt(kr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return pt(ys({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 bO(e,t);case"set-property-changes":return pt(xs({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return pt(bs({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return pt(Es({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return pt(Rs({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function bO(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!im(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ve(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:om({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function pt(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 Za,SiteEditCompositionContextSchema as EO,SiteEditCompositionSelectorSchema as SO}from"@vcp-dev/contracts";var bt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Db(e,t){throw new bt("INVALID_COMPOSITION",e,{value:t})}function Qa(e){let t=EO.safeParse(e);return t.success?t.data:Db("Invalid SiteEditCompositionContext.",e)}function Mb(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Qa(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new bt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Za(u);if(n.has(d))throw new bt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new bt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});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 bt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Qa(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new bt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Za(u);if(!n.has(d))throw new bt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new bt("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=SO.safeParse(l);if(!u.success)return Db("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new bt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new bt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Qa(l),d=Za(u),f=n.get(d);if(!f)throw new bt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=Qa(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new bt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Za(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new bt("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 bt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let p={context:u,entryFile:l.entryFile,key:d};return t.push(p),n.set(d,p),p}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.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 Xd(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 Bb(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 vO,stripSiteEditRepeatInstanceKeys as jb}from"@vcp-dev/contracts";function $b(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=jb(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 IO(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 qa(e){return e?.map(t=>({...t}))}function zd(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=qa(e.collectionPathMap?.[t])??qa(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:qa(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>qa(o)??[])}}function Vb(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let p of g.childKeys)r.add(p);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,p)=>vO(g,p),c=(g,p,h)=>{let y=o.get(g);if(!y)return a(g,h);let x=a(g,h),E={...y,key:x,parentKey:p,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(b=>l(b,h,x)),x},l=(g,p,h)=>{if(!r.has(g))return[c(g,h,p)];let y=d(g,p),x=[];for(let E=0;E<y;E+=1)x.push(c(g,h,[...p,E]));return x},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 p=d(g,[]);for(let h=0;h<p;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,p){let h=new Set;for(let y of f(g)){let x=n.get(y);if(x){for(let E of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let b of kO(E))b.length<=p.length||RO(b,p)&&h.add(b[p.length])}}return h.size>0?h.size:IO(n.get(g))}function f(g){let p=s.get(g);if(p)return p;let h=[g],y=o.get(g);for(let x of y?.childKeys??[])h.push(...f(x));return s.set(g,h),h}}function Ub(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Kb(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((jb(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function kO(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 RO(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 Jb(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 Xb(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 zb(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function CO(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ji=class extends Error{constructor(t){let n=t.map(zb);super(CO(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Hb(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ji?{routeId:e,message:n,diagnostics:t.diagnostics.map(zb)}:{routeId:e,message:n}}function Hd(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Wd(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function xo(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Wb(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Gd(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 Gb(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 FO=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,LO=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],Yb=32,Yd=256;function DO(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Zb={maxEntries:50,maxBytes:8*1024*1024};function MO(){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 _s(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 Qb(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 BO(){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>Zb.maxEntries||jO(e)>Zb.maxBytes;)e.shift()}}function jO(e){return e.reduce((t,n)=>t+$O(n),0)}function $O(e){return qb(e.preSnapshots)+qb(e.postSnapshots)+VO(e.provenance)}function VO(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function qb(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function eE(e,t){return{key:_O(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex: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 tc=class extends Error{constructor(t){super(t.reason),this.result=t}},Br=class extends Error{constructor(t){super(Hd(t)),this.failedRoutes=t}};function tE(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=At(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(At(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function UO(e,t,n){if(!n)return;let r=At(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 KO=/\.(?:[cm]?[jt]sx?)$/i,JO=/\.json$/i,XO=/\.(?:css|scss|sass)$/i,zO=/\.mdx$/i,HO=/\.ya?ml$/i;function WO(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 GO(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function YO(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=aE(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(ZO(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 ZO(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function aE(e){return Array.isArray(e)?{files:e}:e}function QO(e){if(!AO(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!==wO||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=PO(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(KO.test(e.path)){let t=un({source:e.content,profile:hr({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(JO.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${St(t)}`,details:{path:e.path}}}if(XO.test(e.path)){let t=nE({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(zO.test(e.path)){let t=nE({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(HO.test(e.path))try{OO(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${St(t)}`,details:{path:e.path}}}return{ok:!0}}function nE({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 f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let p=e.indexOf(`
|
|
1
|
+
import*as LS from"@babel/parser";import*as ht from"@babel/types";import*as Kn from"node:path";var _c=[".tsx",".ts",".jsx",".js"],DS=_c.map(e=>`/index${e}`),MS=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 Qp(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&MS.has(n[1].toLowerCase())}function qp(e){let t=[];for(let n of e.program.body)ht.isImportDeclaration(n)&&typeof n.source.value=="string"&&St(n.source.value)&&t.push(n.source.value),ht.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&St(n.source.value)&&t.push(n.source.value),ht.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&St(n.source.value)&&t.push(n.source.value);return ht.traverseFast(e.program,n=>{let r=ht.isImportExpression(n)?n.source:ht.isCallExpression(n)&&ht.isImport(n.callee)?n.arguments[0]:null;ht.isStringLiteral(r)&&St(r.value)&&t.push(r.value)}),t}function St(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function un(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Kn.dirname(e);return Kn.join(n,t).replace(/\\/g,"/")}async function BS(e,t){for(let n of ef(e))if(await t(n))return n;return null}function ef(e){return[..._c.some(t=>e.endsWith(t))?[e]:[],..._c.map(t=>`${e}${t}`),...DS.map(t=>`${e}${t}`)]}function tf(e,t,n){let r=un(e,t);if(!St(t)||!nf(e,t,r))return null;for(let o of ef(r))if(n.has(o))return o;return null}async function mr(e,t,n){let r=await Zi(e,t,n);return r.ok?r.path:null}async function Zi(e,t,n){let r=un(e,t);try{if(!nf(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 BS(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 nf(e,t,n){if(!St(t)||t.includes("\0")||t.includes("\\")||Kn.posix.isAbsolute(n))return!1;let r=Kn.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!Kn.posix.isAbsolute(e)}import{createHash as $S}from"node:crypto";import*as rf from"@babel/parser";function gr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function Z(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gr(t,n,r,o)}}function Pc(e,t,n,r,o){return{ok:!1,source:e,diagnostic:gr(t,n,r,o)}}var jS={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function dn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:rf.parse(t,{sourceType:"module",plugins:jS[n]})}}catch(r){return{ok:!1,source:t,diagnostic:gr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Ac(e,t){return dn({source:e,profile:of(t.kind)})}function _o(e,t){return dn({source:e,profile:of(t)})}function of(e){return"next-app-entry"}function hr(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 Je=(e,t)=>{let n=dn({source:t,profile:hr({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${$S("sha256").update(t).digest("hex")}`,ast:n.ast,imports:qp(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function VS(e,t){return Je(e,t)}function US(e,t){return un(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as KS,parseComponentI18nResourcesJson as JS,resolveSiteTextDirection as XS,SiteLocaleSchema as zS}from"@vcp-dev/contracts";var HS=["i18next","react-i18next"],WS="components/ui/site-locale-provider.tsx",GS="components/ui/component-i18n-provider.tsx",sf="app/layout.tsx";async function Po(e){let t=e.files.filter(f=>f.path.endsWith(KS));if(t.length===0)return{ok:!0};for(let f of["package.json",sf,WS,GS])if(!await e.exists(f))return Jn(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return Jn("Target snapshot package.json is invalid.")}let r=af(n)&&af(n.dependencies)?n.dependencies:{},o=HS.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return Jn(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(sf),s=Tc(i,"html","lang"),a=Tc(i,"html","dir"),c=Tc(i,"SiteLocaleProvider","locale"),l=zS.safeParse(s);if(!l.success||!a||!c||s!==c||a!==XS(l.data))return Jn("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 Jn("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return Jn("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=JS(f.content);if(!g.success)return Jn(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return Jn(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Tc(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 af(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jn(e){return{ok:!1,message:e}}import Oc from"@babel/generator";import*as ff from"@babel/parser";import Fc from"@babel/traverse";import*as je from"@babel/types";import{computeSiteEditSourceIdentityKey as ZS}from"@vcp-dev/contracts";var cf="data-vcp-ui-component",Qi="components/ui";function _n(e){if(!e)return!1;let t=wc(e);return t===Qi||t.startsWith(`${Qi}/`)||t.includes(`/${Qi}/`)||t.endsWith(`/${Qi}`)}function yr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?_n(e.slice(2)):e.startsWith("./")||e.startsWith("../")?_n(wc(`${YS(t)}/${e}`)):_n(e):!1}function wc(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 YS(e){let t=wc(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as JM}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as zM,isSiteEditRuntimeTextTag as HM}from"@vcp-dev/contracts/site-edit-runtime-capability";var lf={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 QS=typeof Oc=="function"?Oc:Oc.default,qS=typeof Fc=="function"?Fc:Fc.default,ev=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),tv="suppressHydrationWarning",nv=new Set(["SiteEditBootstrap"]);function rv(e){let t=sv(e.file,e.projectRoot);if(!iv(e.source)||_n(t))return{code:e.source,elements:[]};let n=e.attributes??lf,r=ff.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=cv(r,t);return qS(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!uv(c)||mf(a,n.key))return;let l=pv(s)??"default",u=mv(s),d=ZS(t,l,u),f=es(c)??"unknown",g=av(c)?"jsx":"component-call";if(g==="component-call"&&!fv(s.node.children)&&nv.has(f))return;let p=g==="component-call"&&lv(f,i);dv(a,n.key,d),p&&uf(a,cf),ov(s)&&uf(a,tv),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:QS(r,{jsescOption:{minimal:!0}}).code,elements:o}}function ov(e){return!e.findParent(t=>t.isJSXElement())}function iv(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function sv(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 av(e){return je.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function es(e){return je.isJSXIdentifier(e)?e.name:je.isJSXMemberExpression(e)?hf(e):null}function cv(e,t){let n=new Set;for(let r of e.program.body)if(!(!je.isImportDeclaration(r)||!yr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function lv(e,t){let n=e.split(".")[0]??e;return t.has(n)}function uv(e){let t=es(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!ev.has(t)}function mf(e,t){return e.attributes.some(n=>je.isJSXAttribute(n)&&je.isJSXIdentifier(n.name,{name:t}))}function dv(e,t,n){gf(e,je.jsxAttribute(je.jsxIdentifier(t),je.stringLiteral(n)))}function uf(e,t){mf(e,t)||gf(e,je.jsxAttribute(je.jsxIdentifier(t),null))}function gf(e,t){let n=e.attributes.findIndex(r=>je.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function hf(e){return`${je.isJSXIdentifier(e.object)?e.object.name:hf(e.object)}.${e.property.name}`}function pv(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&je.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 fv(e){return e.some(t=>je.isJSXElement(t)||je.isJSXFragment(t))}var df=new WeakMap,qi=new WeakMap,Lc=new WeakMap;function mv(e){let t=df.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=gv(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return df.set(e.node,o),o}function gv(e){let t=es(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${pf(e,t)}`:`${t}#${pf(e,t)}`}function pf(e,t){let n=yf(e)??e.getFunctionParent();if(!n)return 0;let r=Lc.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Lc.get(n.node);o||(o=new Map,Lc.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()?ts(n):hv(n);for(let c of a)if(es(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 hv(e){let t=qi.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!yf(r)&&n.push(r)}}),qi.set(e.node,n),n}function yf(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 ts(e){let t=qi.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(...ts(o));continue}o.isJSXExpressionContainer()&&n.push(...xr(o.get("expression")))}return qi.set(e.node,n),n}function xr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return ts(e);if(e.isParenthesizedExpression())return xr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return xr(e.get("right"));if(e.isConditionalExpression())return[...xr(e.get("consequent")),...xr(e.get("alternate"))];if(e.isCallExpression()&&xv(e.node)){let t=e.get("arguments")[0];return yv(t)}return[]}function yv(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return ts(t);if(t.isParenthesizedExpression())return xr(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?xr(r):[]}return[]}function xv(e){return je.isMemberExpression(e.callee)&&je.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as EF,SiteEditPatchPlanSchema as SF}from"@vcp-dev/contracts";function br(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 ns(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 rs(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}:{}})),...e.pageBlocks!==void 0?{pageBlocks:e.pageBlocks}:{},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 os(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:bv(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 is(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:br(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 bv(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 TO,computeSiteEditCompositionKey as wO,getSiteEditSourceDeleteProtectionReason as OO,isSiteEditTextSourcePath as FO,parseSiteEditRepeatInstanceKey as LO,SITE_EDIT_SOURCE_DELETE_CAPABILITY as DO,stripSiteEditRepeatInstanceKeys as At}from"@vcp-dev/contracts";import tc from"node:path";import{parse as MO}from"yaml";import $c from"node:path";import{TextDecoder as Sv}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as bf,SITE_EDIT_SOURCE_ALLOWED_DIRS as Ef,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Sf,SiteEditCompositionContextSchema as vv,SiteEditSourceFileResponseSchema as Dc,SiteEditSourceLocationSchema as Iv,SiteEditSourcePathSchema as ss,SiteEditSourceTreeResponseSchema as kv,isSiteEditTextSourcePath as Rv}from"@vcp-dev/contracts";import{createHash as Ev}from"node:crypto";var Ao=class{constructor(t){this.original=new Map,this.files=new Map,this.versions=new Map;for(let n of t)this.original.set(n.path,n.content),this.files.set(n.path,n.content),this.versions.set(n.path,n.version??1)}async readFile(t){let n=this.files.get(t);if(n===void 0)throw new Error(`Snapshot file not found: ${t}`);return n}async readFileBytes(t){return Buffer.from(await this.readFile(t),"utf8")}async getFileInfo(t){let n=this.files.get(t);return n===void 0?null:{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async writeFile(t,n){this.files.set(t,n)}async createExclusive(t,n){if(this.files.has(t))throw Object.assign(new Error(`Snapshot file already exists: ${t}`),{code:"EEXIST"});this.files.set(t,n)}async deleteFile(t){this.files.delete(t)}async exists(t){return this.files.has(t)}async listFiles(t={}){let n=t.roots??[],r=[...this.files.keys()].filter(a=>n.length===0?!0:n.some(c=>a===c||a.startsWith(`${c}/`))),o=[],i=new Set,s=0;for(let a of r.sort()){let c=Buffer.byteLength(this.files.get(a)??"","utf8"),l=a.split("/").length;if(t.maxDepth!==void 0&&l>t.maxDepth){i.add("max-depth");continue}if(t.maxFiles!==void 0&&o.length>=t.maxFiles){i.add("max-files");break}if(t.maxTotalBytes!==void 0&&s+c>t.maxTotalBytes){i.add("max-total-bytes");break}o.push({path:a,sizeBytes:c}),s+=c}return i.size>0?{files:o,truncated:{reasons:[...i]}}:{files:o}}getVersion(t){return this.versions.get(t)??0}bumpVersion(t){let n=this.getVersion(t)+1;return this.versions.set(t,n),n}getChangedFiles(){let t=new Set([...this.original.keys(),...this.files.keys()]),n=[];for(let r of[...t].sort()){let o=this.original.get(r),i=this.files.get(r);o!==i&&n.push({path:r,before:o,after:i})}return n}};function ve(e){return`sha256:${Ev("sha256").update(e).digest("hex")}`}var Cv=[...Sf,...bf,...Ef];function Vc(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return vv.parse(e.composition)}var Mc=2e3,Bc=12,jc=24*1024*1024,xf=512*1024,Nv=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),_v={".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"},Pv={".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"},Av=new Sv("utf-8",{fatal:!0});async function as(e,t={}){let n=Vc(t),{files:r,truncated:o}=await Mv(e,t),i=$v(r.map(s=>s.metadata));return kv.parse({composition:n,nodes:i,defaultPath:Vv(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function cs(e,t,n={}){let r=Vc(n),o=ss.parse(t.path),i=await wv(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Kc(o)){let a=kf(o),c=await Fv(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Dc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Uc(e,o);return s.ok?Dc.parse({composition:r,path:o,kind:"text",language:Rf(o),sizeBytes:s.sizeBytes,contentHash:ve(s.content),readonly:!1,content:s.content}):Dc.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Uc(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=Tv(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 Tv(e){if(e.includes(0))return null;try{return Av.decode(e)}catch{return null}}async function wv(e,t,n){if(!Lv(t,n))return null;let r=await Ov(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function Ov(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=vf(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(Kc(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function Fv(e,t){if(!Nv.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>xf)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>xf?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function Lv(e,t){return Sf.some(n=>n===e)||bf.some(n=>n===e)||Ef.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=ss.safeParse(n);return r.success&&r.data===e})}function ls(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return Iv.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 vf(e){return Array.isArray(e)?{files:e}:e}function Dv(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function Mv(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=vf(await e.listFiles({roots:Bv(t),maxFiles:Mc+1,maxDepth:Bc,maxTotalBytes:jc+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=ss.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Bc){o.add("max-depth");continue}if(r.size>=Mc){o.add("max-files");break}if(i+a.sizeBytes>jc){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:jv(l,a.sizeBytes,Vc(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:Dv([...o]),maxFiles:Mc,maxDepth:Bc,maxTotalBytes:jc}}:{}}}function Bv(e){let t=new Set(Cv);for(let n of e.routeEntryFiles??[]){let r=ss.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function jv(e,t,n){return Kc(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:kf(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Rf(e),sizeBytes:t,readonly:!1}}function $v(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 If(t)}function If(e){return e.map(t=>t.kind==="directory"?{...t,children:If(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function Vv(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 Kc(e){return!Rv(e)}function kf(e){let t=$c.posix.extname(e).toLowerCase();return!t&&$c.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":_v[t]??"application/octet-stream"}function Rf(e){let t=$c.posix.extname(e).toLowerCase();return Pv[t]??"plaintext"}import*as Sr from"@babel/types";import Jc from"@babel/traverse";import*as pn from"@babel/types";function Ke(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(pn.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(pn.isIdentifier(s)&&s.name==="Fragment"||pn.isStringLiteral(s)&&s.value==="Fragment")&&Cf(i.parentPath)}if(!pn.isJSXMemberExpression(t)||!pn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!pn.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())&&Cf(r.parentPath)}function Cf(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Xn=typeof Jc=="function"?Jc:Jc.default,us=new WeakMap,ds=new WeakMap;function fn(e,t){let n=Ac(e,t);if(!n.ok)return Pc(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=xe(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}}:Pc(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function xe(e,t){return t.kind==="jsx-node"?Af(e,t):t.kind==="jsx-attribute"?Hv(e,t):t.kind==="value"?Wv(e,t):t.kind==="expression"?Gv(e,t):t.kind==="directive"?Yv(e,t):t.kind==="export"?Zv(e,t):{ok:!1,diagnostic:gr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Af(e,t){return t.strategy==="source-range"?Uv(e,t):Kv(e,t)}function Uv(e,t){let n=null;if(Xn(e,{JSXElement(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Er(o.node,t.sourceRange))return;let i=Ye("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return qe("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!lI(r.path,t.expectedIdentity)?qe("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function Kv(e,t){if(t.structuralPath===""){let r=Xv(e,t.component);if(r){let o=zv(r);if(o)return o}}let n=null;return Xn(e,{JSXElement(r){if(wo(r)!==t.component||zc(r)!==t.structuralPath)return;let i=Ye("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(wo(r)!==t.component||zc(r)!==t.structuralPath)return;let i=Ye("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=Jv(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:qe("jsx-node","locator-miss","JSX node not found for structural-path locator")}function Jv(e,t,n){let r=null;return Xn(e,{JSXElement(o){if(wo(o)!==t||!Er(o.node,n))return;let i=Ye("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(wo(o)!==t||!Er(o.node,n))return;let i=Ye("jsx-node",o);i&&(r=i,o.stop())}}),r}function Xv(e,t){let n=null;return Xn(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 zv(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 qe("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?qe("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 qe("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function Hv(e,t){let n=Af(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>uI(c,t.name));if(!s||!s.isJSXAttribute())return qe("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ye("jsx-attribute",s);return a?{ok:!0,match:a}:qe("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function Wv(e,t){let n=Qv(e,t);if(!n.ok)return n;let r=qv(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!An(r.match.path.node.loc,t.expectedRange)?qe("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function Gv(e,t){let n=null;return Xn(e,{Identifier(r){if(!iI(r))return;let o=_f(r);if(!o||!Pf(o,t))return;let i=Ye("expression",r);i&&(t.expectedRange&&!An(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=_f(r);if(!o||!Pf(o,t))return;let i=Ye("expression",r);i&&(t.expectedRange&&!An(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:qe("expression","locator-miss","Expression not found")}function Yv(e,t){let n=null;return Xn(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!An(i.node.loc,t.expectedRange))return;let s=Ye("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:qe("directive","locator-miss",`Directive '${t.value}' not found`)}function Zv(e,t){let n=null;return Xn(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=Ye("export",c);if(!f||t.expectedRange&&!An(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=Hc(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ye("export",u);if(!d||t.expectedRange&&!An(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Hc(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!An(s.node.loc,t.expectedRange))return;let a=Ye("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ye("export",o);i&&(t.expectedRange&&!An(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:qe("export","export-not-found",`Export '${cI(t)}' not found`)}function Qv(e,t){let n=null;return Xn(e,{Expression(r){if(n||t.root.kind!=="expression"||!Er(r.node,t.root.sourceRange))return;let o=Ye("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 p=Ye("value",g);if(!p)return;n=p,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 f=Ye("value",d);f&&(n=f,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Hc(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ye("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ye("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:qe("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 qv(e,t){let n=Xc(e);for(let o of t){if(n=Xc(n),o.kind==="property"){if(!n.isObjectExpression())return qe("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return qe("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>dI(l,o.name));if(!c||!c.isObjectProperty())return qe("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return qe("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return qe("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return qe("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Xc(n);let r=Ye("value",n);return r?{ok:!0,match:r}:qe("value","locator-miss","Resolved value has no source range")}function Xc(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ye(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 Er(e,t){return An(e.loc,t)}function An(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 zc(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ke(n)){let o=wf(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Nf(n,o)}`):t.unshift(`${o}#${Nf(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||rI(n.parentPath)&&!oI(n.parentPath))break;n=n.parentPath}return t.join("/")}function Nf(e,t){let n=Tf(e)??e.getFunctionParent();if(!n)return 0;let r=us.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=us.get(n.node)?.get(t);if(!i){let a=us.get(n.node);a||(a=new Map,us.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?To(n):eI(n);for(let a of s)if(wf(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function eI(e){let t=ds.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Tf(r)&&n.push(r)}}),ds.set(e.node,n),n}function Tf(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ke(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function To(e){let t=ds.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(Ke(o)){n.push(...To(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...To(o));continue}o.isJSXExpressionContainer()&&n.push(...Pn(o.get("expression")))}return ds.set(e.node,n),n}function Pn(e){if(e.isJSXElement())return Ke(e)?To(e):[e];if(e.isJSXFragment())return To(e);if(e.isParenthesizedExpression())return Pn(e.get("expression"));if(e.isLogicalExpression()&&tI(e.node.operator))return Pn(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(...Pn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Pn(a));break}}return i}else if(o.node&&o.isExpression())return Pn(o)}}}}return e.isConditionalExpression()?[...Pn(e.get("consequent")),...Pn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Pn(t)):[]}function tI(e){return e==="&&"||e==="||"||e==="??"}function wf(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?nI(e.name):null}function nI(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 wo(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 rI(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function oI(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 iI(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function _f(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 Pf(e,t){return e.base===t.base&&sI(e.path,t.path??[])}function sI(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 aI(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function cI(e){return e.exportKind==="named"?e.name:e.exportKind}function qe(e,t,n,r){return{ok:!1,diagnostic:gr(t,n,e,r)}}function lI(e,t){return wo(e)!==t.component?!1:zc(e)===t.structuralPath}function uI(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Hc(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function dI(e,t){return e.isObjectProperty()?aI(e.node)===t:!1}import*as Ff from"@babel/parser";import{arrayExpression as hI,booleanLiteral as yI,identifier as xI,jsxAttribute as bI,jsxExpressionContainer as EI,jsxIdentifier as SI,nullLiteral as vI,numericLiteral as II,objectExpression as kI,objectProperty as RI,stringLiteral as Gc}from"@babel/types";import Wc from"@babel/generator";var pI=typeof Wc=="function"?Wc:Wc.default;function fI(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 mI(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 gI(e,t){return e.split(`
|
|
3
|
+
`).map(r=>mI(r,t)).join(`
|
|
4
|
+
`)}function ps(e){let{ast:t,source:n}=e;try{let r=fI(n),i=pI(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=gI(i,r)),{ok:!0,source:i}}catch(r){return Z(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Of(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 Oo(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Of(e),afterSourceHash:Of(t),inverse:n.inverse}}}function Ae(e,t,n){let r=ps({ast:e,source:t});return r.ok?Oo(t,r.source,n):r}function $e(e,t){let n=_o(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function fs(e,t){return ps({ast:e,source:t})}function CI(e,t,n){let r=xe(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Kr(e,t,n){let r=CI(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:Z(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function zn(e){return typeof e=="string"?Gc(e):typeof e=="number"?II(e):typeof e=="boolean"?yI(e):e===null?vI():Array.isArray(e)?hI(e.map(t=>zn(t))):kI(Object.entries(e).map(([t,n])=>{let r=RI(Yc(t),zn(n));return t==="__proto__"&&(r.computed=!0),r}))}function NI(e){return typeof e=="string"?Gc(e):EI(zn(e))}function Fo(e,t){return bI(SI(e),NI(t))}function ms(e,t){try{let r=Ff.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:Z(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:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Yc(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?xI(e):Gc(e)}function gs(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=$e(t,"jsx-node");if(!i.ok)return i.result;let s=xe(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=_I(s.match.path)[r];if(!c)return Z(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]??"",f=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[Sr.jsxText(d)]:[],Sr.jsxExpressionContainer(Sr.stringLiteral("")),...f?[Sr.jsxText(f)]:[]]);break}let u=PI(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 Ae(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function _I(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=AI(r.get("expression"));o.length>0&&t.push(...o)}}return t}function PI(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function AI(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 Zc}from"@babel/types";function vr(e){let{source:t,locator:n}=e,r=$e(t,"jsx-node");if(!r.ok)return r.result;let o=xe(r.ast,n);return o.ok?(TI(o.match.path),Ae(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function TI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Zc());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Zc());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Zc());return}e.remove()}import{cloneNode as wI}from"@babel/types";function Jr(e){let t=$e(e.source,"jsx-node");if(!t.ok)return t.result;let n=xe(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=ms(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(wI(r.node,!0)),Ae(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as KI}from"@babel/types";import Qc from"@babel/traverse";import*as ue from"@babel/types";function Lo(e,t,n){return`${e}::${t}::${n}`}var M={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 OI=typeof Qc=="function"?Qc:Qc.default;function Ut(e,t,n,r){if(!e.ok)return e;let o=Vt(n,t);if(!o)return e;let i=FI(t,o,r);return i?{...e,selectionRef:i}:e}function FI(e,t,n){let r=LI(e,t);if(!r)return;let o=n.sourceLocator?Lf(n.sourceLocator):void 0,i=n.targetParentLocator?Lf(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??MI(r)??i?.component??o?.component;if(!(!s||!a))return{key:Lo(s,a,BI(r))}}function Lf(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function LI(e,t){let n=Vf(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Vf(e,t){let n=null;return OI(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Vt(e,t){if(!e)return null;if(ue.isJSXElement(e))return UI(t,e)?Df(e.children,t):e;if(ue.isJSXFragment(e))return Df(e.children,t);if(ue.isJSXExpressionContainer(e)||ue.isParenthesizedExpression(e)||ue.isTSAsExpression(e)||ue.isTSSatisfiesExpression(e)||ue.isTSTypeAssertion(e)||ue.isTSNonNullExpression(e))return Vt(e.expression,t);if(ue.isLogicalExpression(e))return Vt(e.right,t);if(ue.isConditionalExpression(e))return Vt(e.consequent,t)??Vt(e.alternate,t);if(ue.isCallExpression(e)||ue.isOptionalCallExpression(e))return Uf(e)?DI(e.arguments[0],t):null;if(ue.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Vt(n,t);if(r)return r}return null}function Df(e,t){for(let n of e){let r=Vt(n,t);if(r)return r}return null}function DI(e,t){return!e||!ue.isArrowFunctionExpression(e)&&!ue.isFunctionExpression(e)?null:ue.isBlockStatement(e.body)?Do(e.body.body,t):Vt(e.body,t)}function Do(e,t){for(let n of e){if(ue.isReturnStatement(n)){let r=Vt(n.argument,t);if(r)return r;continue}if(ue.isBlockStatement(n)){let r=Do(n.body,t);if(r)return r;continue}if(ue.isIfStatement(n)){let r=Mf(n.consequent,t);if(r)return r;let o=n.alternate?Mf(n.alternate,t):null;if(o)return o;continue}if(ue.isSwitchStatement(n))for(let r of n.cases){let o=Do(r.consequent,t);if(o)return o}}return null}function Mf(e,t){return ue.isBlockStatement(e)?Do(e.body,t):Do([e],t)}function MI(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(ue.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&ue.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 Bf=new WeakMap,jf=new WeakMap,qc=new WeakMap;function BI(e){let t=Bf.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=jI(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Bf.set(e.node,o),o}function jI(e){let t=Kf(e.node.openingElement.name);return!t||Ke(e)?null:/^[A-Z]/.test(t)?`component:${t}#${$f(e,t)}`:`${t}#${$f(e,t)}`}function $f(e,t){let n=$I(e);if(!n)return 0;let r=qc.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=qc.get(n.node);o||(o=new Map,qc.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of Ir(n))if(Kf(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 $I(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ke(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Ir(e){let t=jf.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(Ke(o)){n.push(...Ir(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Ir(o));continue}o.isJSXExpressionContainer()&&n.push(...mn(o.get("expression")))}return jf.set(e.node,n),n}function mn(e){if(e.isJSXElement())return Ke(e)?Ir(e):[e];if(e.isJSXFragment())return Ir(e);if(e.isParenthesizedExpression())return mn(e.get("expression"));if(e.isLogicalExpression())return mn(e.get("right"));if(e.isConditionalExpression())return[...mn(e.get("consequent")),...mn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:mn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Uf(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?VI(n):[]}return[]}function VI(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ke(t)?Ir(t):[t];if(t.isJSXFragment())return Ir(t);if(t.isParenthesizedExpression())return mn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return mn(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(...mn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...mn(o)),n}return n}function Uf(e){let t=e.callee;return(ue.isMemberExpression(t)||ue.isOptionalMemberExpression(t))&&ue.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function UI(e,t){let n=Vf(e,t);return n?Ke(n):!1}function Kf(e){return ue.isJSXIdentifier(e)?e.name:ue.isJSXMemberExpression(e)?Jf(e):ue.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Jf(e){return`${ue.isJSXIdentifier(e.object)?e.object.name:Jf(e.object)}.${e.property.name}`}function Hn(e,t){if(t.parentPath===e&&t.listKey==="children"&&el(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!el(n))return null;let r=n;for(;r&&r!==e;){if(!el(r)||!Ke(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function el(e){return e.isJSXElement()||e.isJSXFragment()}function Kt(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=$e(t,"jsx-node");if(!a.ok)return a.result;let c=xe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return Z(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 b=c.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=ms(t,r.jsx);if(!u.ok)return u.result;let d=KI(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=b=>s?Ut(b,a.ast,d,g):b;if(o==="append")return f.push(d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let h=xe(a.ast,i);if(!h.ok)return{ok:!1,source:t,diagnostic:h.diagnostic};let y=Hn(c.match.path,h.match.path);if(!y)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let x=l.node.children,E=x.findIndex(b=>b===h.match.path.node);return E===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),p(Ae(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Xf from"@babel/parser";import{cloneNode as JI}from"@babel/types";function hs(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=$e(t,"jsx-node");if(!a.ok)return a.result;let c=XI(t,r);if(!c.ok)return c.result;let l=xe(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Z(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=xe(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=Hn(l.match.path,x.match.path);if(!E)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=x.match.path.node}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=JI(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},h=x=>s?Ut(x,a.ast,f,p):x;if(o==="append")return g.push(f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),h(Ae(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function XI(e,t){try{let r=Xf.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:Z(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as zI,nullLiteral as tl}from"@babel/types";import*as Wn from"@babel/types";import*as zf from"@babel/types";function Mo(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!zf.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function kr(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=$e(t,"jsx-node");if(!a.ok)return a.result;let c=xe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=xe(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return Z(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 b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=xe(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let v=b.match.path.isJSXElement()?Mo(b.match.path,l.match.path):b.match.path,_=Hn(l.match.path,v);if(!_)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=_,d=v}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return Z(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?Mo(c.match.path,l.match.path):c.match.path,p=zI(g.node,!0);if(!Wn.isJSXElement(p)&&!Wn.isJSXExpressionContainer(p)&&!Wn.isJSXFragment(p)&&!Wn.isJSXText(p))return Z(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 Z(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");HI(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),Ut(fs(a.ast,t),a.ast,p,x);if(o==="prepend")return y.unshift(p),Ut(fs(a.ast,t),a.ast,p,x);let E=f-(h!==-1&&h<f?1:0);return y.splice(o==="before"?E:E+1,0,p),Ut(fs(a.ast,t),a.ast,p,x)}function HI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(tl());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(tl());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(tl());return}e.remove()}import*as Hf from"@babel/parser";import{cloneNode as WI,nullLiteral as nl}from"@babel/types";function ys(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=$e(t,"jsx-node");if(!c.ok)return c.result;let l=GI(t,s);if(!l.ok)return l.result;let u=xe(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=xe(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return Z(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let b=d.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return Z(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let b=xe(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let v=Hn(d.match.path,b.match.path);if(!v)return Z(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=v,g=b.match.path.node}else if(o==="before"||o==="after")return Z(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return Z(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,h=WI(l.node,!0);YI(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=p.children;if(o==="append")return x.push(h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);if(o==="prepend")return x.unshift(h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y);let E=x.findIndex(b=>b===g);return E===-1?Z(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,h),Ut(Ae(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,h,y))}function GI(e,t){try{let r=Hf.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:Z(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:Z(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function YI(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(nl());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(nl());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(nl());return}e.remove()}import{SiteEditSetPropsParamsSchema as ZI,classifySiteEditPropertyName as QI}from"@vcp-dev/contracts";import*as Xr from"@babel/types";function xs(e){let t=ZI.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return Z(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=$e(e.source,"jsx-node");if(!n.ok)return n.result;let r=Kr(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=QI(a.name);if(c.owner!=="generic")return Z(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(Xr.isJSXAttribute),s=new Map;for(let a of i){let c=qI(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 Z(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=Fo(a.name,a.value).value;c?c.value=l:o.attributes.push(Fo(a.name,a.value))}return Ae(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function qI(e){return Xr.isJSXIdentifier(e.name)?e.name.name:Xr.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as ek}from"@vcp-dev/contracts";import*as te from"@babel/types";var Wf=["prefetch","replace","scroll","locale","onNavigate"],tk=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function nk(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>te.isJSXAttribute(n)&&te.isJSXIdentifier(n.name)&&tk.test(n.name.name)))return!0;t=t.parentPath}return!1}function bs(e){let t=$e(e.source,"jsx-node");if(!t.ok)return t.result;let n=Kr(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=ek.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Tn(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=lk(s.name);if(!a)return Tn(e.source,"Unsupported JSX link tag");if(s.attributes.some(te.isJSXSpreadAttribute))return Tn(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!te.isJSXAttribute(p))continue;let h=ol(p);if(!h)return Tn(e.source,"Unsupported JSX attribute name");let y=c.get(h)??[];y.push(p),c.set(h,y)}if([...c.values()].some(p=>p.length>1))return Tn(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!ck(l))return Tn(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:ik(o,s.name);if(!u&&!d)return Tn(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&nk(o))return Tn(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let f=null;if(e.link.kind==="internal-route")if(d)f=a;else{let p=sk(t.ast,o);if(!p.ok)return Tn(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=te.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=te.jsxIdentifier("a")),ak(t.ast,d,o)}else f&&u&&(s.name=te.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=te.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Wf.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&Wf.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!te.isJSXAttribute(p))return!0;let h=ol(p);return!h||!g.has(h)}),e.link.kind!=="none"&&s.attributes.push(te.jsxAttribute(te.jsxIdentifier("href"),te.stringLiteral(e.link.href))),rk(s,e.changes),Ae(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function rk(e,t){for(let n of t){let r=e.attributes.find(s=>te.isJSXAttribute(s)&&ol(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?te.stringLiteral(n.value):te.jsxExpressionContainer(rl(n.value)),i=te.jsxAttribute(te.jsxIdentifier(n.name),o);r&&te.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function rl(e){return e===null?te.nullLiteral():typeof e=="string"?te.stringLiteral(e):typeof e=="number"?te.numericLiteral(e):typeof e=="boolean"?te.booleanLiteral(e):Array.isArray(e)?te.arrayExpression(e.map(t=>rl(t))):typeof e=="object"?te.objectExpression(Object.entries(e).map(([t,n])=>te.objectProperty(te.isValidIdentifier(t)?te.identifier(t):te.stringLiteral(t),rl(n)))):te.nullLiteral()}function ok(e){return te.isImportDefaultSpecifier(e)||te.isImportSpecifier(e)&&e.importKind!=="type"&&(te.isIdentifier(e.imported,{name:"default"})||te.isStringLiteral(e.imported,{value:"default"}))}function Gf(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(te.isIdentifier(e.node.imported,{name:"default"})||te.isStringLiteral(e.node.imported,{value:"default"}))}function ik(e,t){if(!te.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Gf(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function sk(e,t){let n=e.program.body.filter(c=>te.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(ok);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=te.importDefaultSpecifier(te.identifier(s));if(r)r.specifiers.unshift(a);else{let c=te.importDeclaration([a],te.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&te.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function ak(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Gf(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 ck(e){return!e.value||te.isStringLiteral(e.value)}function lk(e){return te.isJSXIdentifier(e)?e.name:null}function ol(e){return te.isJSXIdentifier(e.name)?e.name.name:null}function Tn(e,t){return Z(e,"unsupported-syntax",t,"jsx-node")}import*as ot from"@babel/types";import{classifySiteEditPropertyName as Yf}from"@vcp-dev/contracts";function Es(e){let t=Yf(e.name),n=Yf(e.property);if(t.owner!=="generic"||n.owner!=="generic")return Z(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Zf(e.object))return Z(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return Z(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=$e(e.source,"jsx-node");if(!r.ok)return r.result;let o=Kr(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>ot.isJSXAttribute(l)&&dk(l)===e.name);if(s.length>1)return Z(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=uk(e.object,e.property),c=s[0];if(c)c.value=ot.jsxExpressionContainer(a);else{let l=Fo(e.name,"");l.value=ot.jsxExpressionContainer(a),i.attributes.push(l)}return Ae(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function uk(e,t){return Zf(t)?ot.memberExpression(ot.identifier(e),ot.identifier(t)):ot.memberExpression(ot.identifier(e),ot.stringLiteral(t),!0)}function Zf(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function dk(e){return ot.isJSXIdentifier(e.name)?e.name.name:ot.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as fk,identifier as Bo,importDeclaration as mk,importDefaultSpecifier as gk,importNamespaceSpecifier as hk,importSpecifier as yk,isImportDefaultSpecifier as Qf,isImportNamespaceSpecifier as qf,isImportSpecifier as em,stringLiteral as xk}from"@babel/types";function Jt(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!Nk(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return Z(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=kk(r);if(!i.ok)return Z(t,"unsupported-syntax",i.message);let s=$e(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(x=>{let E=_k(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(sm(y)));if(d.length===0)return Oo(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=Rk(c.body),g=d.find(y=>f.has(il(y)));if(g)return Z(t,"unsupported-syntax",`Import local binding already exists: ${il(g)}`);let p=Ik(d);if(p.reduce((y,x)=>y+x.length,0)!==d.length)return Z(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!om(nm(y)))return Z(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>bk(E,y));if(x)Ek(x,y);else{let E=mk(tm(y),xk(n));Ck(c.body,E),l.push(E)}}return Ae(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function bk(e,t){return e.importKind==="type"?!1:om(vk(Sk(e),nm(t)))}function Ek(e,t){let n=!1,r=new Set(e.specifiers.map(o=>sl(o)));for(let o of tm(t)){let i=sl(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return im(e.specifiers),{changed:n}}function tm(e){let t=e.map(n=>{switch(n.kind){case"named":return yk(n.local?Bo(n.local):Bo(n.imported),Bo(n.imported));case"default":return gk(Bo(n.local));case"namespace":return hk(Bo(n.local));default:return n}});return im(t),t}function nm(e){let t=rm();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 Sk(e){let t=rm();for(let n of e.specifiers)Qf(n)?t.defaultLocals.add(n.local.name):qf(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function rm(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function vk(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function om(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function im(e){let t=[...e.filter(n=>Qf(n)),...e.filter(n=>qf(n)),...e.filter(n=>em(n))];e.splice(0,e.length,...t)}function Ik(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 kk(e){let t=new Map,n=new Map;for(let r of e){let o=sm(r);if(t.has(o))continue;let i=il(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 Rk(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(fk(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 Ck(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 Nk(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 sm(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 il(e){return e.kind==="named"?e.local??e.imported:e.local}function _k(e,t){return e.importKind==="type"||em(t)&&t.importKind==="type"?null:sl(t)}function sl(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 zr(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!Ak(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return Z(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=$e(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 Oo(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),Ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>Pk(u,d))),l.specifiers.length===0&&a.body.splice(c,1),Ae(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function Pk(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 Ak(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 jo(e){let{source:t,locator:n,next:r}=e,o=ks(t,n);return o.ok?(o.path.replaceWith(zn(r)),Ae(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Ss(e){let{source:t,locator:n,index:r,value:o}=e,i=ks(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?Z(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?Z(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,zn(o)),Ae(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):Z(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function vs(e){let{source:t,locator:n,index:r}=e,o=ks(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?Z(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?Z(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),Ae(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):Z(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Is(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ks(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return Z(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return Z(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 Z(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),Ae(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ks(e,t){let n=$e(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=xe(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 ut from"@babel/types";function Rs(e){let t=$e(e.source,"value");if(!t.ok)return t.result;let n=xe(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return Z(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>ut.isSpreadElement(a)||ut.isObjectProperty(a)&&a.computed))return Z(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>ut.isObjectProperty(a)&&Tk(a.key)===e.name);if(o.length>1)return Z(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?ut.unaryExpression("void",ut.numericLiteral(0)):zn(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=ut.objectProperty(Yc(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return Ae(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function Tk(e){return ut.isIdentifier(e)?e.name:ut.isStringLiteral(e)?e.value:ut.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as wk,isSiteEditRuntimeVoidElementTag as Ok}from"@vcp-dev/contracts/site-edit-runtime-capability";function Hr(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function Fk(e,t,n){let r=Hr(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(v=>({kind:v.kind,message:v.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&Ok(u),g=d||wk(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,h=i.textSegments.length>0&&i.textSegments.some(v=>v.editable);f&&!s.some(v=>v.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(v=>v.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=h&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!f&&g&&(!a||p);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function Cs(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,Fk(r,e,t));return n}function al(e){let t=e.route.graph.elements.get(e.key);if(!t)return{key:e.key,composition:e.route.composition,filePath:"",componentName:"",sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=Lk(e.route.source,t);if(!n)return{key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,openingElementRange:{start:0,end:0},version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.openingElement,o=r.attributes.find(c=>c.type==="JSXAttribute"&&c.name.type==="JSXIdentifier"&&c.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:cm(r),version:{documentVersion:e.route.graph.version,contentHash:ve(e.route.source)}};if(!o)return{...i,sourceKind:"missing",attrRaw:null,valueRaw:null,attrRange:null,diagnostics:[{code:"missing-class-name",message:"No className attribute is present on this element."}]};let s=o.value,a=s?.type==="StringLiteral"?"stringLiteral":"expression";return{...i,sourceKind:a,attrRaw:am(e.route.source,o),valueRaw:s?am(e.route.source,s):null,attrRange:cm(o),diagnostics:[]}}function lm(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 Lk(e,t){let n=dn({source:e,profile:hr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=xe(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:Dk(t.sourceRange)});return!r.ok||r.match.node.type!=="JSXElement"?null:r.match.node}function um(e){let t=dn({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 am(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function cm(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 Dk(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dm(){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 Mk}from"node:crypto";import Ns from"node:fs/promises";import cl from"node:path";import{setTimeout as Bk}from"node:timers/promises";var jk={async mkdir(e,t){await Ns.mkdir(e,t)},async writeFile(e,t,n){await Ns.writeFile(e,t,n)},async rename(e,t){await Ns.rename(e,t)},async rm(e,t){await Ns.rm(e,t)}},$k=new Set(["EACCES","EBUSY","EPERM"]),Vk=[10,20,40,80,160];async function Uk(e,t,n){for(let r of Vk)try{await e.rename(t,n);return}catch(o){if(!Kk(o))throw o;await Bk(r)}await e.rename(t,n)}function Kk(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&$k.has(e.code)}async function _s(e,t,n=jk){let r=cl.dirname(e),o=cl.basename(e),i=cl.join(r,`.${o}.${process.pid}.${Mk()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await Uk(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import ll from"@babel/traverse";import*as k from"@babel/types";import*as Ne from"@babel/types";function gn(e,t={}){if(Ne.isTSAsExpression(e)||Ne.isTSSatisfiesExpression(e)||Ne.isTSNonNullExpression(e)||Ne.isTypeCastExpression(e)||Ne.isParenthesizedExpression(e))return gn(e.expression,t);if(Ne.isStringLiteral(e))return{status:"resolved",value:e.value};if(Ne.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Ne.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Ne.isNullLiteral(e))return{status:"resolved",value:null};if(Ne.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(Ne.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Ne.isUnaryExpression(e)&&e.operator==="void"&&Ne.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Ne.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Ne.isSpreadElement(r))return{status:"unresolved"};let o=gn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Ne.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Ne.isObjectProperty(r)||r.computed||!Ne.isExpression(r.value))return{status:"unresolved"};let o=Jk(r.key);if(o===null)return{status:"unresolved"};let i=gn(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 Ne.isMemberExpression(e)||Ne.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function Jk(e){return Ne.isIdentifier(e)?e.name:Ne.isStringLiteral(e)?e.value:Ne.isNumericLiteral(e)?String(e.value):null}var Xk=typeof ll=="function"?ll:ll.default;function yt(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 zk(e){return/^[A-Z]/.test(e)}function ml(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 Gr(e){return k.isJSXFragment(e)}function fm(e){return k.isJSXIdentifier(e.name)?e.name.name:k.isJSXMemberExpression(e.name)?mm(e.name):k.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function mm(e){return k.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:k.isJSXMemberExpression(e.object)?`${mm(e.object)}.${e.property.name}`:e.property.name}function Hk(e){return e.split(".")[0]??e}function Wk(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 Gk(){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 Yk(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 wn(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)?wn(n.value,t):k.isRestElement(n)&&wn(n.argument,t);return t}if(k.isArrayPattern(e)){for(let n of e.elements)n&&(k.isRestElement(n)?wn(n.argument,t):wn(n,t));return t}return k.isAssignmentPattern(e)?(wn(e.left,t),t):(k.isRestElement(e)&&wn(e.argument,t),t)}function en(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function $o(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 Zk(e,t,n){e.set(t,{resolved:!0,value:n})}function gl(e,t){e.set(t,{resolved:!1})}function gm(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 tt(e,t,n){if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e))return tt(e.expression,t,n);if(k.isLogicalExpression(e))return Ps([tt(e.left,t,n),tt(e.right,t,n)]);if(k.isBinaryExpression(e))return Ps([k.isExpression(e.left)?tt(e.left,t,n):null,k.isExpression(e.right)?tt(e.right,t,n):null]);if(k.isConditionalExpression(e))return Ps([tt(e.consequent,t,n),tt(e.alternate,t,n)]);if(k.isTemplateLiteral(e))return Ps(e.expressions.filter(k.isExpression).map(i=>tt(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=Gn(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:en(e,t),base:o.name,path:r}:null}function Ps(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 Gn(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=$o(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=Gn(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=$o(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Gn(r.value,t);if(i===void 0)return;n[o]=i}return n}if(k.isMemberExpression(e)){let n=tt(e,"",t);if(!n)return;let r=$o(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=gm(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(k.isCallExpression(e))return ym(e,t)??void 0}function hm(e,t,n){let r=tt(e,n,t);if(!r)return k.isMemberExpression(e)||k.isBinaryExpression(e)||k.isLogicalExpression(e)||k.isConditionalExpression(e)||k.isCallExpression(e)?{value:en(e,n),source:null}:null;let o=$o(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?gm(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 ul(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:Gk(),parentStack:[],valueScopes:i,importMap:o}}function pl(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of wn(o.id))gl(n,s);if(!k.isIdentifier(o.id)||!o.init||!k.isExpression(o.init))continue;let i=Gn(o.init,t);i!==void 0&&Zk(n,o.id.name,i)}}function Qk(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 qk(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:yt(i),editable:!0,source:null})}else if(k.isJSXExpressionContainer(i)&&k.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:yt(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:yt(i),editable:!0,source:null}):r.push({index:o++,value:en(s,n),sourceRange:yt(i),editable:!0,source:tt(s,n,t)})}else if(k.isJSXExpressionContainer(i)&&k.isExpression(i.expression)){let s=hm(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:yt(i),editable:!0,source:s.source})}return r}function eR(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!k.isJSXAttribute(i))continue;let s=nR(i.name);if(!s)continue;let a=en(i,n);if(k.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:yt(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:yt(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=Gn(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?ym(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:yt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=hm(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:lR(c),sourceRange:yt(i),source:tt(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=rR(i.value.expression,t),d=tt(i.value.expression,n,t),f=l?.value??en(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:yt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function tR(e,t,n){return e.attributes.flatMap((r,o)=>!k.isJSXSpreadAttribute(r)||!k.isExpression(r.argument)?[]:[{raw:en(r.argument,n),sourceRange:yt(r),order:o,source:tt(r.argument,n,t)}])}function nR(e){return k.isJSXIdentifier(e)?e.name:k.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function rR(e,t){return gn(e,{resolveIdentifier(n){let r=$o(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=Gn(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function ym(e,t){let n=Wr(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Wr(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=Gn(e,t);return typeof n=="string"?[n]:null}if(k.isConditionalExpression(e)){let n=Wr(e.consequent,t),r=Wr(e.alternate,t);return!n||!r?null:[...n,...r]}if(k.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Gn(e.left,t);return n===!1||n===null?[]:Wr(e.right,t)}if(k.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||k.isSpreadElement(r))return null;let o=Wr(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=iR(r.key);if(!o)return null;n.push(o)}return n}if(k.isCallExpression(e)){let n=oR(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=Wr(o,t);if(!i)return null;r.push(...i)}return r}return null}function oR(e){return k.isIdentifier(e)?e.name:k.isMemberExpression(e)&&k.isIdentifier(e.property)?e.property.name:null}function iR(e){return k.isIdentifier(e)?e.name:k.isStringLiteral(e)?e.value:null}function sR(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 aR(e,t){for(let n of t){let r=sR(e,n);if(r)return r}return null}function cR(e){return k.isJSXIdentifier(e.name)?e.name.name:null}function lR(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function uR(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 dl(e){return k.isArrowFunctionExpression(e)||k.isFunctionExpression(e)}function dR(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function pR(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function pm(e,t,n,r){if(!e||!k.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:en(e,n),collectionSource:tt(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 On(e,t,n){if(!e)return[];if(k.isJSXElement(e)){if(ml(e))return Fs(e.children,t,n);let r=ws(e,t,n);return r?[r]:[]}return Gr(e)?Os(e,t,n):k.isParenthesizedExpression(e)?On(e.expression,t,n):k.isExpression(e)?Ls(e,t,n):[]}function As(e,t,n){let r=new Map;for(let o of e.params)for(let i of wn(o))gl(r,i);t.valueScopes.push(r);try{if(!k.isBlockStatement(e.body))return On(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return xm(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function xm(e,t,n){let r=[];for(let o of e){if(k.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){pl([o],t,i);for(let s of o.declarations)k.isIdentifier(s.id)&&(k.isJSXElement(s.init)||k.isJSXFragment(s.init))&&r.push(...On(s.init,t,n))}continue}r.push(...fl(o,t,n))}return r}function fl(e,t,n){if(k.isReturnStatement(e))return e.argument?On(e.argument,t,n):[];if(k.isBlockStatement(e))return Rr(e.body,t,n);if(k.isIfStatement(e)){let r=k.isBlockStatement(e.consequent)?Rr(e.consequent.body,t,n):fl(e.consequent,t,n),o=e.alternate?k.isBlockStatement(e.alternate)?Rr(e.alternate.body,t,n):fl(e.alternate,t,n):[];return[...r,...o]}if(k.isSwitchStatement(e))return Rr(e.cases.flatMap(r=>r.consequent),t,n);if(k.isTryStatement(e)){let r=Rr(e.block.body,t,n);return e.handler&&r.push(...Rr(e.handler.body.body,t,n)),e.finalizer&&r.push(...Rr(e.finalizer.body,t,n)),r}return[]}function Rr(e,t,n){let r=new Map;t.valueScopes.push(r);try{return xm(e,t,n)}finally{t.valueScopes.pop()}}function Ts(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:yt(r),sourceCandidates:i&&i.length>0?i:void 0})}function fR(e,t,n,r){let o=aR(e.openingElement,["items","dataSource","data"]),i={key:t,tag:fm(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!k.isJSXAttribute(s))continue;let a=cR(s);if(!a||!k.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!k.isJSXEmptyExpression(c)){if(dR(a)&&dl(c)){let l=As(c,n,r),u=pm(o,c,r,n);Ts(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(pR(a)){let l=dl(c)?As(c,n,r):On(c,n,r);Ts(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!k.isJSXExpressionContainer(s)||!dl(s.expression))continue;let a=As(s.expression,n,r),c=pm(o,s.expression,r,n);Ts(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ws(e,t,n){let r=fm(e.openingElement);if(r==="Fragment"||ml(e))return Fs(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=zk(r),a;if(s){let v=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${v}`}else{let v=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${v}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=Lo(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=qk(e.children,t,n),p=eR(e.openingElement,t,n),h=tR(e.openingElement,t,n),y,x,E=!1;if(s){let v=t.importMap.get(r)??t.importMap.get(Hk(r));v&&(y=v.specifier,x=v.exportName,E=yr(v.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:yt(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:h.length>0?h:void 0,boundaryKind:f,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:x};return t.elements.set(u,b),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),fR(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),mR(e.children,t,n),t.parentStack.pop()),u}function Os(e,t,n){return Fs(e.children,t,n)}function Fs(e,t,n){let r=[];for(let o of e)if(k.isJSXElement(o))if(ml(o))r.push(...Fs(o.children,t,n));else{let i=ws(o,t,n);i&&r.push(i)}else Gr(o)?r.push(...Os(o,t,n)):k.isJSXExpressionContainer(o)&&r.push(...Ls(o.expression,t,n));return r}function mR(e,t,n){for(let r of e)k.isJSXElement(r)?ws(r,t,n):Gr(r)?Os(r,t,n):k.isJSXExpressionContainer(r)&&Ls(r.expression,t,n)}function gR(e){return e==="&&"||e==="||"||e==="??"}function Ls(e,t,n){if(k.isJSXEmptyExpression(e))return[];let r=uR(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:en(r.collection,n),collectionSource:tt(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:yt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(k.isArrowFunctionExpression(a)||k.isFunctionExpression(a))&&l.childKeys.push(...As(a,t,n)),l.childKeys}if(k.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:en(e.test,n),conditionSource:tt(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:yt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...On(e.consequent,t,n)),s.childKeys.push(...On(e.alternate,t,n)),s.childKeys}if(k.isLogicalExpression(e)&&gR(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:en(e.left,n),conditionSource:tt(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:yt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...On(e.right,t,n)),s.childKeys}if(k.isParenthesizedExpression(e))return Ls(e.expression,t,n);if(k.isJSXElement(e)){let o=ws(e,t,n);return o?[o]:[]}return Gr(e)?Os(e,t,n):[]}function hR(e){let t=e.argument;return t&&(k.isExpression(t)||Gr(t))?t:null}function Vo(e,t){let n=[];for(let r of e){if(k.isReturnStatement(r)){let o=hR(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(...Vo(o,r.test)),r.alternate){let i=k.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Vo(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(...Vo(o.consequent,i))}}return n}function Ds(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function bm(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!k.traverseFast(r,f=>{if(k.isJSXElement(f)||k.isJSXFragment(f))return k.traverseFast.stop}))return{graph:Ds(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=Yk(r);Xk(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=Wk(f);if(!g)return;let p=f.node,h=[];if(k.isArrowFunctionExpression(p))k.isExpression(p.body)||Gr(p.body)?h=[{argument:p.body,statement:k.returnStatement(k.isExpression(p.body)?p.body:null)}]:k.isBlockStatement(p.body)&&(h=Vo(p.body.body));else{let _=p.body;k.isBlockStatement(_)&&(h=Vo(_.body))}if(h.length===0){f.skip();return}let y=new Map;pl(Qk(r.program.body),ul(t,g,s,a,u,[y]),y);let x=new Map;for(let _ of p.params)for(let P of wn(_))gl(x,P);let E=k.isBlockStatement(p.body)?p.body.body:[],b=h[0]?.statement??null;for(let _ of E){if(b&&_===b)break;k.isVariableDeclaration(_)&&pl([_],ul(t,g,s,a,u,[y,x]),x)}let v=ul(t,g,s,a,u,[y,x]);for(let _ of h){let P=On(_.argument,v,n);for(let R of P)c.includes(R)||c.push(R);if(_.condition){let R={kind:"conditional-branch",conditionExpression:en(_.condition,n),conditionSource:tt(_.condition,n,v)};Ts(v,"conditional-region","",_.statement,P,[R])}}f.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 hl(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Ms(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Em(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 Bs(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Je,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;f.has(E)||(f.add(E),d.push(x))},p=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(x=>({file:x.file,source:x.source,depth:0,diagnosticEntryFile:x.file,importStack:[]}))],h=new Set;for(;p.length>0;){let x=p.shift(),{file:E,source:b,depth:v,diagnosticEntryFile:_,importStack:P}=x;if(h.has(E))continue;h.add(E),c.set(E,b);let R=o.validationOnly&&v<i?o.validatedImports?.(E,b):void 0,N,A;if(R)N=Ds(E),A=R;else{let z=a(E,b);if(!z.ok){g(Ms(z.diagnostic,_,P));continue}u.set(E,z.module);let Q=o.validationOnly&&v<i?{graph:Ds(E),localImports:z.module.imports.map(ke=>ke.specifier)}:bm(z.module);N=Q.graph,A=Q.localImports}let L=[...new Set([...N.elements.values()].map(z=>z.importedFrom).filter(z=>typeof z=="string"&&St(z)))],$=L.length?await Em(L,z=>Zi(E,z,r)):[],U=new Map(L.map((z,Q)=>[z,$[Q]]));for(let z of N.elements.values())if(z.importedFrom&&St(z.importedFrom)){let Q=z.importedFrom,ke=U.get(Q);ke.ok?(z.importedFrom=ke.path,_n(ke.path)&&(z.isPublicUiComponent=!0)):yr(Q,E)||g(Ms(ke.diagnostic,_,hl(P,E,Q,ke.diagnostic.path)))}if(l.set(E,N),v>=i)continue;let de=await Em(A,async z=>{if(Qp(z))return null;let Q=U.get(z)??await Zi(E,z,r);if(!Q.ok)return yr(z,E)?null:{diagnostic:Ms(Q.diagnostic,_,hl(P,E,z,Q.diagnostic.path))};let ke=Q.path;if(h.has(ke)||_n(ke))return null;let ct=hl(P,E,z,ke);try{let lt=await n(ke);return{entry:{file:ke,source:lt,depth:v+1,diagnosticEntryFile:_,importStack:ct}}}catch(lt){return{diagnostic:Ms({path:ke,code:"import-read-failed",message:`Failed to read imported file: ${ke}`,details:{fromFile:E,specifier:z,reason:lt instanceof Error?lt.message:String(lt)}},_,ct)}}});for(let z of de)z&&"entry"in z?p.push(z.entry):z&&g(z.diagnostic)}let y=yR(e,l,s,(o.additionalEntries??[]).map(x=>x.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function yR(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 f=s.get(u)??[];s.set(u,[...f,...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 Sm(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 zR}from"@vcp-dev/contracts";import{createHash as xR,randomUUID as Cl}from"node:crypto";import We from"node:fs/promises";import Ge from"node:path";var Tm=new WeakMap;function Yr(e){return Tm.get(e)?.()??e.readIndex()}var Xt=1,xl=1,bR=2,ER="index.json",SR="recovery.json",vR="transaction-journal.json",IR="document-version.json",Vs={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},fe={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"},ge=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Fn(){return{entries:new Map,blobSizes:new Map}}function js(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)wm(n,r,t);return n}function wm(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 Om(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 Fm(e,t={}){let n=$R(e),r=JR(t.limits),o=yl(n),i=VR(n),s=await Ct(i),a=await Ct(o)||s;a||(await wR(n),await OR(n)),a||await XR(n);let c=Fn(),l=await Ks(n,c),u=new Set(a?(await Ws(n)).map(E=>E.stageId):[]);a||await Cm(n,l.entryIds,c);let d=l.digest,f=js(l.entryIds,c),g=async E=>{let{index:b,sizeBytes:v}=await zo(n);if(Vm(b,E),b.digest!==d){let _=Fn();await Bm(n,b.entryIds,_,v),f=js(b.entryIds,_),d=b.digest}return{...Gs(b),totalBytes:f.objectBytes+v}},p=async E=>{Nl(E),await g(),await km(n,f,[E.entryId],E.blobIds,E.stageId),await Us(n,E.stageId)},h=async(E,b)=>{let v=await g(b);Dm(E,v.entryIds.length);let _=Fn();for(let P of v.entryIds.slice(Math.min(v.cursor,E)+1,Math.max(v.cursor,E)+1))await Ko(n,P,_);return v},y=async()=>{if(await Ct(o)||s)throw new ge(fe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Pm(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new ge(fe.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await Pm(n);E<=b||await Uo(Xm(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let v=await CR(E,r),_={schemaVersion:xl,stageId:Cl(),entryId:v.entryId,blobIds:v.blobs.map(P=>P.digest)};try{await NR(n,v),await PR(n,_,b.durableManifest!==!1)}catch(P){try{await p(_)}catch(R){throw new ge(fe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw P}return{stageId:_.stageId,entryId:_.entryId,blobIds:_.blobIds}},async discardStage(E){await y(),Sl(E);let b=await bl(n,E);b&&await p(b)},async previewStagedAppend(E,b){await y();let v=await g(b);return(await vm(n,r,E,v,f)).transition},async previewCursor(E,b){await y();let v=await h(E,b);return Lm(v,v.entryIds,E)},async publishStagedAppend(E,b,v){if(await y(),Xs(E,"entryId"),v){Sl(v);let A=await bl(n,v);if(!A||A.entryId!==E)throw new ge(fe.INVALID_SCHEMA,"history stage does not match the published entry")}let _=await g(b),P=f,R=await vm(n,r,E,_,P),N=await _m({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>Nm(n,R.usage),afterWrite:async()=>{v?await Us(n,v):await TR(n,E),await km(n,R.usage,[...P.entries.keys()].filter(A=>!R.usage.entries.has(A)),[...P.blobs.keys()].filter(A=>!R.usage.blobs.has(A)))}});return f=R.usage,d=N.digest,N},async append(E){await y();let b=await g(),v=await x.stageAppend(E);try{return await x.publishStagedAppend(v.entryId,b.digest,v.stageId)}catch(_){throw await x.discardStage(v.stageId),_}},async readEntry(E){return Xs(E,"entryId"),Ko(n,E)},async readBlob(E){Xs(E,"blobId");let b=await Hm(n,E),v=await Jo(b,fe.NOT_FOUND,"blob");return Jm(v,E,b),v},async readIndex(){let E=Fn(),b=await Ks(n,E);return f=js(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await Js(n);return{canUndo:E.undoIds.length>0,canRedo:E.redoIds.length>0,undoDepth:E.undoIds.length,redoDepth:E.redoIds.length,cursor:E.cursor,recoveryRequired:await Ct(o)||await Ct(i)}},async readUndoRedoIds(){let E=await Js(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await y();let v=await h(E,b),_=await _m({rootDir:n,previousDigest:v.digest,entryIds:v.entryIds,cursor:E,readback:async()=>Nm(n,f)});return d=_.digest,_},async markRecoveryRequired(E){await Ct(o)||await Uo(yl(n),{schemaVersion:Xt,reason:UR(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await We.rm(yl(n),{force:!0})},async readTransactionJournal(){return await Ct(i)?$s(i):null},async writeTransactionJournal(E){await y(),zm(E);try{await Uo(i,E)}catch(v){let _=await $s(i).catch(()=>null);if(_&&Buffer.from(Nt(_)).equals(Buffer.from(Nt(E))))return;throw _?new ge(fe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:v}):v}let b=await $s(i);if(!Buffer.from(Nt(b)).equals(Buffer.from(Nt(E))))throw new ge(fe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await Ct(i)?await $s(i):null;if(b&&b.transactionId!==E)throw new ge(fe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await We.rm(i,{force:!0})}catch(v){if(!await Ct(i))return;throw v}if(await Ct(i))throw new ge(fe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let v of u)await Us(n,v),u.delete(v);await FR(n);let E=Fn(),b=await Ks(n,E);await Cm(n,b.entryIds,E),f=js(b.entryIds,E),d=b.digest}};return Tm.set(x,()=>Js(n)),x}async function vm(e,t,n,r,o){Xs(n,"entryId");let i=Fn(),s=await Ko(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))Om(a,u);wm(a,s.id,i),c.push(s.id);let l=_R(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Lm(r,l.entryIds,l.cursor)}}function Lm(e,t,n){return Dm(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:kR(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function kR(e,t){return Yn(Nt({schemaVersion:Xt,entryIds:e,cursor:t}))}function Dm(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ge(fe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function RR(e){if(!tn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Ot(e.expectedIndexDigest)||!Ot(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Ot(n)?!1:t===-1?n===null:Ot(n)}async function CR(e,t){if(!e.kind.trim())throw new ge(fe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ge(fe.INVALID_JSON,"history blob name must not be empty");let l=jR(c.data),u=Yn(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:Xt,kind:e.kind,manifest:e.manifest,blobs:r},i=Nt({...o}),s=Yn(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ge(fe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function NR(e,t){let n=Tl(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=>Im(wl(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Fl(e,c.digest))),Im(n,Nt(r),{kind:"entry",digest:t.entryId},Ol(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function Im(e,t,n,r){let o=await kl(e)??(r?await kl(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ge(n.kind==="blob"?fe.BLOB_CORRUPT:fe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Um(e,t)}function _R(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Nt($m(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ge(fe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Om(n,r.shift()),o-=1}}async function PR(e,t,n){Nl(t);let r=Al(e,t.stageId);if(n){await Uo(r,t);return}await BR(r,t)}async function bl(e,t){let n=await kl(Al(e,t));if(n===null)return null;let r=Ho(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Nl(r);if(o.stageId!==t)throw new ge(fe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ws(e){let t=[];for(let n of await Hs(Pl(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Sl(r);let o=await bl(e,r);o&&t.push(o)}return t}async function km(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 Ws(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 Rm(Tl(e,a),Ol(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Rm(wl(e,a),Fl(e,a));await Rl(Wo(e)),await Rl(Go(e))}async function Us(e,t){await El(Al(e,t)),await AR(e)}async function AR(e){try{await We.rmdir(Pl(e))}catch(t){if(Yo(t)||tn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function TR(e,t){for(let n of await Ws(e))n.entryId===t&&await Us(e,n.stageId)}async function El(e){if(await We.rm(e,{force:!0}),await Ct(e))throw new ge(fe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Rm(e,t){await El(e),await El(t)}function Nl(e){if(!tn(e)||e.schemaVersion!==xl||typeof e.stageId!="string"||!Mm(e.stageId)||!Ot(e.entryId))throw new ge(fe.INVALID_SCHEMA,"history stage schema is invalid");let t=Km(e.blobIds,"history stage blobIds");return{schemaVersion:xl,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Sl(e){if(!Mm(e))throw new ge(fe.INVALID_PATH,"history stageId must be a UUID")}function Mm(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 Cm(e,t,n=Fn()){let r=new Set(t),o=new Set;for(let l of t){let u=await Ko(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ws(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Wo(e),s=await Hs(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Am(l.slice(0,-5));u&&!r.has(u)&&await zs(Ge.join(i,l))}let a=Go(e),c=await Hs(a);for(let l of c){let u=Am(l);u&&!o.has(u)&&await zs(Ge.join(a,l))}}async function Ks(e,t=Fn()){let{index:n,sizeBytes:r}=await zo(e),{totalBytes:o}=await Bm(e,n.entryIds,t,r);return{...Gs(n),totalBytes:o}}async function Nm(e,t){let{index:n,sizeBytes:r}=await zo(e);return{...Gs(n),totalBytes:t.objectBytes+r}}async function zo(e){let t=_l(e),n=await Jo(t,fe.NOT_FOUND,"index"),r=Ho(Buffer.from(n).toString("utf8"),"index");return{index:LR(r),sizeBytes:n.byteLength}}async function Js(e){return Gs((await zo(e)).index)}function Gs(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:Xt,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Bm(e,t,n,r){let o=0,i=new Set;o+=r??(await zo(e)).sizeBytes;for(let s of new Set(t)){let a=await Ko(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 Ko(e,t,n=Fn()){let r=n.entries.get(t);if(r)return r.entry;let o=await KR(e,t),i=await Jo(o,fe.NOT_FOUND,"entry"),s=Ho(Buffer.from(i).toString("utf8"),`entry ${t}`),a=DR(s);if(a.id!==t)throw new ge(fe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Yn(Nt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ge(fe.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 f=await Hm(e,d),g=await Jo(f,fe.NOT_FOUND,"blob");return Jm(g,d,f),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),f=[],g=0,p=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&f.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(E){f.push({index:x,error:E})}}}),h=await Promise.allSettled(p),y=f.sort((x,E)=>x.index-E.index)[0];if(y)throw y.error;for(let x of h)if(x.status==="rejected")throw x.reason;for(let x=0;x<l.length;x++)n.blobSizes.set(l[x],d[x])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function jm(e,t,n){await Uo(_l(e),$m(t,n))}function $m(e,t){return{schemaVersion:Xt,digest:Yn(Nt({schemaVersion:Xt,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Vm(e,t){if(t!==void 0&&e.digest!==t)throw new ge(fe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function _m(e){Vm(await Js(e.rootDir),e.previousDigest);let t=Yn(Nt({schemaVersion:Xt,entryIds:e.entryIds,cursor:e.cursor}));try{await jm(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ge(fe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ks(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ge(fe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function wR(e){await We.mkdir(e,{recursive:!0}),await We.mkdir(Wo(e),{recursive:!0}),await We.mkdir(Go(e),{recursive:!0}),await We.mkdir(Xo(e),{recursive:!0})}async function OR(e){await We.rm(Xo(e),{recursive:!0,force:!0}),await We.mkdir(Xo(e),{recursive:!0})}async function FR(e){let t=Xo(e);await We.mkdir(t,{recursive:!0});for(let n of await Hs(t))n!=="stages"&&await We.rm(Ge.join(t,n),{recursive:!0,force:!0})}function LR(e){if(!tn(e))throw new ge(fe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==Xt)throw new ge(fe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Km(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ge(fe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Ot(o))throw new ge(fe.INDEX_CORRUPT,"index digest is invalid");let i=Yn(Nt({schemaVersion:Xt,entryIds:t,cursor:r}));if(o!==i)throw new ge(fe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:Xt,digest:o,entryIds:t,cursor:r}}function DR(e){if(!tn(e))throw new ge(fe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==Xt)throw new ge(fe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Ot(t))throw new ge(fe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ge(fe.ENTRY_CORRUPT,"entry kind is invalid");let r=Il(e.manifest,"entry.manifest"),o=MR(e.blobs);return{id:t,schemaVersion:Xt,kind:n,manifest:r,blobs:o}}function MR(e){if(!Array.isArray(e))throw new ge(fe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!tn(t))throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Ot(o))throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ge(fe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Uo(e,t){await Um(e,Nt(t))}async function BR(e,t){let n=Ge.dirname(e),r=Ge.basename(e),o=Ge.join(n,`.${r}.${process.pid}.${Cl()}.tmp`);await We.mkdir(n,{recursive:!0});try{await We.writeFile(o,Nt(t),{flag:"wx"}),await We.rename(o,e)}finally{await zs(o)}}async function Um(e,t){let n=Ge.dirname(e),r=Ge.basename(e),o=Ge.join(n,`.${r}.${process.pid}.${Cl()}.tmp`);await We.mkdir(n,{recursive:!0});try{let i=await We.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await We.rename(o,e),await Rl(n)}finally{await zs(o)}}function Nt(e){return Buffer.from(JSON.stringify(vl(e)),"utf8")}function vl(e){if(Array.isArray(e))return e.map(t=>vl(t));if(tn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=vl(e[n]);return t}return e}function Ho(e,t){try{return JSON.parse(e)}catch(n){throw new ge(fe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Il(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=>Il(n,t));if(tn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Il(o,t);return n}break}throw new ge(fe.INVALID_JSON,`${t} must be JSON-serializable`)}function Km(e,t){if(!Array.isArray(e))throw new ge(fe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Ot(n))throw new ge(fe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Xs(e,t){if(!Ot(e))throw new ge(fe.INVALID_PATH,`${t} must be a sha256 digest`)}function Ot(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Yn(e){return`sha256:${xR("sha256").update(e).digest("hex")}`}function jR(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Jo(e,t,n){try{return await We.readFile(e)}catch(r){throw new ge(t,`${n} not found: ${e}`,{cause:r})}}async function kl(e){try{return await We.readFile(e)}catch(t){if(Yo(t))return null;throw t}}function Jm(e,t,n){if(Yn(e)!==t)throw new ge(fe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Ct(e){try{return await We.access(e),!0}catch(t){if(Yo(t))return!1;throw t}}async function zs(e){try{await We.rm(e,{force:!0,recursive:!0})}catch{}}async function Rl(e){try{let t=await We.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Hs(e){try{return await We.readdir(e)}catch(t){if(Yo(t))return[];throw t}}function $R(e){if(typeof e!="string"||e.trim().length===0)throw new ge(fe.INVALID_ROOT,"history store rootDir must be a non-empty string");return Ge.resolve(e)}function _l(e){return Ge.join(e,ER)}function yl(e){return Ge.join(e,SR)}function VR(e){return Ge.join(e,vR)}function Xm(e){return Ge.join(e,IR)}async function Pm(e){try{let t=await We.readFile(Xm(e),"utf8"),n=Ho(t,"document version");if(!tn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ge(fe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Yo(t))return 0;throw t}}async function $s(e){let t=await Jo(e,fe.RECOVERY_PENDING,"transaction journal"),n=Ho(Buffer.from(t).toString("utf8"),"transaction journal");return zm(n),n}function zm(e){if(!tn(e)||e.schemaVersion!==bR||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!RR(e.historyTransition)||!Array.isArray(e.files))throw new ge(fe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!tn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Ot(t.preDigest)||t.postDigest!==null&&!Ot(t.postDigest))throw new ge(fe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function UR(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Wo(e){return Ge.join(e,"entries")}function Go(e){return Ge.join(e,"blobs")}function Xo(e){return Ge.join(e,"tmp")}function Pl(e){return Ge.join(Xo(e),"stages")}function Al(e,t){return Ge.join(Pl(e),`${t}.json`)}function Tl(e,t){return Ge.join(Wo(e),`${Gm(t)}.json`)}function wl(e,t){return Ge.join(Go(e),Gm(t))}function Ol(e,t){return Ge.join(Wo(e),`${t}.json`)}function Fl(e,t){return Ge.join(Go(e),t)}async function KR(e,t){return Wm(Tl(e,t),Ol(e,t))}async function Hm(e,t){return Wm(wl(e,t),Fl(e,t))}async function Wm(e,t){return await Ct(e)?e:await Ct(t)?t:e}function Gm(e){return e.slice(7)}function Am(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Ot(t)?t:null}function tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function JR(e){return{maxEntries:e?.maxEntries??Vs.maxEntries,maxSessionBytes:e?.maxSessionBytes??Vs.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Vs.maxEntryBytes}}async function XR(e){let t=_l(e);await Ct(t)||await jm(e,[],-1)}var HR={affectedCompositions:[]};function eg(e){let t=null,n=new WeakMap;async function r(){return t??=WR(e),t}async function o(i){if(!i)return null;let s=Ll(i);return s?GR(e,s):i}return{async prepareAppend(i){let s=await Yr(e),a=await e.stageAppend(Qm(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 Yr(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 Yr(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);Ym(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,Zr(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Ll(c.at(-1))!==Ll(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Ym(l,i.historyTransition),Object.assign(a,Zr(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await Yr(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,Zr(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Qm(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,Zr(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,Zr(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 Ym(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 Ll(e){return typeof e=="string"?e:e?.historyId}async function WR(e){let t=await Yr(e);return Zr(t)}function Zr(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function GR(e,t){let n=await e.readEntry(t),r=YR(n),o=r.provenance??HR;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 Zm(e,n,r.preSnapshots),postSnapshots:await Zm(e,n,r.postSnapshots)}}async function Zm(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(qR(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Qm(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=ZR(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 YR(e){if(!ng(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:tg(t.provenance)}:{},preSnapshots:qm(t.preSnapshots,"preSnapshots"),postSnapshots:qm(t.postSnapshots,"postSnapshots")}}function ZR(e){if(e.provenance!==void 0)return tg(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function tg(e){let t=zR.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 qm(e,t){return e.map((n,r)=>{if(!ng(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&&!QR(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 QR(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function qR(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as eC}from"@vcp-dev/contracts";var rg={schema_version:1,policy_version:"starter-capabilities-v1",source:{starter_package_path:"templates/next-starter/package.json",components_catalog_path:"templates/next-starter/components.catalog.json",package_name:"vcp-next-starter",package_version:"0.0.0"},runtime_dependencies:[{name:"@gsap/react",version:"2.1.2"},{name:"@hookform/resolvers",version:"3.10.0"},{name:"@opennextjs/cloudflare",version:"1.19.11"},{name:"@radix-ui/react-accordion",version:"1.2.12"},{name:"@radix-ui/react-alert-dialog",version:"1.1.15"},{name:"@radix-ui/react-aspect-ratio",version:"1.1.8"},{name:"@radix-ui/react-avatar",version:"1.1.11"},{name:"@radix-ui/react-checkbox",version:"1.3.3"},{name:"@radix-ui/react-collapsible",version:"1.1.12"},{name:"@radix-ui/react-context-menu",version:"2.2.16"},{name:"@radix-ui/react-dialog",version:"1.1.15"},{name:"@radix-ui/react-dropdown-menu",version:"2.1.16"},{name:"@radix-ui/react-hover-card",version:"1.1.15"},{name:"@radix-ui/react-label",version:"2.1.8"},{name:"@radix-ui/react-menubar",version:"1.1.16"},{name:"@radix-ui/react-navigation-menu",version:"1.2.14"},{name:"@radix-ui/react-popover",version:"1.1.15"},{name:"@radix-ui/react-progress",version:"1.1.8"},{name:"@radix-ui/react-radio-group",version:"1.3.8"},{name:"@radix-ui/react-scroll-area",version:"1.2.10"},{name:"@radix-ui/react-select",version:"2.2.6"},{name:"@radix-ui/react-separator",version:"1.1.8"},{name:"@radix-ui/react-slider",version:"1.3.6"},{name:"@radix-ui/react-slot",version:"1.2.3"},{name:"@radix-ui/react-switch",version:"1.2.6"},{name:"@radix-ui/react-tabs",version:"1.1.13"},{name:"@radix-ui/react-toggle",version:"1.1.10"},{name:"@radix-ui/react-toggle-group",version:"1.1.11"},{name:"@radix-ui/react-tooltip",version:"1.2.8"},{name:"class-variance-authority",version:"0.7.1"},{name:"clsx",version:"2.1.1"},{name:"cmdk",version:"1.1.1"},{name:"date-fns",version:"4.3.0"},{name:"embla-carousel-react",version:"8.6.0"},{name:"gsap",version:"3.15.0"},{name:"i18next",version:"26.3.0"},{name:"input-otp",version:"1.4.2"},{name:"lucide-react",version:"0.525.0"},{name:"motion",version:"12.40.0"},{name:"next",version:"16.3.4"},{name:"react",version:"19.2.6"},{name:"react-day-picker",version:"9.14.0"},{name:"react-dom",version:"19.2.6"},{name:"react-hook-form",version:"7.76.1"},{name:"react-i18next",version:"17.0.8"},{name:"recharts",version:"2.15.4"},{name:"sonner",version:"2.0.7"},{name:"tailwind-merge",version:"3.6.0"},{name:"vaul",version:"1.1.2"},{name:"zod",version:"3.25.76"}],catalog_dependencies:["@hookform/resolvers","@radix-ui/react-accordion","@radix-ui/react-alert-dialog","@radix-ui/react-aspect-ratio","@radix-ui/react-avatar","@radix-ui/react-checkbox","@radix-ui/react-collapsible","@radix-ui/react-context-menu","@radix-ui/react-dialog","@radix-ui/react-dropdown-menu","@radix-ui/react-hover-card","@radix-ui/react-label","@radix-ui/react-menubar","@radix-ui/react-navigation-menu","@radix-ui/react-popover","@radix-ui/react-progress","@radix-ui/react-radio-group","@radix-ui/react-scroll-area","@radix-ui/react-select","@radix-ui/react-separator","@radix-ui/react-slider","@radix-ui/react-slot","@radix-ui/react-switch","@radix-ui/react-tabs","@radix-ui/react-toggle","@radix-ui/react-toggle-group","@radix-ui/react-tooltip","class-variance-authority","clsx","cmdk","date-fns","embla-carousel-react","input-otp","lucide-react","motion","react-day-picker","react-hook-form","recharts","sonner","tailwind-merge","vaul","zod"],public_paths:["components.json","components/site/generated/*","components/ui/*","components/ui/accordion.tsx","components/ui/alert-dialog.tsx","components/ui/alert.tsx","components/ui/aspect-ratio.tsx","components/ui/avatar.tsx","components/ui/badge.tsx","components/ui/border-beam.tsx","components/ui/breadcrumb.tsx","components/ui/button-group.tsx","components/ui/button.tsx","components/ui/calendar.tsx","components/ui/callout.tsx","components/ui/card.tsx","components/ui/carousel.tsx","components/ui/chart.tsx","components/ui/checkbox.tsx","components/ui/code-block.tsx","components/ui/collapsible.tsx","components/ui/command.tsx","components/ui/composite-carousel.tsx","components/ui/context-menu.tsx","components/ui/dialog.tsx","components/ui/drawer.tsx","components/ui/dropdown-menu.tsx","components/ui/empty.tsx","components/ui/field.tsx","components/ui/form.tsx","components/ui/hover-card.tsx","components/ui/input-group.tsx","components/ui/input-otp.tsx","components/ui/input.tsx","components/ui/item.tsx","components/ui/kbd.tsx","components/ui/label.tsx","components/ui/magic-card.tsx","components/ui/marquee.tsx","components/ui/menubar.tsx","components/ui/multi-step-form.tsx","components/ui/navigation-menu.tsx","components/ui/number-ticker.tsx","components/ui/pagination.tsx","components/ui/popover.tsx","components/ui/progress.tsx","components/ui/radio-group.tsx","components/ui/safe-image.tsx","components/ui/scroll-area.tsx","components/ui/scroll-choreographer.tsx","components/ui/select.tsx","components/ui/separator.tsx","components/ui/sheet.tsx","components/ui/site-footer-shell.tsx","components/ui/site-header.tsx","components/ui/skeleton.tsx","components/ui/slider.tsx","components/ui/sonner.tsx","components/ui/spinner.tsx","components/ui/stepper.tsx","components/ui/switch.tsx","components/ui/table.tsx","components/ui/tabs.tsx","components/ui/textarea.tsx","components/ui/toggle-group.tsx","components/ui/toggle.tsx","components/ui/tooltip.tsx","components/ui/video-frame.tsx","lib/cms","lib/utils.ts#cn"],generated_sections_path:"components/site/generated/*",ui_baseline:{kit:"shadcn-style",components_config:"components.json",class_name_helper:"lib/utils.ts#cn"},host_contract_digest:"03208e0d83ae2140368f162b6051dd45d4d6ac97f3652958b3ba24a6273d6eca"};function Dl(){let e=eC.safeParse(rg);return e.success?e.data:null}import{randomBytes as gC}from"node:crypto";import Zs from"node:path";import{parse as mg}from"@babel/parser";import hC from"@babel/traverse";import*as gg from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Bl,PageResourceArtifactSchema as yC,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as xC,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as bC,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as EC,parseComponentI18nResourcesJson as SC}from"@vcp-dev/contracts";var ig={colorMixPolicy:"always",includeExtendedColorFunctions:!0},sg=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,ag=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,tC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,nC=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,rC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,oC=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,iC=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,sC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,aC=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,cC=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,lC=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,uC=/\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,dC=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,pC=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Zo(e,t){let n=Ys([...zt(e,tC),...zt(e,nC),...zt(e,rC),...zt(e,t.includeRgbBackgroundImage?oC:iC),...t.includeExtendedColorFunctions?[...zt(e,sC),...zt(e,aC)]:[]]),r=Ys([...zt(e,cC),...zt(e,lC)]).filter(o=>t.colorMixPolicy==="always"||sg.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...zt(e,uC).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...zt(e,pC).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Ys(zt(e,ag)),hardCodedSurfaceOccurrences:mC(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?Ys(zt(e,dC)):[]}}function zt(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var og=160,fC=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function mC(e){let t=new RegExp(ag.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=fC.exec(l),d=r(i.index),f=e.indexOf(`
|
|
6
|
+
`,i.index),g=e.slice(n[d]??0,f===-1?void 0:f).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>og?`${g.slice(0,og-1)}\u2026`:g})}return o}function Ys(e){return[...new Set(e)]}var jl="{{$INSTANCE}}",vC=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,IC=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,$l="components/site/generated",kC=/\.(?:tsx?|json)$/,RC=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,CC=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],NC=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Ml=hC,_C=typeof Ml=="function"?Ml:Ml.default;async function Vl(e){let t=yC.safeParse(e.artifact);if(!t.success)return Xe("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>gC(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=MC(r());if(!i)return Xe("Random instance suffix must be 8 lowercase hex chars.");let s=`${BC(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let v=b.final_route.slice(1);a.set(b.template_page_id,b.final_route),c.set(b.template_page_id,b.title),l.push({template_page_id:b.template_page_id,title:b.title,final_route:b.final_route,route_file_path:`app/${v}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,p=new Map,h=[],y=new Set(n.pages.flatMap(b=>b.components.map(v=>v.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let v=cg({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!v.ok)return v;for(let _ of v.files){let P=ug(_,d,u);if(P)return P}f.add(v.entry),p.set(v.entry,v.entryExport),g.set(b.component_id,v.entry)}for(let[b,v]of n.pages.entries()){let _=l[b],P=cg({materialization:v.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:_.route_file_path,pageTitle:_.title});if(!P.ok)return P;for(let R of P.files){let N=ug(R,d,u);if(N)return N}f.add(P.entry),p.set(P.entry,P.entryExport),h.push({entry:P.entry,declaredComponentIds:new Set(v.components.map(R=>R.component_id))})}let x=AC(u,f,s,g,h,p);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?Vl({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${b.file}`,path:b.file};let E=TC(u);return E||(u.sort((b,v)=>b.file.localeCompare(v.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function cg(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:lg(o.pathTemplate,e.packageInstanceId);if(!s)return Xe("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=PC(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?OC(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??lg(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?Xe("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function PC(e,t,n,r){let o,i=e.replace(vC,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return Xe(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(IC,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return Xe(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(jl,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?Xe("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function lg(e,t){let n=`${$l}/${t}`;if(e.split(jl).length>2)return null;let o=e.replace(jl,t),i=`${$l}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Zs.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!kC.test(a)||RC.test(a)?null:a}function ug(e,t,n){return t.has(e.file)?Xe(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function AC(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${$l}/${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 Xe("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Bl)&&!SC(g.content).success)return Xe("Materialization component i18n resources are invalid.",g.file);continue}try{let h=mg(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,h);for(let x of h.program.body)if((x.type==="ImportDeclaration"||x.type==="ExportAllDeclaration"||x.type==="ExportNamedDeclaration"&&x.source)&&x.source){let E=x.source.value,b=LC(g.file,E,s,a);if(!b.allowed)return Xe(`Materialization import is outside the controlled package: ${E}`,g.file);b.internalPath&&c.get(g.file).add(b.internalPath)}let y;if(_C(h,{Identifier(x){x.isReferencedIdentifier()&&NC.has(x.node.name)&&(y??=x.node.name,x.stop())},JSXAttribute(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name==="style"&&(y??="inline style",x.stop())},JSXOpeningElement(x){x.node.name.type==="JSXIdentifier"&&x.node.name.name.toLowerCase()==="style"&&(y??="style element",x.stop())}}),y)return Xe(`Materialization source uses forbidden capability: ${y}`,g.file)}catch{return Xe("Materialization source must parse as TS/TSX.",g.file)}let p=Zo(g.content,{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0});if(p.hardCodedSurfaceHits.length>0||p.rawColorHits.length>0||p.privateTokenHits.length>0)return Xe("Materialization source violates the public theme token policy.",g.file)}if([...t].some(g=>!s.has(g)))return Xe("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return Xe("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let h=l.get(g);if(!h||!wC(h,p))return Xe("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,p])=>[p,g]));for(let g of o){let p=fg(g.entry,c);for(let h of g.declaredComponentIds){let y=r.get(h);if(!y||!p.has(y))return Xe(`Page entry does not reach declared component: ${h}`,g.entry)}for(let h of p){let y=u.get(h);if(y&&!g.declaredComponentIds.has(y))return Xe(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of fg(g,c))d.add(p);if(d.size!==e.length)return Xe("Every materialization file must be reachable from a package entry.");let f=DC(e,l,c);return f||{ok:!0}}function TC(e){if(e.length>xC)return Xe("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>bC)return Xe("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>EC?Xe("Page resource exceeds the aggregate content byte limit."):null}function wC(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 OC(e,t,n){let r;try{r=mg(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return Xe("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=dg(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&FC(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=dg(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 dg(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&gg.isExpression(t)?t:null}function FC(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function LC(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=pg(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:CC.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Zs.posix.normalize(Zs.posix.join(Zs.posix.dirname(e),t)),i=pg(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function pg(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 DC(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Bl))continue;let i=o.file.slice(0,-Bl.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return Xe("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 Xe("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function fg(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 MC(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function BC(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function Xe(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as GC}from"node:crypto";import Dn from"node:path";import{parse as YC}from"@babel/parser";import ZC from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Qs,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as xg,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as QC,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as qC,SiteEditMaterializationSchema as eN,parseComponentI18nResourcesJson as tN}from"@vcp-dev/contracts";import{parse as jC}from"@babel/parser";import $C from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as VC,FormDefinitionIdSchema as UC}from"@vcp-dev/contracts";var KC=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],JC=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),hg=new Set(["require","module","exports","__dirname","__filename"]),Ul=$C,XC=typeof Ul=="function"?Ul:Ul.default;function Jl(e,t={}){let n=[],r=zC(t.hostCapabilities),o=Zo(e,t.style??ig),i;try{i=jC(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return{ok:!1,violations:[{code:"parse-failed",message:"Generated source failed Babel parsing."}],styleViolations:o}}t.themeStyleMode==="reject"&&WC(o)&&n.push({code:"style-forbidden",message:"Generated source must use public semantic design tokens instead of raw colors, hard-coded surfaces, or private tokens."});let s=u=>{n.some(f=>f.code===u.code&&f.name===u.name&&f.source===u.source)||n.push(u)};return XC(i,{ImportDeclaration(u){a(u.node.source.value)},ExportNamedDeclaration(u){let d=u.node.source?.value;d&&a(d)},ExportAllDeclaration(u){a(u.node.source.value)},CallExpression(u){let d=u.node.callee;if(d.type==="Import"){s({code:"dynamic-import-forbidden",message:"Generated source cannot use dynamic import()."});return}d.type==="Identifier"&&(d.name==="require"?s({code:"commonjs-forbidden",message:"Generated source cannot use CommonJS require().",name:d.name}):(d.name==="eval"||d.name==="Function")&&s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${d.name}().`,name:d.name}))},NewExpression(u){u.node.callee.type==="Identifier"&&u.node.callee.name==="Function"&&s({code:"dynamic-code-forbidden",message:"Generated source cannot construct functions dynamically through Function().",name:"Function"})},MetaProperty(u){u.node.meta.type==="Identifier"&&u.node.meta.name==="import"&&s({code:"import-meta-forbidden",message:"Generated source cannot use import.meta."})},MemberExpression(u){l(Kl(u.node))},OptionalMemberExpression(u){l(Kl(u.node))},Identifier(u){u.isReferencedIdentifier()&&l(u.node.name)},JSXAttribute(u){t.rejectInlineStyles&&u.node.name.type==="JSXIdentifier"&&u.node.name.name==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot use inline style attributes."})},JSXOpeningElement(u){t.rejectStyleElements&&u.node.name.type==="JSXIdentifier"&&u.node.name.name.toLowerCase()==="style"&&s({code:"inline-style-forbidden",message:"Generated source cannot declare style elements."})}}),{ok:n.length===0,violations:n,styleViolations:o};function a(u){if(!(t.trustedManagedImports?.includes(u)&&UC.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&KC.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?HC(u,r)||s({code:"import-forbidden",message:`Generated source imports a package or public path outside the trusted host capabilities: ${u}.`,source:u}):s({code:t.hostCapabilities===void 0?"host-capabilities-unavailable":"host-capabilities-invalid",message:"Generated code cannot use an external import without trusted host capabilities.",source:u}),c(u)}}function c(u){t.protectedImportPrefixes?.some(d=>u.startsWith(d))&&s({code:"protected-import-forbidden",message:`Generated source cannot import protected host output directly: ${u}.`,source:u})}function l(u){if(!(!u||!JC.has(u))){if(u==="eval"||u==="Function"){s({code:"dynamic-code-forbidden",message:`Generated source cannot execute dynamic code through ${u}.`,name:u});return}s({code:hg.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:hg.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function zC(e){if(e==null)return null;let t=VC.safeParse(e);return t.success?t.data:null}function HC(e,t){if(t.runtime_dependencies.some(({name:r})=>e===r||e.startsWith(`${r}/`)))return!0;if(!e.startsWith("@/"))return!1;let n=e.slice(2);return t.public_paths.some(r=>{let[o]=r.split("#",1);return o.endsWith("/*")?n.startsWith(o.slice(0,-1)):yg(n)===yg(o)})}function yg(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function WC(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function Kl(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?Kl(e.object):null}var kg="components/site/generated",bg="{{$INSTANCE}}",qs=5,nN=/^[a-z][a-z0-9-]{0,48}$/,rN=/^[a-f0-9]{8}$/,Eg=/\.tsx?$/,oN=/\.json$/,iN=/\.(?:tsx?|json)$/,sN=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Xl=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),zl=ZC,aN=typeof zl=="function"?zl:zl.default;function cN(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>xg)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=vN(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=eN.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=bN(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${kg}.`,path:e.generatedRoot}};if(!Rg(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=vg(r.data.files),s=vg(e.controlledFiles);if(!IN(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>xg)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>QC)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>qC?{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 lN(e){let t=cN(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Rg(e.manifest.instanceBaseName),o=Math.max(1,Math.min(qs,e.maxAttempts??qs));for(let i=0;i<o;i+=1){let s=EN(e.instanceNameGenerator?.()??GC(4).toString("hex"));if(!s)return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_INVALID",message:"Static prefab instance suffix must be 8 lowercase hex chars."}};let a=`${r}-${s}`,c=Ng(n,a),l=uN({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await pN(e.exists,c,l.data.files))return{ok:!0,data:l.data}}return{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:"Unable to allocate a create-only static prefab instance after repeated conflicts."}}}async function Hl(e){let t=Math.max(1,Math.min(qs,e.maxAttempts??qs));for(let n=0;n<t;n+=1){let r=await lN({...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 uN(e){let t=dN(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Qo({pathTemplate:s.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!a.ok)return a;if(r.has(a.data))return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${a.data}`,path:a.data}};r.add(a.data),n.push({kind:"create-only",path:a.data,content:s.content,...s.role?{role:s.role}:{},sourcePathTemplate:s.pathTemplate})}n.sort((s,a)=>s.path.localeCompare(a.path));let o=Qo({pathTemplate:e.manifest.entry.pathTemplate,generatedRoot:e.generatedRoot,instanceName:e.instanceName,instanceRoot:e.instanceRoot});if(!o.ok)return o;if(!n.some(s=>s.path===o.data))return{ok:!1,error:{code:"MATERIALIZATION_ENTRY_INVALID",message:"Entry path must match one of the static prefab files.",path:o.data}};let i=Wl({files:n,instanceRoot:e.instanceRoot,entries:[{path:o.data,export:e.manifest.entry.export}],hostCapabilities:e.hostCapabilities,declaredProjectDependencies:Object.keys(e.manifest.projectDependencies??{}),availableHostDependencies:e.availableHostDependencies});return i.ok?{ok:!0,data:{kind:"static-prefab-materialization",instanceName:e.instanceName,generatedRoot:e.generatedRoot,instanceRoot:e.instanceRoot,entry:{path:o.data,export:e.manifest.entry.export},files:n}}:i}function dN(e){if(e.availableHostDependencies===void 0)return null;let t=new Set(Object.keys(e.manifest.projectDependencies??{})),n=new Set(e.availableHostDependencies);return n.size!==e.availableHostDependencies.length||[...n].some(r=>!t.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Target host dependency evidence must match declared materialization dependencies."}:[...t].some(r=>!n.has(r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"The target host does not provide every declared materialization dependency."}:[...t].some(r=>!e.hostCapabilities?.runtime_dependencies.some(({name:o})=>o===r))?{code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Materialization dependencies exceed the trusted host capability contract."}:null}async function pN(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Qo(e){if(e.pathTemplate.split(bg).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(bg,e.instanceName),n=SN(t);return n?Ng(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||!iN.test(n)||sN.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 Wl(e){let{files:t,instanceRoot:n,entries:r,hostCapabilities:o}=e,i=new Set(e.declaredProjectDependencies??[]),s=e.availableHostDependencies===void 0?null:new Set(e.availableHostDependencies),a=new Set(t.map(g=>g.path)),c=new Map,l=new Map(t.map(g=>[g.path,new Set])),u=new Map;for(let g of t){if(oN.test(g.path)){if(g.path.endsWith(Qs)){let x=tN(g.content);if(!x.success)return Ln("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Ln("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=YC(g.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:g.path}}}let h=Jl(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!0,rejectStyleElements:!0,themeStyleMode:"reject",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!0,rejectPrivateTokens:!0,rejectTailwindPalette:!0}}),y=fN(h.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!Eg.test(g.path))continue;let p=c.get(g.path),h=null;if(aN(p,{ImportDeclaration(y){let x=Sg({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab imports must resolve within the controlled instance or match the starter allowlist.",file:g.path},y.stop();else if(!x.internalPath&&!mN(y.node.source.value,i,s))h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:g.path},y.stop();else if(x.internalPath&&(l.get(g.path).add(x.internalPath),x.internalPath.endsWith(Qs))){let E=hN({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:p});E.ok?u.get(x.internalPath).add(g.path):(h??=E.error,y.stop())}},ExportAllDeclaration(y){h??={code:"MATERIALIZATION_ENTRY_INVALID",message:"Static prefab files cannot use export-star declarations.",file:g.path},y.stop()},ExportNamedDeclaration(y){if(y.node.source){let x=Sg({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},y.stop()):x.internalPath&&l.get(g.path).add(x.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use dynamic import().",file:g.path},y.stop();return}y.node.callee.type==="Identifier"&&y.node.callee.name==="require"&&(h??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab files cannot use require().",file:g.path},y.stop())},NewExpression(y){y.node.callee.type==="Identifier"&&y.node.callee.name==="Function"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot construct functions dynamically.",file:g.path},y.stop())},MetaProperty(y){y.node.meta.type==="Identifier"&&y.node.meta.name==="import"&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let x=Ig(y.node);x&&Xl.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=Ig(y.node);x&&Xl.has(x)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&Xl.has(y.node.name)&&(h??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name==="style"&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot use inline style attributes.",file:g.path},y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(h??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())}}),h)return{ok:!1,error:h}}if(r.length===0)return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab requires at least one source entry.");let d=new Set;for(let g of r){if(d.has(g.path))return Ln("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!Eg.test(g.path))return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return Ln("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!yN(p,g.export))return Ln("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",g.path)}for(let[g,p]of u)if(p.size!==1)return Ln("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",g);let f=new Set;for(let g of r)for(let p of xN(g.path,l))f.add(p);return f.size!==t.length?Ln("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function fN(e,t){let n=e[0];if(!n)return null;let r=new Set(["host-capabilities-unavailable","host-capabilities-invalid","import-forbidden","protected-import-forbidden","dynamic-import-forbidden","commonjs-forbidden"]),o=new Set(["inline-style-forbidden","style-forbidden"]);return{code:r.has(n.code)?"MATERIALIZATION_IMPORT_FORBIDDEN":o.has(n.code)?"MATERIALIZATION_STYLE_FORBIDDEN":"MATERIALIZATION_DATA_UNSUPPORTED",message:n.message,file:t}}function Sg(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Dn.posix.normalize(Dn.posix.join(Dn.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 mN(e,t,n){if(n===null)return!0;let r=gN(e);return r===null||t.has(r)&&n.has(r)}function gN(e){if(e.startsWith("@/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("/"))return null;if(e.startsWith("@")){let[t,n]=e.split("/");return t&&n?`${t}/${n}`:e}return e.split("/")[0]||null}function hN(e){let t=Dn.posix.dirname(e.importer),n=Dn.posix.dirname(e.imported),r=Dn.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Dn.posix.basename(e.imported).slice(0,-Qs.length),i=`./${r}${Qs}`;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 yN(e,t){for(let n of e.program.body){if(t.kind==="default"&&n.type==="ExportDefaultDeclaration"||t.kind==="default"&&n.type==="ExportNamedDeclaration"&&n.exportKind!=="type"&&n.specifiers.some(o=>o.type==="ExportSpecifier"&&o.exportKind!=="type"&&o.exported.type==="Identifier"&&o.exported.name==="default"))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 xN(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 Ln(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function bN(e){let t=Cg(e);return t===kg?t:null}function EN(e){let t=e.trim().toLowerCase();return rN.test(t)?t:null}function Rg(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 nN.test(t)?t:null}function Cg(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Dn.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function SN(e){let t=Cg(e);return!t||t!==e?null:t}function Ng(...e){return Dn.posix.join(...e)}function vg(e){return new Set(e.map(t=>t.pathTemplate))}function vN(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 IN(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Ig(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 yu}from"node:crypto";import uu from"@babel/traverse";function Gl(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 MN}from"node:crypto";import Og from"node:path";import*as to from"@babel/parser";import eu from"@babel/traverse";import tu from"@babel/generator";import*as ae from"@babel/types";import Yl from"@babel/generator";import{parse as kN}from"@babel/parser";import Zl from"@babel/traverse";import*as Ie from"@babel/types";import{PortableInvocationBindingSchema as RN}from"@vcp-dev/contracts";var Ql=typeof Yl=="function"?Yl:Yl.default,_g=typeof Zl=="function"?Zl:Zl.default,Ag=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),CN=new Set(["sourceOrder","source_order","originalOrder","original_order"]),NN=new Set(["data-site-block-id","data-site-block-order","data-vcp-block-id","data-vcp-edit-key","data-vcp-order","sourceBlockId","source_block_id","originalBlockId","original_block_id","sourceOrder","source_order","originalOrder","original_order"]),_N=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,PN=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function qr(e){if(!wg(e)||!Array.isArray(e.bindings))return Zn("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=ON(e);if(!t||!PN.test(t))return Zn("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Tg(e.targetBlockId);if(!n.ok)return n;let r=FN(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!_N.test(o))return Zn("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,c=!1,l=0;for(let[d,f]of e.bindings.entries()){let g=RN.safeParse(f);if(!g.success)return Zn("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${d}`);let p=g.data;if(a.has(p.propName))return Zn("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),CN.has(p.propName))return Zn("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(Ag.has(p.propName)&&p.value.kind!=="target-block-id")return Zn("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${d}`);if(p.value.kind==="target-block-id"&&(l+=1,l>1))return Zn("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${d}`);p.value.kind==="route-search-params"&&(c=!0),s.push(p),i.push(Ie.jsxAttribute(Ie.jsxIdentifier(p.propName),Ie.jsxExpressionContainer(TN(p.value,n.value,o))))}let u=Ie.jsxElement(Ie.jsxOpeningElement(wN(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:Ql(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function AN(e){if(!wg(e)||e.jsx===void 0==(e.source===void 0))return Qr("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Tg(e.targetBlockId);if(!t.ok)return Qr("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Qr("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r;try{r=kN(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(u){return Qr("BLOCK_METADATA_PARSE_FAILED",u instanceof Error?u.message:String(u),n?"jsx":"source")}let o=[];if(_g(r,{JSXElement(u){Pg(u)||o.push(u.node)},JSXFragment(u){Pg(u)||o.push(u.node)}}),o.length!==1)return Qr("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let i=o[0],s=LN(i);if(!s)return Qr("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let a=0,c=0;_g(r,{JSXAttribute(u){let d=DN(u.node.name);!d||!NN.has(d)||(d==="data-site-block-id"||d==="data-vcp-block-id"||Ag.has(d)?a+=1:c+=1,u.remove())}}),s.openingElement.attributes.push(Ie.jsxAttribute(Ie.jsxIdentifier("data-site-block-id"),Ie.stringLiteral(t.value)),Ie.jsxAttribute(Ie.jsxIdentifier("data-site-block-order"),Ie.jsxExpressionContainer(Ie.numericLiteral(e.targetOrder))));let l=n?Ql(i,{jsescOption:{minimal:!0}}).code:Ql(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:l,jsx:l,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:a,removedSourceOrderCount:c}}}function TN(e,t,n){return e.kind==="route-search-params"?Ie.identifier(n):e.kind==="target-block-id"?Ie.stringLiteral(t):ql(e.value)}function ql(e){return e===null?Ie.nullLiteral():typeof e=="string"?Ie.stringLiteral(e):typeof e=="number"?Ie.numericLiteral(e):typeof e=="boolean"?Ie.booleanLiteral(e):Array.isArray(e)?Ie.arrayExpression(e.map(t=>ql(t))):Ie.objectExpression(Object.entries(e).map(([t,n])=>Ie.objectProperty(Ie.stringLiteral(t),ql(n))))}function wN(e){let t=e.split("."),n=Ie.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Ie.jsxMemberExpression(n,Ie.jsxIdentifier(r));return n}function ON(e){return typeof e.componentName=="string"?e.componentName:typeof e.component=="string"?e.component:e.component&&typeof e.component=="object"?e.component.localName:null}function Tg(e){return typeof e!="string"||e.length===0||e.trim()!==e||e.length>256?{ok:!1,error:{code:"INVOCATION_TARGET_BLOCK_INVALID",path:"targetBlockId",message:"targetBlockId must be a non-blank stable identity."}}:{ok:!0,value:e}}function FN(e){return e!=null?!Number.isSafeInteger(e)||e<0?{ok:!1,error:{code:"INVOCATION_TARGET_ORDER_INVALID",path:"targetOrder",message:"targetOrder must be a non-negative safe integer."}}:{ok:!0,value:e}:{ok:!0,value:null}}function LN(e){if(Ie.isJSXElement(e))return e;let t=e.children.filter(Ie.isJSXElement),n=e.children.some(r=>Ie.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Pg(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function DN(e){return Ie.isJSXIdentifier(e)?e.name:null}function wg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zn(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Qr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var ru=typeof tu=="function"?tu:tu.default,BN=typeof eu=="function"?eu:eu.default;function ni(e){let t=jg(e);if(t)return{ok:!1,error:t};let n=e.projection,r=lu(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=VN(n,o),s=ZN(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=jN(e);if(i){let p=ou(e);return p.ok?{ok:!0,plan:{kind:"route-composition-rewrite",routeId:e.routeId,entryFile:e.entryFile,documentVersion:e.expectedDocumentVersion,placementKey:e.placementKey,placementUnitKey:o.placementUnitKey,importStep:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},returnStep:{kind:"insert-return",node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"},rewriteStep:{kind:"insert-root-expression",locator:p.locator,sourceHash:p.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:p.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(ea(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return qo("Route page composition does not expose a verifiable container boundary.");let d=ti(l),f=Lg(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?ti(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return qo("Route page composition placement does not expose a verifiable anchor boundary.");let p=Lg(e.source,g,o.anchorSourceHash,"Route page composition anchor");if(!p.ok)return p.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:c,...s.invocation?{invocation:s.invocation}:{},...s.serverParamsStep?{serverParamsStep:s.serverParamsStep}:{},insertStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}},rewriteStep:{kind:"insert-child",parentLocator:d,node:a,placement:o.relation,...g?{anchorLocator:g}:{}}}}}function au(e){let t=Je(e.entryFile,e.source);if(!t.ok)return Qn("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=nn({route:e.routeId,composition:e.composition??{routeId:e.routeId},entryFile:e.entryFile,version:e.documentVersion,source:e.source,ast:t.module.ast});if(!n.ok)return Qn("PORTABLE_ROUTE_UNSUPPORTED","Portable route does not expose a supported page-composition boundary.",n.projection.diagnostics);let r=n.projection.placements.flatMap(l=>{if(l.relation!==e.anchor.relation)return[];if(e.anchor.sourceRange)return l.anchorSourceRange&&ea(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+Mg(f,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return Qn("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Qn("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=ni({routeId:e.routeId,entryFile:e.entryFile,currentDocumentVersion:e.documentVersion,expectedDocumentVersion:e.documentVersion,source:e.source,projection:n.projection,placementKey:r[0].placement.placementKey,component:e.component,invocation:e.invocation});if(!i.ok)return i;let s=e.source,a=i.plan.rewriteStep;if(a.kind==="insert-root-expression"){let l=ri({source:s,locator:a.locator,expectedSourceHash:a.sourceHash,action:{kind:"insert",jsx:a.node.jsx,placement:a.placement,replaceOriginal:a.replaceOriginal}});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=Kt({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=$g({source:s,step:i.plan.serverParamsStep});if(!l.ok)return Qn("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=Jt({source:s,moduleSpecifier:i.plan.importStep.moduleSpecifier,imports:i.plan.importStep.imports});return c.ok?{ok:!0,plan:i.plan,patch:{kind:"portable-route-composition-patch",path:e.entryFile,expectedSourceHash:t.module.sourceHash,source:c.source}}:Qn("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Mg(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Mg(r,t),0)}function Qn(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function jN(e){let t=XN(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 ri(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Cr(e.source,"Root expression rewrite requires an exact expression locator.");let t=_o(e.source,"value");if(!t.ok)return Cr(e.source,t.diagnostic.message);let n=xe(t.ast,e.locator);if(!n.ok)return Cr(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Cr(e.source,"Resolved value locator does not point to an expression.");let o=eo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Cr(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ae.nullLiteral()),{ok:!0,source:ru(t.ast,{}).code};let i;try{i=to.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Cr(e.source,s instanceof Error?s.message:String(s))}return!ae.isJSXElement(i)&&!ae.isJSXFragment(i)?Cr(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith($N(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:ru(t.ast,{}).code})}function $N(e,t,n,r){if(ae.isNullLiteral(e)||r)return t;let o=ae.isJSXFragment(e)?[...e.children]:[ae.isJSXElement(e)?e:ae.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ae.jsxFragment(ae.jsxOpeningFragment(),ae.jsxClosingFragment(),s)}function Cr(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function cu(e){let t=jg(e);if(t)return{ok:!1,error:t};let n=e.projection,r=zg(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(UN(n,o)){let h=ou(e);return h.ok?e.operation==="remove-node"&&!Fg(n,o.placementUnitKey)?qo("The last editable page unit cannot be deleted."):e.operation==="move-node"?qo("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=ti(o.sourceRange),a=fn(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?[]:[ei(a.diagnostic)]}};if(eo(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=ou(e);return h.ok?Fg(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}}}:qo("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||!JN(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=lu(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 f=ti(d),g=fn(e.source,f);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?[]:[ei(g.diagnostic)]}};if(eo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Dg("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 x=ti(h),E=fn(e.source,x);return!E.ok||!E.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:E.ok===!1?E.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:E.ok?[]:[ei(E.diagnostic)]}}:eo(e.source,E.match.node.start??null,E.match.node.end??null)!==y?Dg("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:f,anchorLocator:x,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:f,placement:u.relation}}}}function Fg(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function VN(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&ea(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 UN(e,t){return e.container.kind!=="jsx-container"&&ea(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function ou(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=fn(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?[]:[ei(r.diagnostic)]}}}:eo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Bg("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Lg(e,t,n,r){let o=fn(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?[]:[ei(o.diagnostic)]}}}:eo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Bg(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Bg(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function qo(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Dg(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ei(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function jg(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&&!KN(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 KN(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function JN(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function XN(e,t){let n=Og.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Og.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function ti(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function eo(e,t,n){return t==null||n==null?null:`sha256:${MN("sha256").update(e.slice(t,n)).digest("hex")}`}function ea(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}function $g(e){let t;try{t=to.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(r){return{ok:!1,source:e.source,diagnostic:{message:r instanceof Error?r.message:String(r)}}}let n=zN(t,e.step);return n.ok?{ok:!0,source:ru(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function zN(e,t){let n=Jg(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=su(n.node.params[0]);if(t.action==="reuse")return n.node.params.length!==1||!r?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:Ug(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Vg(n.node.params,t.typescript);if(!o.ok||o.action!=="add"||o.identifier!==t.identifier)return{ok:!1,message:"Route searchParams signature changed before the patch was applied."};if(n.node.params.length===0)return n.node.params.push(t.typescript?iu():HN()),{ok:!0};let i=n.node.params[0],s=su(i);return s?(WN(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function HN(){return ae.objectPattern([ae.objectProperty(ae.identifier("searchParams"),ae.identifier("searchParams"),!1,!0)])}function iu(){let t=to.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ae.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ae.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ae.cloneNode(n,!0)}function WN(e,t){let n=ae.objectProperty(ae.identifier("searchParams"),ae.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ae.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Kg(e);if(!o){e.typeAnnotation=iu().typeAnnotation;return}if(!ae.isTSTypeLiteral(o.typeAnnotation))return;let i=iu().typeAnnotation;if(!i||!ae.isTSTypeAnnotation(i)||!ae.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!GN(o.typeAnnotation)&&o.typeAnnotation.members.push(ae.cloneNode(s,!0))}function GN(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Xg(t.key)==="searchParams")}function YN(e,t){if(t.isFunctionDeclaration()||t.isFunctionExpression()||t.isArrowFunctionExpression())return t;if(!t.isIdentifier())return null;let n=e.scope.getBinding(t.node.name);if(!n)return null;let r=n.path;if(r.isFunctionDeclaration()||r.isFunctionExpression())return r;if(r.isVariableDeclarator()){let o=r.get("init");if(o.isArrowFunctionExpression()||o.isFunctionExpression())return o}return null}function ZN(e){if(!e.invocation)return{ok:!0};let t=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return nu(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=QN(e.source,e.entryFile);if(!r.ok)return nu(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return nu(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function nu(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function QN(e,t){let n;try{n=to.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}if(n.program.directives.some(s=>s.value.value==="use client"))return{ok:!1,message:"Portable route searchParams wiring cannot cross a use client boundary."};let r=Jg(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Vg(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Vg(e,t){if(e.length===0)return{ok:!0,action:"add",identifier:"searchParams"};if(e.length!==1)return{ok:!1,message:"Portable route searchParams wiring rejects a default page with multiple parameters."};let n=su(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Ug(n);return r==="unsupported"?{ok:!1,message:"Portable route searchParams wiring cannot prove the existing searchParams binding."}:r?{ok:!0,action:"reuse",identifier:r}:t&&!qN(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function su(e){return!e||ae.isTSParameterProperty(e)?null:ae.isObjectPattern(e)?e:ae.isAssignmentPattern(e)&&ae.isObjectPattern(e.left)?e.left:null}function Ug(e){for(let t of e.properties)if(!(!ae.isObjectProperty(t)||t.computed||Xg(t.key)!=="searchParams"))return ae.isIdentifier(t.value)?t.value.name:ae.isAssignmentPattern(t.value)&&ae.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function qN(e){let t=Kg(e);return t?ae.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Kg(e){return e.typeAnnotation&&ae.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Jg(e){let t=null;return BN(e,{ExportDefaultDeclaration(n){if(t)return;let r=YN(n,n.get("declaration"));r&&(t=r)}}),t}function Xg(e){return ae.isIdentifier(e)?e.name:ae.isStringLiteral(e)?e.value:null}var e_=typeof uu=="function"?uu:uu.default;function nn(e){if(!e.ast)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=c_(e.ast);if(!t)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=u_(t);if(!n.ok)return rn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=p_(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(m_(r,t))return rn(e,[nt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return pu(e,t,"virtual-route-root",r);if(f_(r)){let o=x_({input:e,source:e.source,expression:r});return du(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ke(r)&&!ii(r)){let o=gu(r),i=Gg({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return du(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=h_(r);if(!o.ok)return rn(e,[o.diagnostic]);let i=no(o.path);if(i.unsupported)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(g_(e.source,r,i.members))return pu(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ke(r);if(i.members.length===0&&s)return pu(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=Gg({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return du(e,t,l,{kind:a,sourceKind:c},r)}return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function lu(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:nt("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:nt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function zg(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:nt("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:nt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Yg(e){return e.ok?t_(e.projection):n_(e.projection)}function t_(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)=>Zg(e,u,h,y,e.container.placementKey)),f=d.filter(({member:h})=>h.isBusinessMember).map(({sourceMember:h})=>o_(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,f);let p=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:p,businessMemberKeys:f.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:r_(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function n_(e){let t=e.diagnostics.map(i_);return{status:"unsupported",version:e.version,composition:e.composition,reason:s_(e.diagnostics),diagnostics:t}}function r_(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 Zg(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)=>Zg(e,t,a,c,i))]}function o_(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function i_(e){return{code:a_(e),message:e.message}}function s_(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 a_(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 c_(e){let t=null;return e_(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=l_(o.path);i&&(t=i,n.stop())}}),t}function l_(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 u_(e){let t=e.get("body");if(!t.isBlockStatement()){let s=oi(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:nt("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:nt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:nt("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(!d_(s))return{ok:!1,diagnostic:nt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Qg(s)||qg(s))return{ok:!1,diagnostic:nt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=oi(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:nt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function d_(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(Qg(o)||qg(o))return null;return r}function Qg(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function qg(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function p_(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=oi(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 f_(e){return e.isConditionalExpression()?Hg(oi(e.get("consequent")))&&Hg(oi(e.get("alternate"))):!1}function Hg(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function oi(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 m_(e,t){if(e.isIdentifier())return Wg(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Wg(n.node.name,t)}return!1}function Wg(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 g_(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&mu(t)}function mu(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(!mu(t))return!1;continue}if(t.isJSXElement()&&!mu(t))return!1}return!0}function h_(e){return{ok:!0,path:e}}function no(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:hu(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Ht(r.node.loc),businessMemberCount:0,parentSourceRange:Ht(e.node.loc),children:[],isBusinessMember:!1,label:"text"});continue}if(r.isJSXExpressionContainer()){let o=r.get("expression");if(o.isJSXEmptyExpression()||o.isNullLiteral())continue;if(o.isJSXFragment()){let i=no(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=ii(o)?no(o):null;n||=i?.unsupported??!1,t.push({...gu(o,i?.members),sourceRange:Ht(r.node.loc),parentSourceRange:Ht(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:hu(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Ht(r.node.loc),businessMemberCount:1,parentSourceRange:Ht(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ke(r)){let o=no(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=ii(r)?no(r):null;n||=o?.unsupported??!1,t.push({...gu(r,o?.members),parentSourceRange:Ht(e.node.loc)})}}return{members:t,unsupported:n}}function gu(e,t){let n=e.isJSXElement()&&ii(e)?t??no(e).members:[],r=e.isJSXElement()&&!ii(e)&&!Ke(e);return{memberKey:hu(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Ht(e.node.loc),businessMemberCount:r?1:eh(n),parentSourceRange:Ht(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:y_(e)}}function ii(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function y_(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 eh(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function ta(e){return e.length===0?0:Math.max(1,eh(e))}function Gg(e){let t=Ht(e.containerPath.node.loc),n=xu(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Wt(e.input,e.containerKind,e.sourceKind,t),o=Wt(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:ta(e.members)<=1,memberCount:ta(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function x_(e){let t=Ht(e.expression.node.loc),n=xu(e.source,e.expression.node.start,e.expression.node.end),r=Wt(e.input,"virtual-route-root","atomic-expression",t),o=Wt(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:Wt(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 th(e,t){let n=Ht(t.node.loc),r=xu(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function du(e,t,n,r,o){let i=th(e,o);if(!i)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=b_(e,n,s),c=Gl(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:rh(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 b_(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,p,h=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:ta(p)<=1,memberCount:ta(p),sourceRange:f,sourceHash:f?fu(e.source,f):null,relation:l,containerSourceRange:h,containerSourceHash:h?fu(e.source,h):null,anchorSourceRange:g,anchorSourceHash:g?fu(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>Wt(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Wt(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Wt(e,i,"placement-unit",l.sourceRange);r.push(o("before",Wt(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Wt(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function pu(e,t,n,r){let o=th(e,r);if(!o)return rn(e,[nt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Wt(e,n,"empty-container",void 0),s=Wt(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=Gl([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:rh(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 rn(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 nt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Wt(e,t,n,r){return nh([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function hu(e,t,n){return nh(["member",e,String(t??-1),String(n??-1)])}function nh(e){return`pc_${yu("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function xu(e,t,n){return t==null||n==null?null:`sha256:${yu("sha256").update(e.slice(t,n)).digest("hex")}`}function fu(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:${yu("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Ht(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function rh(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{createHash as __}from"node:crypto";import bu from"@babel/traverse";import*as Oe from"@babel/types";var S_=typeof bu=="function"?bu:bu.default;function Nr(e){let t=oh(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);if(!t)return ra("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file);let n=I_(t.module.ast,t.node);if(!n)return ra("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=ih(n);if(!r)return ra("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file);let o=[],i=sh(r);return oa(r,o)?{ok:!0,componentName:t.name,sourceFile:t.module.file,metadataOnly:i,roots:o}:ra("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function oh(e,t,n,r){let o=`${e.file}#${t}`;if(r.has(o))return null;let i=new Set(r).add(o),s=(u,d)=>{let f=tf(e.file,u,n),g=f?n.get(f):void 0;return g?oh(g,d,n,i):null},a=u=>{let d=v_(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Oe.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Oe.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Oe.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,na(g.imported))}}return null};for(let u of e.ast.program.body){if(Oe.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(ah(d))return{node:d,name:R_(d)??"default",module:e};if(Oe.isIdentifier(d))return a(d.name)}if(!(!Oe.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=k_(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Oe.isExportSpecifier(d)&&d.exportKind!=="type"&&na(d.exported)===t)return u.source?s(u.source.value,na(d.local)):a(na(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Oe.isExportAllDeclaration(u)||u.exportKind==="type"||t==="default")return[];let d=s(u.source.value,t);return d?[d]:[]}),l=c.filter((u,d)=>c.findIndex(f=>f.node===u.node&&f.module.file===u.module.file)===d);return l.length===1?l[0]:null}function v_(e,t){for(let n of e.ast.program.body){let r=Oe.isExportNamedDeclaration(n)?n.declaration:n;if(Oe.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Oe.isVariableDeclaration(r)){for(let o of r.declarations)if(Oe.isIdentifier(o.id)&&o.id.name===t&&ah(o.init))return{node:o.init,name:t}}}return null}function I_(e,t){let n=null;return S_(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function ih(e){let t=e.get("body");if(!t.isBlockStatement())return t;let n=t.get("body"),r=n.at(-1);return!r?.isReturnStatement()||!r.get("argument").node||!n.slice(0,-1).every(o=>o.isVariableDeclaration())?null:r.get("argument")}function oa(e,t){if(sh(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&Ke(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!oa(r,t)))return!1;return!0}if(e.isJSXElement())return t.push(e),!0;if(e.isJSXExpressionContainer()){let n=e.get("expression");return n.isJSXEmptyExpression()||n.isNullLiteral()||oa(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?oa(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Eu(e){return["base","link","meta","script","style","title"].includes(e)}function sh(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Oe.isJSXIdentifier(o)&&Eu(o.name)?(t=!0,!0):Ke(r)?r.get("children").every(i=>n(i)):!1}if(r.isJSXFragment())return r.get("children").every(o=>n(o));if(r.isJSXText())return r.node.value.trim()==="";if(r.isNullLiteral()||r.isBooleanLiteral()||r.isJSXEmptyExpression())return!0;if(r.isJSXExpressionContainer()||r.isParenthesizedExpression()||r.isTSAsExpression()||r.isTSTypeAssertion()||r.isTSNonNullExpression())return n(r.get("expression"));if(r.isConditionalExpression())return n(r.get("consequent"))&&n(r.get("alternate"));if(r.isArrayExpression())return r.get("elements").every(o=>!o.node||n(o));if(r.isCallExpression()){let o=r.get("callee"),i=r.get("arguments");if(!o.isMemberExpression()||o.node.computed||!Oe.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=ih(s);return a!==null&&n(a)}return!1};return n(e)&&t}function k_(e,t){return Oe.isFunctionDeclaration(e)?e.id?.name===t?t:null:Oe.isVariableDeclaration(e)&&e.declarations.some(n=>Oe.isIdentifier(n.id)&&n.id.name===t)?t:null}function ah(e){return Oe.isFunctionDeclaration(e)||Oe.isFunctionExpression(e)||Oe.isArrowFunctionExpression(e)}function R_(e){return"id"in e&&e.id&&Oe.isIdentifier(e.id)?e.id.name:null}function na(e){return Oe.isIdentifier(e)?e.name:e.value}function ra(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}function ia(e,t){return JSON.stringify([t,e])}function ch(e,t){let n=new Map,r=[],o=new Map,i=(u,d)=>JSON.stringify([u,d.loc?.start.line,d.loc?.start.column,d.loc?.end.line,d.loc?.end.column]);for(let u of e.graph.elements.values()){let d=u.sourceRange;o.set(JSON.stringify([u.sourceFile,d.startLine,d.startColumn,d.endLine,d.endColumn]),u)}let s=u=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:u}),a=(u,d,f,g,p)=>{if(u.isJSXElement()){if(Ke(u)){for(let x of u.get("children"))a(x,d,f,g,p);return}let h=o.get(i(d,u.node));if(!h)return;let y=h.identity.key;if(t.has(y)){p||s(d);let x=n.get(y)??[];x.push(ia(y,f)),n.set(y,x)}if(h.boundaryKind==="component-boundary"&&!h.isPublicUiComponent){let x=e.parsedModules.get(h.importedFrom??d);if(!x)return;let E=h.importedFrom?h.exportName??h.tag:h.tag,b=Nr({module:x,exportName:E,parsedModules:e.parsedModules});if(!b.ok){[...t].some(P=>e.graph.elements.get(P)?.sourceFile===x.file)&&b.diagnostic.code!=="component-export-unresolved"&&s(x.file);return}if(b.metadataOnly)return;let v=`${b.sourceFile}#${b.componentName}`;if(g.has(v)){s(x.file);return}let _=new Set(g).add(v);for(let P of b.roots)a(P,b.sourceFile,[...f,y],_,p);return}for(let x of u.get("children"))a(x,d,f,g,p);return}if(u.isJSXFragment()){for(let h of u.get("children"))a(h,d,f,g,p);return}if(u.isJSXExpressionContainer()){a(u.get("expression"),d,f,g,p);return}if(u.isParenthesizedExpression()||u.isTSAsExpression()||u.isTSNonNullExpression()||u.isTSTypeAssertion()){a(u.get("expression"),d,f,g,p);return}u.traverse({JSXElement(h){a(h,d,f,g,!1),h.skip()}})},c=e.parsedModules.get(e.entryFile);if(!c)return{occurrences:n,diagnostics:r};let l=Nr({module:c,exportName:"default"});if(!l.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let u of l.roots)a(u,c.file,[],new Set,!0);return{occurrences:n,diagnostics:r}}function lh(e){let t=[],n=[];return uh(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function uh(e,t,n,r,o,i,s,a,c){if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(Eu(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let l=t.parsedModules.get(e.importedFrom??e.sourceFile);if(!l){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.importedFrom??e.sourceFile,structuralPath:e.identity.structuralPath});return}let u=Nr({module:l,exportName:e.importedFrom?e.exportName??e.tag:e.tag,parsedModules:t.parsedModules});if(!u.ok){c.push({...u.diagnostic,structuralPath:e.identity.structuralPath});return}if(u.metadataOnly)return;let d=u.sourceFile,f=`${d}#${u.componentName}`;if(s.has(f)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(u.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:d,structuralPath:e.identity.structuralPath});return}let g=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange}}],p=u.roots.length>1?{kind:"component-definition",key:f}:r,h=new Set(s);h.add(f);for(let y of u.roots){let x=N_(y),E=x?C_(t.graph,d,x):[];if(E.length!==1){c.push({code:E.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:d,structuralPath:e.identity.structuralPath});continue}uh(E[0],t,g,p,u.roots.length>1?E[0]:o,u.roots.length>1?g:i,h,a,c)}}function C_(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function N_(e){let t=e.node.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function sa(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!ph(e.projection.composition,e.composition)||e.graph.composition&&!ph(e.graph.composition,e.composition))return{roots:[],diagnostics:[si("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[si("entry-module-unavailable",e.entryFile)]};for(let i of e.graph.diagnostics??[])t.push({code:`source-graph-${i.code}`,message:i.message,file:i.path});let r=e.projection.placements.filter(i=>i.relation==="before").flatMap(i=>i.members);for(let i of r){if(i.kind==="text")continue;if(i.kind!=="jsx-element"||!i.sourceRange){t.push(si("route-member-not-addressable",e.entryFile));continue}let s=A_(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(si(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=lh({element:a,graph:e.graph,parsedModules:e.parsedModules,ownerNode:{kind:"route-member",key:a.parentKey??`${e.entryFile}#${e.projection.container.placementKey}`}});t.push(...c.diagnostics);for(let l of c.roots){let u=l.ownerMember;n.push({...l,parentStructuralPath:u.parentKey?e.graph.elements.get(u.parentKey)?.identity.structuralPath??null:null})}}let o=ch(e,new Set(n.map(i=>i.element.identity.key)));t.push(...o.diagnostics);for(let i of n){let s=i.element.identity.key,a=ia(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(si("render-occurrence-unproven",i.element.sourceFile))}return{roots:P_(n,e.composition,o.occurrences),diagnostics:t}}function P_(e,t,n){let r=e.map(i=>{let s=i.element,a=n.get(s.identity.key)??[],c=i.callChain.map(l=>l.callLocator.key);return{rootKey:__("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(ia(s.identity.key,c)),instanceCount:a.length}:{}},sourceFile:s.sourceFile,structuralPath:s.identity.structuralPath,sourceRange:s.sourceRange,callChain:i.callChain,ownerNode:i.ownerNode,ownerMemberKey:i.ownerMember.identity.key,ownerCallKeys:i.ownerCallChain.map(l=>l.callLocator.key),parentStructuralPath:i.parentStructuralPath,siblingRootKeys:[],siblingIndex:0}}),o=new Map;for(let i of r){let s=dh(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(dh(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function dh(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function A_(e,t,n){return(e.fileIndex.get(t)??[]).map(r=>e.elements.get(r)).filter(r=>!!r&&r.sourceRange.startLine===n.startLine&&r.sourceRange.startColumn===n.startColumn&&r.sourceRange.endLine===n.endLine&&r.sourceRange.endColumn===n.endColumn)}function ph(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function si(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as T_,SiteEditPageBlockDescriptorSchema as w_,SiteEditSourcePathSchema as mh}from"@vcp-dev/contracts";function aa(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}),fh(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function fh(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}),fh(s,t,n,r,o))}}function ai(e){let t=[],n={...e.graph,composition:e.composition},r=Cs(aa(n),n),o=[],i=new Map;for(let a of e.roots){let c=e.graph.elements.get(a.rootRef.key),l=e.graph.elements.get(a.ownerMemberKey),u=e.parsedModules.get(a.sourceFile),d=L_(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!mh.safeParse(a.sourceFile).success||!d||!f||!mh.safeParse(d).success){t.push(Su("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Su("block-key-ambiguous",a.sourceFile));continue}let g=ve(u.source),p=w_.safeParse({blockKey:a.rootKey,rootRef:a.rootRef,definitionKey:a.rootRef.key,source:{file:a.sourceFile,structuralPath:a.structuralPath,contentHash:g},owner:a.ownerNode,siblingBlockKeys:a.siblingRootKeys,placementUnitKey:D_(a,e),capabilities:O_(c,r),...F_(c,r)});if(!p.success){t.push(Su("page-block-descriptor-invalid",a.sourceFile));continue}let h=p.data;o.push(h),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:h,root:a,ownerFile:d,ownerSourceHash:ve(f.source),ownerSourceContent:f.source,sourceHash:g,sourceContent:u.source,ownerLocator:{kind:"jsx-element",file:l.sourceFile,sourceRange:l.sourceRange,structuralPath:l.identity.structuralPath,componentName:l.componentName},rootLocator:{kind:"jsx-element",file:c.sourceFile,sourceRange:c.sourceRange,structuralPath:c.identity.structuralPath,componentName:c.componentName}})}let s=T_.safeParse(o);return s.success?{composition:e.composition,documentVersion:e.documentVersion,descriptors:s.data,bindings:i,diagnostics:t}:{composition:e.composition,documentVersion:e.documentVersion,descriptors:[],bindings:new Map,diagnostics:[...t,{code:"page-block-directory-invalid",message:"The proven page block directory failed its strict contract."}]}}function O_(e,t){let n=t.get(e.identity.key),r=e.parentKey?t.get(e.parentKey):void 0;return{insert:r?r.canInsertChild:!0,replace:!!(n?.canRemove&&(!r||r.canInsertChild)),move:n?.canMove??!1,remove:n?.canRemove??!1,save:!0}}function F_(e,t){let n=t.get(e.identity.key),r={},o=n?.constraints[0]?.message??"The existing Engine capability check denied this operation.";return(!n||!n.canRemove)&&(r.replace={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o},r.remove={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),(!n||!n.canMove)&&(r.move={code:n?"CAPABILITY_DENIED":"CAPABILITY_UNAVAILABLE",reason:o}),Object.keys(r).length?{unavailableReasons:r}:{}}function L_(e,t){if(e.ownerNode.kind==="component-definition"){let n=e.ownerNode.key.lastIndexOf("#");return n>0?e.ownerNode.key.slice(0,n):null}return t.elements.get(e.ownerMemberKey)?.sourceFile??null}function D_(e,t){let n=e.callChain[0]?.callLocator.key??e.rootRef.key,r=t.graph.elements.get(n);if(r)return t.projection.placements.find(o=>o.members.some(i=>i.sourceRange!==null&&i.sourceRange.startLine===r.sourceRange.startLine&&i.sourceRange.startColumn===r.sourceRange.startColumn&&i.sourceRange.endLine===r.sourceRange.endLine&&i.sourceRange.endColumn===r.sourceRange.endColumn))?.placementUnitKey}function Su(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import vu from"@babel/traverse";import{BlockRenderRefSchema as M_,SiteEditPageBlockPositionSchema as B_,SiteEditPageBlockTargetSchema as j_}from"@vcp-dev/contracts";var $_=typeof vu=="function"?vu:vu.default;function ro(e,t,n,r){if(!j_.safeParse(t).success)return _t("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return _t("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return _t("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!M_.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?_t("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:_t("INVALID_TARGET","The page block target was not found.")}function ca(e,t){if(!B_.safeParse(t).success)return _t("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return _t("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return _t("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return _t("INVALID_TARGET","The boundary anchor was not found.");let r=[n,...n.descriptor.siblingBlockKeys.map(u=>e.bindings.get(u))];if(r.some(u=>!u))return _t("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=gh(n);if(!i)return _t("INVALID_TARGET","The operation owner call site is unavailable.");let s=hh(n,i);if(s===void 0)return _t("INVALID_TARGET","The boundary parent source range is ambiguous.");for(let u of o)if(u.ownerFile!==n.ownerFile||u.root.ownerNode.kind!==n.root.ownerNode.kind||u.root.ownerNode.key!==n.root.ownerNode.key||!V_(hh(u,gh(u)),s))return _t("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return _t("INVALID_TARGET","Anchor order is ambiguous.");let c=t.placement==="before"?o[a-1]:n,l=t.placement==="before"?n:o[a+1];return{ok:!0,boundary:{ownerFile:n.ownerFile,parentLocator:s,anchorLocator:i,sourceHash:n.ownerSourceHash,placement:t.placement,beforeBlockKey:c?.blockKey??null,afterBlockKey:l?.blockKey??null}}}function gh(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function hh(e,t){if(!t)return;let n=Je(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if($_(n.module.ast,{JSXElement(i){let s=Iu(i.node);s&&s.startLine===t.sourceRange.startLine&&s.startColumn===t.sourceRange.startColumn&&s.endLine===t.sourceRange.endLine&&s.endColumn===t.sourceRange.endColumn&&r.push(i)}}),r.length!==1)return;let o=r[0].parentPath;for(;o;){if(o.isJSXFragment()){let i=Iu(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Iu(o.node),s=t.structuralPath?.lastIndexOf("/")??-1,a=s<0?void 0:t.structuralPath.slice(0,s);return i?{kind:"jsx-element",file:t.file,sourceRange:i,...a?{structuralPath:a}:{},...t.componentName?{componentName:t.componentName}:{}}:void 0}o=o.parentPath}return null}function V_(e,t){return e===void 0||t===void 0||e===null||t===null?e===t:e.file===t.file&&e.kind===t.kind&&e.sourceRange.startLine===t.sourceRange.startLine&&e.sourceRange.startColumn===t.sourceRange.startColumn&&e.sourceRange.endLine===t.sourceRange.endLine&&e.sourceRange.endColumn===t.sourceRange.endColumn}function Iu(e){let t=e.loc;return t?{startLine:t.start.line,startColumn:t.start.column,endLine:t.end.line,endColumn:t.end.column}:null}function _t(e,t){return{ok:!1,code:e,message:t}}import bh from"node:path";import{SiteEditSourcePathSchema as Q_}from"@vcp-dev/contracts";import la from"node:path";import ku from"@babel/traverse";import*as qn from"@babel/types";import{SiteEditSourcePathSchema as yh,SiteEditPageBlockTargetSchema as U_}from"@vcp-dev/contracts";var K_=typeof ku=="function"?ku:ku.default;function xh(e){if(!e.operationId)return Ze("INVALID_PARAMS","An operationId is required.");if(!U_.safeParse(e.target).success)return Ze("INVALID_PARAMS","Invalid page block target.");if(e.target.kind!=="page-block"||e.target.blockKey!==e.binding.blockKey||e.target.composition.routeId!==e.binding.composition.routeId||e.target.composition.templateId!==e.binding.composition.effectiveTemplateId)return Ze("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return Ze("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return Ze("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return Ze("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!yh.safeParse(t).success)return Ze("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return Ze("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(ve(n)!==e.binding.ownerSourceHash)return Ze("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||ve(r)!==e.binding.descriptor.source.contentHash)return Ze("VERSION_STALE","The block source hash changed after target resolution.");let o;if(e.operation==="insert-child"){if(o=e.boundary,!o||o.ownerFile!==e.binding.ownerFile||o.sourceHash!==e.binding.ownerSourceHash||o.anchorLocator.file!==t||o.parentLocator?.file!==t)return Ze("INVALID_TARGET","The insertion boundary is not in the resolved source owner.");let l=o.placement==="before"?o.afterBlockKey:o.beforeBlockKey;if(l!==e.binding.blockKey&&!e.binding.descriptor.siblingBlockKeys.includes(l??""))return Ze("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return Ze("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=X_(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?Jr({source:n,locator:J_(e.binding),node:{jsx:i.value.jsx}}):Kt({source:n,locator:Ru(o.parentLocator),anchorLocator:Ru(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return Ze("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=Jt({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return Ze("UNSUPPORTED_OPERATION",l.diagnostic.message);a=l.source}return{ok:!0,plan:{operationId:e.operationId,kind:"source-edit",target:e.target,documentVersion:e.documentVersion,conflictPolicy:"compare-and-swap",edits:[{operation:"upsert",file:t,content:a,baseContentHash:e.binding.ownerSourceHash}]}}}function J_(e){return Ru(e.ownerLocator)}function Ru(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function X_(e,t,n,r){if(e.kind==="native-tag")return/^[A-Za-z][A-Za-z0-9:_-]*$/.test(e.tag)?{ok:!0,value:{jsx:e.text===void 0?`<${e.tag} />`:`<${e.tag}>{${JSON.stringify(e.text)}}</${e.tag}>`}}:Ze("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return Ze("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=z_(t,e.component.source,r);if(!o)return Ze("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Je(t,n);if(!i.ok)return Ze("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=H_(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??G_(Y_(e.component.exportName,o),W_(i.module.ast)),c=Z_(e.props??{});if(!c.ok)return c;let l=`<${a}${c.value?` ${c.value}`:""} />`;if(s)return{ok:!0,value:{jsx:l}};let u=e.component.exportName==="default"?{kind:"default",local:a}:{kind:"named",imported:e.component.exportName,...a!==e.component.exportName?{local:a}:{}};return{ok:!0,value:{jsx:l,import:{moduleSpecifier:e.component.source,specifiers:[u]}}}}function z_(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?la.posix.normalize(la.posix.join(la.posix.dirname(e),t)):null;return r?(/\.(?:tsx?|jsx?)$/i.test(r)?[r]:[".tsx",".ts",".jsx",".js"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js"].map(i=>`${r}/index${i}`))).find(i=>yh.safeParse(i).success&&n.has(i))??null:null}function H_(e,t,n){for(let r of e)if(!(!qn.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&qn.isImportDefaultSpecifier(o)||n!=="default"&&qn.isImportSpecifier(o)&&(qn.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function W_(e){let t=new Set;return K_(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function G_(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function Y_(e,t){let r=(e==="default"?la.posix.basename(t).replace(/\.(?:tsx?|jsx?)$/i,""):e).replace(/[^A-Za-z0-9_$]/g,""),o=r?r[0].toUpperCase()+r.slice(1):"Component";return/^[A-Za-z_$][\w$]*$/.test(o)?o:"Component"}function Z_(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return Ze("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return Ze("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return Ze("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function Ze(e,t){return{ok:!1,code:e,message:t}}function Eh(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return ua("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&Q_.safeParse(i.path).success))return ua("MATERIALIZATION_PATH_INVALID","Every materialized output must remain a safe create-only Snapshot source.");if(e.materialization.files.some(i=>e.files.has(i.path)))return ua("MATERIALIZATION_INSTANCE_CONFLICT","A generated materialization path already exists in the fixed Snapshot source map.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!e.files.has(t))return ua("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=eP(t,e.materialization.entry.path),r=xh({operationId:e.operationId,documentVersion:e.documentVersion,target:e.target,binding:e.binding,...e.boundary?{boundary:e.boundary}:{},operation:e.operation,node:{kind:"component-call",component:{source:n,exportName:e.materialization.entry.export.kind==="default"?"default":e.materialization.entry.export.name},props:{}},files:q_(e.files,e.materialization)});if(!r.ok)return r;let o=e.materialization.files.map(i=>({operation:"create-only",file:i.path,content:i.content}));return{ok:!0,plan:{...r.plan,target:e.target,edits:[...o,...r.plan.edits]}}}function q_(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function eP(e,t){let n=bh.posix.relative(bh.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function ua(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as dP}from"@vcp-dev/contracts";import zV from"node:fs";import WV from"node:path";var tP=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ci(e){let t=e.map(r=>uP(r.path)),n=nP(t);return n?t.filter(r=>oP(n,r)).map(r=>({routeId:iP(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Cu(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=lP(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function nP(e){return e.some(r=>r.startsWith("app/")&&!rP(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function rP(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function oP(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return tP.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function iP(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(aP).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function sP(e){return e.startsWith("(")&&e.endsWith(")")}function aP(e){return!e||e.startsWith("@")||e.startsWith("_")||sP(e)?null:cP(e)}function cP(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function lP(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function uP(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var li=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Pt(e,t={}){throw new li("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Nu(e){return dP.safeParse(e).success||Pt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Sh(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Pt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Pt("invalid-template-key",{path:e})}return Nu(t)!==e&&Pt("noncanonical-template-key",{path:e}),t}function pP(e){let t=Cu(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("(")||fP(r)&&!vh(r)))&&Pt("invalid-public-route",{routeId:e}),t}function fP(e){return e.includes("[")||e.includes("]")}function vh(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Ih(e){return e.some(vh)}function kh(e,t,n="app"){n!=="app"&&n!=="src/app"&&Pt("invalid-app-root");let r=pP(e),o=Nu(t),i=Ih(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))&&Pt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Rh(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Ch(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===".")&&Pt("invalid-file-path",{path:i}),n.has(i)&&Pt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function pa(e){let t=Ch(e.files),n=ci([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new li("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(!Rh(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Pt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Ih(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=Sh(u),g=d.length?`/${d.join("/")}`:"/";kh(g,f,a).templateEntryFile!==i&&Pt("candidate-path-mismatch",{path:i,routeId:g});let h=r.get(g);(!h||!h.startsWith(`${a}/`))&&Pt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:h,appRoot:a})}return o.sort((i,s)=>da(i.routeId,s.routeId)||da(i.templateId,s.templateId))}function fa(e){let t=Ch(e.files),n=pa({files:t}),r=ci([...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)=>da(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:da(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function mP(e){let t=Cu(e.selector.routeId),n=fa({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Pt("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||Pt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function da(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as LP}from"@vcp-dev/contracts";import{parse as NP}from"@babel/parser";import{parse as rU}from"@babel/parser";import{FormBlockIdSchema as iU,FormSpecV1Schema as sU}from"@vcp-dev/contracts";var ui="components/site/generated/forms",aU=`${ui}/vcp-form-runtime.tsx`,ma="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",cU=new RegExp(`^${ui}/form-(${ma})\\.spec\\.ts$`),lU=new RegExp(`^${ui}/form-(${ma})\\.tsx$`),uU=new RegExp(`^@/${ui}/form-(${ma})$`),dU=new RegExp(`(?:^|/)${ui}/form-(${ma})(?:\\.tsx?)?$`);var pU=Symbol("invalid-literal");import{createHash as gU}from"node:crypto";import{posix as yU}from"node:path";import{parse as bU}from"@babel/parser";import{FormSpecV1Schema as SU}from"@vcp-dev/contracts";var vU=Symbol("dynamic");import{parse as gP}from"@babel/parser";function ga(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var hP=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Nh(e){let t=hP.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 yP(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function _h(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function xP(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function _u(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(_u);if(t?.type==="ObjectExpression"){let n={};for(let r of ga(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=_h(r.key);if(!o)throw new Error("unsupported object key");n[o]=_u(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Pu(e,t){let n=[],r=Nh(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=gP(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 ga(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of ga(u.declarations)){let f=d.id;f?.type==="Identifier"&&f.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=xP(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 ga(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=_h(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=yP(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=_u(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 bP}from"@babel/parser";var Ph=["page","anchor","external","email","phone","group","file"],EP=["link","cta"],Th=["description","badge","iconKey"],Au=["label","targetType","href","role","openInNewTab","nofollow","children",...Th],SP=new Set(Au);function pi(e){return Array.isArray(e)?e:[]}function di(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function vP(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ah(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Tu(e){let t=[],n;try{n=bP(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 pi(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of pi(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 pi(r.elements).forEach((i,s)=>{let a=wh(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function wh(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 pi(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=vP(l.key);u&&(r[u]=l.value)}let o=di(r.label),i=di(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Ph.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Ph.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 Th){if(r[l]===void 0)continue;let u=di(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))SP.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 ${Au.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=[];pi(r.children.elements).forEach((u,d)=>{let f=wh(u,`${t}.children[${d}]`,n);f&&l.push(f)}),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=di(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=di(r.role);if(c!==void 0&&(EP.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ah(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=Ah(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 IP}from"@babel/parser";function fi(e){return Array.isArray(e)?e:[]}function Oh(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function kP(e){let t;try{t=IP(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of fi(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of fi(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=Oh(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 wu(e,t){let n=Fh(t);if(!n)return{status:"unsupported",source:e};let r=kP(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Tu(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=fi(l.elements);for(let[d,f]of u.entries()){if(CP(f,n)){let p=u[d+1],h=u[d-1],y=f.start,x=f.end;if(typeof y!="number"||typeof x!="number")continue;if(p&&typeof p.start=="number")s.push({start:y,end:p.start});else if(h&&typeof h.end=="number")s.push({start:h.end,end:x});else{let E=/^\s*,/.exec(e.slice(x));s.push({start:y,end:E?x+E[0].length:x})}continue}let g=RP(f);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 RP(e){if(e.type==="ObjectExpression")for(let t of fi(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Oh(t.value)}}function Fh(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function CP(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of fi(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"&&Fh(n??"")===t}import{estimateNavLabelWidth as wU}from"@vcp-dev/contracts";import{parse as LU}from"@babel/parser";function Mn(e,t){let n;try{n=NP(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(N){let A=N.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:N instanceof Error?N.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:A?.line??1}]}}let r=n.program,o=Ft(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=N=>{if(N?.type==="FunctionDeclaration"){let A=N.id;A?.type==="Identifier"&&typeof A.name=="string"&&s.set(A.name,N);return}if(N?.type==="VariableDeclaration")for(let A of Ft(N.declarations)){let L=A.id,$=A.init;L?.type==="Identifier"&&typeof L.name=="string"&&$&&(er($)?s.set(L.name,$):$.type==="Identifier"&&typeof $.name=="string"&&a.set(L.name,$.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let A=N.source?.value;if(typeof A!="string")continue;for(let L of Ft(N.specifiers)){let $=L.local;if(!($?.type!=="Identifier"||typeof $.name!="string")){if(L.type==="ImportDefaultSpecifier")i.set($.name,{source:A,exportName:"default"});else if(L.type==="ImportNamespaceSpecifier")i.set($.name,{source:A,exportName:"*"});else if(L.type==="ImportSpecifier"){let U=L.imported,de=U?.type==="Identifier"&&typeof U.name=="string"?U.name:U?.type==="StringLiteral"&&typeof U.value=="string"?U.value:"";de&&i.set($.name,{source:A,exportName:de})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let $=N.declaration;$&&er($)?c.set("default",$):$?.type==="Identifier"&&typeof $.name=="string"&&c.set("default",$.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let A=N.declaration;if(A?.type==="FunctionDeclaration"){let $=A.id;$?.type==="Identifier"&&typeof $.name=="string"&&c.set($.name,$.name)}else if(A?.type==="VariableDeclaration")for(let $ of Ft(A.declarations)){let U=$.id;U?.type==="Identifier"&&typeof U.name=="string"&&c.set(U.name,U.name)}let L=N.source?.value;for(let $ of Ft(N.specifiers)){let U=Mh($.local),de=Mh($.exported);if(!(!U||!de))if(typeof L=="string"){let z=`#re-export:${de}`;i.set(z,{source:L,exportName:U}),c.set(de,z)}else c.set(de,U)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,h=[],y=new Map,x=!1,E=[],b=new Map,v=new Map,_=(N,A="rendered")=>{let L=Dh(N,i);if(!L)return!1;let $=`${L.source}\0${L.exportName}`;if(A==="uncertain")return!f.has($)&&!p.has($)&&(p.add($),g.push({source:L.source,export_name:L.exportName})),!0;if(!f.has($)&&(f.add($),d.push({source:L.source,export_name:L.exportName}),p.delete($))){let U=g.findIndex(de=>de.source===L.source&&de.export_name===L.exportName);U>=0&&g.splice(U,1)}return!0},P=(N,A="rendered",L=[])=>{let $=`${A}\0${Fu(L)}`,U=b.get(N)??new Set,de=v.get(N)??new Set;if(U.has($)||de.has(A))return;U.add($),b.set(N,U),de.add(A),v.set(N,de);let z=new Map(s),Q=new Map,ke=[],ct=(he,Qe=!1)=>{if(ha(he)){if(!Qe&&er(he)){if(he.type==="FunctionDeclaration"){let Pe=he.id;Pe?.type==="Identifier"&&typeof Pe.name=="string"&&z.set(Pe.name,he)}return}if(he.type==="VariableDeclarator"){let Pe=he.id,ce=he.init;Pe?.type==="Identifier"&&typeof Pe.name=="string"&&ce&&(er(ce)?z.set(Pe.name,ce):Q.set(Pe.name,ce))}else if(he.type==="ReturnStatement"){let Pe=he.argument;Pe&&ke.push(Pe)}if(he.type==="CallExpression"){let Pe=he.callee;if(Pe?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:he.loc?.start.line??1}),mi(Pe)==="cms.forms.getConfig"){let ce=Ft(he.arguments)[0];ce?.type==="StringLiteral"&&typeof ce.value=="string"&&ce.value.trim()?A==="rendered"?u.add(ce.value.trim()):E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a CMS form inside a JSX prop is rendered.",file_path:t.filePath??"",line:he.loc?.start.line??1}):E.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:he.loc?.start.line??1})}}for(let[Pe,ce]of Object.entries(he))if(Pe!=="loc")if(Array.isArray(ce))for(let Ve of ce)ct(Ve);else ct(ce)}};ct(N,!0);let lt=new Set,Ro=new Set,Qt=(he,Qe=A,Pe=L)=>{if(!(!ha(he)||er(he))){if(he.type==="Identifier"&&typeof he.name=="string"){let ce=Q.get(he.name),Ve=`${Qe}\0${he.name}\0${Fu(Pe)}`;ce&&!lt.has(Ve)&&!Ro.has(he.name)?(lt.add(Ve),Ro.add(he.name),Qt(ce,Qe,Pe),Ro.delete(he.name)):_(he.name,Qe);return}if(he.type==="CallExpression"){let ce=he.callee,Ve=Ft(he.arguments),mt=mi(ce),qt=ce?.type==="Identifier"&&typeof ce.name=="string"?i.get(ce.name):void 0;if(Qe==="rendered"&&(mt==="createElement"||mt.endsWith(".createElement")||qt?.source==="react"&&qt.exportName==="createElement")&&Ve[0]?.type==="StringLiteral"&&Ve[0].value==="form"&&(x=!0),ce?.type==="Identifier"&&typeof ce.name=="string"){let gt=z.get(ce.name);if(gt){P(gt,Qe,Pe);return}}if(ce&&er(ce)){P(ce,Qe,Pe);return}if(AP(ce)){for(let gt of Ve)if(er(gt))P(gt,Qe,Pe);else if(gt.type==="Identifier"&&typeof gt.name=="string"){let $r=z.get(gt.name);$r&&P($r,Qe,Pe)}return}for(let gt of Ve)TP(gt)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:gt.loc?.start.line??1});return}if(he.type==="JSXElement"){let ce=he.openingElement,Ve=ce?Lh(Pe,_P(ce)):Pe;Qt(ce,Qe,Ve);for(let mt of Ft(he.children))Qt(mt,Qe,Ve);return}if(he.type==="JSXOpeningElement"){let ce=ya(he.name);Qe==="rendered"&&ce==="form"&&(x=!0);let Ve=ce?Dh(ce,i):void 0;if(Qe==="rendered"&&Ve&&typeof he.start=="number"){let mt=`${Ve.source}\0${Ve.exportName}\0${he.start}`,qt=y.get(mt);if(!qt){let gt=wP(he).get("formBlockId");qt={source:Ve.source,export_name:Ve.exportName,start_offset:he.start,...typeof gt=="string"?{static_form_block_id:gt}:{}},y.set(mt,qt),h.push(qt)}Pe.length>0&&(qt.static_render_blockers=Lh(qt.static_render_blockers??[],Pe))}if(ce&&!_(ce,Qe)){let mt=z.get(ce);mt?P(mt,Qe,Pe):Q.has(ce)?Qt(Q.get(ce),Qe,Pe):PP(ce)||/^[A-Z]/.test(ce)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ce} from a static import.`,file_path:t.filePath??"",line:he.loc?.start.line??1})}for(let mt of Ft(he.attributes))Qt(mt,"uncertain",Pe);return}if(he.type==="JSXAttribute"){let ce=he.value,Ve=ce?.type==="JSXExpressionContainer"?ce.expression:ce;Ve&&er(Ve)?P(Ve,"uncertain",Pe):Qt(Ve,"uncertain",Pe);return}for(let[ce,Ve]of Object.entries(he))if(!(ce==="loc"||ce==="closingElement"))if(Array.isArray(Ve))for(let mt of Ve)Qt(mt,Qe,Pe);else Qt(Ve,Qe,Pe)}},Co=N.body;Co&&Co.type!=="BlockStatement"&&ke.push(Co);for(let he of ke)Qt(he);de.delete(A)},R=c.get(t.exportName);if(typeof R=="string"){let N=R,A=new Set;for(;a.has(N)&&!A.has(N);)A.add(N),N=a.get(N);if(!_(N)){let L=s.get(N);L?P(L):E.push(Bh(t))}}else R?P(R):E.push(Bh(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:h,renders_native_form:x,diagnostics:E}}function Fu(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function Lh(e,t){return[...new Map([...e,...t].map(r=>[Fu([r]),r])).values()]}function _P(e){let t=new Map;for(let a of Ft(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=jh(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=ya(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:FP(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Ou(t.get(a));(c===!0||(a==="aria-hidden"?c==="true":typeof c=="string"))&&o(a)}let i=t.get("style");if(i?.type==="ObjectExpression"){let a=new Map;for(let l of Ft(i.properties)){let u=l.key,d=!l.computed&&u?.type==="Identifier"?u.name:u?.type==="StringLiteral"?u.value:void 0;l.type!=="ObjectProperty"||typeof d!="string"?a.clear():a.set(d,Ou(l.value))}a.get("display")==="none"&&o("style.display=none"),a.get("visibility")==="hidden"&&o("style.visibility=hidden");let c=a.get("opacity");(c===0||typeof c=="string"&&c.trim()==="0")&&o("style.opacity=0")}let s=Ou(t.get("className"));if(typeof s=="string"){let a=s.split(/\s+/).filter(Boolean),l={hidden:new Set(["block","inline","inline-block","flex","inline-flex","grid","inline-grid","table","inline-table","table-row","table-cell","flow-root","contents","list-item"]),invisible:new Set(["visible"]),"sr-only":new Set(["not-sr-only"])};for(let[u,d]of Object.entries(l))a.includes(u)&&!a.some(f=>d.has(f.split(":").at(-1)))&&o(`className=${u}`)}return r}function Ou(e){if(e===null)return!0;if(e){if(e.type==="StringLiteral"||e.type==="BooleanLiteral"||e.type==="NumericLiteral")return e.value;if(e.type==="TemplateLiteral"&&Ft(e.expressions).length===0)return Ft(e.quasis)[0]?.value?.cooked}}function Dh(e,t){let n=t.get(e);if(n)return n;let[r,...o]=e.split(".");if(!r||o.length===0)return;let i=t.get(r);if(i?.exportName==="*")return{source:i.source,exportName:o.join(".")}}function PP(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function er(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function AP(e){let t=mi(e),n=e?.type==="MemberExpression"&&e.computed!==!0?e.property:void 0;return t==="Array.from"||t==="React.Children.map"||n?.type==="Identifier"&&(n.name==="map"||n.name==="flatMap")}function TP(e){let t=!1;return Lu(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&mi(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Mh(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Bh(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function mi(e){if(!e)return"";if(e.type==="Identifier"&&typeof e.name=="string")return e.name;if(e.type!=="MemberExpression"||e.computed===!0)return"";let t=mi(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function wP(e){let t=new Map,n=Array.isArray(e.attributes)?e.attributes:[];for(let r of n){let o=r;if(o.type!=="JSXAttribute")continue;let i=jh(o.name);i&&t.set(i,OP(o.value))}return t}function OP(e){if(e==null)return!0;let t=e;if(t.type==="StringLiteral")return t.value;if(t.type!=="JSXExpressionContainer")return;let n=t.expression;if(n&&(n.type==="StringLiteral"||n.type==="NumericLiteral"))return n.value}function jh(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function FP(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Lu(e,t){if(ha(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)Lu(o,t);continue}Lu(r,t)}}}function ha(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ya(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=ya(t.object),r=ya(t.property);return n&&r?`${n}.${r}`:r||n}return""}function Ft(e){return Array.isArray(e)?e.filter(t=>ha(t)):[]}var DP="components/site/generated/",gi=[".tsx",".ts",".jsx",".js"];function $h(e){if(e.expectedUrlPath===LP)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(ci(Object.keys(e.files).map(h=>({path:h}))).map(h=>h.entryFile)),n=Object.entries(e.files).filter(([h,y])=>{let x=h.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Pu(y,x);return E.found&&E.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=pa({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=MP(e.files);if(!i.ok)return i.error;let s=i.graph,a=VP(o,s),c=UP(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),f=u.map(h=>({operation:"delete",file:h})),g=[],p=[];for(let[h,y]of Object.entries(e.files))if(!d.has(h)){if(y.includes("NAV_ITEMS")){let x=wu(y,e.expectedUrlPath);x.status==="removed"?(f.push({operation:"upsert",file:h,content:x.source}),g.push(h)):x.status==="unsupported"&&p.push(`unsupported_navigation:${h}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&p.push(`preserved_link:${h}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:p}}function MP(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")||!BP(r))continue;let s=Je(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(jP(c))continue;let l=un(r,c),u=$P(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 BP(e){let t=e.toLowerCase();return gi.some(n=>t.endsWith(n))}function jP(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!gi.some(n=>e.endsWith(n)))}function $P(e,t){let n=e.replace(/\\/g,"/");return(gi.some(o=>n.endsWith(o))?[n]:[...gi.map(o=>`${n}${o}`),...gi.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function VP(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(DP)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function UP(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 Vy from"@babel/parser";import*as _e from"@babel/types";import*as La from"node:path";import*as Le from"@babel/types";function Vh(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 hn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return _r(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Le.isObjectPattern(n)||Le.isArrayPattern(n))return _r(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(JP(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function _r(e,t,n=!1){return Le.isIdentifier(e)?e.name===t&&n:Le.isObjectPattern(e)?e.properties.some(r=>Le.isObjectProperty(r)?_r(r.value,t,n):_r(r.argument,t,n)):Le.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Le.isRestElement(r)?r.argument:r;return _r(o,t,n)}):Le.isAssignmentPattern(e)?_r(e.left,t,!0):Le.isRestElement(e)?_r(e.argument,t,n):!1}function oo(e,t){if(e.path.isObjectPattern()){if(t){let r=on(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:hn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:hn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Uh(r),i=!1,s=o?o.initBinding&&Du(o.initBinding)?(i=hn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=oo(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=on(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||hn(e)}}}}let n=HP(e);if(n){let r=KP(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||hn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=XP(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:hn(e)}}let i=hi(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:hn(e)}:null}if(Du(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:hn(e)}}return null}function KP(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=Uh(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Du(i)?(a=hn(i),[...s]):(()=>{let u=oo(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=on(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||hn(t)}:null}function Uh(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=WP(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Du(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function JP(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function XP(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=on(i.node,t);if(a)return a}return null}function Kh(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=xa(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=hi(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=zP(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=hi(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 xa(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=hi(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&on(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=xa(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=xa(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=xa(r,t);if(o)return o}}return null}function on(e,t,n=[]){if(Le.isIdentifier(e))return e.name===t?n:null;if(Le.isObjectPattern(e)){for(let r of e.properties)if(Le.isObjectProperty(r)){let o=hi(r);if(!o)continue;let i=on(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Le.isRestElement(r)){let o=on(r.argument,t,n);if(o)return o}}if(Le.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Le.isRestElement(o)?o.argument:o,s=on(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Le.isAssignmentPattern(e)?on(e.left,t,n):null}function zP(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function HP(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 hi(e){return e.computed?null:Le.isIdentifier(e.key)?e.key.name:Le.isStringLiteral(e.key)?e.key.value:null}function WP(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)?{base:n.name,path:t}:null}import*as Gh from"@babel/parser";import ju from"@babel/traverse";import*as io from"@babel/types";import*as Ee from"@babel/types";var Jh=new WeakMap;function Sa(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?ba(n,t):null}if(e.isMemberExpression()){let n=eA(e.node),r=GP(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?ba(o,[...r,...t]):null}return e.isAwaitExpression()||Bu(e.node)?tr(nA(e.node),t,"awaited or fetched expression"):null}function GP(e){let t=[],n=e;for(;Ee.isMemberExpression(n);){if(n.computed)if(Ee.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ee.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ee.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ee.isIdentifier(n)?t:null}function ba(e,t=[],n){let r=YP(e,t);if(r)return r;let o=ZP(e,t,n);if(o)return o;let i=QP(e,t,n);return i||null}function xi(e){return e?.kind==="api-source"}function YP(e,t){if(e.path.isVariableDeclarator()&&Ee.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Mu(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return tr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ee.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Ee.isObjectProperty(c)&&Hh(c)==="data"&&yi(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Mu(a.node))return tr(e.identifier.name,t,"query hook data binding")}let n=qP(e);if(!n||Hh(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()||!Mu(i.node)?null:tr(e.identifier.name,t,"query hook data binding")}function ZP(e,t,n){if(e.path.isVariableDeclarator()&&Ee.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!zh(c.node))return null;let[l,u]=e.path.node.id.elements;return!Ee.isIdentifier(l)||l.name!==e.identifier.name||!Ee.isIdentifier(u)?null:Xh(e,u.name,n)?tr(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()||!zh(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Ee.isIdentifier(a)&&Xh(e,a.name,n)?tr(e.identifier.name,t,"state setter is updated by API data"):null}function QP(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()?tr(e.identifier.name,t,"awaited binding result"):Bu(o.node,n)?tr(e.identifier.name,t,"fetch-backed binding result"):null:null}function qP(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 yi(e,t){return Ee.isIdentifier(e)?e.name===t:Ee.isAssignmentPattern(e)?yi(e.left,t):Ee.isObjectPattern(e)?e.properties.some(n=>Ee.isObjectProperty(n)?yi(n.value,t):yi(n.argument,t)):Ee.isArrayPattern(e)?e.elements.some(n=>!!n&&yi(Ee.isRestElement(n)?n.argument:n,t)):!1}function Xh(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Jh.get(n);c||(c=new WeakMap,Jh.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){Bu(c.node)&&(r=!0),(tA(c.node.callee,t)||c.node.arguments.some(l=>Ee.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Mu(e){let t=va(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function zh(e){return va(e.callee)==="useState"}function Bu(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Ea(e,o=>Ee.isCallExpression(o)&&va(o.callee)==="fetch");return t?.set(e,r),r}function eA(e){let t=e;for(;Ee.isMemberExpression(t);)t=t.object;return Ee.isIdentifier(t)?t.name:null}function Hh(e){return e.computed?null:Ee.isIdentifier(e.key)?e.key.name:Ee.isStringLiteral(e.key)?e.key.value:null}function va(e){return Ee.isIdentifier(e)?e.name:Ee.isMemberExpression(e)&&Ee.isIdentifier(e.property)?e.property.name:null}function tA(e,t){return Ea(e,n=>Ee.isIdentifier(n)&&n.name===t)}function Ea(e,t){if(t(e))return!0;let n=Ee.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(Ee.isNode(i)&&Ea(i,t))return!0;continue}if(Ee.isNode(o)&&Ea(o,t))return!0}return!1}function nA(e){return Ee.isIdentifier(e)?e.name:Ee.isCallExpression(e)?va(e.callee)??"api":Ee.isAwaitExpression(e)?"awaited-api":"api"}function tr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:rA(e,t),reason:n}}function rA(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Yh=typeof ju=="function"?ju:ju.default;function Zh(e,t){let n=qh(e);if(!n)return{allowed:!0};let r=!1;return Yh(n,{CallExpression(o){if(!ey(o.node,t.sourceRange)||!oA(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||xi(Sa(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Qh(e,t){let n=qh(e);if(!n)return{allowed:!0};let r=!1;return Yh(n,{JSXExpressionContainer(o){ey(o.node,t.sourceRange)&&(io.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 qh(e){try{return Gh.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function oA(e){let t=e.callee;return io.isMemberExpression(t)&&io.isIdentifier(t.property)&&t.property.name==="map"}function ey(e,t){let n=e.loc;return n?Wh({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&Wh({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function Wh(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 q from"@babel/types";import*as ty from"@babel/parser";import $u from"@babel/traverse";import*as ze from"@babel/types";import*as so from"node:path";var sn=typeof $u=="function"?$u:$u.default;function it(e){try{return ty.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Vu(e){return e.computed?ze.isStringLiteral(e.key)||ze.isNumericLiteral(e.key)?String(e.key.value):null:iA(e.key)}function iA(e){return ze.isIdentifier(e)?e.name:ze.isStringLiteral(e)||ze.isNumericLiteral(e)?String(e.value):null}function Pr(e){return ze.isParenthesizedExpression(e)||ze.isTSAsExpression(e)||ze.isTSSatisfiesExpression(e)||ze.isTSNonNullExpression(e)||ze.isTSTypeAssertion(e)?Pr(e.expression):ze.isExpression(e)?e:null}function Uu(e){if(ze.isIdentifier(e))return[e.name];if((ze.isMemberExpression(e)||ze.isOptionalMemberExpression(e))&&!e.computed&&ze.isIdentifier(e.property)){let t=Pr(e.object),n=t?Uu(t):null;return n?[...n,e.property.name]:null}return null}function Ar(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?so.normalize(so.join(so.dirname(e),t)).replace(/\\/g,"/"):t}function Lt(e,t){return Ia(e)===Ia(t)}function Ia(e){let t=ao(e);return t.endsWith("/index")?t.slice(0,-6):t}function ao(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function oy(e,t,n){let r=cy(e,t);if(ly(e,r),uy(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 sn(e,{JSXElement(s){my(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:ka(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 iy(e,t){let n=new Map,r=i=>{let s=co(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 sA(i,n))o=r(s)||o}return[...n.values()]}function sA(e,t){let n=[],r=aA(e,t);for(let o of e.ast.program.body){if(q.isExportDefaultDeclaration(o)&&q.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=bi(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(q.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Ar(e.file,o.source.value);for(let s of o.specifiers){if(q.isExportNamespaceSpecifier(s)){let l=nr(s.exported);for(let u of t.values())Lt(u.file,i)&&n.push({file:e.file,namespace:Ku(l,u.namespace),exportName:u.exportName});continue}if(!q.isExportSpecifier(s))continue;let a=nr(s.local),c=[...t.values()].filter(l=>Lt(l.file,i)&&Tr(l.namespace,a));if(c.length>0){let l=nr(s.exported);for(let u of c){let d=bi(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(co({file:i,exportName:a}))&&n.push({file:e.file,exportName:nr(s.exported)})}continue}if(q.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!q.isExportSpecifier(i))continue;let s=nr(i.local),a=r.get(s)??[];if(a.length>0){let c=nr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=bi(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(q.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Ar(e.file,o.source.value),s=o.exported;if(s){let a=nr(s);for(let c of t.values())Lt(c.file,i)&&n.push({file:e.file,namespace:Ku(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Lt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Ku(e,t){return t?`${e}.${t}`:e}function Tr(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function bi(e,t,n){return!Tr(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function aA(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(!q.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Ar(e.file,i.source.value);for(let a of i.specifiers){if(q.isImportDefaultSpecifier(a)){let c=t.get(co({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Lt(u.file,s)&&Tr(u.namespace,"default"));for(let u of l){let d=bi(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(q.isImportSpecifier(a)){let c=nr(a.imported),l=[...t.values()].filter(d=>Lt(d.file,s)&&Tr(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(co({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(q.isImportNamespaceSpecifier(a))for(let c of t.values())Lt(c.file,s)&&r(a.local.name,{...c,namespace:Ku(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(q.isVariableDeclaration(i))for(let s of i.declarations){if(!q.isIdentifier(s.id)||!s.init)continue;let a=Pr(s.init);if(!a||!q.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(co));for(let d of c){let f=bi(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=co(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function co(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${Ia(e.file)}#${t}`}function nr(e){return q.isIdentifier(e)?e.name:e.value}function sy(e,t){for(let n of e.program.body){if(q.isExportDefaultDeclaration(n)){let o=n.declaration;if((q.isFunctionDeclaration(o)||q.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(q.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!q.isExportNamedDeclaration(n))continue;let r=n.declaration;if((q.isFunctionDeclaration(r)||q.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(q.isVariableDeclaration(r)){for(let o of r.declarations)if(q.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!q.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:q.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Xu(e){let t=cA(e),n=[],r=uy(e.ast,t);return sn(e.ast,{JSXElement(o){Lt(e.file,e.sourceFile)&&ka(o)===e.sourceComponent||my(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function ay(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function cy(e,t){let n=ay();return sn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function cA(e){let t=ay();return Lt(e.file,e.sourceFile)&&lA(t,cy(e.ast,e.sourceComponent)),sn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Ar(e.file,o),s=e.componentIdentities.filter(a=>Lt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(q.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),q.isImportDefaultSpecifier(a)){let l=s.filter(u=>Tr(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=ry(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(q.isImportSpecifier(a)){let l=q.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>Tr(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=ry(f,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(q.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)}}}}}),ly(e.ast,t),t}function lA(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 ly(e,t){sn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Pr(n.node.init);if(r){if(q.isIdentifier(n.node.id)){let o=wr(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Ju(t,i,o);return}if(q.isObjectPattern(n.node.id)){let o=wr(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&fy(n.node.id,o.namespaceMembers,t,n)}}}})}function uy(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return sn(e,{ReferencedIdentifier(r){if(n){r.stop();return}uA(r)||!r.isIdentifier()||!dy(r,t)||dA(r,t)||pA(r)||(n=!0,r.stop())}}),n}function uA(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 dy(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)&&wr(r.node,t,r)?r:null}function dA(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!ny(e,r))return!1;let o=dy(e,t);if(!o)return!1;if(Pr(r.node)===o.node)return!!wr(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&ny(e,a)&&!!wr(a.node,t,a)}function pA(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function ny(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function wr(e,t,n){let r=Pr(e);if(!r)return null;if(q.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(q.isObjectExpression(r))return fA(r,t,n);let o=Uu(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?py(s,o.slice(1).join(".")):null}function fA(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!q.isObjectProperty(i))continue;let s=Vu(i);if(!s||!q.isExpression(i.value)){q.isExpression(i.value)&&(o||=wr(i.value,t,n)!==null);continue}let a=wr(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 py(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 Ju(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 fy(e,t,n,r){for(let o of e.properties){if(q.isRestElement(o)){if(q.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Ju(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!q.isObjectProperty(o))continue;let i=Vu(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=py(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=q.isAssignmentPattern(o.value)?o.value.left:o.value;if(q.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Ju(n,c,s);continue}if(q.isObjectPattern(a)&&s.namespaceMembers.size>0){fy(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function ry(e,t){if(!Tr(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 my(e,t){let n=e.node.openingElement.name;if(q.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=gy(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 gy(e){if(q.isJSXIdentifier(e))return[e.name];if(q.isJSXMemberExpression(e)){let t=gy(e.object);return t?[...t,e.property.name]:null}return null}function ka(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()&&q.isIdentifier(n.node.id))return n.node.id.name}return null}function hy(e,t){let n=it(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Xu({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 Fe(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 Te(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function yn(e,t){let n=Te(e);return!!(n&&Dt(t,n))}function Dt(e,t){return t.start>=e.start&&t.end<=e.end}function Gt(e,t){let n=xe(e,Fe(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Ra(e,t)}function lo(e,t){let n=Te(t);return n?e.slice(n.start,n.end):""}function yy(e,t){return e.start===t.start&&e.end===t.end}function Ra(e,t){let n=null;return sn(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 Ca(e,t){return zu(e,t).length>0}function Na(e,t){let n=Te(e.node),r=Te(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()&&!mA(o,n,r)))return!0;o=o.parentPath}return!1}function mA(e,t,n){let r=Te(e.node.consequent);if(r&&Dt(r,t)&&!Dt(r,n))return!1;let o=e.node.alternate?Te(e.node.alternate):null;return!(o&&Dt(o,t)&&!Dt(o,n))}function zu(e,t){let n=Te(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=Te(o.node.consequent),a=Te(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()&&Hu(o.node.operator)){let s=Te(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 Hu(e){return e==="&&"||e==="||"||e==="??"}function xy(e,t){let n=Te(e.consequent);if(n&&Dt(n,t))return n;let r=Te(e.alternate);return r&&Dt(r,t)?r:null}function by(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=>ao(a.file)));if(!t.has(ao(e.sourceFile))||!t.has(ao(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(ao(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=sy(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=it(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=iy(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Xu({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!Lt(s.file,e.targetFile)||ka(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 EA}from"@vcp-dev/contracts";function _a(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 Ei();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Ei();let u=gA(a,l,o?.instanceCount);if(!u)return Ei();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"?Ei():{ok:!0,target:{kind:"jsx-attribute"}}}function Ei(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function gA(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 xn from"@babel/types";import{SiteEditSetPropsParamsSchema as hA}from"@vcp-dev/contracts";function Ey(e){let t=e.changes??(e.change?[e.change]:[]);if(!hA.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Si("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Si("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=$e(e.source,"value");if(!o.ok)return Si("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=xe(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Si("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?yA(r):xA(c.match.path.node,r.name);if(!l)return Si("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 yA(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function xA(e,t){let n=e.properties.filter(i=>xn.isObjectProperty(i)&&bA(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!xn.isExpression(r.value))return null;let o=gn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function bA(e){return xn.isIdentifier(e)?e.name:xn.isStringLiteral(e)?e.value:xn.isNumericLiteral(e)?String(e.value):null}function Si(e,t){return{ok:!1,errorCode:e,reason:t}}function Sy(e){if(e.change.name!=="className"&&e.change.name!=="class")return vi("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return vi("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return vi("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return vi("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 vi("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 vi(e,t){return{ok:!1,errorCode:e,reason:t}}async function Iy(e){let t=EA.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return rr("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 rr("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 SA(e,r);if(o){if(!o.ok)return rr("owner-plan-failed",o.reason);vy(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return rr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return rr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(kA(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=_a({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return rr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){Wu(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Ey({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return rr("repeat-target-failed",l.reason);vy(n,l.steps);continue}Wu(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:vA(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),IA(n)?rr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function SA(e,t){return t.name!=="className"&&t.name!=="class"?null:Sy({node:e.node,change:t,classNameSource:e.classNameSource})}function vA(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 IA(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 vy(e,t){for(let n of t)Wu(e,{...n,order:e.length})}function Wu(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 kA(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Gu(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Gu(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)=>Gu(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=>Gu(n[i],r[i]))}return!1}function rr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as po from"@babel/types";import*as oe from"@babel/types";function Yu(e,t,n){let r=Gt(t,n);return r?bn(e,r):null}function bn(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(!oe.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=lo(e,u.node),f=r.node.params.map(h=>lo(e,h)),g=Te(i.node),p=Te(r.node);return!d||f.some(h=>h.length===0)||!g||!p?null:{callStart:g.start,callEnd:g.end,callbackStart:p.start,callbackEnd:p.end,collectionExpression:d,callbackParams:f,mapOperator:oe.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Pa(u.node),callbackPath:r,collectionPath:u}}function Ii(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function RA(e,t){let n=Te(e.node);return n?CA(t).some(r=>{let o=Te(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function CA(e){let t=e.callbackPath.node.body;return oe.isBlockStatement(t)?or(t.body):ir(t)}function or(e){let t=[];for(let n of e){if(oe.isReturnStatement(n)){n.argument&&t.push(...ir(n.argument));continue}if(oe.isBlockStatement(n)){t.push(...or(n.body));continue}if(oe.isIfStatement(n)){let r=oe.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...or(r)),n.alternate){let o=oe.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...or(o))}continue}if(oe.isSwitchStatement(n)){for(let r of n.cases)t.push(...or(r.consequent));continue}oe.isTryStatement(n)&&(t.push(...or(n.block.body)),n.handler&&t.push(...or(n.handler.body.body)),n.finalizer&&t.push(...or(n.finalizer.body)))}return t}function ir(e){return oe.isJSXElement(e)?NA(e)?ky(e.children):[e]:oe.isJSXFragment(e)?ky(e.children):oe.isParenthesizedExpression(e)||oe.isTSAsExpression(e)||oe.isTSSatisfiesExpression(e)||oe.isTSNonNullExpression(e)||oe.isTSTypeAssertion(e)?ir(e.expression):oe.isConditionalExpression(e)?[...ir(e.consequent),...ir(e.alternate)]:oe.isLogicalExpression(e)&&Hu(e.operator)?ir(e.right):[]}function ky(e){return e.flatMap(t=>oe.isJSXElement(t)||oe.isJSXFragment(t)?ir(t):oe.isJSXExpressionContainer(t)&&(oe.isJSXElement(t.expression)||oe.isJSXFragment(t.expression)||oe.isConditionalExpression(t.expression)||oe.isLogicalExpression(t.expression))?ir(t.expression):[])}function NA(e){let t=e.openingElement.name;return oe.isJSXIdentifier(t)?t.name==="Fragment":oe.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Ry(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Pa(e){return!(oe.isIdentifier(e)||oe.isThisExpression(e)||oe.isMemberExpression(e)||oe.isOptionalMemberExpression(e)||oe.isCallExpression(e)||oe.isOptionalCallExpression(e))}function Cy(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(oe.isMemberExpression(n)||oe.isOptionalMemberExpression(n))&&oe.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function uo(e,t){let n=it(e);if(!n)return t.isRepeatItemRoot===!0;let r=xe(n,Fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ra(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=bn(e,o);return i?RA(o,i):t.isRepeatItemRoot===!0}function Ny(e,t){let n=it(e);if(!n)return!1;let r=xe(n,Fe(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Ra(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(oe.isMemberExpression(s)||oe.isOptionalMemberExpression(s))&&oe.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Me from"@babel/types";function Zu(e){if(Me.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Me.isJSXMemberExpression(e)){let t=e;for(;Me.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function _A(e,t){let n=Te(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||yn(a.path.node,n)||sr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Zu(i.node.name);s&&o(s,i)}}),[...r].sort()}function Qu(e,t,n){let r=it(e);if(!r)return{ok:!0};let o=xe(r,Fe(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=xe(r,Fe(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=Mo(o.match.path,i.match.path);if(Ca(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=_A(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function Py(e){let t=e;for(;Me.isTSQualifiedName(t);)t=t.left;return Me.isIdentifier(t)?t.name:null}function ki(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Aa(e){let t=[],n=r=>{if(r){if(Me.isIdentifier(r)){t.push(r.name);return}if(Me.isObjectPattern(r)){for(let o of r.properties){if(Me.isRestElement(o)){n(o.argument);continue}Me.isObjectProperty(o)&&n(o.value)}return}if(Me.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Me.isAssignmentPattern(r)){n(r.left);return}if(Me.isRestElement(r)){n(r.argument);return}Me.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function qu(e,t){let n=Te(e.node),r=Te(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=_y(e),i=_y(t);if(!o||!i||!yy(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=xy(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=Te(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())&&Cy(s)){let a=Te(s.node.body)??Te(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 _y(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?Te(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Me.isJSXElement(t.node.body)||Me.isJSXFragment(t.node.body)||Me.isConditionalExpression(t.node.body)||Me.isLogicalExpression(t.node.body)))return Te(t.node.body);t=t.parentPath}return null}function sr(e,t,n){return n.scope.getBinding(t)===e}function ed(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Ca(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=Te(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Aa(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||yn(u.path.node,o)||i.has(u.path.node)||sr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Zu(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function td(e,t,n){let r=Te(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Aa(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return ki(e,s=>{let a=s.scope.getBinding(s.node.name);!a||yn(a.path.node,r)||o.has(a.path.node)||sr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Ay(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Aa(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)||sr(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(po.isIdentifier(l))o(l.name,c);else{let u=Py(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function nd(e,t){let n=Te(e.node),r=new Set;return ki(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&yn(i.path.node,n)||sr(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 Ty(e){let t=[];for(let n of e.callbackPath.node.params){if(po.isIdentifier(n)){t.push(n.name);continue}if(po.isRestElement(n)&&po.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 wy(e,t){return{...e,callbackParams:t}}function rd(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ri(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 Oy(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 Or(e){return{file:e.file,component:e.component}}function PA(e){return e.target.kind==="node"?e.target.key:null}function AA(e){return"kind"in e&&e.kind==="page-composition"}function Oa(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Ta(e){return!AA(e)&&!Oa(e)}function cd(e,t){let n=La.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=La.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function od(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=fn(n,Fe(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function ud(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 TA(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function wA(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 id(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function OA(e){let t=oy(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=qu(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=FA({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Uy(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Pa(o):!0}}}function FA(e){let t=Te(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||yn(a.path.node,t))return;let c=MA(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=jA(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=LA(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=nd(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}sr(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:$A(e.source,t,[...n.values()])}}function LA(e,t){if(t.length===0)return e;let n=Uy(e);if(!n)return null;let r=Pa(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=DA(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function DA(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function MA(e,t,n){let r=BA(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=oo(t,o);if(!i)return null;let s=r?.range??Te(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function BA(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!yn(n.node,t)||n.node.computed||!_e.isIdentifier(n.node.property))return null;let r=Te(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function jA(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()&&_e.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=lo(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 $A(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 Uy(e){try{let n=Vy.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=_e.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&_e.isExpression(r)?r:null}catch{return null}}function VA(e){let t=Te(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||yn(s.path.node,t))return;let a=Fy(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Fy(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!UA(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 ki(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 UA(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 Fy(e,t,n){let r=KA(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Ar(t,i),a=i.startsWith(".")?cd(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=_e.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 KA(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function Ly(e,t,n,r){let o=zu(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=lo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=JA(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${zA(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function JA(e,t){return XA(e.node)?t:`(${t})`}function XA(e){return _e.isIdentifier(e)||_e.isThisExpression(e)||_e.isSuper(e)||_e.isMemberExpression(e)||_e.isOptionalMemberExpression(e)||_e.isCallExpression(e)||_e.isOptionalCallExpression(e)||_e.isBooleanLiteral(e)||_e.isNumericLiteral(e)||_e.isStringLiteral(e)||_e.isNullLiteral(e)||_e.isUnaryExpression(e)}function zA(e){return e.trim().startsWith("<")?e:`(${e})`}var HA={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 wa(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=HA[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 WA(e,t){for(let n of e.program.body){if(!_e.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>_e.isImportDefaultSpecifier(o));if(r&&_e.isImportDefaultSpecifier(r))return r.local.name}return null}function GA(e,t,n){for(let r of e.program.body){if(!_e.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>_e.isImportSpecifier(i)&&(_e.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&_e.isImportSpecifier(o))return o.local.name}return null}function Dy(e){let t=new Set;return sn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function My(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function YA(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=ud(e),o=it(t);if(n.exportName!=="default"){let a=o?GA(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?My(r,Dy(o)):r;return{localName:c,importStep:sd(e,c)}}if(!o)return{localName:r,importStep:sd(e,r)};let i=WA(o,n.source);if(i)return{localName:i};let s=My(r,Dy(o));return{localName:s,importStep:sd(e,s)}}function ZA(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??ud(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 QA(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?qA(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function qA(e){return Object.fromEntries(Object.entries(e).filter(t=>ld(t[1])))}function ld(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ld):typeof e=="object"?Object.values(e).every(ld):!1}function sd(e,t=ud(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 By(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 eT(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function fo(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function dd(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Ci(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:dd(e,t.slice(0,n)),index:r.index}}return null}function ad(e,t){return e.locator?e.collectionPathMap?.[t]?dd(e.locator,e.collectionPathMap[t]):Ci(e.locator)?nT(e.locator,rT(t,e.collectionIndexMap)):null:null}function tT(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:Ky(o,t)}function Ky(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=Ky(r,t);return o===void 0?void 0:{[n.name]:o}}function nT(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},dd(e,i)}return null}function rT(e,t){return t?.[e]??e}function jy(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 oT(e,t){return iT(e.root,t.root)&&aT(e.path??[],t.path??[])}function iT(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&&sT(e.sourceRange,t.sourceRange)}}function sT(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function aT(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 Fa=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:fo(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:fo(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:fo(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:fo(t.kind,t.params.kind)};let r=t;if(Oa(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Ta(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=By(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:fo(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:fo(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=PA(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):$y(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 $y(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:Fe(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?Iy({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 p=ad(u,i.instanceIndex);if(!p)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=p}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:Fe(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=ad(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:Fe(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=it(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=xe(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!TA(a.match.path))return{ok:!0,value:r};let c=wA(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=ad(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=it(this.graph.getFileContent(t));if(!o)return!1;let i=xe(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 f=Ci(d.locator);if(f)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:f.locator,index:f.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=Ri(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:Fe(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||hy(n,t)>1)return null;let r=cd(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(!Ta(n.params.position))return Oa(n.params.position)?{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"}:{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=Ri(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 f=this.getRepeatBackedTemplateStructureReason(r);if(f)return{ok:!1,errorCode:"unsupported-operation",reason:f};let g=Zh(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 p=wa(r,n.params.node);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let h=[],y=0,x=n.params.node.kind==="component-call"?YA(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&h.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),h.push({order:y++,file:r.file,type:"insert-child",parentLocator:Fe(r),node:{jsx:ZA(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?Fe(i):void 0}),this.buildPlan(t,n,h,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ta(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:QA(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(!Ta(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=Ci(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=tT(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"?jy(0,a.collectionIndexMap):jy(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=Ri(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 uo(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:")||Ny(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&&uo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=it(c);if(!l)return null;let u=Gt(l,r),d=Gt(l,o);if(!u||!d)return null;let f=bn(c,u),g=bn(c,d);if(!Ii(f,g))return null;if(a&&(s==="before"||s==="after")){let h=Gt(l,a),y=h?bn(c,h):null;if(!Ii(f,y))return null}if(Na(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=Qu(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Fe(r),targetParentLocator:Fe(o),placement:s,anchorLocator:a?Fe(a):void 0,selectionContext:Or(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:p.reason??`Cannot move node because it depends on bindings outside the target scope: ${p.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&uo(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=it(c);if(!l)return null;let u=Gt(l,r),d=Gt(l,o);if(!u||!d)return null;let f=bn(c,u);if(!f)return null;let g=bn(c,d);if(Ii(f,g))return null;if(g&&!Ry(g,f))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")){let b=Yu(c,l,a);if(g&&!Ii(g,b)||!g&&b)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 b=wa(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let p=od(this.graph,r);if(!p)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Na(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let h=Ly(c,u,d,p);for(let b of h.conditionPaths){let v=td(b,d,f);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${v.bindingNames.join(", ")}`}}let y=ed(u,d,f,{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 x=Ay(f,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=f;if(r.component!==o.component){let b=OA({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=nd(f.collectionPath,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${b.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Fe(r),targetParentLocator:Fe(o),placement:s,anchorLocator:a?Fe(a):void 0,repeatExpression:rd(E,h.sourceJsx),selectionContext:Or(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&uo(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=it(c),d=it(l);if(!u||!d)return null;let f=by({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let g=Gt(u,r),p=Gt(d,o);if(!g||!p)return null;let h=qu(f.callSitePath,p);if(!h.ok)return{ok:!1,errorCode:"unsupported-operation",reason:h.reason};let y=bn(c,g);if(!y)return null;if(bn(l,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&Yu(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 A=wa(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let E=od(this.graph,r);if(!E)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Na(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=Ly(c,g,p,E);for(let A of b.conditionPaths){let L=td(A,p,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 v=ed(g,p,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${v.bindingNames.join(", ")}`};let _=VA({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!_.ok)return{ok:!1,errorCode:"unsupported-operation",reason:_.reason};let P=Ty(y);if(!P.ok)return{ok:!1,errorCode:"unsupported-operation",reason:P.reason};let R=wy(y,P.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Fe(r),removeWhitespace:!0}];for(let A of _.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:A.moduleSpecifier,imports:A.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:Fe(o),expression:rd(R,b.sourceJsx),placement:s,anchorLocator:a?Fe(a):void 0,selectionContext:Or(o)}),this.buildPlan(t,n,N,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(Oa(n.params.target))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if("kind"in n.params.target&&n.params.target.kind==="source-sibling"){let b=n.params.target,v=this.graph.getNode(b.anchorKey);if(!v||r.file!==v.file||r.component!==v.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let _=this.graph.getFileVersion(r.file);if(n.documentVersion!==_)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${_})`};let P=this.graph.getFileContent(r.file),R=it(P),N=R?Gt(R,r):null,A=R?Gt(R,v):null,L=N?.parentPath,$=A?.parentPath;if(!N||!A||!L||!$||L.node!==$.node||!L.isJSXFragment()&&!(L.isJSXElement()&&Ke(L)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let U=L.node.loc;return U?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Fe(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:U.start.line,startColumn:U.start.column,endLine:U.end.line,endColumn:U.end.column}},placement:b.relation,anchorLocator:Fe(v),selectionContext:Or(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=By(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(eT(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 b=n.params.target.relation,v=i.anchorNode&&(b==="before"||b==="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:b,anchorSourceId:v?.kind==="external-entry"?v.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,f=this.graph.getTextProvenance?.(r.key,0)??null,g=Ri(r,c,f);if(g&&!id(g)&&!Oy(r,s,c,f))return{ok:!1,errorCode:"unsupported-operation",reason:g};if(r.isRepeatItemRoot&&d?.isRepeatItemRoot&&r.repeatOwnerKey&&r.repeatOwnerKey===d.repeatOwnerKey&&(u==="before"||u==="after")){let b=c,v=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&v?.kind==="value-binding"&&b.locator&&v.locator){let _=Ci(b.locator),P=Ci(v.locator);if(_&&P&&b.file===v.file&&oT(_.locator,P.locator)){let R=_.index,N=P.index,A=u==="before"?N-(R<N?1:0):N+(R<N?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:_.locator,fromIndex:R,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&uo(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let p=this.getRepeatBackedTemplateStructureReason(r),h=id(g)?g:p;if(h&&id(h)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let v=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(v)return v;let _=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return _||{ok:!1,errorCode:"unsupported-operation",reason:h}}if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};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 b=wa(s,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let x=Qu(this.graph.getFileContent(r.file),r,s);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move node because it depends on bindings outside the target scope: ${x.bindingNames.join(", ")}`};let E=[{order:0,file:r.file,type:"move-node",locator:Fe(r),targetParentLocator:Fe(s),placement:u,anchorLocator:d?Fe(d):void 0,selectionContext:Or(s)}];return this.buildPlan(t,n,E,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=od(this.graph,r)??`<${r.component} />`,f=Qh(u,r);if(!f.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:Fe(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:cd(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:p}]:[{kind:"named",imported:r.exportName,local:p===r.exportName?void 0:p}]};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:Fe(o),node:{jsx:d},placement:s,anchorLocator:a?Fe(a):void 0,selectionContext:Or(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Fe(o),node:{jsx:d},placement:s,anchorLocator:a?Fe(a):void 0,selectionContext:Or(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:ve(this.graph.getFileContent(a))}));return{ok:!0,plan:{operationId:t,kind:n.kind,target:n.target,documentVersion:n.documentVersion,steps:r,preSnapshots:s,validatedCapability:o}}}};function $y(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 hd from"@babel/generator";import{parse as vT}from"@babel/parser";import*as T from"@babel/types";import*as Sn from"@babel/types";import pd from"@babel/generator";import*as De from"@babel/types";var cT=typeof pd=="function"?pd:pd.default,lT=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,uT=/^((?:https?:)?\/\/)[^/@\s]+@/i,dT=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function Xy(e,t){let n=En(e.callee);if(!n)return null;if(n==="fetch")return fd(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Jy(r))return fd(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(Jy(r))return fd(e.arguments[0],r,t,["ky client contract"])}return null}function fd(e,t,n,r){if(!e||De.isSpreadElement(e)||De.isJSXNamespacedName(e))return gT(t,n,r,"missing url argument");let o=Ni(e);return{sourceKind:mT(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 Ni(e){if(De.isStringLiteral(e))return Da(e.value);if(De.isTemplateLiteral(e))return Da(pT(e));if(De.isBinaryExpression(e)&&e.operator==="+"){let t=Ni(e.left),n=Ni(e.right);return!t&&!n?void 0:Da(`${t??md(e.left)}${n??md(e.right)}`)}if(De.isMemberExpression(e)){let t=zy(e);if(t)return`env:${t}`}if(!(De.isCallExpression(e)&&En(e.callee)==="new URL")){if(De.isNewExpression(e)&&De.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!De.isSpreadElement(t)?Ni(t):void 0,o=n&&!De.isSpreadElement(n)?Ni(n):void 0;return o&&r?Da(`${o} + ${r}`):r??o}if(De.isIdentifier(e))return`:${e.name}`}}function pT(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+=md(r))}return t}function md(e){if(De.isIdentifier(e))return`:${e.name}`;if(De.isMemberExpression(e)){let t=zy(e);if(t)return`env:${t}`}return`:${fT(e)}`}function fT(e){return cT(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Da(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(uT,"$1<redacted>@").replace(dT,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?lT.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function mT(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 gT(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function Jy(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function zy(e){return!De.isMemberExpression(e.object)||!De.isIdentifier(e.object.object,{name:"process"})||!hT(e.object.property,"env")?null:De.isIdentifier(e.property)?e.property.name:De.isStringLiteral(e.property)?e.property.value:null}function hT(e,t){return De.isIdentifier(e)&&e.name===t}function En(e){if(De.isIdentifier(e))return e.name;if(De.isMemberExpression(e)){let t=En(e.object),n=De.isIdentifier(e.property)?e.property.name:De.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var yT=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),xT=new Set(["getConfig","submit"]);function Hy(e,t){let n=bT(En(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!yT.has(i))return null;let s=gd(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(!xT.has(i))return null;let s=gd(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=gd(e,0)??ET(e,0,"path")??"/cms/:path",s=ST(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 bT(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 Wy(e,t){let n=En(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 Gy(e){let t=En(e.callee);return typeof t=="string"&&t.startsWith("cms.field.")}function gd(e,t){let n=e.arguments[t];return Sn.isStringLiteral(n)?n.value:null}function ET(e,t,n){let r=e.arguments[t];if(!Sn.isObjectExpression(r))return null;for(let o of r.properties)if(Sn.isObjectProperty(o)&&!o.computed&&(Sn.isIdentifier(o.key)&&o.key.name===n||Sn.isStringLiteral(o.key)&&o.key.value===n)&&Sn.isStringLiteral(o.value))return o.value.value;return null}function ST(e){return/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1]??null}function Yy(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 f={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,p=g.get(a)??new Map,h=p.get(c)??new Map;return h.set(l,f),p.set(c,h),g.set(a,p),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}var O1=typeof hd=="function"?hd:hd.default,ix=new WeakMap;function sx(e){let t=new Map;return ix.set(t,new Map([...e].map(n=>[n.file,n]))),t}var IT={maxFunctionDepth:8,maxImportDepth:6},kT=new Set(["src","href","alt","poster","content","title","aria-label"]),Zy=new WeakMap;function RT(e,t,n){let r=Zy.get(t.fileCache);r||(r=new WeakMap,Zy.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 f={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(f);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let p=g.get(d.tag)??[];p.push(f),g.set(d.tag,p)}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 ax(e){if(!e.element.textSegments.some(s=>s.source)&&!(e.element.attributes??[]).some(s=>s.source&&qy(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=Ed(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...IT,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:vx(n,e.element.componentName)};await cx(e.element.componentName,e.graph,r);let o=[];o.push(...await PT(e.element,e.graph,r),...await AT(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await TT(s,e.element,e.graph,r);a&&o.push(ja(a,"text","children"))}for(let s of e.element.attributes??[]){let a=qy(s,e.element);if(!a)continue;let c=await px(s.source,e.element,e.graph,r);c&&o.push(ja(c,a,s.name))}let i=zT(o).sort(Ex);return{hasDynamicData:i.length>0,bindings:i}}async function cx(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 RT(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 CT(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 dx(l.sourceFile,n);if(!d)continue;let f=Va(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=vx(d,l.componentName),await cx(l.componentName,t,f);let g=await NT(l,f);for(let[p,h]of g){if(!h)continue;let y=a.get(p)??[];y.push(h),a.set(p,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=xx(u);d.length===1&&c.set(l,d[0])}_T(o,c,n)}var Qy=new WeakMap;function CT(e,t,n,r){let o=Qy.get(r.fileCache);return o||(o=Yy(),Qy.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>lx(e,t,n,r))}async function lx(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 dx(e,r))?.imports.get(t);if(!s||!St(s.source))return!1;let a=await Rx(e,s.source,r.exists);return a?a===n?!0:lx(a,s.importedName,n,r,o):!1}async function NT(e,t){let n=new Map,r=t.analysis.jsxElementsByRange.get(ux(e.sourceRange));if(r)for(let i of r.openingElement.attributes)!T.isJSXAttribute(i)||!T.isJSXIdentifier(i.name)||!T.isJSXExpressionContainer(i.value)||!T.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 et(s,t);a&&o.set(i,a)}return o}function ux(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function dx(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 Ed(e,r,t.fileCache)}function _T(e,t,n){if(T.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,bd(Object.fromEntries(t),n.file));return}if(T.isObjectPattern(e))for(let r of e.properties){if(!T.isObjectProperty(r)||r.computed||!T.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=T.isAssignmentPattern(r.value)?r.value.left:r.value;T.isIdentifier(i)&&n.paramSources.set(i.name,dt(o))}}function qy(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":kT.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function PT(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 $a(i.collectionSource,n);s&&r.push(ja(Fr(s),"repeat-region",i.collectionExpression))}return r}async function AT(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 $a(i.conditionSource,n);s&&r.push(ja(Fr(s),"conditional-region",i.conditionExpression))}return r}async function TT(e,t,n,r){return px(e.source,t,n,r)}async function px(e,t,n,r){let o=await wT(e,t,n,r);return o||$a(e,r)}async function wT(e,t,n,r){if(!e)return null;let o=OT(e.base,t,n);if(!o)return null;let i=await $a(o.collectionSource,r);return i?Ti(i,e.path,!0):null}function OT(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 $a(e,t){if(!e)return null;let n=await fx(e.base,t);return n?Ti(n,e.path,!1):null}async function fx(e,t){let n=t.paramSources.get(e);if(n)return dt(n);if(t.variableCache.has(e))return HT(t.variableCache.get(e)??null);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let r=await FT(e,t);if(r)return t.variableCache.set(e,dt(r)),t.resolvingVariables.delete(e),r;let o=t.scopeVariables?.get(e)??t.analysis.variables.get(e);if(o){let s=await et(o,t);return t.variableCache.set(e,s?dt(s):null),t.resolvingVariables.delete(e),s}let i=t.analysis.imports.get(e);if(i&&t.importDepth<t.options.maxImportDepth){let s=await Ix(i,t);if(s){let a=Va(s,t,{importDepth:t.importDepth+1}),c=kx(i,s);if(c){let d=(await Lr(c,[],a)).returnSource;return t.variableCache.set(e,d?dt(d):null),t.resolvingVariables.delete(e),d}let l=s.variables.get(i.importedName);if(l){let u=await et(l,a);return t.variableCache.set(e,u?dt(u):null),t.resolvingVariables.delete(e),u}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}async function FT(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 et(o,t);if(i)return i}return null}async function et(e,t){if(T.isIdentifier(e))return fx(e.name,t);if(T.isMemberExpression(e)||T.isOptionalMemberExpression(e)){let n=T.isMemberExpression(e)?Wy(e,{file:t.file}):null;if(n)return yx(n);let r=await LT(e,t);if(!r)return null;let o=JT(e);return Ti(r,o,!1)}if(T.isAwaitExpression(e))return T.isExpression(e.argument)?et(e.argument,t):null;if(T.isCallExpression(e))return mx(e,t);if(T.isObjectExpression(e)){let n=await gx(e,t);return Object.keys(n).length>0?bd(n,t.file):null}if(T.isConditionalExpression(e)){let n=await et(e.consequent,t),r=await et(e.alternate,t);return Ai(tx(n,r))}if(T.isLogicalExpression(e)){let n=await et(e.left,t),r=await et(e.right,t);return Ai(tx(n,r))}return T.isTSAsExpression(e)||T.isTSSatisfiesExpression(e)||T.isTSNonNullExpression(e)||T.isTypeCastExpression(e)||T.isParenthesizedExpression(e)?et(e.expression,t):null}async function LT(e,t){let n=e;for(;T.isMemberExpression(n)||T.isOptionalMemberExpression(n);)n=n.object;return T.isExpression(n)?et(n,t):null}async function mx(e,t){let n=Hy(e,{file:t.file,imports:t.analysis.imports});if(n)return yx(n);if(Gy(e)){let d=e.arguments[0];if(d&&T.isExpression(d))return Ai(await et(d,t))}let r=await DT(e,t);if(r)return r;let o=Xy(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 jT(e,t);if(i)return i;let s=await $T(e,t);if(s)return s;let a=await VT(e,t);if(a)return a;let c=await UT(e,t);if(c)return c;let l=[];for(let d of e.arguments)if(T.isExpression(d)){let f=await et(d,t);f&&l.push(f)}let u=xx(l);return u.length===1?Ai(u[0]):null}async function DT(e,t){let n=En(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=BT(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(T.isIdentifier(s)){let a=await Pi(s.name,t);if(a)return(await Lr(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!T.isObjectExpression(r))return Ma(t.file,`${n} without static options`);let o=MT(r,"queryFn");if(!o)return Ma(t.file,`${n} without queryFn`);if(T.isIdentifier(o)){let i=await Pi(o.name,t);return i?(await Lr(i.node,[],i.context)).returnSource:Ma(t.file,`${n} queryFn unresolved`)}return T.isArrowFunctionExpression(o)||T.isFunctionExpression(o)?(await Lr(o,[],t)).returnSource:T.isCallExpression(o)?mx(o,t):null}function MT(e,t){for(let n of e.properties){if(!T.isObjectProperty(n)||!T.isExpression(n.value))continue;if(hx(n)===t)return n.value}return null}function BT(e,t,n){return T.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 jT(e,t){if(!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted"].includes(n))return null;let r=T.isExpression(e.callee.object)?await et(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Fr(r);let o=e.arguments[0];if(T.isIdentifier(o)){let i=await Pi(o.name,t);if(!i)return Fr(r);let s=await Lr(i.node,[r],i.context);return{...Fr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(T.isArrowFunctionExpression(o)||T.isFunctionExpression(o)){let i=await Lr(o,[r],t);return{...Fr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Fr(r)}async function $T(e,t){return!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property,{name:"json"})||!T.isExpression(e.callee.object)?null:et(e.callee.object,t)}async function VT(e,t){return!T.isMemberExpression(e.callee)||!T.isIdentifier(e.callee.property,{name:"then"})||!T.isExpression(e.callee.object)?null:Ai(await et(e.callee.object,t))}async function UT(e,t){if(!T.isIdentifier(e.callee))return null;let n=await Pi(e.callee.name,t);if(!n)return null;let r=[];for(let i of e.arguments){if(!T.isExpression(i)){r.push(Ma(t.file,`unsupported argument for ${e.callee.name}`));continue}let s=await et(i,t);r.push(s)}return(await Lr(n.node,r,n.context)).returnSource}async function Pi(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 Ix(r,t);if(!o)return null;let i=Va(o,t,{importDepth:t.importDepth+1}),s=kx(r,o);return s?{node:s,context:i}:Pi(r.importedName,i)}async function Lr(e,t,n){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let r=Va(n.analysis,n,{functionDepth:n.functionDepth+1});r.scopeVariables=n.analysis.functionVariables.get(e),e.params.forEach((c,l)=>{let u=t[l];u&&yd(c,XT(u),r)});let o=KT(e),i=null,s,a=!1;for(let c of o){if(T.isObjectExpression(c)){s={...s??{},...await gx(c,r)},i=i??bd(s,n.file);continue}let l=await et(c,r);if(l){if(!i){i=l;continue}let u=xd(i,l);if(!u){a=!0,i=null;continue}i=u}}return{returnSource:a?null:i,...s?{objectReturnMap:s}:{}}}function yd(e,t,n){if(T.isIdentifier(e)){n.paramSources.set(e.name,dt(t));return}if(T.isAssignmentPattern(e)){yd(e.left,t,n);return}if(T.isObjectPattern(e))for(let r of e.properties){if(!T.isObjectProperty(r)||r.computed||!T.isIdentifier(r.key))continue;let o=Ti(t,[{kind:"property",name:r.key.name}],!0),i=T.isAssignmentPattern(r.value)?r.value.left:r.value;yd(i,o,n)}}function KT(e){if(T.isArrowFunctionExpression(e)&&T.isExpression(e.body))return[e.body];let t=[],n=e.body;if(!T.isBlockStatement(n))return t;let r=o=>{if(T.isFunction(o)&&o!==e)return;if(T.isReturnStatement(o)){o.argument&&T.isExpression(o.argument)&&t.push(o.argument);return}let i=T.VISITOR_KEYS[o.type];for(let s of i??[]){let a=o[s];if(Array.isArray(a))for(let c of a)T.isNode(c)&&r(c);else T.isNode(a)&&r(a)}};return r(n),t}async function gx(e,t){let n={};for(let r of e.properties){if(!T.isObjectProperty(r))continue;let o=hx(r);if(!o||!T.isExpression(r.value))continue;let i=await et(r.value,t);i&&(n[o]=i)}return n}function hx(e){return T.isIdentifier(e.key)&&!e.computed?e.key.name:T.isStringLiteral(e.key)?e.key.value:null}function JT(e){let t=[],n=e;for(;T.isMemberExpression(n)||T.isOptionalMemberExpression(n);){let r=n.property;n.computed?T.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):T.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):T.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return T.isIdentifier(n),t}function Ti(e,t,n){if(t.length===0)return dt(e);let r=t[0];if(r?.kind==="property"&&e.fieldMap?.[r.name])return Ti(e.fieldMap[r.name],t.slice(1),n);let o=dt(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=_i(o.valuePath,"data.items[]"),o.cmsFieldRoot=!1,o):i[0]==="fields"?(o.fieldPath=_i(o.fieldPath,i.slice(1).join(".")),o.cmsFieldRoot=!0,o):o.cmsFieldRoot||n||o.fieldMap?(o.fieldPath=_i(o.fieldPath,i.join(".")),o):(o.valuePath=_i(o.valuePath,ex(t)),o)}return o.valuePath=_i(o.valuePath,ex(t)),o}function ex(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function _i(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function yx(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 Fr(e){let t=dt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function XT(e){let t=dt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&(t.cmsFieldRoot=!1),t}function Ai(e){return e?{...dt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function tx(e,t){return e?t?xd(e,t):dt(e):t?dt(t):null}function xd(e,t){if(Ba(e)!==Ba(t))return null;let n=Sx(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function xx(e){let t=new Map;for(let n of e){let r=Ba(n),o=t.get(r);t.set(r,o?xd(o,n):dt(n))}return[...t.values()]}function Ba(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Ba(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 bd(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 Ma(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function ja(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 bx(e){let t=[...e].sort(Ex),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 zT(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 Ex(e,t){return nx(e.targetKind)-nx(t.targetKind)||Sx(e.confidence,t.confidence)||rx(e.sourceKind)-rx(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function nx(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function rx(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function Sx(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Ed(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=ix.get(n)?.get(e),i=o?.source===t?o.ast:vT(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=[];T.traverse(i,{enter(d){switch(T.isFunction(d)&&a.push(d),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=ux({startLine:f.start.line,startColumn:f.start.column,endLine:f.end.line,endColumn:f.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let f=d.source.value;for(let g of d.specifiers)T.isImportSpecifier(g)&&T.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:T.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):T.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:f,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 f=a.at(-1),g=f&&(T.isFunctionDeclaration(f)||T.isFunctionExpression(f)||T.isArrowFunctionExpression(f))?f:null,p=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,p);for(let h of mo(d.id))p.set(h,T.isExpression(d.init)?d.init:null);if(T.isArrayPattern(d.id)&&T.isCallExpression(d.init)&&En(d.init.callee)==="useState"){let[h,y]=d.id.elements;T.isIdentifier(h)&&T.isIdentifier(y)&&s.stateSetters.set(h.name,y.name)}T.isIdentifier(d.id)&&ox(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let f=d.declaration,g=d.source?.value;if(g)for(let p of d.specifiers){if(!T.isExportSpecifier(p))continue;let h=T.isIdentifier(p.exported)?p.exported.name:p.exported.value,y=p.local.name;s.imports.set(h,{source:g,importedName:y,localName:h,isDefault:y==="default"})}if(T.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),T.isVariableDeclaration(f))for(let p of f.declarations)T.isIdentifier(p.id)&&ox(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((T.isFunctionDeclaration(f)||T.isFunctionExpression(f)||T.isArrowFunctionExpression(f))&&s.functions.set("default",f),T.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){T.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,f)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(f),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let f=T.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&T.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)T.isIdentifier(p)&&p.name!==f&&l.has(p.name)&&g.add(p.name);for(let p of g)u(p,d)}return n.set(e,s),s}function mo(e){return!e||T.isVoidPattern(e)?[]:T.isIdentifier(e)?[e.name]:T.isObjectPattern(e)?e.properties.flatMap(t=>T.isObjectProperty(t)?mo(t.value):mo(t.argument)):T.isArrayPattern(e)?e.elements.flatMap(t=>t?mo(T.isRestElement(t)?t.argument:t):[]):T.isAssignmentPattern(e)?mo(e.left):T.isRestElement(e)?mo(e.argument):[]}function ox(e){return T.isFunctionExpression(e)||T.isArrowFunctionExpression(e)}function vx(e,t){let n=e.functions.get(t)??e.functions.get("default");return n?e.functionVariables.get(n):void 0}async function Ix(e,t){let n=await Rx(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Ed(n,r,t.fileCache)}function kx(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Rx(e,t,n){return St(t)?mr(e,t,n):null}function Va(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 HT(e){return e?dt(e):null}function dt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,dt(n)]))}:{}}}import*as vd from"@babel/parser";import Sd from"@babel/traverse";import*as ie from"@babel/types";import{classifySiteEditPropertyName as WT}from"@vcp-dev/contracts";var Id=typeof Sd=="function"?Sd:Sd.default;function kd(e){let t=WT(e.propertyName);if(t.owner!=="generic")return Mt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return Mt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return Mt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return Mt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=vd.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return Mt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=GT(r,e.element.sourceRange);if(!o)return Mt("repeat-not-found","The selected element is not inside a supported map repeat");if(!ie.isIdentifier(o.callback.params[0]))return Mt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=YT(r,o.collection,e.file,e.sources);if(!i)return Mt("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,x]of s.elements.entries()){if(!x||!ie.isObjectExpression(x)||!Tx(x))return Mt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let E=[{kind:"index",index:y}];l.push(E),u.push({kind:"value",root:a.root,path:E})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return Mt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return Mt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!ie.isObjectExpression(g))return Mt("unsafe-collection","Selected repeat item is not an object");let p=nw(e.element,e.propertyName),h=ew(g,e.propertyName);return h?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[f],sourceItemIndex:f,sourceItemPath:l[f],collectionIndexMap:Array.from({length:d},(y,x)=>x),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:tw(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:Mt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function GT(e,t){let n=[];return Id(e,{CallExpression(r){let o=Cx(r.node);o&&_x(o.callback,t)&&n.push({...o,span:Nx(r.node)})},OptionalCallExpression(r){let o=Cx(r.node);o&&_x(o.callback,t)&&n.push({...o,span:Nx(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function Cx(e){let t=e.callee;if(!ie.isMemberExpression(t)&&!ie.isOptionalMemberExpression(t)||t.computed||!ie.isIdentifier(t.property)||t.property.name!=="map"||!ie.isExpression(t.object))return null;let n=e.arguments[0];return!n||!ie.isExpression(n)||!ie.isArrowFunctionExpression(n)&&!ie.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function YT(e,t,n,r){let o=wi(t);if(o&&ie.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:Ox(o)}},sourceFile:n};if(!ie.isIdentifier(t))return null;let i=[];if(Id(e,{VariableDeclarator(s){ie.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=wi(i[0].init);return!s||!ie.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return ZT(e,t.name,n,r)}function ZT(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!ie.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!ie.isStringLiteral(o.source)||!ie.isImportSpecifier(i))continue;let s=qT(n,o.source.value,r);if(!s)return null;let a=ie.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=vd.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=QT(l,a),d=u?wi(u):null;return!d||!ie.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function QT(e,t){let n=null;return Id(e,{VariableDeclarator(r){n||!ie.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!ie.isExpression(r.node.init)||(n=r.node.init)}}),n}function qT(e,t,n){let r=un(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 wi(e){return ie.isParenthesizedExpression(e)?wi(e.expression):ie.isTSAsExpression(e)?Ax(e.typeAnnotation)?wi(e.expression):null:ie.isTSSatisfiesExpression(e)?null:e}function Ax(e){return ie.isTSTypeReference(e)&&ie.isIdentifier(e.typeName)&&e.typeName.name==="const"}function Tx(e){return e.properties.every(t=>!ie.isObjectProperty(t)||t.computed||!ie.isExpression(t.value)?!1:Ua(t.value))}function Ua(e){if(ie.isTSAsExpression(e)&&Ax(e.typeAnnotation))return Ua(e.expression);if(ie.isTSSatisfiesExpression(e))return!1;if(ie.isArrayExpression(e))return e.elements.every(n=>!n||ie.isSpreadElement(n)||!ie.isExpression(n)?!1:Ua(n));if(ie.isObjectExpression(e))return Tx(e);let t=gn(e);return t.status==="resolved"||t.status==="undefined"}function ew(e,t){let n=e.properties.filter(o=>ie.isObjectProperty(o)&&wx(o.key)===t);if(n.length>1)return null;let r=n[0];return r?ie.isExpression(r.value)?Ua(r.value)?"static":ie.isIdentifier(r.value)||ie.isMemberExpression(r.value)?"binding":null:null:"missing"}function tw(e,t){let n=e.properties.filter(o=>ie.isObjectProperty(o)&&wx(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!ie.isExpression(r.value)?{status:"undefined"}:gn(r.value)}function nw(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function wx(e){return ie.isIdentifier(e)?e.name:ie.isStringLiteral(e)?e.value:ie.isNumericLiteral(e)?String(e.value):null}function Ox(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 Nx(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function _x(e,t){let n=Ox(e);return Px(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&Px(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function Px(e,t,n,r){return e===n?t-r:e-n}function Mt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as $w}from"@vcp-dev/contracts";import*as le from"@babel/types";import Mi from"node:path";import*as W from"@babel/types";import*as jx from"@babel/parser";import Rd from"@babel/traverse";import*as me from"@babel/types";function Ja(e,t){let n=[],r=e;for(;me.isMemberExpression(r);){if(r.computed)if(me.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(me.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!me.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!me.isIdentifier(r)||r.name!==t?null:n}function Fx(e){if(me.isIdentifier(e))return{base:e.name,path:[]};if(!me.isMemberExpression(e))return null;let t=[],n=e;for(;me.isMemberExpression(n);){if(n.computed)if(me.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(me.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!me.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return me.isIdentifier(n)?{base:n.name,path:t}:null}function xt(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 vn=Symbol("not-closed-literal");function Ka(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:vn;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Ka(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||me.isSpreadElement(n))return vn;let r=Ka(n);if(r===vn)return vn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!me.isObjectProperty(n)||n.computed||n.shorthand||!me.isExpression(n.value))return vn;let r=me.isIdentifier(n.key)?n.key.name:me.isStringLiteral(n.key)?n.key.value:null;if(!r)return vn;let o=Ka(n.value);if(o===vn)return vn;t[r]=o}return t}default:return vn}}function Lx(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Ka(i);if(f!==vn)return f;if(!me.isTemplateLiteral(i)){if(me.isTSAsExpression(i)||me.isTSSatisfiesExpression(i)||me.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(me.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let p=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return p?.kind==="static"?p.value:void 0}if(me.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||me.isSpreadElement(p))return;let h=await r(p,s,a,c,l,u,d);if(h===void 0)return;g.push(h)}return g}if(me.isObjectExpression(i)){let g={};for(let p of i.properties){if(!me.isObjectProperty(p)||p.computed)return;let h=null;if(me.isIdentifier(p.key)?h=p.key.name:me.isStringLiteral(p.key)&&(h=p.key.value),!h)return;if(p.shorthand){if(!me.isIdentifier(p.value))return;let x=await r(p.value,s,a,c,l,u,d);if(x===void 0)return;g[h]=x;continue}if(!me.isExpression(p.value))return;let y=await r(p.value,s,a,c,l,u,d);y!==void 0&&(g[h]=y)}return g}if(me.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let p=s.getBinding(g.base);if(!p)return;let h=await t({currentFile:a,binding:p,readFile:c,exists:l,fileCache:u,visited:d});return!h||h.kind!=="static"?void 0:xt(h.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!me.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(me.isIdentifier(i))return{base:i.name,path:[]};if(!me.isMemberExpression(i))return null;let f=[],g=i;for(;me.isMemberExpression(g);){if(g.computed){let p=g.property;if(me.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(me.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let h=me.isExpression(p)?await n(p,s,a,c,l,u,d):void 0;if(typeof h=="string")f.unshift({kind:"property",name:h});else if(Number.isInteger(h))f.unshift({kind:"index",index:h});else return null}}else{if(!me.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return me.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var $x=typeof Rd=="function"?Rd:Rd.default,Dx=new WeakMap;function Vx(e){try{return jx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Xa(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=Vx(n);return e.set(t,{source:n,ast:o}),o}function za(e,t){return Cd(Oi(e).expressionRanges,t,!1)}function Ux(e,t){return Oi(e).exactExpressions.get(Kx(t))??null}function Ha(e,t){return Cd(Oi(e).jsxRanges,t,!0)}function Oi(e){let t=Dx.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return $x(e,{Expression(r){let o=r;n.expressions.push(o);let i=Mx(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=Kx(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=Mx(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(Bx),n.jsxRanges.sort(Bx),Dx.set(e,n),n}function Mx(e,t){let n=Fi(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function Kx(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function Bx(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Cd(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 Fi(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 go(e,t){if(t)return Nd(e,t);let n=Fx(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function Nd(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Li(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Oi(e).expressions){if(Nd(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function Jx(e,t,n,r){return Cd(Oi(e).expressionRanges,r,!0,o=>Nd(o.node,t)===n)}function ho(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Di(e){let t=null;if($x(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function an(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=Vx(o),s={source:o,ast:i};return n.set(e,s),s}function rw(e){return W.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:W.isMemberExpression(e.callee)&&W.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function ow(e){if(!W.isNewExpression(e)||!W.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!W.isIdentifier(e.arguments[0])||!W.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!W.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!W.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(W.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(W.isIfStatement(i)&&W.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=W.isIfStatement(i)?i.test:null,c=a&&W.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=W.isIfStatement(i)?W.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=W.isReturnStatement(s)?s.argument:null;return!a||!W.isLogicalExpression(a,{operator:"&&"})||!W.isBinaryExpression(a.left,{operator:"==="})||!W.isUnaryExpression(a.left.left,{operator:"typeof"})||!W.isIdentifier(a.left.left.argument,{name:r.name})||!W.isStringLiteral(a.left.right,{value:"string"})||!W.isUnaryExpression(c,{operator:"!"})||!W.isBinaryExpression(c.argument,{operator:"in"})||!W.isIdentifier(c.argument.left,{name:r.name})||!W.isIdentifier(c.argument.right,{name:n.name})||!W.isReturnStatement(l)||!W.isIfStatement(i)||i.alternate||!W.isCallExpression(u)||!W.isMemberExpression(u.callee)||!W.isIdentifier(u.callee.object,{name:"Reflect"})||!W.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!W.isIdentifier(u.arguments[0],{name:n.name})||!W.isIdentifier(u.arguments[1],{name:r.name})||!W.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function iw(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()||!W.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 Xx(e,t){let n=iw(e.path);if(!n)return null;let r=oo(e,t);return r?{...n,...r}:null}function zx(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function _d(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 Pd(e,t){for(let n of e.program.body){if(t==="default"&&W.isExportDefaultDeclaration(n))return W.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(W.isFunctionDeclaration(n.declaration)||W.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(W.isExportNamedDeclaration(n)){if(n.declaration){if(W.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(W.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((W.isFunctionDeclaration(n.declaration)||W.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((W.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&W.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 Hx(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=`${h}::${y.kind}::${y.identifier.name}`;if(v.has(_))return null;v.add(_);try{let P=await a({currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v});if(P)return P;if(y.path.isImportSpecifier()||y.path.isImportDefaultSpecifier())return await f({currentFile:h,binding:y,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:b,visited:v});if(y.kind==="param")return null;if(y.path.isVariableDeclarator()){let R=y.path.node.init;if(!R||!W.isExpression(R))return null;let N=ow(R);if(N&&!y.path.scope.getBinding("Proxy")&&!y.path.scope.getBinding("Reflect")){let $=y.path.scope.getBinding(N),U=$?await s({...p,binding:$}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let A=y.path.get("init");if(A&&!Array.isArray(A)&&A.isExpression()){let $=await t({currentFile:h,expressionPath:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if($)return $;if(A.isCallExpression()){let U=await n({currentFile:h,callPath:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(U)return U}}let L=await r(R,y.path.scope,h,x,E,b,v);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 R=y.path.parentPath.node.declaration;if(!W.isExpression(R))return null;let N=await r(R,y.path.scope,h,x,E,b,v);return N===void 0?null:{kind:"static",file:h,root:{kind:"binding",name:y.identifier.name},value:N,sourceKind:"binding"}}return null}finally{v.delete(_)}}async function a(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p;if(!y.path.isVariableDeclarator()||!y.path.get("id").isArrayPattern())return null;let _=y.path,P=_.node.init;if(!P||!W.isCallExpression(P))return null;let R=rw(P);if(!R||!W.isArrayPattern(_.node.id)||_.node.id.elements.findIndex(U=>W.isIdentifier(U)&&U.name===y.identifier.name)!==0)return null;let A=R==="useReducer"?1:0,L=P.arguments[A];if(!L||!W.isExpression(L))return null;let $=await r(L,_.scope,h,x,E,b,v);return $===void 0?null:{kind:"static",file:h,root:{kind:"hook-state",name:y.identifier.name,hook:R},value:$,sourceKind:"binding"}}async function c(p){let h=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!h||!h.constant||h.kind!=="param"||!p.graph)return null;let y=Xx(h,p.sourceInfo);if(!y)return null;let x=[...p.graph.elements.values()].filter(b=>zx(b,p.currentFile,y.componentName,y.exportName));if(!x.length)return null;let E=[];for(let b of x){if(b.sourceFile!==x[0].sourceFile||b.componentName!==x[0].componentName||b.attributeSpreads?.length)return null;let v=await an(b.sourceFile,p.readFile,p.fileCache),_=v.ast?Ha(v.ast,b.sourceRange):null;if(!_)return null;let P=_.parentPath;for(;P&&!P.isFunction();){if(P.isJSXElement()){let de=P.node.openingElement.name;if(!W.isJSXIdentifier(de)||!/^[a-z]/.test(de.name))return null}else if(!P.isJSXFragment()&&!P.isReturnStatement()&&!P.isBlockStatement())return null;P=P.parentPath}if(!P)return null;let R=_.get("openingElement").get("attributes").filter(de=>de.isJSXAttribute()&&W.isJSXIdentifier(de.node.name,{name:y.propName}));if(R.length!==1)return null;let N=R[0];if(!N?.isJSXAttribute())return null;let A=N.get("value"),L=A.isJSXExpressionContainer()?A.get("expression"):A;if(!L.isExpression())return null;let $=await r(L.node,L.scope,b.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),U=$===void 0?void 0:xt($,y.remainingPath);if(U===void 0)return null;E.push(U)}return E}async function l(p){let h=Xx(p.binding,p.sourceInfo);if(!h||!p.graph)return null;let y=[...p.graph.elements.values()].filter(R=>zx(R,p.currentFile,h.componentName,h.exportName));if(y.length!==1)return null;let x=y[0],E=x.attributes?.find(R=>R.name===h.propName);if(E&&!E.source){let R=await u({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(R)return _d(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile})}if(!E?.source){let R=await d({caller:x,propName:h.propName,remainingPath:h.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(R)return _d(R,{componentName:h.componentName,propName:h.propName,file:x.sourceFile});let N=Kh(p.binding,h.componentName,h.propName);if(!N||N.propName!==h.propName)return null;let A=await r(N.expressionPath.node,N.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(A===void 0)return null;let L=h.remainingPath;return L.length>0&&xt(A,L)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:h.propName},path:L,sourceKind:"binding",semanticKind:"component-prop",displayExpression:N.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:N.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let b=await an(x.sourceFile,p.readFile,p.fileCache);if(!b.ast)return null;let v=Jx(b.ast,b.source,E.source.expression,E.sourceRange)??Li(b.ast,b.source,E.source.expression);if(!v)return null;let _={...E.source,expression:ho(E.source.expression,h.remainingPath),path:[...E.source.path,...h.remainingPath]},P=await o({currentFile:x.sourceFile,expressionPath:v,sourceInfo:_,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});return P?_d(P.kind==="external"?P:{...P,displayExpression:_.expression},{componentName:h.componentName,propName:h.propName,file:x.sourceFile}):null}async function u(p){let h=await an(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let y=Ha(h.ast,p.caller.sourceRange);if(!y)return null;let x=y.get("openingElement").get("attributes").find(_=>_.isJSXAttribute()&&_.node.name.type==="JSXIdentifier"&&_.node.name.name===p.propName);if(!x?.isJSXAttribute())return null;let E=x.get("value"),b=E.isStringLiteral()?E:E.isJSXExpressionContainer()?E.get("expression"):null;if(!b?.isExpression())return null;let v=Fi(b.node);return v?{kind:"value",file:p.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:p.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:p.propName,editMode:"upstream",diagnostics:[]}:null}async function d(p){let h=await an(p.caller.sourceFile,p.readFile,p.fileCache);if(!h.ast)return null;let y=Ha(h.ast,p.caller.sourceRange);if(!y)return null;let x=y.get("openingElement");for(let E of x.get("attributes")){if(!E.isJSXSpreadAttribute())continue;let b=E.get("argument");if(!b.isExpression())continue;let v=await i({expression:b.node,scope:b.scope,source:h.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let _=[{kind:"property",name:p.propName},...p.remainingPath],P={...v,expression:ho(v.expression,_),path:[...v.path,..._]},R=await o({currentFile:p.caller.sourceFile,expressionPath:b,sourceInfo:P,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(R)return R.kind==="external"?R:{...R,displayExpression:P.expression}}return null}async function f(p){let{currentFile:h,binding:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=y.path.parentPath;if(!_||!_.isImportDeclaration())return null;let P=_.node.source.value;if(typeof P!="string")return null;let R=await mr(h,P,E);if(!R)return null;if(y.path.isImportDefaultSpecifier()){let de=await an(R,x,b),z=de.ast?Pd(de.ast,"default"):null,Q=await g({file:R,exportName:"default",readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return!Q||Q.kind!=="static"?null:{kind:"static",file:z?.kind==="default-expression"?Q.file:R,root:z?.kind==="default-expression"?Q.root:{kind:"default-export"},value:Q.value,sourceKind:"imported-binding"}}if(!y.path.isImportSpecifier())return null;let N=y.path.node.imported,A=W.isIdentifier(N)?N.name:N.value,L=await an(R,x,b),$=L.ast?Pd(L.ast,A):null,U=await g({file:R,exportName:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return U?U.kind==="external"?U:{kind:"static",file:$?.kind==="re-export"?U.file:R,root:$?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==$?.name?U.root:{kind:"named-export",name:A},value:U.value,sourceKind:"imported-binding"}:null}async function g(p){let{file:h,exportName:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=`export::${h}::${y}`;if(!v.has(_)){v.add(_);try{let P=await an(h,x,b);if(!P.ast)return;let R=Pd(P.ast,y);if(!R)return;if(R.kind==="default-expression"){let $=R.expression;if(!$||!W.isIdentifier($))return;let U=Di(P.ast).getBinding($.name);return U?await s({currentFile:h,binding:U,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v})??void 0:void 0}if(R.kind==="re-export"){if(!R.source||!R.name)return;let $=await mr(h,R.source,E);return $?g({...p,file:$,exportName:R.name}):void 0}let N=R.name;if(!N)return;let A=Di(P.ast).getBinding(N);return A?await s({currentFile:h,binding:A,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v})??void 0:void 0}finally{v.delete(_)}}}return{resolveExportValue:g,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as ne from"@babel/types";function Td(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=on(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!sw(s,r)?null:{callPath:s,basePath:i}}function sw(e,t){let n=e.node.callee;return!ne.isMemberExpression(n)||!ne.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function Zx(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Sa(r,t)}function Wx(e,t){return e?ne.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function Gx(e,t,n,r,o){let i=ne.isExpression(e.body)?e.body:e.body.body.find(a=>ne.isReturnStatement(a))?.argument;if(!i||!ne.isExpression(i))return;let s=Ad(i,t,n,r,o);return typeof s=="number"?s:void 0}function Ad(e,t,n,r,o){if(ne.isNumericLiteral(e)||ne.isStringLiteral(e)||ne.isBooleanLiteral(e))return e.value;if(ne.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(ne.isMemberExpression(e)){let i=Ja(e,t);if(i)return xt(r,i);let s=Ja(e,n);return s?xt(o,s):void 0}if(ne.isBinaryExpression(e)&&e.operator==="-"){let i=ne.isExpression(e.left)?Ad(e.left,t,n,r,o):void 0,s=ne.isExpression(e.right)?Ad(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function aw(e){if(ne.isExpression(e.body))return e.body;for(let t of e.body.body)if(ne.isReturnStatement(t)&&t.argument&&ne.isExpression(t.argument))return t.argument;return null}function cw(e,t,n){let r=Dr(e,t,n);return typeof r=="boolean"?r:void 0}function Dr(e,t,n){if(ne.isStringLiteral(e)||ne.isNumericLiteral(e)||ne.isBooleanLiteral(e))return e.value;if(ne.isNullLiteral(e))return null;if(ne.isIdentifier(e))return e.name===t?n:void 0;if(ne.isMemberExpression(e)){let r=Ja(e,t);return r?xt(n,r):void 0}if(ne.isUnaryExpression(e)&&e.operator==="!"){let r=Dr(e.argument,t,n);return r===void 0?void 0:!r}if(ne.isLogicalExpression(e)){let r=Dr(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Dr(e.right,t,n);if(e.operator==="||")return r||Dr(e.right,t,n)}if(ne.isBinaryExpression(e)){let r=ne.isExpression(e.left)?Dr(e.left,t,n):void 0,o=ne.isExpression(e.right)?Dr(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 Qx(e){let t=[],n=e;for(;ne.isMemberExpression(n)||ne.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(ne.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(ne.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(ne.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(ne.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return ne.isIdentifier(n)?{base:n.name,segments:t}:null}function qx(e){return e.some(t=>t.kind==="dynamic")}function Yx(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function eb(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 lw(e,t){let n=[],r=[];for(let o of t){let i=xt(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 tb(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(p){let{currentFile:h,callPath:y,readFile:x,exists:E,fileCache:b,visited:v}=p,_=y.node.callee;if(!ne.isMemberExpression(_)||!ne.isIdentifier(_.property)||_.property.name!=="map")return null;let P=y.get("callee");if(!P.isMemberExpression())return null;let R=P.get("object");if(Array.isArray(R)||!R.isExpression())return null;let N=await a({currentFile:h,expressionPath:R,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(p){let{currentFile:h,expressionPath:y,readFile:x,exists:E,fileCache:b,visited:v}=p;if(y.isIdentifier()){let _=y.scope.getBinding(y.node.name);if(!_)return null;let P=await t({currentFile:h,binding:_,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});return P?.kind==="static"?P:null}if(y.isCallExpression())return l({currentFile:h,callPath:y,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let _=y.get("expression");if(!Array.isArray(_)&&_.isExpression())return a({...p,expressionPath:_})}if(y.isArrayExpression()){let _=Fi(y.node);if(!_)return null;let P=await n(y.node,y.scope,h,x,E,b,v);return Array.isArray(P)?{kind:"static",file:h,root:{kind:"expression",sourceRange:_},value:P,sourceKind:"binding"}:null}if(y.isMemberExpression()){let _=await r({expression:y.node,scope:y.scope,currentFile:h,readFile:x,exists:E,fileCache:b,visited:v});if(!_)return null;let P=await o({currentFile:h,expressionPath:y,sourceInfo:_,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(!P||P.kind==="external")return null;let R=await c({currentFile:h,expressionPath:y,provenance:P,readFile:x,exists:E,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:b,visited:v});if(!R||R.kind!=="static")return null;if(P.collectionPathMap?.length){let A=lw(R.value,P.collectionPathMap);if(A)return{kind:"static",file:P.file,root:P.root,value:A.value,sourceKind:P.sourceKind,collectionPathMap:A.collectionPathMap}}let N=xt(R.value,P.path);return Array.isArray(N)?{kind:"static",file:P.file,root:P.root,value:N,sourceKind:P.sourceKind,pathPrefix:P.path,collectionIndexMap:P.collectionIndexMap,collectionPathMap:P.collectionPathMap}:null}return null}async function c(p){let{provenance:h}=p;if(h.root.kind==="binding"){let b=p.expressionPath.scope.getBinding(h.root.name);if(!b&&h.file!==p.currentFile){let v=await an(h.file,p.readFile,p.fileCache);b=v.ast?Di(v.ast).getBinding(h.root.name):void 0}return b?await t({currentFile:h.file,binding:b,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited}):null}if(h.root.kind!=="expression")return null;let y=await an(h.file,p.readFile,p.fileCache);if(!y.ast)return null;let x=Ux(y.ast,h.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,h.file,p.readFile,p.exists,p.fileCache,p.visited);return E===void 0?null:{kind:"static",file:h.file,root:h.root,value:E,sourceKind:h.sourceKind}}async function l(p){return await u(p)??await d(p)??await f(p)}async function u(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v]=h.node.arguments;if(!ne.isArrowFunctionExpression(v)&&!ne.isFunctionExpression(v))return null;let _=v.params[0];if(!ne.isIdentifier(_))return null;let P=aw(v);if(!P)return null;let R=[],N=[],A=[];for(let[L,$]of b.value.entries()){let U=cw(P,_.name,$);if(typeof U!="boolean")return null;if(U){R.push($),N.push(b.collectionIndexMap?.[L]??L);let de=b.collectionPathMap?.[L];de&&A.push(de)}}return{...b,value:R,pathPrefix:b.pathPrefix,collectionIndexMap:N,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v,_]=h.node.arguments,P=Wx(v,0),R=Wx(_,b.value.length);if(P===null||R===null)return null;let N=Math.max(0,P<0?b.value.length+P:P),A=Math.max(0,R<0?b.value.length+R:R),L=b.value.map((U,de)=>b.collectionIndexMap?.[de]??de).slice(N,A),$=b.collectionPathMap?.slice(N,A);return{...b,value:b.value.slice(N,A),pathPrefix:b.pathPrefix,collectionIndexMap:L,...$?{collectionPathMap:$}:{}}}async function f(p){let{callPath:h}=p,y=h.node.callee;if(!ne.isMemberExpression(y)||!ne.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=h.get("callee");if(!x.isMemberExpression())return null;let E=x.get("object");if(Array.isArray(E)||!E.isExpression())return null;let b=await a({currentFile:p.currentFile,expressionPath:E,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!b||!Array.isArray(b.value))return null;let[v]=h.node.arguments;if(!ne.isArrowFunctionExpression(v)&&!ne.isFunctionExpression(v))return null;let[_,P]=v.params;if(!ne.isIdentifier(_)||!ne.isIdentifier(P))return null;let R=b.value.map((A,L)=>({value:A,sourceIndex:b.collectionIndexMap?.[L]??L,originalIndex:L})),N=[...R];for(let A of R)for(let L of R)if(Gx(v,_.name,P.name,A.value,L.value)===void 0)return null;return N.sort((A,L)=>{let $=Gx(v,_.name,P.name,A.value,L.value)??0;return $===0?A.originalIndex-L.originalIndex:$}),{...b,value:N.map(A=>A.value),pathPrefix:b.pathPrefix,collectionIndexMap:N.map(A=>A.sourceIndex),...b.collectionPathMap?{collectionPathMap:N.map(A=>b.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let h=null,y=!1,x,E=[];for(let v of p.segments){if(v.kind!=="dynamic")continue;let _=await r({expression:v.expression,scope:p.expressionPath.scope,source:p.fileCache.get(p.currentFile)?.source,currentFile:p.currentFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!_)return null;let P=Td(p.expressionPath,_.base),R;if(P){y=!0;let N=await s({currentFile:p.currentFile,callPath:P.callPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(!N||!Array.isArray(N.value))return null;R=N.value.map((A,L)=>{let $=xt(N.value,[{kind:"index",index:L},...P.basePath,..._.path]);return Yx($)}),x??=N.collectionIndexMap}else{let N=await i({...p,sourceInfo:_});if(!N)return null;R=N.map(Yx)}if(R.some(N=>N===null)||h!==null&&h!==R.length)return null;h=R.length,E.push(R)}if(h===null||h===0)return null;let b=[];for(let v=0;v<h;v+=1){let _=[...p.rootPath],P=0;for(let R of p.segments){if(R.kind==="dynamic"){let N=E[P]?.[v];if(!N)return null;_.push(N),P+=1;continue}_.push({...R})}b.push(_)}return{sourceKind:y||h>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:uw,evaluateStaticExpression:Wa}=Lx({resolveBindingTarget:e=>Ga(e)}),{resolveRepeatCollectionTarget:dw,resolveCollectionCallTarget:pw,resolveDynamicMemberPathMap:fw}=tb({resolveBindingTarget:e=>Ga(e),evaluateStaticExpression:Wa,buildExpressionSourceInfo:In,resolveSourceInfoProvenance:Yt,resolveComponentPropValues:e=>hw(e)}),{resolveExportValue:mw,resolveComponentPropBinding:gw,resolveComponentPropValues:hw,resolveBindingTarget:Ga}=Hx({resolveExternalExpression:Bd,resolveCollectionCallTarget:pw,evaluateStaticExpression:Wa,resolveSourceInfoProvenance:Yt,buildExpressionSourceInfo:In});function ub(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var nb=new WeakMap;function yw(e){let t=nb.get(e);return t||(t=new WeakMap,nb.set(e,t)),t}function rb(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 db(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Xa(s,t,n);if(!a)return null;let c=za(a,r.sourceRange);if(!c)return null;let l=await In({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Ud({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 f?Fd(f,go(c.node,n)):null}let u=new Set,d=await jw({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?Fd(d,l.expression):null}async function yo(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Xa(i,t,n);if(!s)return null;let a=e.sourceRange?za(s,e.sourceRange):e.expression!==void 0?Li(s,n,e.expression):null;if(!a)return null;let c=Ya(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await In({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Yt({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 bb({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 Fd(d,e.expression??go(c.node,n))}async function Md(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Xa(i,t,n);if(!s)return Bt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?xw({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}):bw({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function In(e){if(le.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!le.isMemberExpression(e.expression))return null;let t=await uw(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:go(e.expression,e.source),base:t.base,path:t.path}:null}function Fd(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 xw(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=za(r,o.sourceRange),u=l?await In({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 ob(t,o.value);let f=await Ud({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 f?f.kind==="external"?lb(t,f):Dd(t,go(l.node,n),f):Ew({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Bt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Yt({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 f=Ld(l.node);if(f)return Bt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=Ld(g.path.node.init);if(p)return Bt(p.code,p.message)}return g?.path.isVariableDeclarator()&&le.isCallExpression(g.path.node.init)?Sw("unsupported-expression",hb(g.path.node.init,e.functionCallContracts)):Bt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?lb(t,d):Dd(t,u.expression,d)}async function bw(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Li(r,n,o.conditionExpression);if(!l)return Bt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Yt({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 Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Bt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Dd(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 ob(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 Ew(e){let t=await fb(e);if(t.length===0)return Bt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(vw(e.expression))return pb(t);if(gb(e.expression))return Bt("unsupported-expression","i18n helpers require a static message id string");if(le.isMemberExpression(e.expression)&&e.expression.computed&&!le.isNumericLiteral(e.expression.property)&&!le.isStringLiteral(e.expression.property))return Bt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Bt(n.code,n.message)}function Bt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function Sw(e,t){return pb([{code:e,message:t}])}function pb(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function vw(e){return le.isCallExpression(e)||le.isConditionalExpression(e)||le.isLogicalExpression(e)||le.isBinaryExpression(e)}function Bi(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 fb(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=Ld(t);if(l)return[l];if(le.isCallExpression(t))return[{code:"unsupported-expression",message:hb(t,c)}];if(le.isMemberExpression(t)&&t.computed){let u=t.property;if(!le.isNumericLiteral(u)&&!le.isStringLiteral(u)){if(!le.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await Wa(u,n,r,o,i,s,a);if(typeof f!="string"&&!Number.isInteger(f))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return le.isBinaryExpression(t)?Bi([...await wd(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):le.isLogicalExpression(t)?Bi([...await wd(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"}]):le.isConditionalExpression(t)?Bi([...await wd(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 Ld(e){return gb(e)?ib("i18n helpers require a static message id string"):Nw(e)?ib("CMS helpers require static entry id and field path string arguments"):null}async function wd(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await fb({...t,expression:o}));return r}function Iw(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:[kw(e.sourceType)]}}async function Bd(e){for(let n of Tw){if(!sb(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return cb(ab(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(!sb(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return cb(ab(r),e.externalAdapters)}return null}function kw(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function Rw(e){return{code:"external-source-readonly",message:e}}function ib(e){return{code:"unsupported-expression",message:e}}function jd(e){return!e||!le.isCallExpression(e)?null:le.isIdentifier(e.callee)?e.callee.name:le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&le.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function sb(e,t){if(!t||t.length===0)return!0;let n=jd(e.node);return n?t.includes(n):!1}function ab(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Bi(e.diagnostics??[])}:{match:e,diagnostics:[]}}function cb(e,t){let n=Iw(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:Bi([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function Cw(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!le.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!le.isStringLiteral(n)||!le.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 Nw(e){return!!e&&le.isCallExpression(e)&&le.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!le.isStringLiteral(e.arguments[0])||!le.isStringLiteral(e.arguments[1]))}function mb(e){if(!(!e||!le.isCallExpression(e))){if(le.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&le.isStringLiteral(t)?t.value:null}if(le.isMemberExpression(e.callee)&&!e.callee.computed&&le.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&le.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!le.isObjectExpression(t))return null;for(let n of t.properties)if(le.isObjectProperty(n)&&!n.computed&&(le.isIdentifier(n.key)&&n.key.name==="id"||le.isStringLiteral(n.key)&&n.key.value==="id")&&le.isStringLiteral(n.value))return n.value.value;return null}}}function gb(e){return mb(e)===null}async function _w(e,t,n){let r=new Set,o=Mi.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Mi.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"]:[Mi.posix.join(i,"locales"),Mi.posix.join(i,"messages")];for(let a of s){let c=Mi.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function Pw(e){let t=mb(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await _w(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function Aw(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!le.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!le.isExpression(n))return null;let o=await Wa(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:[Rw("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var Tw=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>Cw(e)},{helperNames:["apiField"],resolve:e=>Aw(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>Pw({currentFile:e,expressionPath:t,exists:n})}];function $d(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function lb(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 Dd(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=Bw(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 ww=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function Vd(e,t){let n=[...ww,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function hb(e,t){let n=e.callee;return le.isIdentifier(n)&&Vd(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 Ud(e){let t=await Bd(e);if(t)return t;let n=await yb({...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 In({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 Yt({...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 Dw(e)}async function yb(e){let t=await cn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Ya(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:$d(t.provenance)}async function cn(e){let t=Ya(e.expressionPath),n=Lw(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 In({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 Yt({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 In({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 Yt({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 cn({...e,expressionPath:r,allowComposed:!0}),a=await cn({...e,expressionPath:o,allowComposed:!1}),c=await cn({...e,expressionPath:i,allowComposed:!1});return Od(s,a,c)}if(t.isCallExpression())return Ow({...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 cn({...e,expressionPath:r,allowComposed:!0}),s=await cn({...e,expressionPath:o,allowComposed:!0});return Od(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 cn({...e,expressionPath:r,allowComposed:!0}),s=await cn({...e,expressionPath:o,allowComposed:!0});return Od(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:cn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Ya(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 Ow(e){let t=jd(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:cn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(le.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:cn({...e,expressionPath:o,allowComposed:!1})}}return null}function Od(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!Fw(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function Fw(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 Lw(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function Dw(e){if(!e.expressionPath.isCallExpression())return null;let t=jd(e.expressionPath.node);if(!t)return null;let n=Vd(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 xb({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?$d(i):null}async function xb(e){let t=await Bd({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 In({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 Yt({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 Ud({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 Mw(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!le.isCallExpression(t))return null;let n=t.callee;if(!le.isIdentifier(n))return null;let r=Vd(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 xb({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?$d(a):null}function Bw(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=ho(t,e.path);return{sourceId:o,displayPath:o}}async function jw(e){let t=e.segment.source;return t?Yt({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 Yt(e){let t=e.sourceInfo,n=Td(e.expressionPath,t.base);if(n){let l=await dw({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=Zx(n.callPath,[...n.basePath,...t.path]);return xi(h)?rb(e.currentFile,h.sourceId,h.displayPath):null}let u=eb(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,f=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return xt(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??f,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 mr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await mw({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(!f||f.kind==="external")return null;let g=t.path.slice(1);return xt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Vh(r);if(o){let l=o.expressionPath,u=await In({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 Yt({...e,expressionPath:l,sourceInfo:{...u,expression:ho(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 f=await bb({...e,expressionPath:Ya(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await yb({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 gw({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 Mw({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=ba(r,t.path,yw(e.fileCache));if(xi(s))return rb(e.currentFile,s.sourceId,s.displayPath);let a=await Ga({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:xt(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 bb(e){let t=Qx(e.expressionPath.node);if(!t||!qx(t.segments))return null;let n=await Yt({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 fw({...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 Ga({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>xt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:go(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function Eb(e){let t=$w(e.propertyName);if(t.owner==="blocked")return ar(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return ar(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 ar("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 Uw(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 ar("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}:ar("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?ar("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):Vw(e,s.attribute)}async function Vw(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await yo({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}}:ar("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 yo({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"?ar("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 Uw(e,t){let n=t.source?.expression;if(!n)return;let r=await yo({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:Kw(r,e.propertyName)}}function Kw(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 ar(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function Sb(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(Mr(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=>Hw(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>Jw({...r,graph:e},n)}function Jw(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=zw(n,r,o,t),a=s?.tag??(Mr(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=Gw(s),u=Yw(n,r,o,i,s),d=Xw(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:Ww(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:Zw(d),alternativeStrategies:Qw(d)}}function Xw(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Kd(e,n)?"instance":!Mr(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function zw(e,t,n,r){if(Mr(t.tag))return t;let o=Kd(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function Hw(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function Ww(e,t){return Mr(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function Gw(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=Kd(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&&Mr(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Kd(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Mr(r.tag))return r;n=r.parentKey}return null}function Mr(e){return/^[A-Z]/.test(e)}function Zw(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function Qw(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function kb(e){let t=e.isRepeat??(e.graph?aO(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=sO(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>qw({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:cO(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 qw(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=eO(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:_a({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=tO(t,n,l,e.isRepeat),d=c?oO(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?rO(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",h=iO(t,n,r);if(f.length===0&&h.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&h.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:p,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:h}}function eO(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 tO(e,t,n,r){return n?vb(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:vb(nO(e))}function nO(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 vb(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function rO(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 oO(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:Ib({...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:Ib(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function iO(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 sO(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function aO(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 Ib(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 cO(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 lO(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var uO=160;function Rb(e,t,n,r={}){let o=Hr(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 Cb(e,t,n,r,o,i,s,a,c,l,u){let d=Hr(t),f=t.elements.get(e),g=n.nodes.get(e),p=r.get(e);if(!f||!g||!p)throw new Error(`Node not found: ${e}`);let h=Tb(f.textSegments,s),y=wb(e,t,f,p,h),x=h?mO(h):void 0,E=gO(i,h),b=f.textSegments.map(R=>({index:R.index,value:R.value,editable:Ob(R,p,s?.get(R.index)??null),source:o.get(R.index)??null})),v=Pb(f,t),_=f.childKeys.map(R=>{let N=t.elements.get(R);return N?{key:R,tag:N.tag,label:N.tag}:null}).filter(R=>R!==null),P=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let N of R.childKeys){if(N===e)continue;let A=t.elements.get(N);A&&P.push({key:N,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:_b(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:v,children:_,siblings:P}}function Nb(e,t,n,r,o,i,s,a){let c=Hr(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 f=Tb(l.textSegments,i),g=dO(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:_b(l),label:l.tag,capabilities:wb(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(p=>({code:p.code,message:p.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(p=>{let h=o.get(p.index);return{index:p.index,editable:Ob(p,d,i?.get(p.index)??null),source:h?{kind:h.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:Pb(l,t)}}function dO(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 _b(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:pO(e.sourceRange),structuralPath:e.identity.structuralPath,...fO(e.textSegments)}}function Pb(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 pO(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function fO(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,uO)}:{}}function Ab(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 Tb(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function wb(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&&Fb(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 Ob(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Fb(n.editMode):!0}function Fb(e){return e==="direct"||e==="proxy"||e==="upstream"}function mO(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 gO(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}:lO(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 Jd=["set-class-name-source","apply-style-draft"];function Lb(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Jd,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:Jd,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Jd}}import Db from"node:path";function zd(){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 Bb(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=bO(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 Za(e){let t=()=>hO(e);return e.mutex?e.mutex.runExclusive(t):t()}async function hO(e){let t=await Bb(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=yO(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 Xd({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 Xd({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 Xd({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 Mb("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Mb("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 yO(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 Xd(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:xO(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 Mb(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function xO(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 bO(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)||Db.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=Db.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 EO=50,SO=8*1024*1024;function Ub(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??EO),s=Math.max(0,t.maxUndoBytes??SO);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let N=[...R.steps].sort((z,Q)=>z.order-Q.order),A=N.filter(z=>z.type!=="invoke-external-adapter");if(A.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let L=new Set(A.map(z=>z.file)),$=await E(L),U=new Map($.map(z=>[z.file,z.exists===!1?"":z.content])),de;for(let z of A){let Q=Vb(z,U.get(z.file)??"");if(!Q.ok)return{ok:!1,errorCode:Q.errorCode,reason:Q.reason};U.set(z.file,Q.source),de=Q.selectionRef??de}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...U].map(([z,Q])=>({operation:"upsert",file:z,content:Q,baseContentHash:$.find(ke=>ke.file===z)?.sha256??null}))},...de?{selectionRef:de}:{}}}async function c(R){let N=[...R.steps].sort((ke,ct)=>ke.order-ct.order),A=N.filter(ke=>ke.type!=="invoke-external-adapter"),L=N.filter(ke=>ke.type==="invoke-external-adapter"),$=new Set(A.map(ke=>ke.file));if(A.length>0&&L.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(A.length===0)return y(R,L);let U=await E($),de=new Map;for(let ke of U)de.set(ke.file,ke.exists===!1?"":ke.content);let z;for(let ke of A){let ct=de.get(ke.file)??"",lt=Vb(ke,ct);if(!lt.ok)return{ok:!1,operationId:R.operationId,errorCode:lt.errorCode,reason:lt.reason,rolledBack:!1};de.set(ke.file,lt.source),lt.selectionRef&&(z=lt.selectionRef)}let Q=await v([...de].map(([ke,ct])=>({file:ke,content:ct,exists:!0,version:0,sha256:ve(ct)})),U);return Q.ok===!1?{ok:!1,operationId:R.operationId,errorCode:Q.rolledBack?"writeback-failed":"rollback-failed",reason:Q.reason,rolledBack:Q.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:U,postSnapshots:Q.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...Q.snapshots.map(ke=>ke.version)),affectedFiles:[...$],...z?{selectionRef:z}:{}})}async function l(R){let N=new Set(R.edits.map(Q=>Q.file)),A=await E(N),L=x(R,A);if(L)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:L.reason,affectedFiles:[L.file],rolledBack:!1};let $=new Map(A.map(Q=>[Q.file,Q])),U=R.edits.find(Q=>Q.operation==="create-only"&&$.get(Q.file)?.exists!==!1);if(U)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${U.file}`,affectedFiles:[U.file],rolledBack:!1};let de=R.edits.map(Q=>Q.operation==="delete"?{file:Q.file,content:"",exists:!1,version:0}:{file:Q.file,content:Q.content,exists:!0,version:0,sha256:ve(Q.content)}),z=await v(de,A,new Set(R.edits.filter(Q=>Q.operation==="create-only").map(Q=>Q.file)));return z.ok===!1?{ok:!1,operationId:R.operationId,errorCode:z.rolledBack?"writeback-failed":"rollback-failed",reason:z.reason,rolledBack:z.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:A,postSnapshots:z.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...z.snapshots.map(Q=>Q.version)),affectedFiles:[...N]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await v(R.preSnapshots,R.postSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:R.preSnapshots.map(A=>A.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await v(R.postSnapshots,R.preSnapshots);return N.ok===!1?{ok:!1,operationId:R.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:R.postSnapshots.map(A=>A.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((R,N)=>R+p(N),0)}function p(R){return h(R.preSnapshots)+h(R.postSnapshots)}function h(R){return R.reduce((N,A)=>N+A.file.length+A.content.length,0)}async function y(R,N){let A=[];for(let L of N){let $=L.capability??"write-text",U=o.find(z=>z.sourceType===L.sourceType&&(L.adapterId===void 0||z.adapterId===L.adapterId)&&(z.capabilities===void 0||z.capabilities.includes($)));if(!U)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${L.sourceType}`,rolledBack:!1};let de=await U.execute(L);if(!de.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:de.reason??`External adapter failed for ${L.sourceType}`,rolledBack:!1};A.push(L.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:A}}function x(R,N){if(R.conflictPolicy!=="compare-and-swap")return null;let A=new Map(N.map(L=>[L.file,L]));for(let L of R.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 $=A.get(L.file),U=L.baseContentHash;if(U===null){if($?.exists!==!1)return{file:L.file,reason:`Source file ${L.file} was created or changed before save.`};continue}if(!U)return{file:L.file,reason:`Source file ${L.file} is missing baseContentHash. Reopen the file before saving.`};if($?.exists===!1||$?.sha256!==U)return{file:L.file,reason:`Source file ${L.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let N=[];for(let A of R)N.push(await b(A));return N}async function b(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(R)),L=await e.readFile(R);return{file:R,content:L,version:A,exists:!0,sha256:ve(L)}}async function v(R,N,A=new Set){let L=[];try{for(let $ of R){if(A.has($.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive($.file,$.content)}else await _($);let U=e.bumpVersion($.file);L.push($.file),$.version=U}}catch($){let U=await P(N.filter(z=>L.includes(z.file)));if(U.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${U.failedFiles.join(", ")}: ${$b($)}`,rolledBack:!1,instanceConflict:jb($)};let de=jb($);return{ok:!1,reason:`${de?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${$b($)}`,rolledBack:!0,instanceConflict:de}}return{ok:!0,snapshots:R.map(vO)}}async function _(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function P(R){let N=[];for(let A of R)try{await _(A),e.bumpVersion(A.file)}catch{N.push(A.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function jb(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function vO(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:ve(e.content)}:{}}}function $b(e){return e instanceof Error?e.message:String(e)}function Vb(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 pt(Jt({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return pt(zr({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return pt(vr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return pt(Kt({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return pt(gs({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return pt(jo({source:t,locator:e.locator,next:e.value}));case"update-array-item":return pt(jo({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return pt(Ss({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return pt(hs({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return pt(vs({source:t,locator:e.locator,index:e.index}));case"move-array-item":return pt(Is({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return pt(kr({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return pt(ys({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 IO(e,t);case"set-property-changes":return pt(xs({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return pt(bs({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return pt(Es({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return pt(Rs({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function IO(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!um(n.newAttrRaw))return{ok:!1,reason:"newAttrRaw must be a valid JSX className attribute.",errorCode:"invalid-params"};let r=n.oldAttrRange!==null&&n.oldAttrRaw!==null,o=n.openingElementRange.start,i=n.openingElementRange.end,s=t.slice(o,i);if(!(Number.isInteger(o)&&Number.isInteger(i)&&o>=0&&i>o&&i<=t.length&&s.startsWith("<")&&s.endsWith(">")&&!s.startsWith("</")&&(n.oldAttrRange===null||n.oldAttrRange.start>=o&&n.oldAttrRange.end<=i)))return{ok:!1,reason:"The opening element range changed before className save.",errorCode:"stale-version"};if(!r&&n.expectedVersion.contentHash!==ve(t))return{ok:!1,reason:"The source file changed before className save.",errorCode:"stale-version"};if(n.oldAttrRange){if(t.slice(n.oldAttrRange.start,n.oldAttrRange.end)!==n.oldAttrRaw)return{ok:!1,reason:"The className attribute changed before save.",errorCode:"stale-version"}}else if(n.oldAttrRaw!==null)return{ok:!1,reason:"The className attribute range no longer matches.",errorCode:"stale-version"};return{ok:!0,source:lm({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function pt(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 Qa,SiteEditCompositionContextSchema as kO,SiteEditCompositionSelectorSchema as RO}from"@vcp-dev/contracts";var bt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function Kb(e,t){throw new bt("INVALID_COMPOSITION",e,{value:t})}function qa(e){let t=kO.safeParse(e);return t.success?t.data:Kb("Invalid SiteEditCompositionContext.",e)}function Jb(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=qa(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new bt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Qa(u);if(n.has(d))throw new bt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new bt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:f});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 bt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=qa(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new bt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Qa(u);if(!n.has(d))throw new bt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new bt("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=RO.safeParse(l);if(!u.success)return Kb("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:f})=>f.routeId===u.data.routeId&&(u.data.templateId===void 0?f.effectiveTemplateId===void 0:f.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new bt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new bt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=qa(l),d=Qa(u),f=n.get(d);if(!f)throw new bt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=qa(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new bt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Qa(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new bt("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 bt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let p={context:u,entryFile:l.entryFile,key:d};return t.push(p),n.set(d,p),p}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(f=>f.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 Hd(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 Xb(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 CO,stripSiteEditRepeatInstanceKeys as zb}from"@vcp-dev/contracts";function Hb(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=zb(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 NO(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 ec(e){return e?.map(t=>({...t}))}function Wd(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=ec(e.collectionPathMap?.[t])??ec(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:ec(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>ec(o)??[])}}function Wb(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let p of g.childKeys)r.add(p);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,p)=>CO(g,p),c=(g,p,h)=>{let y=o.get(g);if(!y)return a(g,h);let x=a(g,h),E={...y,key:x,parentKey:p,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(b=>l(b,h,x)),x},l=(g,p,h)=>{if(!r.has(g))return[c(g,h,p)];let y=d(g,p),x=[];for(let E=0;E<y;E+=1)x.push(c(g,h,[...p,E]));return x},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 p=d(g,[]);for(let h=0;h<p;h+=1)c(g,null,[h])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,p){let h=new Set;for(let y of f(g)){let x=n.get(y);if(x){for(let E of[...x.textTargets.values(),...x.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let b of _O(E))b.length<=p.length||PO(b,p)&&h.add(b[p.length])}}return h.size>0?h.size:NO(n.get(g))}function f(g){let p=s.get(g);if(p)return p;let h=[g],y=o.get(g);for(let x of y?.childKeys??[])h.push(...f(x));return s.set(g,h),h}}function Gb(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function Yb(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((zb(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function _O(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 PO(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 Zb(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 Qb(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 qb(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function AO(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ji=class extends Error{constructor(t){let n=t.map(qb);super(AO(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function eE(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ji?{routeId:e,message:n,diagnostics:t.diagnostics.map(qb)}:{routeId:e,message:n}}function Gd(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Yd(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function xo(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function tE(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Zd(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 nE(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 BO=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,jO=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],rE=32,Qd=256;function $O(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var oE={maxEntries:50,maxBytes:8*1024*1024};function VO(){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 _s(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 iE(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 UO(){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>oE.maxEntries||KO(e)>oE.maxBytes;)e.shift()}}function KO(e){return e.reduce((t,n)=>t+JO(n),0)}function JO(e){return sE(e.preSnapshots)+sE(e.postSnapshots)+XO(e.provenance)}function XO(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function sE(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function aE(e,t){return{key:wO(e),composition:e,routeId:e.routeId,entryFile:t,graph:null,topology:null,capabilities:null,document:null,pageBlockIndex: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 nc=class extends Error{constructor(t){super(t.reason),this.result=t}},Br=class extends Error{constructor(t){super(Gd(t)),this.failedRoutes=t}};function cE(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=At(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(At(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function zO(e,t,n){if(!n)return;let r=At(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 HO=/\.(?:[cm]?[jt]sx?)$/i,WO=/\.json$/i,GO=/\.(?:css|scss|sass)$/i,YO=/\.mdx$/i,ZO=/\.ya?ml$/i;function QO(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 qO(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function eF(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=mE(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(tF(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 tF(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function mE(e){return Array.isArray(e)?{files:e}:e}function nF(e){if(!FO(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!==DO||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=OO(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(HO.test(e.path)){let t=dn({source:e.content,profile:hr({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(WO.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${vt(t)}`,details:{path:e.path}}}if(GO.test(e.path)){let t=lE({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(YO.test(e.path)){let t=lE({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(ZO.test(e.path))try{MO(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${vt(t)}`,details:{path:e.path}}}return{ok:!0}}function lE({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 f=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let p=e.indexOf(`
|
|
8
8
|
`,d);if(p===-1){l=!0;break}d=p,l=!0;continue}if(c){l=f===`
|
|
9
9
|
`||f==="\r";continue}if(s){f==="*"&&g==="/"&&(s=!1,d+=1),l=f===`
|
|
10
10
|
`||f==="\r";continue}if(a){f===`
|
|
11
11
|
`||f==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(f==="\\")i=!0;else if(f===o)o=null;else if(n==="css"&&(f===`
|
|
12
12
|
`||f==="\r"))return bo(t,`Unterminated string literal in ${t}.`);l=f===`
|
|
13
13
|
`||f==="\r";continue}if(f==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&f==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(f==="'"||f==='"'||n==="mdx"&&f==="`"){o=f,l=!1;continue}if(f==="{"||f==="("||f==="["){r.push({char:f,offset:d}),l=!1;continue}if(f==="}"||f===")"||f==="]"){let p=f==="}"?"{":f===")"?"(":"[",h=r.pop();if(!h||h.char!==p)return bo(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
|
|
14
|
-
`||f==="\r"}if(s)return bo(t,`Unterminated block comment in ${t}.`);if(o)return bo(t,`Unterminated string literal in ${t}.`);if(c)return bo(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?bo(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function bo(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function nc(e){let t="idle",n=e.fileSystem??MO(),r=sm(),o=Mb({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Gm(e.historyStore):BO()),u=Lb(n,{externalAdapters:e.externalAdapters}),d=new Map,f=hm(Yd),g=new Set,p=0,h=e.historyStore?.recoveryRequired??!1,y=Jd(),x=_();function E(m){return(ec.isAbsolute(m)?ec.relative(e.projectRoot,m):m).replace(/\\/g,"/").replace(/^\.\//,"")}function b(m,I){let S=ec.posix.dirname(m),C=I.replace(/\.(?:tsx?|jsx?)$/i,""),w=ec.posix.relative(S,C);return w.startsWith(".")?w:`./${w}`}function v(m,I){return m.startLine===I.startLine&&m.startColumn===I.startColumn&&m.endLine===I.endLine&&m.endColumn===I.endColumn}async function _(){let m=e.historyStore;if(m)try{let I=await m.readTransactionJournal();if(!I)return;let S=await m.readIndex(),C=await Promise.all(I.files.map(async O=>await n.exists(O.path)?ve(await n.readFile(O.path)):null));if(Gb({journal:I,index:S,observedFileDigests:C})!=="ambiguous"){await m.clearTransactionJournal(I.transactionId);let O=await m.readStatus();O.recoveryRequired||(await m.cleanupTmp(),O=await m.readStatus()),h=O.recoveryRequired;return}await m.markRecoveryRequired(`Ambiguous transaction journal ${I.transactionId} at phase ${I.phase}`),h=!0}catch(I){h=!0,await m.markRecoveryRequired(`Transaction journal recovery failed: ${St(I)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let m of o.entries){let I=eE(m.context,m.entryFile);i.set(m.key,I),R(I,I.dependencyFiles)}function R(m,I){let S=new Set(I);N(m),m.dependencyFiles=S;for(let C of m.dependencyFiles){let w=s.get(C);w||(w=new Set,s.set(C,w)),w.add(m.key)}}function N(m){for(let I of m.dependencyFiles){let S=s.get(I);S&&(S.delete(m.key),S.size===0&&s.delete(I))}m.dependencyFiles.clear()}function A(m){let I=new Set;for(let S of m)for(let C of s.get(S)??[])I.add(C);return I}function L(m){for(let I of m)if(!s.has(I))return!1;return!0}async function $(m,I,S,C,w,O){let j=new Map,K=mb(m),Y=rb(w.values()),X=qy(w.values()),J=typeof O.exists=="function"?ee=>O.exists(ee):async()=>!1;for(let[ee,se]of m.elements){let be=I.nodes.get(ee);if(!be)continue;let re=S.get(se.sourceFile)??C.get(se.sourceFile),Re=new Map,ye=new Map,D=new Map,G=[];for(let Ve of se.textSegments){if(!re){Re.set(Ve.index,null);continue}let No=await ob({file:se.sourceFile,source:re,segment:Ve,readFile:wt=>O.readFile(wt),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:fr,capabilities:Cc})=>({sourceType:wt,adapterId:fr,capabilities:Cc})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Et=await Ld({file:se.sourceFile,source:re,target:{kind:"text-segment",segment:Ve},readFile:wt=>O.readFile(wt),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:fr,capabilities:Cc})=>({sourceType:wt,adapterId:fr,capabilities:Cc})),functionCallContracts:e.functionCallContracts,fileCache:Y}),$t=WO(No);Re.set(Ve.index,$t),ye.set(Ve.index,No),D.set(Ve.index,Et),G.push({editable:Ve.editable,source:$t})}let pe=new Map,Se=new Map;if(re)for(let Ve of se.attributes??[]){let No=await yo({file:se.sourceFile,source:re,sourceRange:Ve.sourceRange,expression:Ve.source?.expression??Ve.value,sourceInfo:Ve.source,readFile:$t=>O.readFile($t),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:$t,adapterId:wt,capabilities:fr})=>({sourceType:$t,adapterId:wt,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Et=await fb({element:se,file:se.sourceFile,source:re,propertyName:Ve.name,readFile:$t=>O.readFile($t),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:$t,adapterId:wt,capabilities:fr})=>({sourceType:$t,adapterId:wt,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:Y});Se.set(Ve.name,Et),pe.set(Ve.name,No)}let Ce=Ib(GO(be.writeTarget),G),ze=K({key:ee,element:se,provenances:D}),Un=_b(se),Rn=re?await ex({element:se,graph:m,file:se.sourceFile,source:re,readFile:Ve=>O.readFile(Ve),exists:J,fileCache:X}):void 0,pr=m.regions.find(Ve=>Ve.kind==="conditional-region"&&Ve.childKeys.includes(ee)),kt,Cn=pr?.sourceCandidates?.[0];if(re&&pr&&Cn?.kind==="conditional-branch"){let Ve=await Ld({file:se.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Cn},readFile:Et=>O.readFile(Et),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Et,adapterId:$t,capabilities:wt})=>({sourceType:Et,adapterId:$t,capabilities:wt})),functionCallContracts:e.functionCallContracts,fileCache:Y});kt={currentBranch:pr.childKeys.indexOf(ee)<=0?"then":"else",availableBranches:pr.childKeys.length>1?["then","else"]:["then"],conditionExpression:Cn.conditionExpression,provenance:{finalSource:Ve.finalSource?{kind:Ve.finalSource.kind,file:Ve.finalSource.file,displayPath:Ve.finalSource.displayPath}:null,chain:Ve.chain.map(Et=>({kind:Et.kind,file:Et.file,displayName:Et.displayName,canEditHere:Et.canEditHere})),confidence:Ve.confidence,editMode:Ve.editMode,diagnostics:Ve.diagnostics.map(Et=>({code:Et.code,message:Et.message}))}}}j.set(ee,{textSources:Re,textTargets:ye,elementPropertyTargets:pe,propertyProvenances:Se,isRepeat:mF(ee,m),provenances:D,writeTarget:Ce,componentSemantic:ze,styleSource:Un,conditional:kt,dynamicData:Rn})}return j}function U(m){return typeof n.getVersion=="function"?n.getVersion(m):0}function de(m,I){let S=o.initialVersions.get(m.key)??0;for(let C of I.values())S=Math.max(S,C);return Math.max(S,m.graph?.version??0)}function z(m){return i.get(m)?.graph?.version??o.initialVersions.get(m)??0}function Q(m){try{return z(o.resolveSelector(m.composition).key)}catch{return 0}}async function ke(m,I,S=n,C={}){let w=await Bs(m,I,O=>S.readFile(O),O=>S.exists(O),{additionalEntries:await lt(m,S),...C});if(w.diagnostics.length>0)throw new ji(w.diagnostics);return C.validationOnly||f.remember(w.parsedModules.values()),w}async function ct(m,I,S={}){let C=i.get(m);if(!C)return null;let w=S.sourceCache??Wd(d,[]),O=S.fileSystem??Xd(n),{graph:j,allSources:K,parsedModules:Y,entryModule:X}=await ke(C.entryFile,I,O,{version:C.graph?.version??1}),J=new Map;for(let kt of K.keys())J.set(kt,U(kt));let ee=Math.max(de(C,J),S.minimumVersion??0);S.changed&&ee<=(C.graph?.version??0)&&(ee=(C.graph?.version??0)+1),j.version=ee;for(let[kt,Cn]of K)Gd(w,kt,Cn,Yd);let se=await Ro(C.composition,C.entryFile,K,w,O);j.routeId=C.routeId,j.composition=C.composition;let be=sa(j),re=Cs(be,j),Re=await $(j,be,K,w,Y,O),ye=he(j,re,Re),D=Co(Re),G=Vb(xb(j,be,re,{canUpdateTextByKey:ye,dynamicDataSummaryByKey:D}),j,Re),pe=nn({route:C.routeId,composition:C.composition,entryFile:C.entryFile,version:ee,source:I,ast:X?.ast}),Se=Xg(pe),Ce=null,ze=[];if(pe.ok){eF(G,j,pe.projection,Y);let kt=ia({composition:C.composition,entryFile:C.entryFile,graph:j,parsedModules:Y,projection:pe.projection});if(kt.diagnostics.length===0){let Cn=ai({composition:C.composition,entryFile:C.entryFile,graph:j,parsedModules:Y,projection:pe.projection,documentVersion:ee,roots:kt.roots});Cn.diagnostics.length===0&&(Ce=Cn,ze=Cn.descriptors)}}let Un={...G,composition:C.composition,pageBlocks:ze,...se?{styleContext:se}:{},pageComposition:Se},Rn=new Set([C.entryFile,...K.keys()]);if(se){Rn.add(se.entryCss.path);for(let kt of se.stylesheets)Rn.add(kt.path)}let pr={...C,dependencyFiles:Rn,graph:j,topology:be,capabilities:re,document:Un,pageBlockIndex:Ce,pageComposition:Se,pageCompositionProjection:pe.projection,pagePlacementByKey:pe.ok?pe.projection.placementByKey:null,pagePlacementUnitByKey:pe.ok?pe.projection.placementUnitByKey:null,pageUnitByKey:pe.ok?pe.projection.unitByKey:null,pagePlacementsByUnitKey:pe.ok?pe.projection.placementsByUnitKey:null,documentIndex:$b(Un),detailProjections:Re,fileVersions:J,styleContext:se};if(S.publish===!1)return pr;xo(d,w);for(let kt of w.keys())g.delete(kt);return R(C,Rn),Object.assign(C,pr),C}async function lt(m,I=n){let S=[];for(let C of cF(m))typeof I.exists=="function"&&await I.exists(C)&&S.push({file:C,source:await I.readFile(C)});return S}async function Ro(m,I,S,C,w){let O=[];for(let[J,ee]of S){if(Zd(J)){O.push(J);continue}for(let se of uF(ee)){let be=sE(J,se);be&&O.push(be)}}if(!O.length){for(let J of lF(I))if(await w.exists(J)){O.push(J);break}}let j=new Map,K=fF(O).slice(0,Yb);for(;K.length>0&&j.size<Yb;){let J=K.shift();if(j.has(J)||!Zd(J))continue;let ee=await Qt(J,C,w);if(ee!==null){j.set(J,{path:J,content:ee});for(let se of dF(ee)){let be=sE(J,se);be&&!j.has(be)&&!K.includes(be)&&K.push(be)}}}let Y=[...j.values()].map(J=>({...J,hash:ve(J.content)})),X=Y[0];return X?{composition:m,revision:ve(JSON.stringify(Y.map(({path:J,hash:ee})=>({path:J,hash:ee})))),entryCss:X,stylesheets:Y.slice(1)}:null}async function Qt(m,I,S){let C=I.get(m);if(C!==void 0)return C;if(!await S.exists(m))return null;let w=await S.readFile(m);return Gd(I,m,w,Yd),w}function Co(m){let I=new Map;for(let[S,C]of m)C.dynamicData?.bindings.length&&I.set(S,px(C.dynamicData.bindings));return I}function he(m,I,S){let C=new Map;for(let[w,O]of m.elements){if(!I.get(w)?.canUpdateText){C.set(w,!1);continue}let K=S.get(w),Y=O.textSegments.some(X=>{if(!X.editable)return!1;let J=K?.provenances.get(X.index)??null;return!J||Qe(J)});C.set(w,Y)}return C}function Qe(m){return m.editMode==="direct"||m.editMode==="proxy"||m.editMode==="upstream"}async function Pe(m,I={}){let S=[...new Set(m)],C=I.affectedCompositionKeys!==void 0,w=C?new Set(I.affectedCompositionKeys):A(S);if(!C&&(w.size===0||!L(S)))for(let X of i.values())Op(X,S)&&w.add(X.key);let O=!C&&w.size===0&&S.some(iE),j=I.publish===!1?Wd(d,S):void 0,K={rebuiltRoutes:[],failedRoutes:[],...I.publish===!1?{candidateRouteStates:[],candidateSourceCache:j}:{}},Y=Xd(n);for(let X of i.values())if(!(I.excludedCompositionKeys?.has(X.key)||!(w.has(X.key)||O)))try{let ee=!!X.graph,se=await Y.readFile(X.entryFile),be=await ct(X.key,se,{...I,fileSystem:Y,...j?{sourceCache:j}:{}});be?.graph&&(K.rebuiltRoutes.push({documentChanged:ee,composition:X.composition,routeId:X.routeId,version:be.graph.version}),K.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:be}))}catch(ee){K.failedRoutes.push({...Hb(X.routeId,ee),composition:X.composition})}return K}function ce(m){let I=[...new Set(m)],S=A(I);if(S.size>0&&L(I))return[...S];for(let C of i.values())Op(C,I)&&S.add(C.key);return[...S]}function $e(m){let I=new Set(ce(m));return o.entries.filter(S=>I.has(S.key)).map(S=>S.context)}function mt(m){return[...new Set(ce(m))].sort((S,C)=>S<C?-1:S>C?1:0).map(S=>o.getByKey(S)?.context).filter(S=>S!==void 0)}function qt(m,I){let S=new Set(ce(I)),C=m.provenance?.affectedCompositions??[];if(C.length===0)return S;if([...new Set(C.map(O=>o.resolveContext(O).key))].some(O=>!S.has(O)))throw new Error("History provenance does not match the affected composition index.");return S}function gt(m,I){let S=m.composition??m.provenance?.initiatingComposition;if(S){let O=o.resolveContext(S);return{context:O.context,key:O.key}}let C=[...new Set(ce(I))];if(C.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${C.length}).`);let w=o.getByKey(C[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function $r(m,I){r.emit({type:"operation-completed",composition:m.composition,result:m});for(let{composition:S,version:C}of I.rebuiltRoutes)r.emit({type:"document-changed",composition:S,version:C});for(let{composition:S,message:C}of I.failedRoutes)r.emit({type:"graph-error",composition:S,message:C})}function Op(m,I){return I.some(S=>m.dependencyFiles.has(S)||m.entryFile===S||m.graph?.fileIndex.has(S))}function Fp(m){for(let I of m)a.add(I);c||P()||(c=(async()=>{t="building";let I=!1;try{for(;a.size>0;){if(P())return;await lS(),await y.runExclusive(async()=>{if(p>0||P())return;let S=[...a];a.clear();let C=await Lp(S);if(C.length===0)return;let w=ce(C);for(let K of w){let Y=i.get(K)?.composition;Y&&r.emit({type:"graph-invalidated",composition:Y})}let{rebuiltRoutes:O,failedRoutes:j}=await Pe(C,{changed:!0});for(let{documentChanged:K,composition:Y,version:X}of O)r.emit({type:"graph-ready",composition:Y,version:X}),K&&r.emit({type:"document-changed",composition:Y,version:X});for(let{composition:K,message:Y}of j)I=!0,r.emit({type:"graph-error",composition:K,message:Y})})}}finally{c=null,t!=="disposed"&&(t=!I&&[...i.values()].some(S=>S.graph)?"ready":"idle"),a.size>0&&Fp([])}})())}async function lS(){for(;p>0;)await new Promise(m=>setTimeout(m,0))}async function Lp(m){let I=[];for(let S of new Set(m)){let C=d.get(S);if(C===void 0){if(g.has(S)&&!await n.exists(S))continue;g.delete(S),I.push(S);continue}try{await n.readFile(S)!==C&&(g.delete(S),I.push(S))}catch(w){if(!qO(w))try{if(await n.exists(S))continue}catch{continue}g.add(S),I.push(S)}}return I}function Dp(m){Wb(d,m);for(let I of m)I.exists===!1?g.add(I.file):g.delete(I.file)}function Mp(m){g.clear();for(let I of m)g.add(I)}async function Bp(m){let I=await Lp(m);if(I.length===0)return;let S=ce(I);for(let O of S){let j=i.get(O)?.composition;j&&r.emit({type:"graph-invalidated",composition:j})}let{rebuiltRoutes:C,failedRoutes:w}=await Pe(I,{changed:!0});for(let{documentChanged:O,composition:j,version:K}of C)r.emit({type:"graph-ready",composition:j,version:K}),O&&r.emit({type:"document-changed",composition:j,version:K});for(let{composition:O,message:j}of w)r.emit({type:"graph-error",composition:O,message:j})}async function uS(m,I){let S=Ur(m,I);if(!S?.graph)return;let C=At(m)??m,w=S.graph.elements.get(C);w&&await Bp([w.sourceFile])}async function jp(m){let I=new Set;if(m.target.kind==="node"){let S=Ur(m.target.key,m.composition),C=At(m.target.key)??m.target.key,w=S?.graph?.elements.get(C);w&&I.add(w.sourceFile)}else if(m.target.kind==="route"){let S=i.get(o.resolveSelector(m.target.composition).key);S&&I.add(S.entryFile)}else if(m.target.kind==="page-unit"){let S=i.get(o.resolveSelector(m.target.composition).key);S&&I.add(S.entryFile)}else if(m.target.kind==="page-block"){let S=i.get(o.resolveSelector(m.target.composition).key),C=S?.pageBlockIndex?.bindings.get(m.target.blockKey);if(C&&(I.add(C.ownerFile),I.add(C.descriptor.source.file)),S?.pageBlockIndex&&m.params.kind==="move-node"&&"kind"in m.params.target&&m.params.target.kind==="block-boundary"){let w=S.pageBlockIndex.bindings.get(m.params.target.anchorBlockKey);w&&(I.add(w.ownerFile),I.add(w.descriptor.source.file))}}else if(m.target.kind==="source-file")I.add(m.target.path);else if(m.target.kind==="source-batch")for(let S of m.target.paths)I.add(S);if(m.params.kind==="move-node"&&!("kind"in m.params.target)){let S=[m.params.target.parentKey,...m.params.target.relation==="before"||m.params.target.relation==="after"?[m.params.target.anchorKey]:[]];for(let C of S){let w=Ur(C,m.composition),O=At(C)??C,j=w?.graph?.elements.get(O);j&&I.add(j.sourceFile)}}await Bp(I)}async function dS(m){if(m.params.kind!=="source-edit")return vc(m,"invalid-params","source-edit requires source-edit params");for(let I of m.params.edits){let S=QO(I);if(!S.ok)return vc(m,S.errorCode,S.message,S.details)}p+=1;try{let I=await ES(m.params.edits);if(!I.ok)return vc(m,I.errorCode,I.message,I.details);await jp(m);let S={operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:m.params.conflictPolicy,edits:m.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 Vn({request:m,filePlan:S})}catch(I){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.INTERNAL_ERROR,message:St(I)}}}finally{p-=1}}async function pS(m){if(m.target.kind!=="project"||m.params.kind!=="insert-page-resource")return H(m,M.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let I=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...m.params.artifact.components.flatMap(C=>C.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...m.params.artifact.pages.flatMap(C=>C.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:C=>n.exists(C),readFile:C=>n.readFile(C)});if(!I.ok)return H(m,M.MATERIALIZATION_REJECTED,I.message);let S=await $l({artifact:m.params.artifact,exists:C=>n.exists(C)});return S.ok?await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"overwrite",edits:S.files},output:{kind:"insert-page-resource",package_instance_id:S.packageInstanceId,pages:S.pages},historyPolicy:"none"}):H(m,S.code==="MATERIALIZATION_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,S.message,S.path?{path:S.path}:void 0)}catch(I){return H(m,M.INTERNAL_ERROR,St(I))}finally{p-=1}}async function fS(m){if(m.target.kind!=="project"||m.params.kind!=="delete-page-source")return H(m,M.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return H(m,M.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let I=aE(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(I.truncated)return H(m,M.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:I.truncated.reasons});let S=I.files.filter(({path:j})=>/\.(?:tsx?|jsx?)$/.test(j)),C=Object.fromEntries(await Promise.all(S.map(async({path:j})=>[j,await n.readFile(j)]))),w=Oh({expectedUrlPath:m.params.expectedUrlPath,files:C});if(!w.ok)return H(m,w.code==="HOME_PAGE_LOCKED"?M.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?M.ROUTE_NOT_FOUND:M.PLAN_FAILED,w.message);let O=await Promise.all(w.edits.map(async j=>({...j,baseContentHash:ve(await n.readFile(j.file))})));return Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(I){return H(m,M.INTERNAL_ERROR,St(I))}finally{p-=1}}async function mS(m,I){if(m.kind!=="insert-child"&&m.kind!=="replace-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(m.params.kind!=="insert-child"&&m.params.kind!=="replace-node"||m.kind!==m.params.kind)return H(m,M.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(m.params.kind==="insert-child"){if(!("kind"in m.params.position)||m.params.position.kind!=="page-composition")return H(m,M.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(m.params.position.documentVersion!==m.documentVersion)return H(m,M.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let S=I.document,C=I.pageCompositionProjection;if(!S||S.pageComposition?.status!=="supported"||!C||C.status!=="supported")return H(m,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=m.params.node.kind==="component-call"?m.params.node.materialization:void 0;if(!w)return H(m,M.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=m.params.kind==="insert-child"?m.params.position:null,j=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:w.files.map(X=>({path:X.pathTemplate,content:X.content})),exists:X=>n.exists(X),readFile:X=>n.readFile(X)});if(!j.ok)return H(m,M.MATERIALIZATION_REJECTED,j.message);let K=await Qb(n,Object.keys(w.projectDependencies??{})),Y=await zl({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(X=>({pathTemplate:X.pathTemplate})),exists:X=>n.exists(X),availableHostDependencies:K,hostCapabilities:Ll(),commit:async X=>{let J=await n.readFile(I.entryFile),ee=I.document,se=I.pageCompositionProjection;if(!ee||ee.pageComposition?.status!=="supported"||ee.version!==m.documentVersion||!se||se.status!=="supported"||se.documentVersion!==ee.version)return{ok:!0,data:H(m,M.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let be=X.entry.path,re=NS(X.instanceName),Re,ye=[];if(m.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:H(m,M.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Se=ni({routeId:I.routeId,entryFile:I.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:m.documentVersion,source:J,projection:se,placementKey:O.placementKey,component:{source:be,exportName:X.entry.export.kind==="default"?"default":X.entry.export.name,localName:re}});if(!Se.ok)return{ok:!0,data:H(m,Rc(Se.error.code),Se.error.message,{diagnostics:Se.error.diagnostics})};let Ce=Se.plan.rewriteStep,ze;switch(Ce.kind){case"insert-root-expression":ze=ri({source:J,locator:Ce.locator,expectedSourceHash:Ce.sourceHash,action:{kind:"insert",jsx:Ce.node.jsx,placement:Ce.placement,replaceOriginal:Ce.replaceOriginal}});break;case"insert-child":ze=Kt({source:J,locator:Ce.parentLocator,node:Ce.node,placement:Ce.placement,...Ce.anchorLocator?{anchorLocator:Ce.anchorLocator}:{}});break;default:ze={ok:!1,source:J,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ce)}`}}}if(!ze.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,ze.diagnostic.message)};Re=ze.source}else{let Se=au({routeId:I.routeId,composition:I.composition,entryFile:I.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:m.documentVersion,source:J,projection:se,placementUnitKey:m.target.placementUnitKey,operation:"replace-node"});if(!Se.ok)return{ok:!0,data:H(m,Rc(Se.error.code),Se.error.message,{diagnostics:Se.error.diagnostics})};let Ce=Se.plan.rewriteStep,ze;switch(Ce.kind){case"replace-root-expression":ze=ri({source:J,locator:Ce.locator,expectedSourceHash:Ce.sourceHash,action:{kind:"replace",jsx:`<${re} />`}});break;case"replace-node":ze=Jr({source:J,locator:Ce.locator,node:{jsx:`<${re} />`}});break;default:ze={ok:!1,source:J,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ce.kind}`}}}if(!ze.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,ze.diagnostic.message)};let Un=await Sc({routeState:I,placementUnitKey:m.target.placementUnitKey,source:J,mutatedSource:ze.source});Re=Un.source,ye=await Promise.all(Un.files.map(async Rn=>({operation:"delete",file:Rn,baseContentHash:ve(await n.readFile(Rn))})))}let D=Jt({source:Re,moduleSpecifier:b(I.entryFile,be),imports:X.entry.export.kind==="default"?[{kind:"default",local:re}]:[{kind:"named",imported:X.entry.export.name,local:re}]});if(!D.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,D.diagnostic.message)};let G=X.files.map(Se=>({operation:"create-only",file:Se.path,content:Se.content})),pe=[{operation:"upsert",file:I.entryFile,content:D.source,baseContentHash:ve(J)},...G,...ye];p+=1;try{let Se=await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:{kind:"source-file",path:I.entryFile},documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!Se.ok&&Se.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Se.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Se}}finally{p-=1}}});return Y.ok?Y.data:H(m,Y.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,Y.error.message,{materializationCode:Y.error.code})}async function gS(m,I){if(m.kind!=="insert-child"&&m.kind!=="replace-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(m.params.kind!==m.kind||m.kind==="replace-node"&&m.params.kind!=="replace-node"||m.kind==="insert-child"&&m.params.kind!=="insert-child")return H(m,M.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let S=I.document,C=I.pageBlockIndex;if(!S||!C||C.diagnostics.length>0)return H(m,M.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=ro(C,m.target,m.documentVersion,m.selectionRef);if(!w.ok)return H(m,Hi(w.code),w.message);let O=w.binding;if(!(m.kind==="insert-child"?O.descriptor.capabilities.insert:O.descriptor.capabilities.replace)){let re=O.descriptor.unavailableReasons?.[m.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return H(m,M.UNSUPPORTED_OPERATION,re)}let K=(m.kind==="insert-child",m.params);if(K.kind!==m.kind)return H(m,M.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Y=K.node;if(Y.kind!=="component-call"||!Y.materialization)return H(m,M.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let X;if(K.kind==="insert-child"){let re=K.position;if(!("kind"in re&&re.kind==="block-boundary"))return H(m,M.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(re.documentVersion!==m.documentVersion)return H(m,M.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Re=aa(C,re);if(!Re.ok)return H(m,Hi(Re.code),Re.message);X=Re.boundary}let J=Y.materialization,ee=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:J.files.map(re=>({path:re.pathTemplate,content:re.content})),exists:re=>n.exists(re),readFile:re=>n.readFile(re)});if(!ee.ok)return H(m,M.MATERIALIZATION_REJECTED,ee.message);let se=await Qb(n,Object.keys(J.projectDependencies??{})),be=await zl({manifest:J,generatedRoot:"components/site/generated",controlledFiles:J.files.map(re=>({pathTemplate:re.pathTemplate})),exists:re=>n.exists(re),availableHostDependencies:se,hostCapabilities:Ll(),commit:async re=>{let Re=I.document,ye=I.pageBlockIndex;if(!Re||!ye||Re.version!==m.documentVersion||ye.documentVersion!==Re.version||!ye.bindings.has(O.blockKey))return{ok:!0,data:H(m,M.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let D=ye.bindings.get(O.blockKey);if(!D||D.ownerFile!==O.ownerFile||D.ownerSourceHash!==O.ownerSourceHash||D.sourceHash!==O.sourceHash)return{ok:!0,data:H(m,M.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let G=new Set([O.ownerFile,O.descriptor.source.file,...X?[X.ownerFile,X.anchorLocator.file,...X.parentLocator?[X.parentLocator.file]:[]]:[]]),pe=new Map;try{for(let Ce of G)pe.set(Ce,await n.readFile(Ce))}catch{return{ok:!0,data:H(m,M.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Se=fh({operationId:m.id,documentVersion:m.documentVersion,target:m.target,binding:O,...X?{boundary:X}:{},operation:K.kind,materialization:re,files:pe});if(!Se.ok){let Ce=bS(Se.code);return{ok:!0,data:H(m,Ce,Se.message,{materializationCode:Se.code})}}p+=1;try{let Ce=await Vn({request:m,filePlan:Se.plan});return!Ce.ok&&Ce.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ce.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ce}}finally{p-=1}}});return be.ok?be.data:H(m,be.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,be.error.message,{materializationCode:be.error.code})}async function hS(m,I){if(m.kind!=="move-node"&&m.kind!=="remove-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let S=I.document,C=I.pageCompositionProjection;if(!S||S.pageComposition?.status!=="supported"||!C||C.status!=="supported")return H(m,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=await n.readFile(I.entryFile),O=au({routeId:I.routeId,composition:I.composition,entryFile:I.entryFile,currentDocumentVersion:S.version,expectedDocumentVersion:m.documentVersion,source:w,projection:C,placementUnitKey:m.target.placementUnitKey,operation:m.kind,targetPlacement:m.kind==="move-node"&&m.params.kind==="move-node"&&"kind"in m.params.target&&m.params.target.kind==="page-composition"?m.params.target:void 0});if(!O.ok)return H(m,Rc(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let j=O.plan.rewriteStep,K;switch(j.kind){case"move-node":K=kr({source:w,locator:j.locator,targetParentLocator:j.targetParentLocator,placement:j.placement,...j.anchorLocator?{anchorLocator:j.anchorLocator}:{}});break;case"remove-node":K=vr({source:w,locator:j.locator});break;case"remove-root-expression":K=ri({source:w,locator:j.locator,expectedSourceHash:j.sourceHash,action:{kind:"remove"}});break;default:K={ok:!1,source:w,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${j.kind}`}}}if(!K.ok)return H(m,M.AST_PARSE_ERROR,K.diagnostic.message);let Y=K.source,X=[];if(m.kind==="remove-node"){let ee=await Sc({routeState:I,placementUnitKey:m.target.placementUnitKey,source:w,mutatedSource:Y});Y=ee.source,X=await Promise.all(ee.files.map(async se=>({operation:"delete",file:se,baseContentHash:ve(await n.readFile(se))})))}let J=[{operation:"upsert",file:I.entryFile,content:Y,baseContentHash:ve(w)},...X];p+=1;try{return await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:{kind:"source-file",path:I.entryFile},documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:J}})}finally{p-=1}}async function yS(m,I){if(m.kind!=="move-node"&&m.kind!=="remove-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let S=I.document,C=I.pageBlockIndex;if(!S||!C||C.diagnostics.length>0)return H(m,M.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=ro(C,m.target,m.documentVersion,m.selectionRef);if(!w.ok)return H(m,Hi(w.code),w.message);let O=w.binding;if(O.documentVersion!==S.version)return H(m,M.VERSION_STALE,"The resolved page-block binding is stale.");if(!(m.kind==="move-node"?O.descriptor.capabilities.move:O.descriptor.capabilities.remove)){let ye=O.descriptor.unavailableReasons?.[m.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return H(m,M.UNSUPPORTED_OPERATION,ye)}if(m.kind==="remove-node"){let ye=[...i.values()].filter(D=>D.dependencyFiles.has(O.ownerFile));if(ye.includes(I)||ye.push(I),ye.some(D=>!D.pageBlockIndex||D.pageBlockIndex.descriptors.length<=1))return H(m,M.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let K=null;if(m.kind==="move-node"){if(m.params.kind!=="move-node"||!("kind"in m.params.target)||m.params.target.kind!=="block-boundary")return H(m,M.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(m.params.target.anchorBlockKey===O.blockKey)return H(m,M.INVALID_TARGET,"A page block cannot be moved relative to itself.");let ye=aa(C,m.params.target);if(!ye.ok)return H(m,Hi(ye.code),ye.message);let D=C.bindings.get(m.params.target.anchorBlockKey);if(!D||!O.descriptor.siblingBlockKeys.includes(D.blockKey)||!D.descriptor.siblingBlockKeys.includes(O.blockKey)||D.ownerFile!==O.ownerFile||D.root.ownerNode.kind!==O.root.ownerNode.kind||D.root.ownerNode.key!==O.root.ownerNode.key||D.root.parentStructuralPath!==O.root.parentStructuralPath)return H(m,M.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(K=ye.boundary,K.ownerFile!==O.ownerFile||K.sourceHash!==O.ownerSourceHash||!K.parentLocator)return H(m,M.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Y=O.ownerFile,X=await n.readFile(Y);if(ve(X)!==O.ownerSourceHash)return H(m,M.VERSION_STALE,"The page-block owner source changed after resolution.");let J=O.descriptor.source.file===Y?X:await n.readFile(O.descriptor.source.file);if(ve(J)!==O.descriptor.source.contentHash)return H(m,M.VERSION_STALE,"The selected page-block source changed after resolution.");let ee=xS(O),se=m.kind==="remove-node"?vr({source:X,locator:ee}):kr({source:X,locator:ee,targetParentLocator:Ec(K.parentLocator),anchorLocator:Ec(K.anchorLocator),placement:K.placement});if(!se.ok)return H(m,M.AST_PARSE_ERROR,se.diagnostic.message);let be=se.source,re=[];if(m.kind==="remove-node"&&O.root.ownerNode.kind==="route-member"&&O.root.callChain.length>0&&O.descriptor.placementUnitKey){let ye=await Sc({routeState:I,placementUnitKey:O.descriptor.placementUnitKey,source:X,mutatedSource:be});be=ye.source,re=ye.files}let Re=[{operation:"upsert",file:Y,content:be,baseContentHash:O.ownerSourceHash},...await Promise.all(re.map(async ye=>({operation:"delete",file:ye,baseContentHash:ve(await n.readFile(ye))})))];p+=1;try{return await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:Re}})}finally{p-=1}}function xS(m){return Ec(m.ownerLocator)}function Ec(m){return{kind:"jsx-node",strategy:"source-range",sourceRange:m.sourceRange,...m.structuralPath&&m.componentName?{expectedIdentity:{file:m.file,component:m.componentName,structuralPath:m.structuralPath}}:{}}}function Hi(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="INVALID_PARAMS"?M.INVALID_PARAMS:M.INVALID_TARGET}function bS(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="INVALID_PARAMS"?M.INVALID_PARAMS:m==="INVALID_TARGET"?M.INVALID_TARGET:m.startsWith("MATERIALIZATION_")?M.MATERIALIZATION_REJECTED:M.UNSUPPORTED_OPERATION}async function Sc(m){let I={source:m.mutatedSource,files:[]},S=m.routeState.graph,C=m.routeState.pageCompositionProjection;if(!S||!C||C.status!=="supported"||!n.listFiles)return I;let O=C.placementUnitByKey.get(m.placementUnitKey)?.sourceRange;if(!O)return I;let j=[...S.elements.values()].find(D=>D.sourceFile===m.routeState.entryFile&&D.importedFrom&&v(D.sourceRange,O));if(!j?.importedFrom||!j.exportName)return I;let K=E(j.importedFrom),Y="components/site/generated/";if(!K.startsWith(Y))return I;let X=K.slice(Y.length).split("/")[0];if(!X||!/-[0-9a-f]{8}$/i.test(X))return I;let J=`${Y}${X}`;if([...S.elements.values()].filter(D=>D.sourceFile===m.routeState.entryFile&&E(D.importedFrom??"")===K).length!==1)return I;let se=await n.listFiles({maxFiles:5e3,maxDepth:32}),be=Array.isArray(se)?se:se.files;if(!Array.isArray(se)&&se.truncated)return I;let re=be.map(({path:D})=>D).filter(D=>D===J||D.startsWith(`${J}/`));if(re.length===0||!re.includes(K))return I;for(let{path:D}of be)if(!(D===m.routeState.entryFile||D===J||D.startsWith(`${J}/`)))try{if((await n.readFile(D)).includes(X))return I}catch{return I}let Re=b(m.routeState.entryFile,K),ye=zr({source:m.mutatedSource,moduleSpecifier:Re,imports:j.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:j.exportName}]});return ye.ok?ye.source.includes(X)?{source:ye.source,files:[]}:{source:ye.source,files:re.sort((D,G)=>D.localeCompare(G))}:I}async function ES(m){if(n.getFileInfo){for(let j of m)if(await n.exists(j.path)&&await n.getFileInfo(j.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${j.path}`,details:{path:j.path}}}for(let j of m){if(j.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(j.path))continue;let K=await n.exists(j.path)?await Vc(n,j.path):null;if(K?.ok){let Y=NO(K.content,j.content);if(!Y.ok)return{ok:!1,errorCode:"invalid-params",message:Y.message,details:{path:j.path,code:Y.code}}}}let I=SS(m);if(I.length===0)return{ok:!0};let S=YO(n,m),C=new Map,w=(j,K)=>{let Y=C.get(j);if(Y?.source===K)return Y.result;let X=Ke(j,K);return C.set(j,{source:K,result:X}),X},O;try{O=await Bb(I,async j=>{let K=i.get(j);return K?[...(await ke(K.entryFile,await S.readFile(K.entryFile),S,{validationOnly:!0,parseModule:w,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(j){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${St(j)}`,details:{compositionKeys:I}}}for(let j of O)f.remember(j);return{ok:!0}}function SS(m){return m.map(S=>S.path).some(iE)?[...i.keys()]:[]}function vc(m,I,S,C){let w=$i(I);return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:w,message:S,...C?{details:C}:{}}}}async function Ic(m){let I=[];for(let S of new Set(m))I.push(await vS(S));return I}async function vS(m){if(!(typeof n.exists=="function"?await n.exists(m):!0))return{file:m,content:"",version:Math.max(0,U(m)),exists:!1};let S=await n.readFile(m);return{file:m,content:S,version:Math.max(1,U(m)),exists:!0,sha256:ve(S)}}async function $p(m,I,S,C){if(!e.historyStore)return null;let w=new Map(I.map(K=>[K.file,K])),O=new Map(S.map(K=>[K.file,K])),j=[...new Set([...w.keys(),...O.keys()])].sort().map(K=>{let Y=w.get(K),X=O.get(K);return{path:K,preDigest:Y?.exists===!1||!Y?null:ve(Y.content),postDigest:X?.exists===!1||!X?null:ve(X.content)}});return{schemaVersion:2,transactionId:`${m}:${C.expectedIndexDigest}`,operationId:m,phase:"prepared",historyTransition:C,files:j}}async function Vp(m){return!m||!e.historyStore||await e.historyStore.writeTransactionJournal(m),m}async function Vr(m){m&&e.historyStore&&await e.historyStore.clearTransactionJournal(m.transactionId)}async function kc(m,I){let S=[];try{for(let C of m)await Up(C),typeof n.bumpVersion=="function"&&n.bumpVersion(C.file),S.push(C.file)}catch(C){let w=await IS(I.filter(O=>S.includes(O.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${St(C)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${St(C)}`,rolledBack:!1}}return{ok:!0,snapshots:m.map(kS)}}async function Up(m){if(m.exists===!1){await n.deleteFile(m.file);return}await n.writeFile(m.file,m.content)}async function IS(m){let I=[];for(let S of m)try{await Up(S),typeof n.bumpVersion=="function"&&n.bumpVersion(S.file)}catch{I.push(S.file)}return I.length===0?{ok:!0}:{ok:!1,failedFiles:I}}function kS(m){let I=m.exists!==!1;return{file:m.file,content:I?m.content:"",version:m.version,exists:I,...I?{sha256:ve(m.content)}:{}}}async function Vn(m){return y.runExclusive(()=>RS(m))}async function RS(m){let I=m.filePlan.edits.map(D=>D.file),S=o.resolveSelector(m.request.composition),C=S.context,w=m.historyPolicy==="none"?void 0:{initiatingComposition:C,affectedCompositions:mt(I)},O=await Ic(I),j=new Map(O.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),K=Jp(),Y=new Map(d),X=new Set(g),J=new Set([...i.values()].filter(D=>m.filePlan.edits.some(G=>G.operation==="delete"&&G.file===D.entryFile)).map(D=>D.key)),ee=m.filePlan.edits.map(D=>D.operation==="delete"?{file:D.file,content:"",version:0,exists:!1}:{file:D.file,content:D.content,version:0,exists:!0,sha256:ve(D.content)}),se={operationId:m.filePlan.operationId,intents:m.filePlan.edits.map(D=>D.operation==="delete"?{kind:"delete",path:D.file}:{kind:D.operation==="create-only"?"create-only":"upsert",path:D.file,content:D.content})},be=null,re=!1,Re=await Ya({overlay:j,exists:D=>n.exists(D),plan:se,buildCandidate:async({plan:D})=>({plan:D}),prepareHistory:async()=>{let D=m.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(m.request.composition).context,operationId:m.request.id,kind:m.request.kind,target:m.request.target,preSnapshots:O,postSnapshots:ee,...m.selectionRef?{selectionRef:m.selectionRef}:{},...m.output?{output:m.output}:{},...w?{provenance:w}:{}}),G=D?.historyTransition?D.historyTransition:e.historyStore?DO(await e.historyStore.readIndex()):null;if(e.historyStore&&!G)throw new Error("Durable history did not provide an exact index transition.");return be=await $p(m.request.id,O,ee,G),be=await Vp(be),{history:D,historyTransition:G}},reverify:async()=>{},writeCandidate:async()=>{let D=await u.executeFilePlan(m.filePlan);if(!D.ok)throw new tc(D);return{postSnapshots:await Ic(D.affectedFiles),affectedFiles:D.affectedFiles,internalResultVersion:D.resultVersion}},validateCandidate:async({candidate:D,receipt:G})=>{let pe=await Pe(G.affectedFiles,{changed:!0,minimumVersion:G.internalResultVersion,publish:!1,excludedCompositionKeys:J});if(pe.failedRoutes.length>0)throw new Br(pe.failedRoutes);let Se=zp(K,pe.candidateRouteStates??[]),Ce=Xp(Se,S.key);return{...D,rebuild:pe,routeSnapshots:Se,resultVersion:Ce,...tE(m.selectionRef,Se.map(ze=>ze.state.document))?{selectionRef:tE(m.selectionRef,Se.map(ze=>ze.state.document))}:{}}},publishCandidate:async({candidate:D,history:G,receipt:pe})=>{G?.history&&(await l.publishPrepared(G.history),re=!0);let Se=D.resultVersion??pe.internalResultVersion;return{composition:C,requestId:m.request.id,kind:m.request.kind,target:m.request.target,ok:!0,resultVersion:Se,affectedFiles:pe.affectedFiles,fileChanges:pe.postSnapshots.map(Ce=>({path:Ce.file,operation:Ce.exists===!1?"delete":"upsert"})),...m.output?{output:m.output}:{},...D.selectionRef?{selectionRef:D.selectionRef}:{}}},swapCandidate:({candidate:D,receipt:G})=>{D.routeSnapshots&&Wi(D.routeSnapshots),D.rebuild?.candidateSourceCache&&xo(d,D.rebuild.candidateSourceCache),Dp(G.postSnapshots)},finalizeCandidate:async()=>{await Vr(be);for(let D of J)i.delete(D)},emitCommitted:({candidate:D,published:G})=>{$r(G,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:D,receipt:G})=>{if(re)throw new Error("history was published before transaction finalization failed");if(G){let pe=await kc(O,G.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Wi(K),xo(d,Y),Mp(X),D?.history&&await l.discardPrepared?.(D.history),await Vr(be)}});if(Re.ok)return Re.published;if(Re.stage==="precheck"||Re.stage==="build")try{await Vr(be)}catch(D){let G=await Yi(St(D));return H(m.request,G,"Unable to clear an uncommitted transaction journal.")}if(Re.recoveryRequired){let D=await Yi(Re.reason);return H(m.request,D===M.RECOVERY_PERSIST_FAILED?D:M.ROLLBACK_FAILED,Re.reason)}let ye=Re.error;return ye instanceof tc?{...H(m.request,$i(ye.result.errorCode),ye.result.reason),...ye.result.affectedFiles?{affectedFiles:ye.result.affectedFiles}:{}}:ye instanceof Br?H(m.request,M.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Hd(ye.failedRoutes)}`,{failedRoutes:ye.failedRoutes}):H(m.request,Wp(Re.stage),St(ye))}async function Kp(m){return y.runExclusive(async()=>{let I=m==="undo"?await l.prepareUndo():await l.prepareRedo();return I?CS(m,I):{composition:o.entries[0].context,requestId:m,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:M.INTERNAL_ERROR,message:m==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function CS(m,I){let S=I.entry,C=m==="undo"?S.preSnapshots:S.postSnapshots,w=m==="undo"?S.postSnapshots:S.preSnapshots,O=C.map(G=>G.file),{context:j,key:K}=gt(S,O),Y=await Ic(O),X=new Map(Y.filter(G=>G.exists!==!1).map(G=>[G.file,G.content])),J=z(K),ee=Jp(),se=new Map(d),be=new Set(g),re=null,Re=!1,ye,D=await Ya({overlay:X,plan:{operationId:`${m}:${S.operationId}`,intents:C.map(G=>G.exists===!1?{kind:"delete",path:G.file}:{kind:"upsert",path:G.file,content:G.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(re=await $p(`${m}:${S.operationId}`,Y,C,I.historyTransition),re=await Vp(re),I),reverify:async()=>{},writeCandidate:async()=>{let G=await kc(C,w);if(!G.ok)throw new Error(G.reason);return{snapshots:G.snapshots}},validateCandidate:async({candidate:G})=>{ye=qt(S,O);let pe=await Pe(O,{changed:!0,minimumVersion:J+1,publish:!1,affectedCompositionKeys:ye});if(pe.failedRoutes.length>0)throw new Br(pe.failedRoutes);let Se=zp(ee,pe.candidateRouteStates??[]),Ce=Xp(Se,K);return{...G,rebuild:pe,routeSnapshots:Se,resultVersion:Ce}},publishCandidate:async({candidate:G,history:pe,receipt:Se})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),Re=!0;let Ce=G.resultVersion??J+1;return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!0,resultVersion:Ce,affectedFiles:O,fileChanges:Se.snapshots.map(ze=>({path:ze.file,operation:ze.exists===!1?"delete":"upsert"})),...S.output?{output:S.output}:{}}},swapCandidate:({candidate:G,receipt:pe})=>{G.routeSnapshots&&Wi(G.routeSnapshots),G.rebuild?.candidateSourceCache&&xo(d,G.rebuild.candidateSourceCache),Dp(pe.snapshots)},finalizeCandidate:async()=>{await Vr(re)},emitCommitted:({candidate:G,published:pe})=>$r(pe,G.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:G,receipt:pe})=>{if(Re)throw new Error("history cursor was published before transaction finalization failed");if(pe){let Se=await kc(w,pe.snapshots);if(!Se.ok)throw new Error(Se.reason)}Wi(ee),xo(d,se),Mp(be),G&&await l.discardPrepared?.(G),await Vr(re)}});if(D.ok)return D.published;if(D.stage==="precheck"||D.stage==="build")try{await Vr(re)}catch(G){let pe=await Yi(St(G));return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(D.recoveryRequired){let G=await Yi(D.reason);return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,affectedFiles:O,error:{code:G===M.RECOVERY_PERSIST_FAILED?G:M.ROLLBACK_FAILED,message:D.reason}}}return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,affectedFiles:O,error:{code:D.error instanceof Br?M.ROUTE_REBUILD_FAILED:Wp(D.stage),message:St(D.error),...D.error instanceof Br?{details:{failedRoutes:D.error.failedRoutes}}:{}}}}function Jp(){return[...i.values()].map(m=>({composition:m.composition,key:m.key,routeId:m.routeId,state:{...m,dependencyFiles:new Set(m.dependencyFiles),fileVersions:new Map(m.fileVersions)}}))}function Xp(m,I){return m.find(C=>C.key===I)?.state.graph?.version??o.initialVersions.get(I)??0}function zp(m,I){let S=new Map(m.map(C=>[C.key,C]));for(let C of I)S.set(C.key,C);return[...S.values()]}function Wi(m){for(let I of i.values())N(I);for(let I of m){let S={...I.state,dependencyFiles:new Set(I.state.dependencyFiles),fileVersions:new Map(I.state.fileVersions)};i.set(I.key,S),R(S,S.dependencyFiles)}}async function Gi(m){let I=i.get(m);if(!I)throw new Error(`Composition not found: ${m}`);if(I.graph)return;let S=await n.readFile(I.entryFile);await ct(m,S)}function Ur(m,I){let S=i.get(o.resolveSelector(I).key)??null;return!S||!Hp(S,m)?null:S}function Hp(m,I){if(m.documentIndex?.entriesByKey.has(I)||m.graph?.elements.has(I))return!0;let S=At(I);return S&&S!==I?m.graph?.elements.has(S)===!0:!1}function H(m,I,S,C){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:I,message:S,...C?{details:C}:{}}}}function Wp(m){return m==="validate"?M.ROUTE_REBUILD_FAILED:m==="publish"?M.HISTORY_COMMIT_FAILED:M.WRITE_IO_ERROR}async function Yi(m){if(h=!0,!l.markRecoveryRequired)return M.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(m),M.RECOVERY_REQUIRED}catch{return M.RECOVERY_PERSIST_FAILED}}function NS(m){let S=m.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return S?`Prefab${S}`:"GeneratedPrefab"}function Rc(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="CROSS_PAGE_MOVE_UNSUPPORTED"?M.CROSS_PAGE_MOVE_UNSUPPORTED:M.UNSUPPORTED_OPERATION}async function Gp(m){if(m.target.kind==="route"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(m.target.kind==="page-unit"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(m.target.kind==="page-block"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(m.target.kind!=="node")return H(m,M.UNSUPPORTED_OPERATION,`${m.kind} source target execution is not implemented yet.`);let I=i.get(o.resolveSelector(m.composition).key)??null;return I?(I.graph||await Gi(I.key),Hp(I,m.target.key)?I:H(m,M.NODE_NOT_FOUND,`Target key not found: ${m.target.key}`)):H(m,M.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(),f.clear(),g.clear()},registerComposition(m,I){let S=o.register({context:m,entryFile:I}),C=i.get(S.key);if(C?.entryFile===I)return;C&&N(C);let w=eE(S.context,I);i.set(S.key,w),R(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:S.context})},unregisterComposition(m){let I=o.resolveSelector(m),S=i.get(I.key);S&&(N(S),i.delete(I.key),o.unregister(I.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:I.context}))},getCompositionEntryFiles(){return[...i.values()].map(m=>m.entryFile)},getCompositionContext(m){return o.resolveSelector(m).context},async initializeComposition(m){let I=o.resolveSelector(m),S=i.get(I.key);if(!S)throw new Error(`Composition not registered: ${I.key}`);if(S.graph)t="ready";else{t="building";try{let C=await n.readFile(S.entryFile);await ct(I.key,C),t="ready",r.emit({type:"graph-ready",composition:I.context,version:i.get(I.key)?.graph?.version??0})}catch(C){throw t="idle",r.emit({type:"graph-error",composition:I.context,message:St(C)}),C}}},getDocument(m){let I=o.resolveSelector(m),S=i.get(I.key);if(!S)throw new Error(`Composition not registered: ${I.key}`);if(!S.document)throw new Error(`Composition not built: ${I.key}`);return S.document},async getHistoryStatus(){await x;let m=await l.getStatus?.();return m?{...m,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(m,I,S){let C=Ur(m,I),w=At(m)??m;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let O=C.detailProjections.get(w);if(O){let j=C.graph.elements.get(w);if(!j)throw new Error(`Key not found: ${m}`);let K=UO(m,w,S),Y=new Map;if(O.isRepeat&&K?.instanceIndex!==void 0)for(let ee of j.attributes??[])Y.set(ee.name,vd({file:j.sourceFile,source:d.get(j.sourceFile)??"",element:j,propertyName:ee.name,selectionRef:K,graph:C.graph,sources:d}));let X=yb({element:j,graph:C.graph,source:d.get(j.sourceFile),documentVersion:C.graph.version,selectionRef:S,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:Y}),J=Eb(w,C.graph,C.topology,C.capabilities,O.textSources,O.provenances,O.dynamicData,X);return m===w?J:Xb(J,m,C.document??null,C.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${m}`)},getRenderDetail(m,I){let S=Ur(m,I),C=At(m)??m;if(S?.graph&&S.topology&&S.capabilities&&S.detailProjections){let w=S.detailProjections.get(C);if(w){let O=bb(C,S.graph,S.topology,S.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return m===C?O:Jb(O,m,S.document??null,S.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${m}`)},getClassNameSource(m,I){let S=Ur(m,I),C=At(m)??m;if(!S?.graph)throw new Error(`Key not found: ${m}`);let w=S.graph.elements.get(C);if(!w)throw new Error(`Key not found: ${m}`);let O=d.get(w.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return sl({key:C,route:{composition:S.composition,routeId:S.routeId,graph:S.graph,source:O}})},refreshSourceForKey:uS,async execute(m){if(await x,h)return H(m,M.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(m.kind==="source-edit")return dS(m);if(m.kind==="insert-page-resource")return pS(m);if(m.kind==="delete-page-source")return fS(m);let I=await Gp(m);if("ok"in I)return I;await jp(m);let S=await Gp(m);if("ok"in S)return S;let C=S;if(m.target.kind==="page-unit"){let J=m;return m.kind==="insert-child"||m.kind==="replace-node"?mS(J,C):m.kind==="move-node"||m.kind==="remove-node"?hS(J,C):H(m,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(m.target.kind==="page-block"){let J=m;return m.kind==="insert-child"||m.kind==="replace-node"?gS(J,C):m.kind==="move-node"||m.kind==="remove-node"?yS(J,C):H(m,M.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let O=m.params,j=m.target.kind==="node"?m.target.key:null;if(O.kind==="move-node"&&"kind"in O.target&&O.target.kind==="source-sibling"){let J=O.target,ee=j?C.document?.entries.find(G=>G.key===j):null,se=C.document?.entries.find(G=>G.key===J.anchorKey),be=ee?.pageCompositionActionScope,re=be?.kind==="source-siblings"?be.siblingKeys:null,Re=re?.indexOf(ee?.key??"")??-1,ye=re?.indexOf(J.anchorKey)??-1,D=J.relation==="before"?Re-1:Re+1;if(!ee||!se||!re||Re<0||ye!==D||se.pageCompositionActionScope?.kind!=="source-siblings"||se.pageCompositionActionScope.siblingKeys.length!==re.length||se.pageCompositionActionScope.siblingKeys.some((G,pe)=>G!==re[pe])||!ee.operationSummary.canMove)return H(m,M.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(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:m.target.kind==="route"?M.ROUTE_NOT_FOUND:M.NODE_NOT_FOUND,message:m.target.kind==="route"?"Composition not ready for route target.":m.target.kind==="node"?`Target key not found: ${m.target.key}`:`${m.kind} source target execution is not implemented yet.`}};let K=sF(C,C.graph,C.capabilities,d,i),Y=await new Oa(K).plan(m);if(!Y.ok)return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:$i(Y.errorCode),message:Y.reason}};let X=Y.plan;if(X.steps.length===0)return m.kind==="set-props"?{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!0,resultVersion:Q(m),affectedFiles:[]}:{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(X.steps.some(ee=>ee.type==="invoke-external-adapter")){let ee=await u.execute(X);if(!ee.ok)return H(m,$i(ee.errorCode),ee.reason);let se={composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!0,resultVersion:Math.max(Q(m),ee.resultVersion),affectedFiles:ee.affectedFiles,...ee.selectionRef?{selectionRef:ee.selectionRef}:{}};return $r(se,{rebuiltRoutes:[],failedRoutes:[]}),se}let J=await u.prepareRewritePlan(X);return J.ok?await Vn({request:m,filePlan:J.filePlan,...J.selectionRef?{selectionRef:J.selectionRef}:{}}):H(m,$i(J.errorCode),J.reason)}catch(J){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.INTERNAL_ERROR,message:St(J)}}}finally{p-=1}},async undo(m){if(await x,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await Kp("undo")}finally{p-=1}},async redo(m){if(await x,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await Kp("redo")}finally{p-=1}},notifyFileChanged(m){Fp([m])},getAffectedCompositions(m){return $e(m)},subscribe(m){return r.subscribe(m)}}}function qO(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function eF(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let p=d.get(f)??new Set,h=p.size;return p.add(g),d.set(f,p),p.size!==h},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||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 f=n.placements.find(p=>p.members.some(h=>h.sourceRange!==null&&Vi(d.sourceRange,h.sourceRange)));if(!f)continue;let g=f.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 f=c(d);if(f)for(let g of f)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 f=At(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&Vi(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(Vi(g.sourceRange,E.sourceRange)||iF(E.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let p=o.get(`${g.sourceFile}#${g.componentName}`);if(p){p.size===1&&(d.pageCompositionUnitKey=p.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}tF(e,t,n,r)}function tF(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(p=>p.sourceRange!==null&&Vi(f.sourceRange,p.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let p of l){let h=s.get(p.owner)??s.get(p.ownerDefault)??0;if(!h)continue;let y=s.get(p.target)??0,x=Math.min(2,y+h);x!==y&&(s.set(p.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==(At(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let h=xe(p.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&Ue(x))){u(g)===1&&rE(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!rE(x))continue;let E=d.get(x.node)??[];E.push({entry:f,element:g,parentPath:x}),d.set(x.node,E)}for(let f of d.values()){let g=f[0];if(!g)continue;let p=g.entry.pageCompositionUnitKey,h=[],y=!!(p&&u(g.element)===1);for(let E of g.parentPath.node.children){if(nF(E))continue;if(!rF(E)){y=!1;break}let b=[...t.elements.values()].find(_=>_.sourceFile===g.element.sourceFile&&_.componentName===g.element.componentName&&Vi(_.sourceRange,oF(E))),v=b?o.get(b.identity.key):null;if(!b||!v||v.parentKey||v.pageCompositionUnitKey!==p||u(b)!==1){y=!1;break}h.push(v)}if(!y||h.length!==f.length||f.some(({entry:E})=>!h.some(b=>b.key===E.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let x=h.map(E=>E.key);for(let E of h)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function rE(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function nF(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function rF(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function oF(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 Vi(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function iF(e,t){return oE(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&oE(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function oE(e,t,n,r){return e!==n?e-n:t-r}function sF(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 f=t.elements.get(u);for(let g of f?.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),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=At(h)??h,x=t.elements.get(y);return x?l(h,x):null}).filter(h=>h!==null);let p=t.elements.get(d.baseKey);return p?p.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),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.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),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:sl({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 f=c(u);return zd(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return zd(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=p.attributes?.find(E=>E.name===d);return x?x.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:x,target:{kind:"jsx-attribute",file:p.sourceFile,sourceRange:x.sourceRange}}:(p.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,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return vd({file:p.sourceFile,source:r.get(p.sourceFile)??"",element:p,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=TO(u);return d?{baseKey:d.baseKey,repeatIndex:Kb(e.document??null,u,d.baseKey,e.documentIndex)??Ub(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=At(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(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(p=>({name:p.name,value:p.value,source:p.source?{expression:p.source.expression,base:p.source.base,path:p.source.path.map(h=>({...h}))}:null,resolvedValue:p.resolvedValue}))}}}var aF={"stale-version":M.VERSION_STALE,"capability-denied":M.CAPABILITY_REJECTED,"invalid-params":M.INVALID_PARAMS,"locator-miss":M.LOCATOR_FAILED,"route-not-found":M.ROUTE_NOT_FOUND,"unsupported-operation":M.UNSUPPORTED_OPERATION,"invalid-target":M.INVALID_TARGET,"ast-error":M.AST_PARSE_ERROR,"writeback-failed":M.WRITE_IO_ERROR,"rollback-failed":M.RECOVERY_REQUIRED,unknown:M.INTERNAL_ERROR};function $i(e){return aF[e]}function St(e){return e instanceof Error&&e.message?e.message:String(e)}function iE(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function cF(e){let t=jr(e);if(!FO.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=>LO.map(a=>`${s}/${a}`))}function lF(e){let n=jr(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function uF(e){return cE(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function dF(e){return cE(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function cE(e,t){let n=[];for(let r of e.matchAll(t)){let o=lE(r[1]??"");o&&n.push(o)}return n}function sE(e,t){let n=lE(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?jr(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?jr(`${pF(e)}/${n}`):n.startsWith("/")?jr(n.slice(1)):Zd(n)?jr(n):null}function lE(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Zd(e){return/\.css$/i.test(e)}function pF(e){let t=jr(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function fF(e){return Array.from(new Set(e))}function jr(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 mF(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 rc=class{constructor(t){this.options=t,this.fileSystem=new Ao(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return rs(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 os(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return as(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return cs(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ls(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=hF.safeParse(t);if(!n.success)return{result:ns(t,n.error.issues.map(i=>i.message))};let r=new Ao(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:br(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=yF.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>xF(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 nc({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=is(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 xF(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function bF(e){return new rc(e)}import{SiteEditOperationRequestSchema as vF}from"@vcp-dev/contracts";import ln from"node:fs/promises";import vt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as EF,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as SF}from"@vcp-dev/contracts";var oc=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=nc({...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 as(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return cs(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ls(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 ln.readFile(vt.join(n,r),"utf8")},async readFileBytes(r){return ln.readFile(vt.join(n,r))},async getFileInfo(r){let o=vt.join(n,...r.split("/"));try{let i=await ln.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await _s(vt.join(n,r),o)},async createExclusive(r,o){let i=vt.join(n,r);await ln.mkdir(vt.dirname(i),{recursive:!0});let s=await ln.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await ln.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await ln.rm(vt.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=vt.join(n,i),a=vt.dirname(vt.join(n,o));for(;a!==s&&a.startsWith(`${s}${vt.sep}`);){try{await ln.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=vt.dirname(a);continue}break}a=vt.dirname(a)}},async exists(r){try{return await ln.access(vt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...SF,...EF],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let p=vt.join(n,...d.split("/")),h;try{h=await ln.lstat(p)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let x=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await ln.readdir(p,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,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 Qd(e){return new oc(e)}var ic=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Qd({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=is(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:rs(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:os(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=vF.safeParse(r);if(!o.success)return ns(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:br(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:br(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:br(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 IF(e){return new ic(e)}import{GeneratedSiteCapabilitiesSchema as PF}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as kF}from"@vcp-dev/contracts";function sc(e){let t=CF(e.host_capabilities),n=e.platform_managed_paths??[],r=new Set(e.platform_managed_packages??[]);return e.node.kind==="external"?r.has(e.node.path)?Bn(e.node,"platform-managed","controlled platform package"):t?NF(e.node.path,t)?Bn(e.node,"host-public","declared Starter runtime dependency"):Bn(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Bn(e.node,"unknown","trusted host capability contract is invalid"):uE(e.node.path,n)?Bn(e.node,"platform-managed","controlled platform path"):t?pE(e.node.path,t.generated_sections_path)?Bn(e.node,"private","site-generated section path"):uE(e.node.path,t.public_paths)?Bn(e.node,"host-public","declared Starter public path"):Bn(e.node,"private","site-local file outside host public paths"):Bn(e.node,"unknown","trusted host capability contract is invalid")}function RF(e){return e.nodes.map(t=>sc({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Bn(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function CF(e){let t=kF.safeParse(e);return t.success?t.data:null}function NF(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function uE(e,t){return t.some(n=>pE(e,n))}function pE(e,t){let n=_F(t),r=fE(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):dE(r)===dE(n)}function _F(e){return fE(e.split("#",1)[0]??e)}function fE(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function dE(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function AF(e){let t=PF.safeParse(e.host_capabilities).success,n=[];t||n.push({code:"HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Portable dependency audit requires the schema-validated Starter host contract."}),e.closure.complete||n.push({code:"INCOMPLETE_SOURCE_NODE",path:"<closure>",message:"Portable source closure is not complete."});for(let i of e.closure.errors)n.push({...i});let r=e.closure.nodes.map(i=>{let s=sc({node:i,host_capabilities:e.host_capabilities,platform_managed_paths:e.platform_managed_paths,platform_managed_packages:e.platform_managed_packages});return s.ownership==="unknown"?n.push({code:"UNKNOWN_DEPENDENCY_OWNERSHIP",path:i.path,message:`Portable dependency ownership is not proven for ${i.path}.`}):s.ownership==="unsupported-external-private"&&n.push({code:"UNSUPPORTED_EXTERNAL_DEPENDENCY",path:i.path,message:`Portable source closure depends on unsupported external package ${i.path}.`}),i.status!=="complete"&&n.push({code:"INCOMPLETE_SOURCE_NODE",path:i.path,message:`Portable source node ${i.path} is ${i.status}.`}),{...i,ownership:s.ownership,ownership_reason:s.reason}}),o=TF(n).sort(wF);return{complete:o.length===0,nodes:r.sort(OF),edges:[...e.closure.edges].sort(FF),errors:o}}function TF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function wF(e,t){return jt(e.path,t.path)||jt(e.code,t.code)||jt(e.specifier??"",t.specifier??"")||jt(e.message,t.message)}function OF(e,t){return jt(e.path,t.path)||jt(e.kind,t.kind)||jt(e.ownership,t.ownership)||jt(e.status,t.status)}function FF(e,t){return jt(e.from,t.from)||jt(e.target??"",t.target??"")||jt(e.specifier??"",t.specifier??"")||jt(e.kind,t.kind)||jt(e.resolution,t.resolution)}function jt(e,t){return e<t?-1:e>t?1:0}import*as It from"@babel/types";var mE=[".tsx",".ts",".jsx",".js"],LF=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 Ui(e){let t=jF(e.files),n=hE(e.max_depth??32,"max_depth"),r=hE(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(bE).filter(Boolean))],i=new Map,s=[],a=[],c=new Set,l=new Set,u=new Set,d=[];o.length===0&&a.push({code:"SOURCE_ENTRY_UNRESOLVED",path:"<entry>",message:"Portable source closure requires at least one entry file."});for(let h of o)if(!(!h||l.has(h))){if(!Eo(h,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:h,message:"Portable source closure node budget was exhausted."});continue}l.add(h),d.push({path:h,depth:0})}for(;d.length>0;){let h=d.shift();if(u.has(h.path))continue;u.add(h.path);let y=t.get(h.path);if(y===void 0){let P=o.includes(h.path)?"SOURCE_ENTRY_UNRESOLVED":So(h.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";cr(i,{path:h.path,kind:So(h.path)?"asset":"source",depth:h.depth,status:"unresolved"}),a.push({code:P,path:h.path,message:`Portable source closure could not read ${h.path}.`});continue}let x=So(h.path)?"asset":"source";if(x==="asset"){let P=$F(h.path,y);cr(i,{path:h.path,kind:x,depth:h.depth,status:P?"parse-failed":"complete"}),P&&a.push(P);continue}let E=EE(y),b=Ke(h.path,E);if(!b.ok){cr(i,{path:h.path,kind:x,depth:h.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:h.path,message:b.diagnostic.message});continue}let v=MF(b.module.ast),_=!1;for(let P of v){let R=DF({from:h.path,depth:h.depth,reference:P,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(R.edge),R.next&&(R.next.depth>n?_=!0:!u.has(R.next.path)&&!l.has(R.next.path)&&(l.add(R.next.path),d.push(R.next))),R.depthExhausted&&(_=!0)}cr(i,{path:h.path,kind:x,depth:h.depth,status:_?"depth-exhausted":"complete"}),_&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:h.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(zF),g=JF(s).sort(HF),p=XF(a).sort(WF);return{entry_files:o.sort(In),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function DF(e){let{reference:t}=e;if(t.specifier===null)return e.errors.push({code:"SOURCE_DYNAMIC_IMPORT_UNRESOLVED",path:e.from,message:"Portable source closure cannot resolve a non-literal dynamic import."}),{edge:{from:e.from,specifier:null,kind:t.kind,target:null,resolution:"non-literal"},depthExhausted:!1};if(!Rt(t.specifier)){let o=UF(t.specifier);return Eo(o,e.discovered,e.maxNodes)?(cr(e.nodes,{path:o,kind:"external",depth:null,status:"complete"}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"external"},depthExhausted:!1}):(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:o,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"budget-exhausted"},depthExhausted:!1})}let n=ep(e.from,t.specifier);if(SE(e.from,t.specifier,n))return e.errors.push({code:"SOURCE_UNSAFE_IMPORT",path:n,specifier:t.specifier,message:`Portable source closure rejected unsafe local import ${t.specifier} from ${e.from}.`}),Eo(n,e.discovered,e.maxNodes)?cr(e.nodes,{path:n,kind:So(n)?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1};let r=xE(e.from,t.specifier,e.files);if(!r){let o=So(n);return e.errors.push({code:o?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED",path:n,specifier:t.specifier,message:`Portable source closure could not resolve ${t.specifier} from ${e.from}.`}),Eo(n,e.discovered,e.maxNodes)?cr(e.nodes,{path:n,kind:o?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1}}if(e.depth>=e.maxDepth&&!e.visited.has(r)&&!e.queued.has(r)){let o=So(r)?"asset":"source";return Eo(r,e.discovered,e.maxNodes)?cr(e.nodes,{path:r,kind:o,depth:e.depth+1,status:"depth-exhausted"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!0}}return Eo(r,e.discovered,e.maxNodes)?{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"resolved"},next:{path:r,depth:e.depth+1},depthExhausted:!1}:(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!1})}function MF(e){let t=[];for(let n of e.program.body)It.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):It.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):It.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return qd(e.program,n=>{if(It.isCallExpression(n)&&It.isImport(n.callee)){let r=n.arguments[0];It.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}It.isTSImportType(n)&&t.push({specifier:It.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),KF(t)}function qd(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)yE(r)&&qd(r,t);else yE(n)&&qd(n,t)}function BF(e,t,n){let r=ep(e,t);return!Rt(t)||SE(e,t,r)?null:xE(e,t,n)}function xE(e,t,n){let r=ep(e,t);if(!r||r.startsWith("../")||r==="..")return null;if(n.has(r))return r;let o=r.replace(/[?#].*$/u,"");if(o!==r&&n.has(o))return o;if(VF(o))return null;for(let i of mE){let s=`${o}${i}`;if(n.has(s))return s}for(let i of mE){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function ep(e,t){let n=Nn(e,t);return bE(n)}function bE(e){let t=e.replace(/\\/g,"/"),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.length>0&&n.at(-1)!==".."?n.pop():n.push("..");continue}n.push(r)}return n.join("/")}function jF(e){return e instanceof Map?e:new Map(Object.entries(e))}function EE(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function $F(e,t){if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(EE(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function cr(e,t){let n=e.get(t.path);(!n||gE(t.status)>gE(n.status))&&e.set(t.path,t)}function Eo(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function gE(e){return e==="complete"?1:0}function So(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&LF.has(n)}function VF(e){return/\.[a-z0-9]+$/iu.test(e)}function UF(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function KF(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}\0${n.specifier??"<dynamic>"}`;return t.has(r)?!1:(t.add(r),!0)})}function JF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function XF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function zF(e,t){return In(e.path,t.path)||In(e.kind,t.kind)}function HF(e,t){return In(e.from,t.from)||In(e.target??"",t.target??"")||In(e.specifier??"",t.specifier??"")||In(e.kind,t.kind)}function WF(e,t){return In(e.path,t.path)||In(e.code,t.code)||In(e.specifier??"",t.specifier??"")}function In(e,t){return e<t?-1:e>t?1:0}function hE(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function yE(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function SE(e,t,n){if(t.includes("\0")||t.includes("\\")||n.startsWith("../")||n===".."||n.startsWith("/"))return!0;if(t.startsWith("@/")){let r=t.slice(2);return r.length===0||r.split("/").some(o=>o==="..")}return e.startsWith("/")}import{parse as pp}from"@babel/parser";import*as B from"@babel/types";import{PortableCollectionRecipeFactsSchema as fL}from"@vcp-dev/contracts";import{parse as lr}from"@babel/parser";import*as V from"@babel/types";function GF(e){let t=PE(e.files),n=(d,f,g)=>({complete:!1,relation:null,errors:[{code:d,path:f,message:g}]}),r=vo(e.list_entry_file,e.selected_component_source,t),o=r?t.get(r):void 0;if(!r||typeof o!="string")return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",e.list_entry_file,"The selected Page Unit does not resolve to one Snapshot list container.");if(!QF(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=ZF(o,r),s=i?ac(r,o,i,"listStrict"):null;if(!i||!s)return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",r,"The selected list container does not prove one literal CMS collection.");let a=[...t.entries()].flatMap(([d,f])=>{if(typeof f!="string"||!/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(d))return[];let g=ac(d,f,i,"getByUrlStrict");return g&&RE(g.ast,i)===`/${i}`?[g]:[]});if(a.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let c=a[0],l=Mn(c.source,{filePath:c.path,exportName:"default"}).components.flatMap(d=>{let f=vo(c.path,d.source,t),g=f?t.get(f):void 0;return!f||typeof g!="string"||!kE(g,d.export_name)||!rp(g,c.adapter_source,c.interface_name)?[]:[{path:f,export_name:d.export_name}]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c.path,"The collection detail route does not prove one private detail view.");let u=l[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:c.path,detail_view_file:u.path,detail_view_export:u.export_name},errors:[]}}function ap(e){let t=PE(e.files),n=[],r=[],o=[],i=null;e.source_closure.complete||n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"The selected Page Unit source closure is incomplete; related entries cannot be proven."}),tp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),tp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),tp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),np(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),np(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=Ui({entry_files:[e.collection.detail_entry_file],files:t});s.complete||n.push(...s.errors.map(f=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:f.message})));let a=s.nodes.find(f=>f.path===e.collection.detail_view_file);!a||a.status!=="complete"?n.push({code:"RELATED_DETAIL_VIEW_NOT_REACHED",path:e.collection.detail_view_file,message:"The trusted detail route does not reach the declared detail-view entry."}):r.push({path:e.collection.detail_view_file,export:e.collection.detail_view_export==="default"?{kind:"default"}:{kind:"named",name:e.collection.detail_view_export},purpose:"collection-detail-view"});for(let f of s.nodes)if(f.kind!=="external"&&f.path!==e.collection.detail_entry_file&&f.path!==e.collection.detail_view_file){if(oL(f.path,e.collection)){np(o,{path:f.path,kind:f.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}iL(f.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:f.path,export:{kind:"default"},purpose:"i18n-companion"})}let c=t.get(e.collection.detail_view_file);typeof c=="string"&&nL(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=rL(e.page_template,t,n));let l=e.trusted_schema===void 0?null:YF(e,t,n,e.trusted_schema),u=cL(r).map((f,g)=>({key:uL(f,g),pathTemplate:f.path,export:f.export,purpose:f.purpose,requirementKey:e.collection.requirement_key})),d=dL(n).sort(pL);return{complete:d.length===0,entries:u.sort((f,g)=>f.pathTemplate.localeCompare(g.pathTemplate)||f.purpose.localeCompare(g.purpose)||f.key.localeCompare(g.key)),managed_requirements:o.sort(lL),thin_entry_plan:i,collection_wiring:l,errors:d}}function YF(e,t,n,r){let o=n.length,i=r.fields.map(v=>({...v}));(r.source_slug!==e.collection.slug||!r.evidence_path.trim()||i.length===0)&&n.push({code:"RELATED_COLLECTION_SCHEMA_UNPROVEN",path:r.evidence_path||`trusted-schema:${e.collection.slug}`,message:"Collection recipe facts require a non-empty trusted CMS schema with matching source identity."});let s=e.source_closure.nodes.filter(v=>v.kind==="source"&&v.status==="complete"&&v.path!==e.collection.list_entry_file).flatMap(v=>{let _=t.get(v.path);if(typeof _!="string")return[];let P=ac(v.path,_,e.collection.slug,"listStrict");return P?[P]:[]});s.length!==1&&n.push({code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.collection.list_entry_file,message:"Exactly one rendered source module must prove the selected collection listStrict wiring."});let a=s[0]??null,c=a?vE(a,t,v=>v!==e.collection.detail_view_file):null;c?a&&!rp(t.get(c.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:c.source_path,message:"The rendered list view does not consume the generated collection interface."}):n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:a?.path??e.collection.list_entry_file,message:"The generated list container must render one resolvable private list view."});let l=t.get(e.collection.detail_entry_file),u=typeof l=="string"?ac(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict"):null,d=u?vE(u,t,v=>v===e.collection.detail_view_file):null;!u||!d||d.export_name!==e.collection.detail_view_export?n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The trusted detail route must consume the declared detail view through the same collection adapter."}):rp(t.get(d.source_path),u.adapter_source,u.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:d.source_path,message:"The rendered detail view does not consume the generated collection interface."}),a&&u&&(a.adapter_source!==u.adapter_source||a.interface_name!==u.interface_name)&&n.push({code:"RELATED_COLLECTION_ADAPTER_UNPROVEN",path:e.collection.detail_entry_file,message:"List and detail consumers must use the same generated collection adapter and view interface."});let f=new Set(i.map(v=>v.name)),g=a?vo(a.path,a.adapter_source,t):null,p=g?t.get(g):null,h=[...e.required_fields??i.filter(v=>v.required).map(v=>v.name)].sort(sp),y=[...e.force_multi_media??(typeof p=="string"?CE(p):[])].sort(sp);for(let v of[...h,...y])f.has(v)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${v}`,message:`Collection field ${v} is not present in the trusted schema.`});if(a&&y.length)for(let v of y)(typeof p!="string"||!tL(p,v))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${v}.`});let x=u?RE(u.ast,e.collection.slug):null;x||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The detail route does not prove a literal getByUrlStrict prefix."});let E=u?qF(u.ast):null;E||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The generated detail route must expose a literal PAGE_SEO title."});let b=u?eL(u,t,x):null;return b==="unproven"&&n.push({code:"RELATED_COLLECTION_BREADCRUMB_UNPROVEN",path:e.collection.detail_entry_file,message:"The rendered collection breadcrumb exists but its fallback labels are not literal."}),n.length!==o||!a||!c||!u||!d||!x?null:{source_slug:e.collection.slug,detail_prefix:x,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...c,interface_name:a.interface_name},detail_view:{...d,interface_name:u.interface_name},...E?{title:E}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...h.length>0?{required_fields:h}:{},...y.length>0?{force_multi_media:y}:{}}}function ac(e,t,n,r){let o;try{o=lr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let i=jn(o,c=>{if(!V.isCallExpression(c)||!lc(c.callee,r))return!1;let l=c.arguments[0];return r==="listStrict"?V.isStringLiteral(l)&&l.value===n:op(l,ip(o))!==null});if(r==="listStrict"&&i.length!==1||r==="getByUrlStrict"&&(i.length===0||i.some(c=>op(c.arguments[0],ip(o))!==`/${n}`)))return null;let a=o.program.body.flatMap(c=>V.isImportDeclaration(c)?c.specifiers.flatMap(l=>{if(!V.isImportSpecifier(l))return[];let u=V.isIdentifier(l.imported)?l.imported.name:l.imported.value,d=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(u);return d?[{source:c.source.value,local_name:l.local.name,interface_name:d[1]}]:[]}):[]).filter(c=>jn(o,l=>V.isIdentifier(l,{name:c.local_name})).length>1);return a.length!==1?null:{path:e,source:t,ast:o,adapter_source:a[0].source,interface_name:a[0].interface_name}}function ZF(e,t){let n;try{n=lr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=jn(n,o=>V.isCallExpression(o)&&lc(o.callee,"listStrict")&&V.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9]{1,30}$/u.test(r[0])?r[0]:null}function QF(e,t,n){let r;try{r=lr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return jn(r,o=>V.isCallExpression(o)&&lc(o.callee,n)).length>0}function vE(e,t,n){let r=Mn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=vo(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!kE(a,i.export_name)?[]:[{source_path:s,target_path:s,export_name:i.export_name,import_specifier:i.source}]});return o.length===1?o[0]:null}function kE(e,t){let n;try{n=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&V.isExportDefaultDeclaration(r))return!0;if(V.isExportNamedDeclaration(r)&&(r.declaration&&(V.isFunctionDeclaration(r.declaration)||V.isClassDeclaration(r.declaration)||V.isTSInterfaceDeclaration(r.declaration)||V.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||V.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>V.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>V.isExportSpecifier(o)?(V.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function rp(e,t,n){if(typeof e!="string")return!1;let r;try{r=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!V.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>V.isImportSpecifier(s)?(V.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>jn(r,s=>V.isIdentifier(s,{name:i})).length>1)}function lc(e,t){return V.isMemberExpression(e)&&!e.computed&&V.isIdentifier(e.property,{name:t})&&V.isMemberExpression(e.object)&&!e.object.computed&&V.isIdentifier(e.object.property,{name:"collections"})&&V.isIdentifier(e.object.object,{name:"cms"})}function RE(e,t){let n=ip(e),r=jn(e,i=>V.isCallExpression(i)&&lc(i.callee,"getByUrlStrict"));return r.length===0?null:r.map(i=>op(i.arguments[0],n)).every(i=>i===`/${t}`)?`/${t}`:null}function op(e,t){return V.isBinaryExpression(e,{operator:"+"})&&V.isStringLiteral(e.left)&&V.isIdentifier(e.right)&&t.has(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):V.isTemplateLiteral(e)&&e.expressions.length===1&&V.isIdentifier(e.expressions[0])&&t.has(e.expressions[0].name)&&e.quasis.length>0&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.quasis[0].value.cooked??"")?(e.quasis[0].value.cooked??"").slice(0,-1):null}function ip(e){let t=e.program.body.find(i=>V.isExportDefaultDeclaration(i));if(!V.isExportDefaultDeclaration(t))return new Set;let n=t.declaration;if(!V.isFunctionDeclaration(n)&&!V.isFunctionExpression(n)&&!V.isArrowFunctionExpression(n))return new Set;let r=new Set;for(let i of n.params)if(V.isObjectPattern(i))for(let s of i.properties)V.isObjectProperty(s)&&!s.computed&&cc(s.key)==="params"&&V.isIdentifier(s.value)&&r.add(s.value.name);if(r.size===0)return new Set;let o=new Set;for(let i of jn(n.body,s=>V.isVariableDeclarator(s)))if(!(!V.isObjectPattern(i.id)||!V.isAwaitExpression(i.init)||!V.isIdentifier(i.init.argument)||!r.has(i.init.argument.name)))for(let s of i.id.properties)V.isObjectProperty(s)&&!s.computed&&cc(s.key)==="slug"&&V.isIdentifier(s.value)&&o.add(s.value.name);return o}function qF(e){for(let t of e.program.body)if(V.isVariableDeclaration(t))for(let n of t.declarations){if(!V.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=NE(n.init);if(!V.isObjectExpression(r))return null;let o=r.properties.find(i=>V.isObjectProperty(i)&&!i.computed&&cc(i.key)==="title");return o&&V.isStringLiteral(o.value)?o.value.value:null}return null}function eL(e,t,n){let o=Mn(e.source,{filePath:e.path,exportName:"default"}).components.filter(c=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(c.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=vo(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=lr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of jn(a,l=>V.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!V.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!V.isObjectProperty(p)||p.computed)continue;let h=cc(p.key);h&&V.isStringLiteral(p.value)&&g.set(h,p.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=l.find(f=>f.get("href")==="/"),d=l.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function CE(e){let t;try{t=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(jn(t,n=>{if(!V.isCallExpression(n))return!1;let r=n.callee;if(!V.isMemberExpression(r)||r.computed||!V.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return V.isMemberExpression(o)&&!o.computed&&V.isIdentifier(o.object,{name:"d"})&&V.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return V.isMemberExpression(r)&&!r.computed&&V.isIdentifier(r.property)?[r.property.name]:[]}))].sort(sp)}function tL(e,t){return CE(e).includes(t)}function jn(e,t){let n=[],r=o=>{t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)IE(s)&&r(s);else IE(i)&&r(i)};return r(e),n}function IE(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function NE(e){return e?V.isTSAsExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e)?NE(e.expression):e:null}function cc(e){return V.isIdentifier(e)?e.name:V.isStringLiteral(e)?e.value:null}function sp(e,t){return e.localeCompare(t)}function nL(e,t,n,r,o){let i=Mn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=vo(t,s.source,r);if(!a)continue;let c=n.find(u=>u.path===a),l=r.get(a);!c||c.kind==="external"||typeof l!="string"||sL(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function rL(e,t,n){let r=t.get(e.entry_file);if(typeof r!="string")return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:"The PageTemplate entry source is not available as text."}),null;let o=Mn(r,{filePath:e.entry_file,exportName:"default"});if(o.diagnostics.length>0)return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:o.diagnostics[0]?.message??"PageTemplate AST is incomplete."}),null;let i=o.rendered_component_openings;if(i.length!==1)return n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"A single-file PageTemplate is portable only when one real component call can be isolated; the whole page cannot be copied."}),null;let s=i[0];return e.component_source&&s.source!==e.component_source||e.component_export&&s.export_name!==e.component_export?(n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"The declared PageTemplate root does not match its real rendered component call."}),null):{kind:"managed-root-thin-entry",source_file:e.entry_file,component_source:s.source,component_export:s.export_name,adds_dom:!1}}function tp(e,t,n,r){e.has(t)||r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function oL(e,t){return e===t.list_entry_file||e===t.detail_entry_file||e.startsWith("lib/cms/")||e===`components/site/generated/${t.slug}-list.tsx`||e===`components/site/generated/${t.slug}-list.ts`||e===`components/site/generated/${t.slug}-list.jsx`||e===`components/site/generated/${t.slug}-list.js`||e===`components/site/generated/${t.slug}-breadcrumb.tsx`||e===`components/site/generated/${t.slug}-breadcrumb.ts`||e===`components/site/generated/${t.slug}-breadcrumb.jsx`||e===`components/site/generated/${t.slug}-breadcrumb.js`}function iL(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=_E(t),s=o.slice(o.lastIndexOf("/")+1),a=s.endsWith("-detail-view")?s.slice(0,-12):n;return r===`${o}.i18n.json`||r===`${o}.messages.json`||r===`${i}/${a}.i18n.json`||r===`${i}/${a}.messages.json`||/(?:^|\/)(?:i18n|locales?)\/[^/]+\.json$/u.test(r)||/\.(?:i18n|messages)\.[^/]+\.json$/u.test(r)}function sL(e){try{let n=lr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return n?.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&n.expression.value==="use client"}catch{return!1}}function vo(e,t,n){let r=t.startsWith("@/")?t.slice(2):aL(`${_E(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 _E(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function aL(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.length>0&&t.at(-1)!==".."?t.pop():t.push(".."):t.push(n));return t.join("/")}function PE(e){return e instanceof Map?e:new Map(Object.entries(e))}function cL(e){let t=new Set;return e.filter(n=>{let r=`${n.path}\0${n.purpose}\0${JSON.stringify(n.export)}`;return t.has(r)?!1:(t.add(r),!0)})}function np(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function lL(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function uL(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function dL(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function pL(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var mL=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),gL=new Set(["data-vcp-block-id","data-vcp-edit-key"]),hL=new Set(["data-vcp-order","sourceOrder","source_order"]);function Ji(e){let t=f=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...f].sort(dp)}),n;try{n=pp(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(f){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:f instanceof Error?f.message:String(f)}])}let r=CL(n),o=Mn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(f=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:f.file_path||e.file_path,message:f.message})),s=new Set(o.rendered_component_openings.filter(f=>f.source===e.target.source&&f.export_name===e.target.export_name).map(f=>f.start_offset)),a=[],c=0;if(up(n,new Set,(f,g)=>{if(!B.isJSXElement(f))return;let p=f.openingElement,h=p.start;if(typeof h!="number"||e.call_source_range&&(p.loc?.start.line!==e.call_source_range.start_line||p.loc.start.column!==e.call_source_range.start_column))return;let y=TL(p.name);if(!y)return;let x=wL(p.name,r);x&&(e.target.local_name&&e.target.local_name!==y||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(h)&&a.push({node:p,element:f,local:x,context:g,ordinal:c++}))}),a.length===0)return t([...i,{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let l=a.map(f=>NL(e,f.node,f.element,f.local,f.context,f.ordinal)),u=_L(l,e.target.original_block_id);if(!u)return t([...i,{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected component is rendered more than once and no unique original block identity was provided."}]);let d=[...i,...u.errors];return{complete:d.length===0,entry_file:e.file_path,target:e.target,call:u.call,bindings:d.length===0?u.bindings:[],original_block_id:u.original_block_id,original_order:u.original_order,semantic_props:u.semantic_props,errors:OE(d).sort(dp)}}function yL(e){let t;try{t=pp(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return{invocation:null,errors:[{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}]}}let n=nn({route:e.route,composition:e.composition.templateId===void 0?{routeId:e.composition.routeId}:{routeId:e.composition.routeId,effectiveTemplateId:e.composition.templateId},entryFile:e.file_path,version:e.document_version,source:e.source,ast:t});if(!n.ok)return{invocation:null,errors:n.projection.diagnostics.map(a=>({code:"INVOCATION_PAGE_UNIT_UNSUPPORTED",path:e.file_path,message:a.message}))};let r=n.projection.placementUnitByKey.get(e.placement_unit_key),o=r?.sourceRange;if(!r||!o)return{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit key does not belong to the pinned document version."}]};let i=Mn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Ji({file_path:e.file_path,source:e.source,target:a,call_source_range:{start_line:o.startLine,start_column:o.startColumn}})).filter(a=>a.call!==null);return s.length!==1?{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit does not resolve to exactly one rendered imported component."}]}:{invocation:s[0],errors:s[0].errors}}function xL(e){let t=Ji(e),n=ap({files:e.files,source_closure:e.source_closure,collection:e.collection,trusted_schema:e.trusted_schema,...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),r=[...t.errors],o=[];e.source_closure.complete||r.push({code:"COLLECTION_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"Collection recipe analysis requires a complete selected source closure."});for(let f of n.errors)r.push({code:SL(f.code),path:f.path,message:f.message});t.call&&o.push({fact:"invocation",path:t.call.source_file,reason:"The selected rendered component call supplies the portable invocation bindings.",source_range:t.call.source_range});let i=vL(e.files),s=n.collection_wiring,a=IL(e.file_path,e.target.source,i),c=a?i.get(a):null,l=a&&typeof c=="string"?bL(c,a,e.collection.slug):null;if(!a)r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation target does not resolve to a Snapshot source file."});else if(!l)r.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:a,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{o.push({fact:"pagination",path:a,reason:l.paginate?`listStrict consumes route searchParams with literal pageSize ${l.limit}.`:`listStrict is embedded and uses literal top-N ${l.limit}.`});let f=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(l.paginate&&f.length!==1||!l.paginate&&f.length!==0)&&r.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:l.paginate?"A paginated collection must receive the selected route searchParams exactly once.":"An embedded collection cannot carry a route searchParams binding.",source_range:t.call?.source_range})}s&&a!==s.list_container_file&&r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation does not resolve to the proven collection list container."});let u=null;if(s&&l&&r.length===0){let f={source_slug:s.source_slug,list_mode:l.paginate?"page":"embedded",paginate:l.paginate,...l.paginate?{page_size:l.limit}:{top_n:l.limit},detail_prefix:s.detail_prefix,schema:s.schema.map(p=>({...p})),list_view:{...s.list_view},detail_view:{...s.detail_view},...s.title?{title:s.title}:{},...s.breadcrumb?{breadcrumb:{...s.breadcrumb}}:{},...s.required_fields?{required_fields:[...s.required_fields]}:{},...s.force_multi_media?{force_multi_media:[...s.force_multi_media]}:{},list_route_required:l.paginate},g=fL.safeParse(f);g.success?(u=g.data,o.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${s.detail_prefix}.`},{fact:"list-view",path:s.list_view.source_path,reason:`The list container renders ${s.list_view.export_name} with ${s.list_view.interface_name}.`},{fact:"detail-view",path:s.detail_view.source_path,reason:`The detail route renders ${s.detail_view.export_name} with ${s.detail_view.interface_name}.`},{fact:"schema",path:s.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):r.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${s.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=OE(r).sort(dp);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(RL),related_entries:n}}function bL(e,t,n){let r;try{r=pp(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=EL(r);if(!o)return null;let i=cp(o,f=>{if(!B.isCallExpression(f))return!1;let g=f.callee;return B.isMemberExpression(g)&&!g.computed&&B.isIdentifier(g.property,{name:"listStrict"})&&B.isMemberExpression(g.object)&&!g.object.computed&&B.isIdentifier(g.object.property,{name:"collections"})&&B.isIdentifier(g.object.object,{name:"cms"})&&B.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!B.isObjectExpression(s)||s.properties.some(f=>B.isSpreadElement(f)))return null;let a=s.properties.find(f=>B.isObjectProperty(f)&&!f.computed&&dc(f.key)==="pageSize");if(!a||!B.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>B.isObjectProperty(f)&&!f.computed&&dc(f.key)==="page"))return null;let l=s.properties.some(f=>B.isObjectProperty(f)&&!f.computed&&dc(f.key)==="category"),u=cp(o,f=>B.isAwaitExpression(f)&&B.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=cp(o,f=>{if(!B.isCallExpression(f))return!1;let g=f.callee;return B.isMemberExpression(g)&&!g.computed&&B.isIdentifier(g.property,{name:"categories"})&&B.isMemberExpression(g.object)&&!g.object.computed&&B.isIdentifier(g.object.property,{name:"collections"})&&B.isIdentifier(g.object.object,{name:"cms"})&&B.isStringLiteral(f.arguments[0],{value:n})}).length;return u===1&&(!l||d!==1)||u===0&&(l||d!==0)?null:{paginate:u===1,limit:a.value.value}}function EL(e){let t=e.program.body.find(n=>B.isExportDefaultDeclaration(n));return B.isExportDefaultDeclaration(t)&&(B.isFunctionDeclaration(t.declaration)||B.isFunctionExpression(t.declaration)||B.isArrowFunctionExpression(t.declaration))?t.declaration:null}function cp(e,t){let n=[],r=o=>{if(!(o!==e&&mp(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)pc(s)&&r(s);else pc(i)&&r(i)}};return r(e),n}function SL(e){return e==="RELATED_COLLECTION_SCHEMA_UNPROVEN"?"COLLECTION_SCHEMA_UNPROVEN":e==="RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN"?"COLLECTION_LIST_CONTAINER_UNPROVEN":e==="RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN"||e==="RELATED_DETAIL_ENTRY_MISSING"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function vL(e){return e instanceof Map?e:new Map(Object.entries(e))}function IL(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):kL(`${r}/${t}`);return[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`,`${o}/index.tsx`,`${o}/index.ts`,`${o}/index.jsx`,`${o}/index.js`].find(i=>n.has(i))??null}function kL(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function RL(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function CL(e){let t=new Map;for(let n of e.program.body){if(!B.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(B.isIdentifier(o.local)){if(B.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(B.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(B.isImportSpecifier(o)){let i=B.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{source:r,export_name:i,local_name:o.local.name})}}}return t}function NL(e,t,n,r,o,i){let s=FL(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(h,y)=>{if(u.has(h)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${h}`,message:`Portable invocation contains duplicate prop ${h}.`,source_range:s});return}u.add(h),c.push({propName:h,value:y}),(h==="type"||h==="variant")&&y.kind==="json-literal"&&(l[h]=y.value)};for(let h of t.attributes){if(B.isJSXSpreadAttribute(h)){let v=ur(h.argument);if(!v.ok||!wE(v.value)){a.push({code:"INVOCATION_SPREAD_UNRESOLVED",path:`${e.file_path}:spread`,message:"Portable invocation cannot prove the props supplied by a spread expression.",source_range:s});continue}for(let[_,P]of Object.entries(v.value)){if(!TE(_)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${_}`,message:`Portable invocation cannot encode prop ${_}.`,source_range:s});continue}g(_,lp(P))}continue}let y=OL(h.name);if(!y)continue;let x=h.value,E=x&&B.isJSXExpressionContainer(x)?x.expression:null;if(gL.has(y)){let v=x?uc(x):{ok:!0,value:!0};!v.ok||typeof v.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=v.value;continue}if(hL.has(y)){let v=x?uc(x):{ok:!0,value:!0};!v.ok||typeof v.value!="number"||!Number.isSafeInteger(v.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=v.value;continue}if(!TE(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(mL.has(y)){let v=x?uc(x):{ok:!0,value:!0};v.ok&&typeof v.value=="string"?d=v.value:E&&AE(E,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),g(y,{kind:"target-block-id"});continue}if(E&&AE(E,o)){g(y,{kind:"route-search-params"});continue}let b=x?uc(x):{ok:!0,value:!0};if(!b.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot prove a JSON-literal value for ${y}.`,source_range:s});continue}g(y,lp(b.value))}let p=PL(n);return p.ok?p.value!==null&&g("children",lp(p.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:p.message,source_range:s}),{call:{source_file:e.file_path,component_source:r.source,export_name:r.export_name,local_name:r.local_name,ordinal:i,source_range:s},bindings:c,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:l,errors:a}}function _L(e,t){if(e.length===1)return e[0]??null;if(!t)return null;let n=e.filter(r=>r.original_block_id===t);return n.length===1?n[0]??null:null}function uc(e){return e===null?{ok:!0,value:!0}:B.isStringLiteral(e)?{ok:!0,value:e.value}:B.isJSXExpressionContainer(e)?ur(e.expression):{ok:!1}}function ur(e){if(!e)return{ok:!1};if(B.isStringLiteral(e))return{ok:!0,value:e.value};if(B.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(B.isBooleanLiteral(e))return{ok:!0,value:e.value};if(B.isNullLiteral(e))return{ok:!0,value:null};if(B.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(B.isTSAsExpression(e)||B.isTSTypeAssertion(e)||B.isTSNonNullExpression(e))return ur(e.expression);if(B.isUnaryExpression(e)){let t=ur(e.argument);return!t.ok||e.operator==="+"&&typeof t.value=="number"?t:e.operator==="-"&&typeof t.value=="number"?{ok:!0,value:-t.value}:e.operator==="!"&&typeof t.value=="boolean"?{ok:!0,value:!t.value}:{ok:!1}}if(B.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=ur(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(B.isObjectExpression(e)){let t={};for(let n of e.properties){if(B.isSpreadElement(n)){let i=ur(n.argument);if(!i.ok||!wE(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!B.isObjectProperty(n)||n.computed)return{ok:!1};let r=dc(n.key);if(!r)return{ok:!1};let o=ur(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function PL(e){if(e.children.length===0)return{ok:!0,value:null};let t=[];for(let n of e.children){if(B.isJSXText(n)){n.value&&t.push(n.value);continue}if(B.isJSXExpressionContainer(n)){let r=ur(n.expression);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value);continue}return{ok:!1,message:"Portable invocation cannot move JSX child components as JSON props."}}return t.length===0?{ok:!0,value:null}:{ok:!0,value:t.length===1?t[0]:t}}function up(e,t,n){let r=mp(e)?new Set([...t,...AL(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)pc(i)&&up(i,r,n);else pc(o)&&up(o,r,n)}function AL(e){if(!mp(e))return[];let t=[];for(let n of e.params)Ki(n,t);return t}function Ki(e,t){if(B.isIdentifier(e)){t.push(e.name);return}if(B.isAssignmentPattern(e)){Ki(e.left,t);return}if(B.isObjectPattern(e)){for(let n of e.properties)B.isRestElement(n)?Ki(n.argument,t):B.isObjectProperty(n)&&Ki(n.value,t);return}if(B.isArrayPattern(e))for(let n of e.elements)n&&Ki(n,t)}function AE(e,t){return B.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):B.isMemberExpression(e)&&!e.computed&&B.isIdentifier(e.property)&&e.property.name==="searchParams"&&B.isIdentifier(e.object)&&t.names.has(e.object.name)}function lp(e){return{kind:"json-literal",value:e}}function wE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function TE(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function TL(e){if(B.isJSXIdentifier(e))return e.name;if(!B.isJSXMemberExpression(e))return null;let t=fp(e.object);return t?`${t}.${e.property.name}`:null}function fp(e){if(B.isJSXIdentifier(e))return e.name;if(!B.isJSXMemberExpression(e))return null;let t=fp(e.object);return t?`${t}.${e.property.name}`:null}function wL(e,t){if(B.isJSXIdentifier(e))return t.get(e.name)??null;if(!B.isJSXMemberExpression(e))return null;let n=fp(e.object);if(!n)return null;let r=t.get(n);return!r||r.export_name!=="*"?null:{source:r.source,export_name:e.property.name,local_name:`${n}.${e.property.name}`}}function OL(e){return B.isJSXIdentifier(e)?e.name:B.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function dc(e){return B.isIdentifier(e)?e.name:B.isStringLiteral(e)||B.isNumericLiteral(e)?String(e.value):null}function mp(e){return B.isFunctionDeclaration(e)||B.isFunctionExpression(e)||B.isArrowFunctionExpression(e)}function pc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function FL(e){return{start_offset:e.start??0,end_offset:e.end??e.start??0,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function OE(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function dp(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import gp from"@babel/generator";import{parse as LL}from"@babel/parser";import DL from"@babel/traverse";import*as rt from"@babel/types";var hp=DL,ML=typeof hp=="function"?hp:hp.default,BL=typeof gp=="function"?gp:gp.default,jE="components/site/generated/{{$INSTANCE}}/",$E=new Set([".tsx",".ts",".jsx",".js"]),FE=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),jL=new Set(["data-site-block-order","data-vcp-order"]);function $L(e){let t=[],n=new Map,r=new Map;/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e.instance_base_name)||t.push({code:"SOURCE_INPUT_INVALID",path:"instance_base_name",message:"The portable instance base name is not safe."});for(let b of e.source_files){let v=$n(b.path);if(!v||n.has(v)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(v,{...b,path:v})}for(let b of e.ownership){let v=$n(b.path);if(!v||r.has(v)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(v,{...b,path:v})}let o=$n(e.entry_file);n.get(o)?r.get(o)?.ownership!=="private"&&t.push({code:"SOURCE_ENTRY_NOT_PRIVATE",path:o,message:"The selected portable source entry must be private source."}):t.push({code:"SOURCE_ENTRY_NOT_FOUND",path:e.entry_file,message:"The selected portable source entry is not present."});for(let b of n.keys())r.has(b)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:b,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(b=>r.get(b)?.ownership==="private").sort((b,v)=>b.localeCompare(v)),a=s.map(b=>({source_path:b,path_template:WL(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=VL(e.source_mapping??[],c,t),u=UL(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let b of s){let v=n.get(b);if(!v)continue;let _=JL(b,v.content,r,c,d,f,t);_!==null&&g.push({path_template:c.get(b),content:_,...v.role?{role:v.role}:{}})}let p=ME(t).sort(BE);if(p.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:p};let h=g.map(b=>{let v=a.find(P=>P.path_template===b.path_template)?.source_path,_=n.get(v)?.content??"";return{source_path:v,path_template:b.path_template,original_byte_size:LE(_),output_byte_size:LE(b.content),original_line_count:DE(_),output_line_count:DE(b.content)}}),y=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,v)=>b.source_path.localeCompare(v.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=KL(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let E=ME(t).sort(BE);return E.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:E}:{complete:!0,entry_path_template:x,files:g.sort((b,v)=>b.path_template.localeCompare(v.path_template)),source_path_mappings:h.sort((b,v)=>b.path_template.localeCompare(v.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(qL),block_metadata:y,errors:[]}}function VL(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=$n(s.generated_path),c=$n(s.source_file),l=a,u=t.get(a);if(!a||a!==s.generated_path||!c||c!==s.source_file||!s.structural_path||r.has(l)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`source_mapping.${i}`,message:"Portable selected-source mappings require unique safe paths and structural identities."});continue}if(r.add(l),!u){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:s.generated_path,message:"A selected-source mapping must resolve to one private normalized entry path."});continue}o.push({...s,path_template:u})}return o.sort((i,s)=>i.path_template.localeCompare(s.path_template)||i.source_file.localeCompare(s.source_file)||i.structural_path.localeCompare(s.structural_path))}function UL(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=$n(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!c||r.has(a.key)||o.has(c)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`required_source_paths.${s}`,message:"Required portable source paths must use unique safe keys and source identities."});continue}r.add(a.key),o.add(c);let l=t.get(c);if(!l){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:a.source_path,message:"A required portable source identity must map to exactly one private package path."});continue}i.push({key:a.key,source_path:c,path_template:l})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function KL(e,t,n){if(e.adds_dom!==!1)return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.source_file,message:"A managed-root thin entry must not add DOM."}),null;let r=t.get($n(e.component_source));if(!r)return n.push({code:"SOURCE_THIN_ENTRY_TARGET_MISSING",path:e.component_source,message:"The managed-root thin entry target is not private materialized source."}),null;if(!/^(?:default|[A-Za-z_$][A-Za-z0-9_$]*)$/u.test(e.component_export))return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.component_export,message:"The managed-root thin entry export is not a safe export name."}),null;let o=`${jE}__managed-root-entry.tsx`,i=VE(o,r,"./component"),s=e.component_export==="default"?`import Root from ${JSON.stringify(i)};`:`import { ${e.component_export} as Root } from ${JSON.stringify(i)};`;return{path_template:o,role:"managed-root-thin-entry",content:`${s}
|
|
14
|
+
`||f==="\r"}if(s)return bo(t,`Unterminated block comment in ${t}.`);if(o)return bo(t,`Unterminated string literal in ${t}.`);if(c)return bo(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?bo(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function bo(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function rc(e){let t="idle",n=e.fileSystem??VO(),r=dm(),o=Jb({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?eg(e.historyStore):UO()),u=Ub(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Sm(Qd),g=new Set,p=0,h=e.historyStore?.recoveryRequired??!1,y=zd(),x=_();function E(m){return(tc.isAbsolute(m)?tc.relative(e.projectRoot,m):m).replace(/\\/g,"/").replace(/^\.\//,"")}function b(m,I){let S=tc.posix.dirname(m),C=I.replace(/\.(?:tsx?|jsx?)$/i,""),w=tc.posix.relative(S,C);return w.startsWith(".")?w:`./${w}`}function v(m,I){return m.startLine===I.startLine&&m.startColumn===I.startColumn&&m.endLine===I.endLine&&m.endColumn===I.endColumn}async function _(){let m=e.historyStore;if(m)try{let I=await m.readTransactionJournal();if(!I)return;let S=await m.readIndex(),C=await Promise.all(I.files.map(async O=>await n.exists(O.path)?ve(await n.readFile(O.path)):null));if(nE({journal:I,index:S,observedFileDigests:C})!=="ambiguous"){await m.clearTransactionJournal(I.transactionId);let O=await m.readStatus();O.recoveryRequired||(await m.cleanupTmp(),O=await m.readStatus()),h=O.recoveryRequired;return}await m.markRecoveryRequired(`Ambiguous transaction journal ${I.transactionId} at phase ${I.phase}`),h=!0}catch(I){h=!0,await m.markRecoveryRequired(`Transaction journal recovery failed: ${vt(I)}`).catch(()=>{})}}function P(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let m of o.entries){let I=aE(m.context,m.entryFile);i.set(m.key,I),R(I,I.dependencyFiles)}function R(m,I){let S=new Set(I);N(m),m.dependencyFiles=S;for(let C of m.dependencyFiles){let w=s.get(C);w||(w=new Set,s.set(C,w)),w.add(m.key)}}function N(m){for(let I of m.dependencyFiles){let S=s.get(I);S&&(S.delete(m.key),S.size===0&&s.delete(I))}m.dependencyFiles.clear()}function A(m){let I=new Set;for(let S of m)for(let C of s.get(S)??[])I.add(C);return I}function L(m){for(let I of m)if(!s.has(I))return!1;return!0}async function $(m,I,S,C,w,O){let j=new Map,K=Sb(m),Y=ub(w.values()),X=sx(w.values()),J=typeof O.exists=="function"?ee=>O.exists(ee):async()=>!1;for(let[ee,se]of m.elements){let be=I.nodes.get(ee);if(!be)continue;let re=S.get(se.sourceFile)??C.get(se.sourceFile),Re=new Map,ye=new Map,D=new Map,G=[];for(let Ue of se.textSegments){if(!re){Re.set(Ue.index,null);continue}let No=await db({file:se.sourceFile,source:re,segment:Ue,readFile:wt=>O.readFile(wt),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:fr,capabilities:Nc})=>({sourceType:wt,adapterId:fr,capabilities:Nc})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Et=await Md({file:se.sourceFile,source:re,target:{kind:"text-segment",segment:Ue},readFile:wt=>O.readFile(wt),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:wt,adapterId:fr,capabilities:Nc})=>({sourceType:wt,adapterId:fr,capabilities:Nc})),functionCallContracts:e.functionCallContracts,fileCache:Y}),$t=QO(No);Re.set(Ue.index,$t),ye.set(Ue.index,No),D.set(Ue.index,Et),G.push({editable:Ue.editable,source:$t})}let pe=new Map,Se=new Map;if(re)for(let Ue of se.attributes??[]){let No=await yo({file:se.sourceFile,source:re,sourceRange:Ue.sourceRange,expression:Ue.source?.expression??Ue.value,sourceInfo:Ue.source,readFile:$t=>O.readFile($t),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:$t,adapterId:wt,capabilities:fr})=>({sourceType:$t,adapterId:wt,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:Y}),Et=await Eb({element:se,file:se.sourceFile,source:re,propertyName:Ue.name,readFile:$t=>O.readFile($t),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:$t,adapterId:wt,capabilities:fr})=>({sourceType:$t,adapterId:wt,capabilities:fr})),functionCallContracts:e.functionCallContracts,fileCache:Y});Se.set(Ue.name,Et),pe.set(Ue.name,No)}let Ce=Ab(qO(be.writeTarget),G),He=K({key:ee,element:se,provenances:D}),Un=Lb(se),Cn=re?await ax({element:se,graph:m,file:se.sourceFile,source:re,readFile:Ue=>O.readFile(Ue),exists:J,fileCache:X}):void 0,pr=m.regions.find(Ue=>Ue.kind==="conditional-region"&&Ue.childKeys.includes(ee)),Rt,Nn=pr?.sourceCandidates?.[0];if(re&&pr&&Nn?.kind==="conditional-branch"){let Ue=await Md({file:se.sourceFile,source:re,target:{kind:"conditional-branch",candidate:Nn},readFile:Et=>O.readFile(Et),exists:J,graph:m,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Et,adapterId:$t,capabilities:wt})=>({sourceType:Et,adapterId:$t,capabilities:wt})),functionCallContracts:e.functionCallContracts,fileCache:Y});Rt={currentBranch:pr.childKeys.indexOf(ee)<=0?"then":"else",availableBranches:pr.childKeys.length>1?["then","else"]:["then"],conditionExpression:Nn.conditionExpression,provenance:{finalSource:Ue.finalSource?{kind:Ue.finalSource.kind,file:Ue.finalSource.file,displayPath:Ue.finalSource.displayPath}:null,chain:Ue.chain.map(Et=>({kind:Et.kind,file:Et.file,displayName:Et.displayName,canEditHere:Et.canEditHere})),confidence:Ue.confidence,editMode:Ue.editMode,diagnostics:Ue.diagnostics.map(Et=>({code:Et.code,message:Et.message}))}}}j.set(ee,{textSources:Re,textTargets:ye,elementPropertyTargets:pe,propertyProvenances:Se,isRepeat:xF(ee,m),provenances:D,writeTarget:Ce,componentSemantic:He,styleSource:Un,conditional:Rt,dynamicData:Cn})}return j}function U(m){return typeof n.getVersion=="function"?n.getVersion(m):0}function de(m,I){let S=o.initialVersions.get(m.key)??0;for(let C of I.values())S=Math.max(S,C);return Math.max(S,m.graph?.version??0)}function z(m){return i.get(m)?.graph?.version??o.initialVersions.get(m)??0}function Q(m){try{return z(o.resolveSelector(m.composition).key)}catch{return 0}}async function ke(m,I,S=n,C={}){let w=await Bs(m,I,O=>S.readFile(O),O=>S.exists(O),{additionalEntries:await lt(m,S),...C});if(w.diagnostics.length>0)throw new ji(w.diagnostics);return C.validationOnly||f.remember(w.parsedModules.values()),w}async function ct(m,I,S={}){let C=i.get(m);if(!C)return null;let w=S.sourceCache??Yd(d,[]),O=S.fileSystem??Hd(n),{graph:j,allSources:K,parsedModules:Y,entryModule:X}=await ke(C.entryFile,I,O,{version:C.graph?.version??1}),J=new Map;for(let Rt of K.keys())J.set(Rt,U(Rt));let ee=Math.max(de(C,J),S.minimumVersion??0);S.changed&&ee<=(C.graph?.version??0)&&(ee=(C.graph?.version??0)+1),j.version=ee;for(let[Rt,Nn]of K)Zd(w,Rt,Nn,Qd);let se=await Ro(C.composition,C.entryFile,K,w,O);j.routeId=C.routeId,j.composition=C.composition;let be=aa(j),re=Cs(be,j),Re=await $(j,be,K,w,Y,O),ye=he(j,re,Re),D=Co(Re),G=Wb(Rb(j,be,re,{canUpdateTextByKey:ye,dynamicDataSummaryByKey:D}),j,Re),pe=nn({route:C.routeId,composition:C.composition,entryFile:C.entryFile,version:ee,source:I,ast:X?.ast}),Se=Yg(pe),Ce=null,He=[];if(pe.ok){oF(G,j,pe.projection,Y);let Rt=sa({composition:C.composition,entryFile:C.entryFile,graph:j,parsedModules:Y,projection:pe.projection});if(Rt.diagnostics.length===0){let Nn=ai({composition:C.composition,entryFile:C.entryFile,graph:j,parsedModules:Y,projection:pe.projection,documentVersion:ee,roots:Rt.roots});Nn.diagnostics.length===0&&(Ce=Nn,He=Nn.descriptors)}}let Un={...G,composition:C.composition,pageBlocks:He,...se?{styleContext:se}:{},pageComposition:Se},Cn=new Set([C.entryFile,...K.keys()]);if(se){Cn.add(se.entryCss.path);for(let Rt of se.stylesheets)Cn.add(Rt.path)}let pr={...C,dependencyFiles:Cn,graph:j,topology:be,capabilities:re,document:Un,pageBlockIndex:Ce,pageComposition:Se,pageCompositionProjection:pe.projection,pagePlacementByKey:pe.ok?pe.projection.placementByKey:null,pagePlacementUnitByKey:pe.ok?pe.projection.placementUnitByKey:null,pageUnitByKey:pe.ok?pe.projection.unitByKey:null,pagePlacementsByUnitKey:pe.ok?pe.projection.placementsByUnitKey:null,documentIndex:Hb(Un),detailProjections:Re,fileVersions:J,styleContext:se};if(S.publish===!1)return pr;xo(d,w);for(let Rt of w.keys())g.delete(Rt);return R(C,Cn),Object.assign(C,pr),C}async function lt(m,I=n){let S=[];for(let C of pF(m))typeof I.exists=="function"&&await I.exists(C)&&S.push({file:C,source:await I.readFile(C)});return S}async function Ro(m,I,S,C,w){let O=[];for(let[J,ee]of S){if(qd(J)){O.push(J);continue}for(let se of mF(ee)){let be=fE(J,se);be&&O.push(be)}}if(!O.length){for(let J of fF(I))if(await w.exists(J)){O.push(J);break}}let j=new Map,K=yF(O).slice(0,rE);for(;K.length>0&&j.size<rE;){let J=K.shift();if(j.has(J)||!qd(J))continue;let ee=await Qt(J,C,w);if(ee!==null){j.set(J,{path:J,content:ee});for(let se of gF(ee)){let be=fE(J,se);be&&!j.has(be)&&!K.includes(be)&&K.push(be)}}}let Y=[...j.values()].map(J=>({...J,hash:ve(J.content)})),X=Y[0];return X?{composition:m,revision:ve(JSON.stringify(Y.map(({path:J,hash:ee})=>({path:J,hash:ee})))),entryCss:X,stylesheets:Y.slice(1)}:null}async function Qt(m,I,S){let C=I.get(m);if(C!==void 0)return C;if(!await S.exists(m))return null;let w=await S.readFile(m);return Zd(I,m,w,Qd),w}function Co(m){let I=new Map;for(let[S,C]of m)C.dynamicData?.bindings.length&&I.set(S,bx(C.dynamicData.bindings));return I}function he(m,I,S){let C=new Map;for(let[w,O]of m.elements){if(!I.get(w)?.canUpdateText){C.set(w,!1);continue}let K=S.get(w),Y=O.textSegments.some(X=>{if(!X.editable)return!1;let J=K?.provenances.get(X.index)??null;return!J||Qe(J)});C.set(w,Y)}return C}function Qe(m){return m.editMode==="direct"||m.editMode==="proxy"||m.editMode==="upstream"}async function Pe(m,I={}){let S=[...new Set(m)],C=I.affectedCompositionKeys!==void 0,w=C?new Set(I.affectedCompositionKeys):A(S);if(!C&&(w.size===0||!L(S)))for(let X of i.values())Lp(X,S)&&w.add(X.key);let O=!C&&w.size===0&&S.some(pE),j=I.publish===!1?Yd(d,S):void 0,K={rebuiltRoutes:[],failedRoutes:[],...I.publish===!1?{candidateRouteStates:[],candidateSourceCache:j}:{}},Y=Hd(n);for(let X of i.values())if(!(I.excludedCompositionKeys?.has(X.key)||!(w.has(X.key)||O)))try{let ee=!!X.graph,se=await Y.readFile(X.entryFile),be=await ct(X.key,se,{...I,fileSystem:Y,...j?{sourceCache:j}:{}});be?.graph&&(K.rebuiltRoutes.push({documentChanged:ee,composition:X.composition,routeId:X.routeId,version:be.graph.version}),K.candidateRouteStates?.push({composition:X.composition,key:X.key,routeId:X.routeId,state:be}))}catch(ee){K.failedRoutes.push({...eE(X.routeId,ee),composition:X.composition})}return K}function ce(m){let I=[...new Set(m)],S=A(I);if(S.size>0&&L(I))return[...S];for(let C of i.values())Lp(C,I)&&S.add(C.key);return[...S]}function Ve(m){let I=new Set(ce(m));return o.entries.filter(S=>I.has(S.key)).map(S=>S.context)}function mt(m){return[...new Set(ce(m))].sort((S,C)=>S<C?-1:S>C?1:0).map(S=>o.getByKey(S)?.context).filter(S=>S!==void 0)}function qt(m,I){let S=new Set(ce(I)),C=m.provenance?.affectedCompositions??[];if(C.length===0)return S;if([...new Set(C.map(O=>o.resolveContext(O).key))].some(O=>!S.has(O)))throw new Error("History provenance does not match the affected composition index.");return S}function gt(m,I){let S=m.composition??m.provenance?.initiatingComposition;if(S){let O=o.resolveContext(S);return{context:O.context,key:O.key}}let C=[...new Set(ce(I))];if(C.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${C.length}).`);let w=o.getByKey(C[0]);if(!w)throw new Error("Legacy history entry references an unknown affected composition.");return{context:w.context,key:w.key}}function $r(m,I){r.emit({type:"operation-completed",composition:m.composition,result:m});for(let{composition:S,version:C}of I.rebuiltRoutes)r.emit({type:"document-changed",composition:S,version:C});for(let{composition:S,message:C}of I.failedRoutes)r.emit({type:"graph-error",composition:S,message:C})}function Lp(m,I){return I.some(S=>m.dependencyFiles.has(S)||m.entryFile===S||m.graph?.fileIndex.has(S))}function Dp(m){for(let I of m)a.add(I);c||P()||(c=(async()=>{t="building";let I=!1;try{for(;a.size>0;){if(P())return;await hS(),await y.runExclusive(async()=>{if(p>0||P())return;let S=[...a];a.clear();let C=await Mp(S);if(C.length===0)return;let w=ce(C);for(let K of w){let Y=i.get(K)?.composition;Y&&r.emit({type:"graph-invalidated",composition:Y})}let{rebuiltRoutes:O,failedRoutes:j}=await Pe(C,{changed:!0});for(let{documentChanged:K,composition:Y,version:X}of O)r.emit({type:"graph-ready",composition:Y,version:X}),K&&r.emit({type:"document-changed",composition:Y,version:X});for(let{composition:K,message:Y}of j)I=!0,r.emit({type:"graph-error",composition:K,message:Y})})}}finally{c=null,t!=="disposed"&&(t=!I&&[...i.values()].some(S=>S.graph)?"ready":"idle"),a.size>0&&Dp([])}})())}async function hS(){for(;p>0;)await new Promise(m=>setTimeout(m,0))}async function Mp(m){let I=[];for(let S of new Set(m)){let C=d.get(S);if(C===void 0){if(g.has(S)&&!await n.exists(S))continue;g.delete(S),I.push(S);continue}try{await n.readFile(S)!==C&&(g.delete(S),I.push(S))}catch(w){if(!rF(w))try{if(await n.exists(S))continue}catch{continue}g.add(S),I.push(S)}}return I}function Bp(m){tE(d,m);for(let I of m)I.exists===!1?g.add(I.file):g.delete(I.file)}function jp(m){g.clear();for(let I of m)g.add(I)}async function $p(m){let I=await Mp(m);if(I.length===0)return;let S=ce(I);for(let O of S){let j=i.get(O)?.composition;j&&r.emit({type:"graph-invalidated",composition:j})}let{rebuiltRoutes:C,failedRoutes:w}=await Pe(I,{changed:!0});for(let{documentChanged:O,composition:j,version:K}of C)r.emit({type:"graph-ready",composition:j,version:K}),O&&r.emit({type:"document-changed",composition:j,version:K});for(let{composition:O,message:j}of w)r.emit({type:"graph-error",composition:O,message:j})}async function yS(m,I){let S=Ur(m,I);if(!S?.graph)return;let C=At(m)??m,w=S.graph.elements.get(C);w&&await $p([w.sourceFile])}async function Vp(m){let I=new Set;if(m.target.kind==="node"){let S=Ur(m.target.key,m.composition),C=At(m.target.key)??m.target.key,w=S?.graph?.elements.get(C);w&&I.add(w.sourceFile)}else if(m.target.kind==="route"){let S=i.get(o.resolveSelector(m.target.composition).key);S&&I.add(S.entryFile)}else if(m.target.kind==="page-unit"){let S=i.get(o.resolveSelector(m.target.composition).key);S&&I.add(S.entryFile)}else if(m.target.kind==="page-block"){let S=i.get(o.resolveSelector(m.target.composition).key),C=S?.pageBlockIndex?.bindings.get(m.target.blockKey);if(C&&(I.add(C.ownerFile),I.add(C.descriptor.source.file)),S?.pageBlockIndex&&m.params.kind==="move-node"&&"kind"in m.params.target&&m.params.target.kind==="block-boundary"){let w=S.pageBlockIndex.bindings.get(m.params.target.anchorBlockKey);w&&(I.add(w.ownerFile),I.add(w.descriptor.source.file))}}else if(m.target.kind==="source-file")I.add(m.target.path);else if(m.target.kind==="source-batch")for(let S of m.target.paths)I.add(S);if(m.params.kind==="move-node"&&!("kind"in m.params.target)){let S=[m.params.target.parentKey,...m.params.target.relation==="before"||m.params.target.relation==="after"?[m.params.target.anchorKey]:[]];for(let C of S){let w=Ur(C,m.composition),O=At(C)??C,j=w?.graph?.elements.get(O);j&&I.add(j.sourceFile)}}await $p(I)}async function xS(m){if(m.params.kind!=="source-edit")return Ic(m,"invalid-params","source-edit requires source-edit params");for(let I of m.params.edits){let S=nF(I);if(!S.ok)return Ic(m,S.errorCode,S.message,S.details)}p+=1;try{let I=await NS(m.params.edits);if(!I.ok)return Ic(m,I.errorCode,I.message,I.details);await Vp(m);let S={operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:m.params.conflictPolicy,edits:m.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 Vn({request:m,filePlan:S})}catch(I){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.INTERNAL_ERROR,message:vt(I)}}}finally{p-=1}}async function bS(m){if(m.target.kind!=="project"||m.params.kind!=="insert-page-resource")return H(m,M.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let I=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...m.params.artifact.components.flatMap(C=>C.materialization.files.map(w=>({path:w.pathTemplate,content:w.content}))),...m.params.artifact.pages.flatMap(C=>C.materialization.files.map(w=>({path:w.pathTemplate,content:w.content})))],exists:C=>n.exists(C),readFile:C=>n.readFile(C)});if(!I.ok)return H(m,M.MATERIALIZATION_REJECTED,I.message);let S=await Vl({artifact:m.params.artifact,exists:C=>n.exists(C)});return S.ok?await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"overwrite",edits:S.files},output:{kind:"insert-page-resource",package_instance_id:S.packageInstanceId,pages:S.pages},historyPolicy:"none"}):H(m,S.code==="MATERIALIZATION_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,S.message,S.path?{path:S.path}:void 0)}catch(I){return H(m,M.INTERNAL_ERROR,vt(I))}finally{p-=1}}async function ES(m){if(m.target.kind!=="project"||m.params.kind!=="delete-page-source")return H(m,M.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return H(m,M.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let I=mE(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(I.truncated)return H(m,M.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:I.truncated.reasons});let S=I.files.filter(({path:j})=>/\.(?:tsx?|jsx?)$/.test(j)),C=Object.fromEntries(await Promise.all(S.map(async({path:j})=>[j,await n.readFile(j)]))),w=$h({expectedUrlPath:m.params.expectedUrlPath,files:C});if(!w.ok)return H(m,w.code==="HOME_PAGE_LOCKED"?M.HOME_PAGE_LOCKED:w.code==="ROUTE_NOT_FOUND"?M.ROUTE_NOT_FOUND:M.PLAN_FAILED,w.message);let O=await Promise.all(w.edits.map(async j=>({...j,baseContentHash:ve(await n.readFile(j.file))})));return Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:O},output:{kind:"delete-page-source",deleted_files:w.deletedFiles,updated_files:w.updatedFiles,preserved_shared_files:w.preservedSharedFiles,warnings:w.warnings},historyPolicy:"none"})}catch(I){return H(m,M.INTERNAL_ERROR,vt(I))}finally{p-=1}}async function SS(m,I){if(m.kind!=="insert-child"&&m.kind!=="replace-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(m.params.kind!=="insert-child"&&m.params.kind!=="replace-node"||m.kind!==m.params.kind)return H(m,M.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(m.params.kind==="insert-child"){if(!("kind"in m.params.position)||m.params.position.kind!=="page-composition")return H(m,M.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(m.params.position.documentVersion!==m.documentVersion)return H(m,M.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let S=I.document,C=I.pageCompositionProjection;if(!S||S.pageComposition?.status!=="supported"||!C||C.status!=="supported")return H(m,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=m.params.node.kind==="component-call"?m.params.node.materialization:void 0;if(!w)return H(m,M.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let O=m.params.kind==="insert-child"?m.params.position:null,j=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:w.files.map(X=>({path:X.pathTemplate,content:X.content})),exists:X=>n.exists(X),readFile:X=>n.readFile(X)});if(!j.ok)return H(m,M.MATERIALIZATION_REJECTED,j.message);let K=await iE(n,Object.keys(w.projectDependencies??{})),Y=await Hl({manifest:w,generatedRoot:"components/site/generated",controlledFiles:w.files.map(X=>({pathTemplate:X.pathTemplate})),exists:X=>n.exists(X),availableHostDependencies:K,hostCapabilities:Dl(),commit:async X=>{let J=await n.readFile(I.entryFile),ee=I.document,se=I.pageCompositionProjection;if(!ee||ee.pageComposition?.status!=="supported"||ee.version!==m.documentVersion||!se||se.status!=="supported"||se.documentVersion!==ee.version)return{ok:!0,data:H(m,M.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let be=X.entry.path,re=FS(X.instanceName),Re,ye=[];if(m.params.kind==="insert-child"){if(!O||!("kind"in O)||O.kind!=="page-composition")return{ok:!0,data:H(m,M.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Se=ni({routeId:I.routeId,entryFile:I.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:m.documentVersion,source:J,projection:se,placementKey:O.placementKey,component:{source:be,exportName:X.entry.export.kind==="default"?"default":X.entry.export.name,localName:re}});if(!Se.ok)return{ok:!0,data:H(m,Cc(Se.error.code),Se.error.message,{diagnostics:Se.error.diagnostics})};let Ce=Se.plan.rewriteStep,He;switch(Ce.kind){case"insert-root-expression":He=ri({source:J,locator:Ce.locator,expectedSourceHash:Ce.sourceHash,action:{kind:"insert",jsx:Ce.node.jsx,placement:Ce.placement,replaceOriginal:Ce.replaceOriginal}});break;case"insert-child":He=Kt({source:J,locator:Ce.parentLocator,node:Ce.node,placement:Ce.placement,...Ce.anchorLocator?{anchorLocator:Ce.anchorLocator}:{}});break;default:He={ok:!1,source:J,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Ce)}`}}}if(!He.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,He.diagnostic.message)};Re=He.source}else{let Se=cu({routeId:I.routeId,composition:I.composition,entryFile:I.entryFile,currentDocumentVersion:ee.version,expectedDocumentVersion:m.documentVersion,source:J,projection:se,placementUnitKey:m.target.placementUnitKey,operation:"replace-node"});if(!Se.ok)return{ok:!0,data:H(m,Cc(Se.error.code),Se.error.message,{diagnostics:Se.error.diagnostics})};let Ce=Se.plan.rewriteStep,He;switch(Ce.kind){case"replace-root-expression":He=ri({source:J,locator:Ce.locator,expectedSourceHash:Ce.sourceHash,action:{kind:"replace",jsx:`<${re} />`}});break;case"replace-node":He=Jr({source:J,locator:Ce.locator,node:{jsx:`<${re} />`}});break;default:He={ok:!1,source:J,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Ce.kind}`}}}if(!He.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,He.diagnostic.message)};let Un=await vc({routeState:I,placementUnitKey:m.target.placementUnitKey,source:J,mutatedSource:He.source});Re=Un.source,ye=await Promise.all(Un.files.map(async Cn=>({operation:"delete",file:Cn,baseContentHash:ve(await n.readFile(Cn))})))}let D=Jt({source:Re,moduleSpecifier:b(I.entryFile,be),imports:X.entry.export.kind==="default"?[{kind:"default",local:re}]:[{kind:"named",imported:X.entry.export.name,local:re}]});if(!D.ok)return{ok:!0,data:H(m,M.AST_PARSE_ERROR,D.diagnostic.message)};let G=X.files.map(Se=>({operation:"create-only",file:Se.path,content:Se.content})),pe=[{operation:"upsert",file:I.entryFile,content:D.source,baseContentHash:ve(J)},...G,...ye];p+=1;try{let Se=await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:{kind:"source-file",path:I.entryFile},documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:pe}});return!Se.ok&&Se.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Se.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Se}}finally{p-=1}}});return Y.ok?Y.data:H(m,Y.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,Y.error.message,{materializationCode:Y.error.code})}async function vS(m,I){if(m.kind!=="insert-child"&&m.kind!=="replace-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(m.params.kind!==m.kind||m.kind==="replace-node"&&m.params.kind!=="replace-node"||m.kind==="insert-child"&&m.params.kind!=="insert-child")return H(m,M.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let S=I.document,C=I.pageBlockIndex;if(!S||!C||C.diagnostics.length>0)return H(m,M.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=ro(C,m.target,m.documentVersion,m.selectionRef);if(!w.ok)return H(m,Hi(w.code),w.message);let O=w.binding;if(!(m.kind==="insert-child"?O.descriptor.capabilities.insert:O.descriptor.capabilities.replace)){let re=O.descriptor.unavailableReasons?.[m.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return H(m,M.UNSUPPORTED_OPERATION,re)}let K=(m.kind==="insert-child",m.params);if(K.kind!==m.kind)return H(m,M.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Y=K.node;if(Y.kind!=="component-call"||!Y.materialization)return H(m,M.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let X;if(K.kind==="insert-child"){let re=K.position;if(!("kind"in re&&re.kind==="block-boundary"))return H(m,M.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(re.documentVersion!==m.documentVersion)return H(m,M.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Re=ca(C,re);if(!Re.ok)return H(m,Hi(Re.code),Re.message);X=Re.boundary}let J=Y.materialization,ee=await Po({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:J.files.map(re=>({path:re.pathTemplate,content:re.content})),exists:re=>n.exists(re),readFile:re=>n.readFile(re)});if(!ee.ok)return H(m,M.MATERIALIZATION_REJECTED,ee.message);let se=await iE(n,Object.keys(J.projectDependencies??{})),be=await Hl({manifest:J,generatedRoot:"components/site/generated",controlledFiles:J.files.map(re=>({pathTemplate:re.pathTemplate})),exists:re=>n.exists(re),availableHostDependencies:se,hostCapabilities:Dl(),commit:async re=>{let Re=I.document,ye=I.pageBlockIndex;if(!Re||!ye||Re.version!==m.documentVersion||ye.documentVersion!==Re.version||!ye.bindings.has(O.blockKey))return{ok:!0,data:H(m,M.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let D=ye.bindings.get(O.blockKey);if(!D||D.ownerFile!==O.ownerFile||D.ownerSourceHash!==O.ownerSourceHash||D.sourceHash!==O.sourceHash)return{ok:!0,data:H(m,M.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let G=new Set([O.ownerFile,O.descriptor.source.file,...X?[X.ownerFile,X.anchorLocator.file,...X.parentLocator?[X.parentLocator.file]:[]]:[]]),pe=new Map;try{for(let Ce of G)pe.set(Ce,await n.readFile(Ce))}catch{return{ok:!0,data:H(m,M.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Se=Eh({operationId:m.id,documentVersion:m.documentVersion,target:m.target,binding:O,...X?{boundary:X}:{},operation:K.kind,materialization:re,files:pe});if(!Se.ok){let Ce=CS(Se.code);return{ok:!0,data:H(m,Ce,Se.message,{materializationCode:Se.code})}}p+=1;try{let Ce=await Vn({request:m,filePlan:Se.plan});return!Ce.ok&&Ce.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ce.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ce}}finally{p-=1}}});return be.ok?be.data:H(m,be.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?M.MATERIALIZATION_CONFLICT:M.MATERIALIZATION_REJECTED,be.error.message,{materializationCode:be.error.code})}async function IS(m,I){if(m.kind!=="move-node"&&m.kind!=="remove-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let S=I.document,C=I.pageCompositionProjection;if(!S||S.pageComposition?.status!=="supported"||!C||C.status!=="supported")return H(m,M.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=await n.readFile(I.entryFile),O=cu({routeId:I.routeId,composition:I.composition,entryFile:I.entryFile,currentDocumentVersion:S.version,expectedDocumentVersion:m.documentVersion,source:w,projection:C,placementUnitKey:m.target.placementUnitKey,operation:m.kind,targetPlacement:m.kind==="move-node"&&m.params.kind==="move-node"&&"kind"in m.params.target&&m.params.target.kind==="page-composition"?m.params.target:void 0});if(!O.ok)return H(m,Cc(O.error.code),O.error.message,{diagnostics:O.error.diagnostics});let j=O.plan.rewriteStep,K;switch(j.kind){case"move-node":K=kr({source:w,locator:j.locator,targetParentLocator:j.targetParentLocator,placement:j.placement,...j.anchorLocator?{anchorLocator:j.anchorLocator}:{}});break;case"remove-node":K=vr({source:w,locator:j.locator});break;case"remove-root-expression":K=ri({source:w,locator:j.locator,expectedSourceHash:j.sourceHash,action:{kind:"remove"}});break;default:K={ok:!1,source:w,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${j.kind}`}}}if(!K.ok)return H(m,M.AST_PARSE_ERROR,K.diagnostic.message);let Y=K.source,X=[];if(m.kind==="remove-node"){let ee=await vc({routeState:I,placementUnitKey:m.target.placementUnitKey,source:w,mutatedSource:Y});Y=ee.source,X=await Promise.all(ee.files.map(async se=>({operation:"delete",file:se,baseContentHash:ve(await n.readFile(se))})))}let J=[{operation:"upsert",file:I.entryFile,content:Y,baseContentHash:ve(w)},...X];p+=1;try{return await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:{kind:"source-file",path:I.entryFile},documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:J}})}finally{p-=1}}async function kS(m,I){if(m.kind!=="move-node"&&m.kind!=="remove-node")return H(m,M.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let S=I.document,C=I.pageBlockIndex;if(!S||!C||C.diagnostics.length>0)return H(m,M.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(m.documentVersion!==S.version||C.documentVersion!==S.version)return H(m,M.VERSION_STALE,`Document version ${m.documentVersion} is stale (current: ${S.version}).`);let w=ro(C,m.target,m.documentVersion,m.selectionRef);if(!w.ok)return H(m,Hi(w.code),w.message);let O=w.binding;if(O.documentVersion!==S.version)return H(m,M.VERSION_STALE,"The resolved page-block binding is stale.");if(!(m.kind==="move-node"?O.descriptor.capabilities.move:O.descriptor.capabilities.remove)){let ye=O.descriptor.unavailableReasons?.[m.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return H(m,M.UNSUPPORTED_OPERATION,ye)}if(m.kind==="remove-node"){let ye=[...i.values()].filter(D=>D.dependencyFiles.has(O.ownerFile));if(ye.includes(I)||ye.push(I),ye.some(D=>!D.pageBlockIndex||D.pageBlockIndex.descriptors.length<=1))return H(m,M.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let K=null;if(m.kind==="move-node"){if(m.params.kind!=="move-node"||!("kind"in m.params.target)||m.params.target.kind!=="block-boundary")return H(m,M.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(m.params.target.anchorBlockKey===O.blockKey)return H(m,M.INVALID_TARGET,"A page block cannot be moved relative to itself.");let ye=ca(C,m.params.target);if(!ye.ok)return H(m,Hi(ye.code),ye.message);let D=C.bindings.get(m.params.target.anchorBlockKey);if(!D||!O.descriptor.siblingBlockKeys.includes(D.blockKey)||!D.descriptor.siblingBlockKeys.includes(O.blockKey)||D.ownerFile!==O.ownerFile||D.root.ownerNode.kind!==O.root.ownerNode.kind||D.root.ownerNode.key!==O.root.ownerNode.key||D.root.parentStructuralPath!==O.root.parentStructuralPath)return H(m,M.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(K=ye.boundary,K.ownerFile!==O.ownerFile||K.sourceHash!==O.ownerSourceHash||!K.parentLocator)return H(m,M.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Y=O.ownerFile,X=await n.readFile(Y);if(ve(X)!==O.ownerSourceHash)return H(m,M.VERSION_STALE,"The page-block owner source changed after resolution.");let J=O.descriptor.source.file===Y?X:await n.readFile(O.descriptor.source.file);if(ve(J)!==O.descriptor.source.contentHash)return H(m,M.VERSION_STALE,"The selected page-block source changed after resolution.");let ee=RS(O),se=m.kind==="remove-node"?vr({source:X,locator:ee}):kr({source:X,locator:ee,targetParentLocator:Sc(K.parentLocator),anchorLocator:Sc(K.anchorLocator),placement:K.placement});if(!se.ok)return H(m,M.AST_PARSE_ERROR,se.diagnostic.message);let be=se.source,re=[];if(m.kind==="remove-node"&&O.root.ownerNode.kind==="route-member"&&O.root.callChain.length>0&&O.descriptor.placementUnitKey){let ye=await vc({routeState:I,placementUnitKey:O.descriptor.placementUnitKey,source:X,mutatedSource:be});be=ye.source,re=ye.files}let Re=[{operation:"upsert",file:Y,content:be,baseContentHash:O.ownerSourceHash},...await Promise.all(re.map(async ye=>({operation:"delete",file:ye,baseContentHash:ve(await n.readFile(ye))})))];p+=1;try{return await Vn({request:m,filePlan:{operationId:m.id,kind:"source-edit",target:m.target,documentVersion:m.documentVersion,conflictPolicy:"compare-and-swap",edits:Re}})}finally{p-=1}}function RS(m){return Sc(m.ownerLocator)}function Sc(m){return{kind:"jsx-node",strategy:"source-range",sourceRange:m.sourceRange,...m.structuralPath&&m.componentName?{expectedIdentity:{file:m.file,component:m.componentName,structuralPath:m.structuralPath}}:{}}}function Hi(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="INVALID_PARAMS"?M.INVALID_PARAMS:M.INVALID_TARGET}function CS(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="INVALID_PARAMS"?M.INVALID_PARAMS:m==="INVALID_TARGET"?M.INVALID_TARGET:m.startsWith("MATERIALIZATION_")?M.MATERIALIZATION_REJECTED:M.UNSUPPORTED_OPERATION}async function vc(m){let I={source:m.mutatedSource,files:[]},S=m.routeState.graph,C=m.routeState.pageCompositionProjection;if(!S||!C||C.status!=="supported"||!n.listFiles)return I;let O=C.placementUnitByKey.get(m.placementUnitKey)?.sourceRange;if(!O)return I;let j=[...S.elements.values()].find(D=>D.sourceFile===m.routeState.entryFile&&D.importedFrom&&v(D.sourceRange,O));if(!j?.importedFrom||!j.exportName)return I;let K=E(j.importedFrom),Y="components/site/generated/";if(!K.startsWith(Y))return I;let X=K.slice(Y.length).split("/")[0];if(!X||!/-[0-9a-f]{8}$/i.test(X))return I;let J=`${Y}${X}`;if([...S.elements.values()].filter(D=>D.sourceFile===m.routeState.entryFile&&E(D.importedFrom??"")===K).length!==1)return I;let se=await n.listFiles({maxFiles:5e3,maxDepth:32}),be=Array.isArray(se)?se:se.files;if(!Array.isArray(se)&&se.truncated)return I;let re=be.map(({path:D})=>D).filter(D=>D===J||D.startsWith(`${J}/`));if(re.length===0||!re.includes(K))return I;for(let{path:D}of be)if(!(D===m.routeState.entryFile||D===J||D.startsWith(`${J}/`)))try{if((await n.readFile(D)).includes(X))return I}catch{return I}let Re=b(m.routeState.entryFile,K),ye=zr({source:m.mutatedSource,moduleSpecifier:Re,imports:j.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:j.exportName}]});return ye.ok?ye.source.includes(X)?{source:ye.source,files:[]}:{source:ye.source,files:re.sort((D,G)=>D.localeCompare(G))}:I}async function NS(m){if(n.getFileInfo){for(let j of m)if(await n.exists(j.path)&&await n.getFileInfo(j.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${j.path}`,details:{path:j.path}}}for(let j of m){if(j.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(j.path))continue;let K=await n.exists(j.path)?await Uc(n,j.path):null;if(K?.ok){let Y=TO(K.content,j.content);if(!Y.ok)return{ok:!1,errorCode:"invalid-params",message:Y.message,details:{path:j.path,code:Y.code}}}}let I=_S(m);if(I.length===0)return{ok:!0};let S=eF(n,m),C=new Map,w=(j,K)=>{let Y=C.get(j);if(Y?.source===K)return Y.result;let X=Je(j,K);return C.set(j,{source:K,result:X}),X},O;try{O=await Xb(I,async j=>{let K=i.get(j);return K?[...(await ke(K.entryFile,await S.readFile(K.entryFile),S,{validationOnly:!0,parseModule:w,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(j){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${vt(j)}`,details:{compositionKeys:I}}}for(let j of O)f.remember(j);return{ok:!0}}function _S(m){return m.map(S=>S.path).some(pE)?[...i.keys()]:[]}function Ic(m,I,S,C){let w=$i(I);return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:w,message:S,...C?{details:C}:{}}}}async function kc(m){let I=[];for(let S of new Set(m))I.push(await PS(S));return I}async function PS(m){if(!(typeof n.exists=="function"?await n.exists(m):!0))return{file:m,content:"",version:Math.max(0,U(m)),exists:!1};let S=await n.readFile(m);return{file:m,content:S,version:Math.max(1,U(m)),exists:!0,sha256:ve(S)}}async function Up(m,I,S,C){if(!e.historyStore)return null;let w=new Map(I.map(K=>[K.file,K])),O=new Map(S.map(K=>[K.file,K])),j=[...new Set([...w.keys(),...O.keys()])].sort().map(K=>{let Y=w.get(K),X=O.get(K);return{path:K,preDigest:Y?.exists===!1||!Y?null:ve(Y.content),postDigest:X?.exists===!1||!X?null:ve(X.content)}});return{schemaVersion:2,transactionId:`${m}:${C.expectedIndexDigest}`,operationId:m,phase:"prepared",historyTransition:C,files:j}}async function Kp(m){return!m||!e.historyStore||await e.historyStore.writeTransactionJournal(m),m}async function Vr(m){m&&e.historyStore&&await e.historyStore.clearTransactionJournal(m.transactionId)}async function Rc(m,I){let S=[];try{for(let C of m)await Jp(C),typeof n.bumpVersion=="function"&&n.bumpVersion(C.file),S.push(C.file)}catch(C){let w=await AS(I.filter(O=>S.includes(O.file)));return w.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${vt(C)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${w.failedFiles.join(", ")}: ${vt(C)}`,rolledBack:!1}}return{ok:!0,snapshots:m.map(TS)}}async function Jp(m){if(m.exists===!1){await n.deleteFile(m.file);return}await n.writeFile(m.file,m.content)}async function AS(m){let I=[];for(let S of m)try{await Jp(S),typeof n.bumpVersion=="function"&&n.bumpVersion(S.file)}catch{I.push(S.file)}return I.length===0?{ok:!0}:{ok:!1,failedFiles:I}}function TS(m){let I=m.exists!==!1;return{file:m.file,content:I?m.content:"",version:m.version,exists:I,...I?{sha256:ve(m.content)}:{}}}async function Vn(m){return y.runExclusive(()=>wS(m))}async function wS(m){let I=m.filePlan.edits.map(D=>D.file),S=o.resolveSelector(m.request.composition),C=S.context,w=m.historyPolicy==="none"?void 0:{initiatingComposition:C,affectedCompositions:mt(I)},O=await kc(I),j=new Map(O.filter(D=>D.exists!==!1).map(D=>[D.file,D.content])),K=zp(),Y=new Map(d),X=new Set(g),J=new Set([...i.values()].filter(D=>m.filePlan.edits.some(G=>G.operation==="delete"&&G.file===D.entryFile)).map(D=>D.key)),ee=m.filePlan.edits.map(D=>D.operation==="delete"?{file:D.file,content:"",version:0,exists:!1}:{file:D.file,content:D.content,version:0,exists:!0,sha256:ve(D.content)}),se={operationId:m.filePlan.operationId,intents:m.filePlan.edits.map(D=>D.operation==="delete"?{kind:"delete",path:D.file}:{kind:D.operation==="create-only"?"create-only":"upsert",path:D.file,content:D.content})},be=null,re=!1,Re=await Za({overlay:j,exists:D=>n.exists(D),plan:se,buildCandidate:async({plan:D})=>({plan:D}),prepareHistory:async()=>{let D=m.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(m.request.composition).context,operationId:m.request.id,kind:m.request.kind,target:m.request.target,preSnapshots:O,postSnapshots:ee,...m.selectionRef?{selectionRef:m.selectionRef}:{},...m.output?{output:m.output}:{},...w?{provenance:w}:{}}),G=D?.historyTransition?D.historyTransition:e.historyStore?$O(await e.historyStore.readIndex()):null;if(e.historyStore&&!G)throw new Error("Durable history did not provide an exact index transition.");return be=await Up(m.request.id,O,ee,G),be=await Kp(be),{history:D,historyTransition:G}},reverify:async()=>{},writeCandidate:async()=>{let D=await u.executeFilePlan(m.filePlan);if(!D.ok)throw new nc(D);return{postSnapshots:await kc(D.affectedFiles),affectedFiles:D.affectedFiles,internalResultVersion:D.resultVersion}},validateCandidate:async({candidate:D,receipt:G})=>{let pe=await Pe(G.affectedFiles,{changed:!0,minimumVersion:G.internalResultVersion,publish:!1,excludedCompositionKeys:J});if(pe.failedRoutes.length>0)throw new Br(pe.failedRoutes);let Se=Wp(K,pe.candidateRouteStates??[]),Ce=Hp(Se,S.key);return{...D,rebuild:pe,routeSnapshots:Se,resultVersion:Ce,...cE(m.selectionRef,Se.map(He=>He.state.document))?{selectionRef:cE(m.selectionRef,Se.map(He=>He.state.document))}:{}}},publishCandidate:async({candidate:D,history:G,receipt:pe})=>{G?.history&&(await l.publishPrepared(G.history),re=!0);let Se=D.resultVersion??pe.internalResultVersion;return{composition:C,requestId:m.request.id,kind:m.request.kind,target:m.request.target,ok:!0,resultVersion:Se,affectedFiles:pe.affectedFiles,fileChanges:pe.postSnapshots.map(Ce=>({path:Ce.file,operation:Ce.exists===!1?"delete":"upsert"})),...m.output?{output:m.output}:{},...D.selectionRef?{selectionRef:D.selectionRef}:{}}},swapCandidate:({candidate:D,receipt:G})=>{D.routeSnapshots&&Wi(D.routeSnapshots),D.rebuild?.candidateSourceCache&&xo(d,D.rebuild.candidateSourceCache),Bp(G.postSnapshots)},finalizeCandidate:async()=>{await Vr(be);for(let D of J)i.delete(D)},emitCommitted:({candidate:D,published:G})=>{$r(G,D.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:D,receipt:G})=>{if(re)throw new Error("history was published before transaction finalization failed");if(G){let pe=await Rc(O,G.postSnapshots);if(!pe.ok)throw new Error(pe.reason)}Wi(K),xo(d,Y),jp(X),D?.history&&await l.discardPrepared?.(D.history),await Vr(be)}});if(Re.ok)return Re.published;if(Re.stage==="precheck"||Re.stage==="build")try{await Vr(be)}catch(D){let G=await Yi(vt(D));return H(m.request,G,"Unable to clear an uncommitted transaction journal.")}if(Re.recoveryRequired){let D=await Yi(Re.reason);return H(m.request,D===M.RECOVERY_PERSIST_FAILED?D:M.ROLLBACK_FAILED,Re.reason)}let ye=Re.error;return ye instanceof nc?{...H(m.request,$i(ye.result.errorCode),ye.result.reason),...ye.result.affectedFiles?{affectedFiles:ye.result.affectedFiles}:{}}:ye instanceof Br?H(m.request,M.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Gd(ye.failedRoutes)}`,{failedRoutes:ye.failedRoutes}):H(m.request,Yp(Re.stage),vt(ye))}async function Xp(m){return y.runExclusive(async()=>{let I=m==="undo"?await l.prepareUndo():await l.prepareRedo();return I?OS(m,I):{composition:o.entries[0].context,requestId:m,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:M.INTERNAL_ERROR,message:m==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function OS(m,I){let S=I.entry,C=m==="undo"?S.preSnapshots:S.postSnapshots,w=m==="undo"?S.postSnapshots:S.preSnapshots,O=C.map(G=>G.file),{context:j,key:K}=gt(S,O),Y=await kc(O),X=new Map(Y.filter(G=>G.exists!==!1).map(G=>[G.file,G.content])),J=z(K),ee=zp(),se=new Map(d),be=new Set(g),re=null,Re=!1,ye,D=await Za({overlay:X,plan:{operationId:`${m}:${S.operationId}`,intents:C.map(G=>G.exists===!1?{kind:"delete",path:G.file}:{kind:"upsert",path:G.file,content:G.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(re=await Up(`${m}:${S.operationId}`,Y,C,I.historyTransition),re=await Kp(re),I),reverify:async()=>{},writeCandidate:async()=>{let G=await Rc(C,w);if(!G.ok)throw new Error(G.reason);return{snapshots:G.snapshots}},validateCandidate:async({candidate:G})=>{ye=qt(S,O);let pe=await Pe(O,{changed:!0,minimumVersion:J+1,publish:!1,affectedCompositionKeys:ye});if(pe.failedRoutes.length>0)throw new Br(pe.failedRoutes);let Se=Wp(ee,pe.candidateRouteStates??[]),Ce=Hp(Se,K);return{...G,rebuild:pe,routeSnapshots:Se,resultVersion:Ce}},publishCandidate:async({candidate:G,history:pe,receipt:Se})=>{if(!pe)throw new Error("history cursor intent is missing");await l.publishPrepared(pe),Re=!0;let Ce=G.resultVersion??J+1;return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!0,resultVersion:Ce,affectedFiles:O,fileChanges:Se.snapshots.map(He=>({path:He.file,operation:He.exists===!1?"delete":"upsert"})),...S.output?{output:S.output}:{}}},swapCandidate:({candidate:G,receipt:pe})=>{G.routeSnapshots&&Wi(G.routeSnapshots),G.rebuild?.candidateSourceCache&&xo(d,G.rebuild.candidateSourceCache),Bp(pe.snapshots)},finalizeCandidate:async()=>{await Vr(re)},emitCommitted:({candidate:G,published:pe})=>$r(pe,G.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:G,receipt:pe})=>{if(Re)throw new Error("history cursor was published before transaction finalization failed");if(pe){let Se=await Rc(w,pe.snapshots);if(!Se.ok)throw new Error(Se.reason)}Wi(ee),xo(d,se),jp(be),G&&await l.discardPrepared?.(G),await Vr(re)}});if(D.ok)return D.published;if(D.stage==="precheck"||D.stage==="build")try{await Vr(re)}catch(G){let pe=await Yi(vt(G));return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,error:{code:pe,message:"Unable to clear an uncommitted transaction journal."}}}if(D.recoveryRequired){let G=await Yi(D.reason);return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,affectedFiles:O,error:{code:G===M.RECOVERY_PERSIST_FAILED?G:M.ROLLBACK_FAILED,message:D.reason}}}return{composition:j,requestId:m,kind:S.kind,target:S.target,ok:!1,resultVersion:J,affectedFiles:O,error:{code:D.error instanceof Br?M.ROUTE_REBUILD_FAILED:Yp(D.stage),message:vt(D.error),...D.error instanceof Br?{details:{failedRoutes:D.error.failedRoutes}}:{}}}}function zp(){return[...i.values()].map(m=>({composition:m.composition,key:m.key,routeId:m.routeId,state:{...m,dependencyFiles:new Set(m.dependencyFiles),fileVersions:new Map(m.fileVersions)}}))}function Hp(m,I){return m.find(C=>C.key===I)?.state.graph?.version??o.initialVersions.get(I)??0}function Wp(m,I){let S=new Map(m.map(C=>[C.key,C]));for(let C of I)S.set(C.key,C);return[...S.values()]}function Wi(m){for(let I of i.values())N(I);for(let I of m){let S={...I.state,dependencyFiles:new Set(I.state.dependencyFiles),fileVersions:new Map(I.state.fileVersions)};i.set(I.key,S),R(S,S.dependencyFiles)}}async function Gi(m){let I=i.get(m);if(!I)throw new Error(`Composition not found: ${m}`);if(I.graph)return;let S=await n.readFile(I.entryFile);await ct(m,S)}function Ur(m,I){let S=i.get(o.resolveSelector(I).key)??null;return!S||!Gp(S,m)?null:S}function Gp(m,I){if(m.documentIndex?.entriesByKey.has(I)||m.graph?.elements.has(I))return!0;let S=At(I);return S&&S!==I?m.graph?.elements.has(S)===!0:!1}function H(m,I,S,C){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:I,message:S,...C?{details:C}:{}}}}function Yp(m){return m==="validate"?M.ROUTE_REBUILD_FAILED:m==="publish"?M.HISTORY_COMMIT_FAILED:M.WRITE_IO_ERROR}async function Yi(m){if(h=!0,!l.markRecoveryRequired)return M.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(m),M.RECOVERY_REQUIRED}catch{return M.RECOVERY_PERSIST_FAILED}}function FS(m){let S=m.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return S?`Prefab${S}`:"GeneratedPrefab"}function Cc(m){return m==="VERSION_STALE"?M.VERSION_STALE:m==="CROSS_PAGE_MOVE_UNSUPPORTED"?M.CROSS_PAGE_MOVE_UNSUPPORTED:M.UNSUPPORTED_OPERATION}async function Zp(m){if(m.target.kind==="route"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(m.target.kind==="page-unit"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(m.target.kind==="page-block"){let S=i.get(o.resolveSelector(m.target.composition).key)??null;return S?(S.graph||await Gi(S.key),S):H(m,M.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(m.target.kind!=="node")return H(m,M.UNSUPPORTED_OPERATION,`${m.kind} source target execution is not implemented yet.`);let I=i.get(o.resolveSelector(m.composition).key)??null;return I?(I.graph||await Gi(I.key),Gp(I,m.target.key)?I:H(m,M.NODE_NOT_FOUND,`Target key not found: ${m.target.key}`)):H(m,M.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(),f.clear(),g.clear()},registerComposition(m,I){let S=o.register({context:m,entryFile:I}),C=i.get(S.key);if(C?.entryFile===I)return;C&&N(C);let w=aE(S.context,I);i.set(S.key,w),R(w,w.dependencyFiles),r.emit({type:"graph-invalidated",composition:S.context})},unregisterComposition(m){let I=o.resolveSelector(m),S=i.get(I.key);S&&(N(S),i.delete(I.key),o.unregister(I.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:I.context}))},getCompositionEntryFiles(){return[...i.values()].map(m=>m.entryFile)},getCompositionContext(m){return o.resolveSelector(m).context},async initializeComposition(m){let I=o.resolveSelector(m),S=i.get(I.key);if(!S)throw new Error(`Composition not registered: ${I.key}`);if(S.graph)t="ready";else{t="building";try{let C=await n.readFile(S.entryFile);await ct(I.key,C),t="ready",r.emit({type:"graph-ready",composition:I.context,version:i.get(I.key)?.graph?.version??0})}catch(C){throw t="idle",r.emit({type:"graph-error",composition:I.context,message:vt(C)}),C}}},getDocument(m){let I=o.resolveSelector(m),S=i.get(I.key);if(!S)throw new Error(`Composition not registered: ${I.key}`);if(!S.document)throw new Error(`Composition not built: ${I.key}`);return S.document},async getHistoryStatus(){await x;let m=await l.getStatus?.();return m?{...m,recoveryRequired:h}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:h}},getObjectEditContext(m,I,S){let C=Ur(m,I),w=At(m)??m;if(C?.graph&&C.topology&&C.capabilities&&C.detailProjections){let O=C.detailProjections.get(w);if(O){let j=C.graph.elements.get(w);if(!j)throw new Error(`Key not found: ${m}`);let K=zO(m,w,S),Y=new Map;if(O.isRepeat&&K?.instanceIndex!==void 0)for(let ee of j.attributes??[])Y.set(ee.name,kd({file:j.sourceFile,source:d.get(j.sourceFile)??"",element:j,propertyName:ee.name,selectionRef:K,graph:C.graph,sources:d}));let X=kb({element:j,graph:C.graph,source:d.get(j.sourceFile),documentVersion:C.graph.version,selectionRef:S,isRepeat:O.isRepeat,propertyProvenance:O.propertyProvenances,repeatTargets:Y}),J=Nb(w,C.graph,C.topology,C.capabilities,O.textSources,O.provenances,O.dynamicData,X);return m===w?J:Qb(J,m,C.document??null,C.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${m}`)},getRenderDetail(m,I){let S=Ur(m,I),C=At(m)??m;if(S?.graph&&S.topology&&S.capabilities&&S.detailProjections){let w=S.detailProjections.get(C);if(w){let O=Cb(C,S.graph,S.topology,S.capabilities,w.textSources,w.writeTarget,w.provenances,w.conditional,w.componentSemantic,w.styleSource,w.dynamicData);return m===C?O:Zb(O,m,S.document??null,S.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${m}`)},getClassNameSource(m,I){let S=Ur(m,I),C=At(m)??m;if(!S?.graph)throw new Error(`Key not found: ${m}`);let w=S.graph.elements.get(C);if(!w)throw new Error(`Key not found: ${m}`);let O=d.get(w.sourceFile);if(O===void 0)throw new Error(`Source not loaded: ${w.sourceFile}`);return al({key:C,route:{composition:S.composition,routeId:S.routeId,graph:S.graph,source:O}})},refreshSourceForKey:yS,async execute(m){if(await x,h)return H(m,M.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(m.kind==="source-edit")return xS(m);if(m.kind==="insert-page-resource")return bS(m);if(m.kind==="delete-page-source")return ES(m);let I=await Zp(m);if("ok"in I)return I;await Vp(m);let S=await Zp(m);if("ok"in S)return S;let C=S;if(m.target.kind==="page-unit"){let J=m;return m.kind==="insert-child"||m.kind==="replace-node"?SS(J,C):m.kind==="move-node"||m.kind==="remove-node"?IS(J,C):H(m,M.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(m.target.kind==="page-block"){let J=m;return m.kind==="insert-child"||m.kind==="replace-node"?vS(J,C):m.kind==="move-node"||m.kind==="remove-node"?kS(J,C):H(m,M.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let O=m.params,j=m.target.kind==="node"?m.target.key:null;if(O.kind==="move-node"&&"kind"in O.target&&O.target.kind==="source-sibling"){let J=O.target,ee=j?C.document?.entries.find(G=>G.key===j):null,se=C.document?.entries.find(G=>G.key===J.anchorKey),be=ee?.pageCompositionActionScope,re=be?.kind==="source-siblings"?be.siblingKeys:null,Re=re?.indexOf(ee?.key??"")??-1,ye=re?.indexOf(J.anchorKey)??-1,D=J.relation==="before"?Re-1:Re+1;if(!ee||!se||!re||Re<0||ye!==D||se.pageCompositionActionScope?.kind!=="source-siblings"||se.pageCompositionActionScope.siblingKeys.length!==re.length||se.pageCompositionActionScope.siblingKeys.some((G,pe)=>G!==re[pe])||!ee.operationSummary.canMove)return H(m,M.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(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:m.target.kind==="route"?M.ROUTE_NOT_FOUND:M.NODE_NOT_FOUND,message:m.target.kind==="route"?"Composition not ready for route target.":m.target.kind==="node"?`Target key not found: ${m.target.key}`:`${m.kind} source target execution is not implemented yet.`}};let K=uF(C,C.graph,C.capabilities,d,i),Y=await new Fa(K).plan(m);if(!Y.ok)return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:$i(Y.errorCode),message:Y.reason}};let X=Y.plan;if(X.steps.length===0)return m.kind==="set-props"?{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!0,resultVersion:Q(m),affectedFiles:[]}:{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(X.steps.some(ee=>ee.type==="invoke-external-adapter")){let ee=await u.execute(X);if(!ee.ok)return H(m,$i(ee.errorCode),ee.reason);let se={composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!0,resultVersion:Math.max(Q(m),ee.resultVersion),affectedFiles:ee.affectedFiles,...ee.selectionRef?{selectionRef:ee.selectionRef}:{}};return $r(se,{rebuiltRoutes:[],failedRoutes:[]}),se}let J=await u.prepareRewritePlan(X);return J.ok?await Vn({request:m,filePlan:J.filePlan,...J.selectionRef?{selectionRef:J.selectionRef}:{}}):H(m,$i(J.errorCode),J.reason)}catch(J){return{composition:o.resolveSelector(m.composition).context,requestId:m.id,kind:m.kind,target:m.target,ok:!1,resultVersion:Q(m),error:{code:M.INTERNAL_ERROR,message:vt(J)}}}finally{p-=1}},async undo(m){if(await x,h)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await Xp("undo")}finally{p-=1}},async redo(m){if(await x,h)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:z(o.entries[0].key),error:{code:M.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await Xp("redo")}finally{p-=1}},notifyFileChanged(m){Dp([m])},getAffectedCompositions(m){return Ve(m)},subscribe(m){return r.subscribe(m)}}}function rF(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function oF(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let p=d.get(f)??new Set,h=p.size;return p.add(g),d.set(f,p),p.size!==h},a=(d,f)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,f);let g=s(o,`${d.importedFrom}#${d.tag}`,f);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,f)||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 f=n.placements.find(p=>p.members.some(h=>h.sourceRange!==null&&Vi(d.sourceRange,h.sourceRange)));if(!f)continue;let g=f.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 f=c(d);if(f)for(let g of f)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 f=At(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(f);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&Vi(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(Vi(g.sourceRange,E.sourceRange)||lF(E.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let p=o.get(`${g.sourceFile}#${g.componentName}`);if(p){p.size===1&&(d.pageCompositionUnitKey=p.values().next().value);continue}let h=i.get(g.sourceFile);h?.size===1&&(d.pageCompositionUnitKey=h.values().next().value)}iF(e,t,n,r)}function iF(e,t,n,r){let o=new Map(e.entries.map(f=>[f.key,f])),i=e.entries.filter(f=>{let g=f.pageCompositionUnitKey;return g?f.parentKey?o.get(f.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(f,g)=>{s.set(f,Math.min(2,(s.get(f)??0)+g))},c=f=>n.placements.some(g=>g.members.some(p=>p.sourceRange!==null&&Vi(f.sourceRange,p.sourceRange)));for(let f of t.elements.values())f.sourceFile!==n.entryFile||!f.importedFrom||!/^[A-Z]/.test(f.tag)||!c(f)||a(`${f.importedFrom}#${f.exportName??f.tag}`,1);let l=[...t.elements.values()].flatMap(f=>f.sourceFile!==n.entryFile&&f.importedFrom&&/^[A-Z]/.test(f.tag)?[{owner:`${f.sourceFile}#${f.componentName}`,ownerDefault:`${f.sourceFile}#default`,target:`${f.importedFrom}#${f.exportName??f.tag}`}]:[]);for(let f=0;f<=l.length;f+=1){let g=!1;for(let p of l){let h=s.get(p.owner)??s.get(p.ownerDefault)??0;if(!h)continue;let y=s.get(p.target)??0,x=Math.min(2,y+h);x!==y&&(s.set(p.target,x),g=!0)}if(!g)break}let u=f=>s.get(`${f.sourceFile}#${f.componentName}`)??s.get(`${f.sourceFile}#default`)??0;for(let f of i){f.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(f.key);f.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(f.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let f of i){let g=t.elements.get(f.key);if(!g||g.sourceFile===n.entryFile||f.key!==(At(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let h=xe(p.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!h.ok||!h.match.path.isJSXElement())continue;let y=h.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&Ke(x))){u(g)===1&&uE(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!uE(x))continue;let E=d.get(x.node)??[];E.push({entry:f,element:g,parentPath:x}),d.set(x.node,E)}for(let f of d.values()){let g=f[0];if(!g)continue;let p=g.entry.pageCompositionUnitKey,h=[],y=!!(p&&u(g.element)===1);for(let E of g.parentPath.node.children){if(sF(E))continue;if(!aF(E)){y=!1;break}let b=[...t.elements.values()].find(_=>_.sourceFile===g.element.sourceFile&&_.componentName===g.element.componentName&&Vi(_.sourceRange,cF(E))),v=b?o.get(b.identity.key):null;if(!b||!v||v.parentKey||v.pageCompositionUnitKey!==p||u(b)!==1){y=!1;break}h.push(v)}if(!y||h.length!==f.length||f.some(({entry:E})=>!h.some(b=>b.key===E.key)))continue;if(h.length===1){h[0].pageCompositionActionScope={kind:"route-unit"};continue}if(h.length<2)continue;let x=h.map(E=>E.key);for(let E of h)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function uE(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function sF(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function aF(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function cF(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 Vi(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function lF(e,t){return dE(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&dE(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function dE(e,t,n,r){return e!==n?e-n:t-r}function uF(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 f=t.elements.get(u);for(let g of f?.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),f=t.elements.get(d.baseKey);return f?l(u,f):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(h=>{let y=At(h)??h,x=t.elements.get(y);return x?l(h,x):null}).filter(h=>h!==null);let p=t.elements.get(d.baseKey);return p?p.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),f=n.get(d.baseKey);return f?{...f,key:u,constraints:f.constraints.map(g=>({...g})),...f.editModes?{editModes:{...f.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),f=t.elements.get(d.baseKey),g=f?r.get(f.sourceFile):void 0;return!f||g===void 0?null:al({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 f=c(u);return Wd(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return Wd(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=p.attributes?.find(E=>E.name===d);return x?x.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:x,target:{kind:"jsx-attribute",file:p.sourceFile,sourceRange:x.sourceRange}}:(p.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,f){let g=c(u),p=t.elements.get(g.baseKey);if(!p)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let h=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return kd({file:p.sourceFile,source:r.get(p.sourceFile)??"",element:p,propertyName:d,selectionRef:h,graph:t,sources:r})},getTextProvenance(u,d){let f=c(u);return e.detailProjections?.get(f.baseKey)?.provenances.get(d)??null}};function c(u){let d=LO(u);return d?{baseKey:d.baseKey,repeatIndex:Yb(e.document??null,u,d.baseKey,e.documentIndex)??Gb(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=At(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(f),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(f),repeatOwnerKey:i.get(f)??s.get(f),attributes:d.attributes?.map(p=>({name:p.name,value:p.value,source:p.source?{expression:p.source.expression,base:p.source.base,path:p.source.path.map(h=>({...h}))}:null,resolvedValue:p.resolvedValue}))}}}var dF={"stale-version":M.VERSION_STALE,"capability-denied":M.CAPABILITY_REJECTED,"invalid-params":M.INVALID_PARAMS,"locator-miss":M.LOCATOR_FAILED,"route-not-found":M.ROUTE_NOT_FOUND,"unsupported-operation":M.UNSUPPORTED_OPERATION,"invalid-target":M.INVALID_TARGET,"ast-error":M.AST_PARSE_ERROR,"writeback-failed":M.WRITE_IO_ERROR,"rollback-failed":M.RECOVERY_REQUIRED,unknown:M.INTERNAL_ERROR};function $i(e){return dF[e]}function vt(e){return e instanceof Error&&e.message?e.message:String(e)}function pE(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function pF(e){let t=jr(e);if(!BO.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=>jO.map(a=>`${s}/${a}`))}function fF(e){let n=jr(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function mF(e){return gE(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function gF(e){return gE(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function gE(e,t){let n=[];for(let r of e.matchAll(t)){let o=hE(r[1]??"");o&&n.push(o)}return n}function fE(e,t){let n=hE(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?jr(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?jr(`${hF(e)}/${n}`):n.startsWith("/")?jr(n.slice(1)):qd(n)?jr(n):null}function hE(e){return e.split(/[?#]/,1)[0]?.trim()??""}function qd(e){return/\.css$/i.test(e)}function hF(e){let t=jr(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function yF(e){return Array.from(new Set(e))}function jr(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 xF(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 oc=class{constructor(t){this.options=t,this.fileSystem=new Ao(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return rs(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 os(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return as(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return cs(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return ls(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=EF.safeParse(t);if(!n.success)return{result:ns(t,n.error.issues.map(i=>i.message))};let r=new Ao(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:br(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=SF.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>vF(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 rc({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=is(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 vF(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:ve(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:ve(e.before)},fullContent:e.after}}function IF(e){return new oc(e)}import{SiteEditOperationRequestSchema as CF}from"@vcp-dev/contracts";import ln from"node:fs/promises";import It from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as kF,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as RF}from"@vcp-dev/contracts";var ic=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=rc({...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 as(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return cs(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return ls(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 ln.readFile(It.join(n,r),"utf8")},async readFileBytes(r){return ln.readFile(It.join(n,r))},async getFileInfo(r){let o=It.join(n,...r.split("/"));try{let i=await ln.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await _s(It.join(n,r),o)},async createExclusive(r,o){let i=It.join(n,r);await ln.mkdir(It.dirname(i),{recursive:!0});let s=await ln.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await ln.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await ln.rm(It.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=It.join(n,i),a=It.dirname(It.join(n,o));for(;a!==s&&a.startsWith(`${s}${It.sep}`);){try{await ln.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=It.dirname(a);continue}break}a=It.dirname(a)}},async exists(r){try{return await ln.access(It.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...RF,...kF],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,f)=>d.path.localeCompare(f.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,f,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let p=It.join(n,...d.split("/")),h;try{h=await ln.lstat(p)}catch{return}if(h.isSymbolicLink())return;if(h.isFile()){let x=h.ino>0?`${String(h.dev)}:${String(h.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+h.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),f.push({path:d,sizeBytes:h.size}),c+=h.size;return}if(!h.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await ln.readdir(p,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,f,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 ep(e){return new ic(e)}var sc=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=ep({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=is(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:rs(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:os(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=CF.safeParse(r);if(!o.success)return ns(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:br(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:br(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:br(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 NF(e){return new sc(e)}import{GeneratedSiteCapabilitiesSchema as OF}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as _F}from"@vcp-dev/contracts";function ac(e){let t=AF(e.host_capabilities),n=e.platform_managed_paths??[],r=new Set(e.platform_managed_packages??[]);return e.node.kind==="external"?r.has(e.node.path)?Bn(e.node,"platform-managed","controlled platform package"):t?TF(e.node.path,t)?Bn(e.node,"host-public","declared Starter runtime dependency"):Bn(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Bn(e.node,"unknown","trusted host capability contract is invalid"):yE(e.node.path,n)?Bn(e.node,"platform-managed","controlled platform path"):t?bE(e.node.path,t.generated_sections_path)?Bn(e.node,"private","site-generated section path"):yE(e.node.path,t.public_paths)?Bn(e.node,"host-public","declared Starter public path"):Bn(e.node,"private","site-local file outside host public paths"):Bn(e.node,"unknown","trusted host capability contract is invalid")}function PF(e){return e.nodes.map(t=>ac({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Bn(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function AF(e){let t=_F.safeParse(e);return t.success?t.data:null}function TF(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function yE(e,t){return t.some(n=>bE(e,n))}function bE(e,t){let n=wF(t),r=EE(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):xE(r)===xE(n)}function wF(e){return EE(e.split("#",1)[0]??e)}function EE(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function xE(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function FF(e){let t=OF.safeParse(e.host_capabilities).success,n=[];t||n.push({code:"HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Portable dependency audit requires the schema-validated Starter host contract."}),e.closure.complete||n.push({code:"INCOMPLETE_SOURCE_NODE",path:"<closure>",message:"Portable source closure is not complete."});for(let i of e.closure.errors)n.push({...i});let r=e.closure.nodes.map(i=>{let s=ac({node:i,host_capabilities:e.host_capabilities,platform_managed_paths:e.platform_managed_paths,platform_managed_packages:e.platform_managed_packages});return s.ownership==="unknown"?n.push({code:"UNKNOWN_DEPENDENCY_OWNERSHIP",path:i.path,message:`Portable dependency ownership is not proven for ${i.path}.`}):s.ownership==="unsupported-external-private"&&n.push({code:"UNSUPPORTED_EXTERNAL_DEPENDENCY",path:i.path,message:`Portable source closure depends on unsupported external package ${i.path}.`}),i.status!=="complete"&&n.push({code:"INCOMPLETE_SOURCE_NODE",path:i.path,message:`Portable source node ${i.path} is ${i.status}.`}),{...i,ownership:s.ownership,ownership_reason:s.reason}}),o=LF(n).sort(DF);return{complete:o.length===0,nodes:r.sort(MF),edges:[...e.closure.edges].sort(BF),errors:o}}function LF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function DF(e,t){return jt(e.path,t.path)||jt(e.code,t.code)||jt(e.specifier??"",t.specifier??"")||jt(e.message,t.message)}function MF(e,t){return jt(e.path,t.path)||jt(e.kind,t.kind)||jt(e.ownership,t.ownership)||jt(e.status,t.status)}function BF(e,t){return jt(e.from,t.from)||jt(e.target??"",t.target??"")||jt(e.specifier??"",t.specifier??"")||jt(e.kind,t.kind)||jt(e.resolution,t.resolution)}function jt(e,t){return e<t?-1:e>t?1:0}import*as kt from"@babel/types";var SE=[".tsx",".ts",".jsx",".js"],jF=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 Ui(e){let t=KF(e.files),n=IE(e.max_depth??32,"max_depth"),r=IE(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(CE).filter(Boolean))],i=new Map,s=[],a=[],c=new Set,l=new Set,u=new Set,d=[];o.length===0&&a.push({code:"SOURCE_ENTRY_UNRESOLVED",path:"<entry>",message:"Portable source closure requires at least one entry file."});for(let h of o)if(!(!h||l.has(h))){if(!Eo(h,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:h,message:"Portable source closure node budget was exhausted."});continue}l.add(h),d.push({path:h,depth:0})}for(;d.length>0;){let h=d.shift();if(u.has(h.path))continue;u.add(h.path);let y=t.get(h.path);if(y===void 0){let P=o.includes(h.path)?"SOURCE_ENTRY_UNRESOLVED":So(h.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";cr(i,{path:h.path,kind:So(h.path)?"asset":"source",depth:h.depth,status:"unresolved"}),a.push({code:P,path:h.path,message:`Portable source closure could not read ${h.path}.`});continue}let x=So(h.path)?"asset":"source";if(x==="asset"){let P=JF(h.path,y);cr(i,{path:h.path,kind:x,depth:h.depth,status:P?"parse-failed":"complete"}),P&&a.push(P);continue}let E=NE(y),b=Je(h.path,E);if(!b.ok){cr(i,{path:h.path,kind:x,depth:h.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:h.path,message:b.diagnostic.message});continue}let v=VF(b.module.ast),_=!1;for(let P of v){let R=$F({from:h.path,depth:h.depth,reference:P,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(R.edge),R.next&&(R.next.depth>n?_=!0:!u.has(R.next.path)&&!l.has(R.next.path)&&(l.add(R.next.path),d.push(R.next))),R.depthExhausted&&(_=!0)}cr(i,{path:h.path,kind:x,depth:h.depth,status:_?"depth-exhausted":"complete"}),_&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:h.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(YF),g=WF(s).sort(ZF),p=GF(a).sort(QF);return{entry_files:o.sort(kn),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function $F(e){let{reference:t}=e;if(t.specifier===null)return e.errors.push({code:"SOURCE_DYNAMIC_IMPORT_UNRESOLVED",path:e.from,message:"Portable source closure cannot resolve a non-literal dynamic import."}),{edge:{from:e.from,specifier:null,kind:t.kind,target:null,resolution:"non-literal"},depthExhausted:!1};if(!St(t.specifier)){let o=zF(t.specifier);return Eo(o,e.discovered,e.maxNodes)?(cr(e.nodes,{path:o,kind:"external",depth:null,status:"complete"}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"external"},depthExhausted:!1}):(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:o,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:o,resolution:"budget-exhausted"},depthExhausted:!1})}let n=np(e.from,t.specifier);if(_E(e.from,t.specifier,n))return e.errors.push({code:"SOURCE_UNSAFE_IMPORT",path:n,specifier:t.specifier,message:`Portable source closure rejected unsafe local import ${t.specifier} from ${e.from}.`}),Eo(n,e.discovered,e.maxNodes)?cr(e.nodes,{path:n,kind:So(n)?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1};let r=RE(e.from,t.specifier,e.files);if(!r){let o=So(n);return e.errors.push({code:o?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED",path:n,specifier:t.specifier,message:`Portable source closure could not resolve ${t.specifier} from ${e.from}.`}),Eo(n,e.discovered,e.maxNodes)?cr(e.nodes,{path:n,kind:o?"asset":"source",depth:e.depth+1,status:"unresolved"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:n,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:n,resolution:"unresolved"},depthExhausted:!1}}if(e.depth>=e.maxDepth&&!e.visited.has(r)&&!e.queued.has(r)){let o=So(r)?"asset":"source";return Eo(r,e.discovered,e.maxNodes)?cr(e.nodes,{path:r,kind:o,depth:e.depth+1,status:"depth-exhausted"}):e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!0}}return Eo(r,e.discovered,e.maxNodes)?{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"resolved"},next:{path:r,depth:e.depth+1},depthExhausted:!1}:(e.errors.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:r,specifier:t.specifier,message:"Portable source closure node budget was exhausted."}),{edge:{from:e.from,specifier:t.specifier,kind:t.kind,target:r,resolution:"budget-exhausted"},depthExhausted:!1})}function VF(e){let t=[];for(let n of e.program.body)kt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):kt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):kt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return tp(e.program,n=>{if(kt.isCallExpression(n)&&kt.isImport(n.callee)){let r=n.arguments[0];kt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}kt.isTSImportType(n)&&t.push({specifier:kt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),HF(t)}function tp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)kE(r)&&tp(r,t);else kE(n)&&tp(n,t)}function UF(e,t,n){let r=np(e,t);return!St(t)||_E(e,t,r)?null:RE(e,t,n)}function RE(e,t,n){let r=np(e,t);if(!r||r.startsWith("../")||r==="..")return null;if(n.has(r))return r;let o=r.replace(/[?#].*$/u,"");if(o!==r&&n.has(o))return o;if(XF(o))return null;for(let i of SE){let s=`${o}${i}`;if(n.has(s))return s}for(let i of SE){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function np(e,t){let n=un(e,t);return CE(n)}function CE(e){let t=e.replace(/\\/g,"/"),n=[];for(let r of t.split("/"))if(!(!r||r===".")){if(r===".."){n.length>0&&n.at(-1)!==".."?n.pop():n.push("..");continue}n.push(r)}return n.join("/")}function KF(e){return e instanceof Map?e:new Map(Object.entries(e))}function NE(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function JF(e,t){if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(NE(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function cr(e,t){let n=e.get(t.path);(!n||vE(t.status)>vE(n.status))&&e.set(t.path,t)}function Eo(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function vE(e){return e==="complete"?1:0}function So(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&jF.has(n)}function XF(e){return/\.[a-z0-9]+$/iu.test(e)}function zF(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function HF(e){let t=new Set;return e.filter(n=>{let r=`${n.kind}\0${n.specifier??"<dynamic>"}`;return t.has(r)?!1:(t.add(r),!0)})}function WF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function GF(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function YF(e,t){return kn(e.path,t.path)||kn(e.kind,t.kind)}function ZF(e,t){return kn(e.from,t.from)||kn(e.target??"",t.target??"")||kn(e.specifier??"",t.specifier??"")||kn(e.kind,t.kind)}function QF(e,t){return kn(e.path,t.path)||kn(e.code,t.code)||kn(e.specifier??"",t.specifier??"")}function kn(e,t){return e<t?-1:e>t?1:0}function IE(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function kE(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function _E(e,t,n){if(t.includes("\0")||t.includes("\\")||n.startsWith("../")||n===".."||n.startsWith("/"))return!0;if(t.startsWith("@/")){let r=t.slice(2);return r.length===0||r.split("/").some(o=>o==="..")}return e.startsWith("/")}import{parse as mp}from"@babel/parser";import*as B from"@babel/types";import{PortableCollectionRecipeFactsSchema as yL}from"@vcp-dev/contracts";import{parse as lr}from"@babel/parser";import*as V from"@babel/types";function qF(e){let t=DE(e.files),n=(d,f,g)=>({complete:!1,relation:null,errors:[{code:d,path:f,message:g}]}),r=vo(e.list_entry_file,e.selected_component_source,t),o=r?t.get(r):void 0;if(!r||typeof o!="string")return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",e.list_entry_file,"The selected Page Unit does not resolve to one Snapshot list container.");if(!nL(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};let i=tL(o,r),s=i?cc(r,o,i,"listStrict"):null;if(!i||!s)return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",r,"The selected list container does not prove one literal CMS collection.");let a=[...t.entries()].flatMap(([d,f])=>{if(typeof f!="string"||!/\[slug\]\/page\.(?:[cm]?[jt]sx?)$/u.test(d))return[];let g=cc(d,f,i,"getByUrlStrict");return g&&wE(g.ast,i)===`/${i}`?[g]:[]});if(a.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let c=a[0],l=Mn(c.source,{filePath:c.path,exportName:"default"}).components.flatMap(d=>{let f=vo(c.path,d.source,t),g=f?t.get(f):void 0;return!f||typeof g!="string"||!TE(g,d.export_name)||!ip(g,c.adapter_source,c.interface_name)?[]:[{path:f,export_name:d.export_name}]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c.path,"The collection detail route does not prove one private detail view.");let u=l[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:c.path,detail_view_file:u.path,detail_view_export:u.export_name},errors:[]}}function lp(e){let t=DE(e.files),n=[],r=[],o=[],i=null;e.source_closure.complete||n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"The selected Page Unit source closure is incomplete; related entries cannot be proven."}),rp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),rp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),rp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),op(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),op(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key});let s=Ui({entry_files:[e.collection.detail_entry_file],files:t});s.complete||n.push(...s.errors.map(f=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:f.path,message:f.message})));let a=s.nodes.find(f=>f.path===e.collection.detail_view_file);!a||a.status!=="complete"?n.push({code:"RELATED_DETAIL_VIEW_NOT_REACHED",path:e.collection.detail_view_file,message:"The trusted detail route does not reach the declared detail-view entry."}):r.push({path:e.collection.detail_view_file,export:e.collection.detail_view_export==="default"?{kind:"default"}:{kind:"named",name:e.collection.detail_view_export},purpose:"collection-detail-view"});for(let f of s.nodes)if(f.kind!=="external"&&f.path!==e.collection.detail_entry_file&&f.path!==e.collection.detail_view_file){if(cL(f.path,e.collection)){op(o,{path:f.path,kind:f.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}lL(f.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:f.path,export:{kind:"default"},purpose:"i18n-companion"})}let c=t.get(e.collection.detail_view_file);typeof c=="string"&&sL(c,e.collection.detail_view_file,s.nodes,t,r),e.page_template&&(i=aL(e.page_template,t,n));let l=e.trusted_schema===void 0?null:eL(e,t,n,e.trusted_schema),u=pL(r).map((f,g)=>({key:mL(f,g),pathTemplate:f.path,export:f.export,purpose:f.purpose,requirementKey:e.collection.requirement_key})),d=gL(n).sort(hL);return{complete:d.length===0,entries:u.sort((f,g)=>f.pathTemplate.localeCompare(g.pathTemplate)||f.purpose.localeCompare(g.purpose)||f.key.localeCompare(g.key)),managed_requirements:o.sort(fL),thin_entry_plan:i,collection_wiring:l,errors:d}}function eL(e,t,n,r){let o=n.length,i=r.fields.map(v=>({...v}));(r.source_slug!==e.collection.slug||!r.evidence_path.trim()||i.length===0)&&n.push({code:"RELATED_COLLECTION_SCHEMA_UNPROVEN",path:r.evidence_path||`trusted-schema:${e.collection.slug}`,message:"Collection recipe facts require a non-empty trusted CMS schema with matching source identity."});let s=e.source_closure.nodes.filter(v=>v.kind==="source"&&v.status==="complete"&&v.path!==e.collection.list_entry_file).flatMap(v=>{let _=t.get(v.path);if(typeof _!="string")return[];let P=cc(v.path,_,e.collection.slug,"listStrict");return P?[P]:[]});s.length!==1&&n.push({code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.collection.list_entry_file,message:"Exactly one rendered source module must prove the selected collection listStrict wiring."});let a=s[0]??null,c=a?PE(a,t,v=>v!==e.collection.detail_view_file):null;c?a&&!ip(t.get(c.source_path),a.adapter_source,a.interface_name)&&n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:c.source_path,message:"The rendered list view does not consume the generated collection interface."}):n.push({code:"RELATED_COLLECTION_LIST_VIEW_UNPROVEN",path:a?.path??e.collection.list_entry_file,message:"The generated list container must render one resolvable private list view."});let l=t.get(e.collection.detail_entry_file),u=typeof l=="string"?cc(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict"):null,d=u?PE(u,t,v=>v===e.collection.detail_view_file):null;!u||!d||d.export_name!==e.collection.detail_view_export?n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The trusted detail route must consume the declared detail view through the same collection adapter."}):ip(t.get(d.source_path),u.adapter_source,u.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:d.source_path,message:"The rendered detail view does not consume the generated collection interface."}),a&&u&&(a.adapter_source!==u.adapter_source||a.interface_name!==u.interface_name)&&n.push({code:"RELATED_COLLECTION_ADAPTER_UNPROVEN",path:e.collection.detail_entry_file,message:"List and detail consumers must use the same generated collection adapter and view interface."});let f=new Set(i.map(v=>v.name)),g=a?vo(a.path,a.adapter_source,t):null,p=g?t.get(g):null,h=[...e.required_fields??i.filter(v=>v.required).map(v=>v.name)].sort(cp),y=[...e.force_multi_media??(typeof p=="string"?OE(p):[])].sort(cp);for(let v of[...h,...y])f.has(v)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${v}`,message:`Collection field ${v} is not present in the trusted schema.`});if(a&&y.length)for(let v of y)(typeof p!="string"||!iL(p,v))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${v}.`});let x=u?wE(u.ast,e.collection.slug):null;x||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The detail route does not prove a literal getByUrlStrict prefix."});let E=u?rL(u.ast):null;E||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:e.collection.detail_entry_file,message:"The generated detail route must expose a literal PAGE_SEO title."});let b=u?oL(u,t,x):null;return b==="unproven"&&n.push({code:"RELATED_COLLECTION_BREADCRUMB_UNPROVEN",path:e.collection.detail_entry_file,message:"The rendered collection breadcrumb exists but its fallback labels are not literal."}),n.length!==o||!a||!c||!u||!d||!x?null:{source_slug:e.collection.slug,detail_prefix:x,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...c,interface_name:a.interface_name},detail_view:{...d,interface_name:u.interface_name},...E?{title:E}:{},...b&&b!=="unproven"?{breadcrumb:b}:{},...h.length>0?{required_fields:h}:{},...y.length>0?{force_multi_media:y}:{}}}function cc(e,t,n,r){let o;try{o=lr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let i=jn(o,c=>{if(!V.isCallExpression(c)||!uc(c.callee,r))return!1;let l=c.arguments[0];return r==="listStrict"?V.isStringLiteral(l)&&l.value===n:sp(l,ap(o))!==null});if(r==="listStrict"&&i.length!==1||r==="getByUrlStrict"&&(i.length===0||i.some(c=>sp(c.arguments[0],ap(o))!==`/${n}`)))return null;let a=o.program.body.flatMap(c=>V.isImportDeclaration(c)?c.specifiers.flatMap(l=>{if(!V.isImportSpecifier(l))return[];let u=V.isIdentifier(l.imported)?l.imported.name:l.imported.value,d=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(u);return d?[{source:c.source.value,local_name:l.local.name,interface_name:d[1]}]:[]}):[]).filter(c=>jn(o,l=>V.isIdentifier(l,{name:c.local_name})).length>1);return a.length!==1?null:{path:e,source:t,ast:o,adapter_source:a[0].source,interface_name:a[0].interface_name}}function tL(e,t){let n;try{n=lr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=jn(n,o=>V.isCallExpression(o)&&uc(o.callee,"listStrict")&&V.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9]{1,30}$/u.test(r[0])?r[0]:null}function nL(e,t,n){let r;try{r=lr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return jn(r,o=>V.isCallExpression(o)&&uc(o.callee,n)).length>0}function PE(e,t,n){let r=Mn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=vo(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!TE(a,i.export_name)?[]:[{source_path:s,target_path:s,export_name:i.export_name,import_specifier:i.source}]});return o.length===1?o[0]:null}function TE(e,t){let n;try{n=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&V.isExportDefaultDeclaration(r))return!0;if(V.isExportNamedDeclaration(r)&&(r.declaration&&(V.isFunctionDeclaration(r.declaration)||V.isClassDeclaration(r.declaration)||V.isTSInterfaceDeclaration(r.declaration)||V.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||V.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>V.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>V.isExportSpecifier(o)?(V.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function ip(e,t,n){if(typeof e!="string")return!1;let r;try{r=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!V.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>V.isImportSpecifier(s)?(V.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>jn(r,s=>V.isIdentifier(s,{name:i})).length>1)}function uc(e,t){return V.isMemberExpression(e)&&!e.computed&&V.isIdentifier(e.property,{name:t})&&V.isMemberExpression(e.object)&&!e.object.computed&&V.isIdentifier(e.object.property,{name:"collections"})&&V.isIdentifier(e.object.object,{name:"cms"})}function wE(e,t){let n=ap(e),r=jn(e,i=>V.isCallExpression(i)&&uc(i.callee,"getByUrlStrict"));return r.length===0?null:r.map(i=>sp(i.arguments[0],n)).every(i=>i===`/${t}`)?`/${t}`:null}function sp(e,t){return V.isBinaryExpression(e,{operator:"+"})&&V.isStringLiteral(e.left)&&V.isIdentifier(e.right)&&t.has(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):V.isTemplateLiteral(e)&&e.expressions.length===1&&V.isIdentifier(e.expressions[0])&&t.has(e.expressions[0].name)&&e.quasis.length>0&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.quasis[0].value.cooked??"")?(e.quasis[0].value.cooked??"").slice(0,-1):null}function ap(e){let t=e.program.body.find(i=>V.isExportDefaultDeclaration(i));if(!V.isExportDefaultDeclaration(t))return new Set;let n=t.declaration;if(!V.isFunctionDeclaration(n)&&!V.isFunctionExpression(n)&&!V.isArrowFunctionExpression(n))return new Set;let r=new Set;for(let i of n.params)if(V.isObjectPattern(i))for(let s of i.properties)V.isObjectProperty(s)&&!s.computed&&lc(s.key)==="params"&&V.isIdentifier(s.value)&&r.add(s.value.name);if(r.size===0)return new Set;let o=new Set;for(let i of jn(n.body,s=>V.isVariableDeclarator(s)))if(!(!V.isObjectPattern(i.id)||!V.isAwaitExpression(i.init)||!V.isIdentifier(i.init.argument)||!r.has(i.init.argument.name)))for(let s of i.id.properties)V.isObjectProperty(s)&&!s.computed&&lc(s.key)==="slug"&&V.isIdentifier(s.value)&&o.add(s.value.name);return o}function rL(e){for(let t of e.program.body)if(V.isVariableDeclaration(t))for(let n of t.declarations){if(!V.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=FE(n.init);if(!V.isObjectExpression(r))return null;let o=r.properties.find(i=>V.isObjectProperty(i)&&!i.computed&&lc(i.key)==="title");return o&&V.isStringLiteral(o.value)?o.value.value:null}return null}function oL(e,t,n){let o=Mn(e.source,{filePath:e.path,exportName:"default"}).components.filter(c=>/(?:^|\/)components\/site\/generated\/[A-Za-z0-9_-]+-breadcrumb$/u.test(c.source));if(o.length===0)return null;if(o.length!==1||!n)return"unproven";let i=vo(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=lr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of jn(a,l=>V.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!V.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!V.isObjectProperty(p)||p.computed)continue;let h=lc(p.key);h&&V.isStringLiteral(p.value)&&g.set(h,p.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=l.find(f=>f.get("href")==="/"),d=l.find(f=>f.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function OE(e){let t;try{t=lr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(jn(t,n=>{if(!V.isCallExpression(n))return!1;let r=n.callee;if(!V.isMemberExpression(r)||r.computed||!V.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return V.isMemberExpression(o)&&!o.computed&&V.isIdentifier(o.object,{name:"d"})&&V.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return V.isMemberExpression(r)&&!r.computed&&V.isIdentifier(r.property)?[r.property.name]:[]}))].sort(cp)}function iL(e,t){return OE(e).includes(t)}function jn(e,t){let n=[],r=o=>{t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)AE(s)&&r(s);else AE(i)&&r(i)};return r(e),n}function AE(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function FE(e){return e?V.isTSAsExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e)?FE(e.expression):e:null}function lc(e){return V.isIdentifier(e)?e.name:V.isStringLiteral(e)?e.value:null}function cp(e,t){return e.localeCompare(t)}function sL(e,t,n,r,o){let i=Mn(e,{filePath:t,exportName:"default"});for(let s of i.components){let a=vo(t,s.source,r);if(!a)continue;let c=n.find(u=>u.path===a),l=r.get(a);!c||c.kind==="external"||typeof l!="string"||uL(l)&&o.push({path:a,export:s.export_name==="default"?{kind:"default"}:{kind:"named",name:s.export_name},purpose:"client-importer"})}}function aL(e,t,n){let r=t.get(e.entry_file);if(typeof r!="string")return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:"The PageTemplate entry source is not available as text."}),null;let o=Mn(r,{filePath:e.entry_file,exportName:"default"});if(o.diagnostics.length>0)return n.push({code:"RELATED_PAGE_TEMPLATE_PARSE_FAILED",path:e.entry_file,message:o.diagnostics[0]?.message??"PageTemplate AST is incomplete."}),null;let i=o.rendered_component_openings;if(i.length!==1)return n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"A single-file PageTemplate is portable only when one real component call can be isolated; the whole page cannot be copied."}),null;let s=i[0];return e.component_source&&s.source!==e.component_source||e.component_export&&s.export_name!==e.component_export?(n.push({code:"RELATED_PAGE_TEMPLATE_NOT_SEPARABLE",path:e.entry_file,message:"The declared PageTemplate root does not match its real rendered component call."}),null):{kind:"managed-root-thin-entry",source_file:e.entry_file,component_source:s.source,component_export:s.export_name,adds_dom:!1}}function rp(e,t,n,r){e.has(t)||r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function cL(e,t){return e===t.list_entry_file||e===t.detail_entry_file||e.startsWith("lib/cms/")||e===`components/site/generated/${t.slug}-list.tsx`||e===`components/site/generated/${t.slug}-list.ts`||e===`components/site/generated/${t.slug}-list.jsx`||e===`components/site/generated/${t.slug}-list.js`||e===`components/site/generated/${t.slug}-breadcrumb.tsx`||e===`components/site/generated/${t.slug}-breadcrumb.ts`||e===`components/site/generated/${t.slug}-breadcrumb.jsx`||e===`components/site/generated/${t.slug}-breadcrumb.js`}function lL(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=LE(t),s=o.slice(o.lastIndexOf("/")+1),a=s.endsWith("-detail-view")?s.slice(0,-12):n;return r===`${o}.i18n.json`||r===`${o}.messages.json`||r===`${i}/${a}.i18n.json`||r===`${i}/${a}.messages.json`||/(?:^|\/)(?:i18n|locales?)\/[^/]+\.json$/u.test(r)||/\.(?:i18n|messages)\.[^/]+\.json$/u.test(r)}function uL(e){try{let n=lr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0];return n?.type==="ExpressionStatement"&&n.expression.type==="StringLiteral"&&n.expression.value==="use client"}catch{return!1}}function vo(e,t,n){let r=t.startsWith("@/")?t.slice(2):dL(`${LE(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 LE(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function dL(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.length>0&&t.at(-1)!==".."?t.pop():t.push(".."):t.push(n));return t.join("/")}function DE(e){return e instanceof Map?e:new Map(Object.entries(e))}function pL(e){let t=new Set;return e.filter(n=>{let r=`${n.path}\0${n.purpose}\0${JSON.stringify(n.export)}`;return t.has(r)?!1:(t.add(r),!0)})}function op(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function fL(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function mL(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function gL(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function hL(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var xL=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),bL=new Set(["data-vcp-block-id","data-vcp-edit-key"]),EL=new Set(["data-vcp-order","sourceOrder","source_order"]);function Ji(e){let t=f=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...f].sort(fp)}),n;try{n=mp(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(f){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:f instanceof Error?f.message:String(f)}])}let r=AL(n),o=Mn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(f=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:f.file_path||e.file_path,message:f.message})),s=new Set(o.rendered_component_openings.filter(f=>f.source===e.target.source&&f.export_name===e.target.export_name).map(f=>f.start_offset)),a=[],c=0;if(pp(n,new Set,(f,g)=>{if(!B.isJSXElement(f))return;let p=f.openingElement,h=p.start;if(typeof h!="number"||e.call_source_range&&(p.loc?.start.line!==e.call_source_range.start_line||p.loc.start.column!==e.call_source_range.start_column))return;let y=LL(p.name);if(!y)return;let x=DL(p.name,r);x&&(e.target.local_name&&e.target.local_name!==y||x.source!==e.target.source||x.export_name!==e.target.export_name||s.has(h)&&a.push({node:p,element:f,local:x,context:g,ordinal:c++}))}),a.length===0)return t([...i,{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let l=a.map(f=>TL(e,f.node,f.element,f.local,f.context,f.ordinal)),u=wL(l,e.target.original_block_id);if(!u)return t([...i,{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected component is rendered more than once and no unique original block identity was provided."}]);let d=[...i,...u.errors];return{complete:d.length===0,entry_file:e.file_path,target:e.target,call:u.call,bindings:d.length===0?u.bindings:[],original_block_id:u.original_block_id,original_order:u.original_order,semantic_props:u.semantic_props,errors:$E(d).sort(fp)}}function SL(e){let t;try{t=mp(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return{invocation:null,errors:[{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}]}}let n=nn({route:e.route,composition:e.composition.templateId===void 0?{routeId:e.composition.routeId}:{routeId:e.composition.routeId,effectiveTemplateId:e.composition.templateId},entryFile:e.file_path,version:e.document_version,source:e.source,ast:t});if(!n.ok)return{invocation:null,errors:n.projection.diagnostics.map(a=>({code:"INVOCATION_PAGE_UNIT_UNSUPPORTED",path:e.file_path,message:a.message}))};let r=n.projection.placementUnitByKey.get(e.placement_unit_key),o=r?.sourceRange;if(!r||!o)return{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit key does not belong to the pinned document version."}]};let i=Mn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Ji({file_path:e.file_path,source:e.source,target:a,call_source_range:{start_line:o.startLine,start_column:o.startColumn}})).filter(a=>a.call!==null);return s.length!==1?{invocation:null,errors:[{code:"INVOCATION_PAGE_UNIT_NOT_FOUND",path:e.file_path,message:"The selected Page Unit does not resolve to exactly one rendered imported component."}]}:{invocation:s[0],errors:s[0].errors}}function vL(e){let t=Ji(e),n=lp({files:e.files,source_closure:e.source_closure,collection:e.collection,trusted_schema:e.trusted_schema,...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),r=[...t.errors],o=[];e.source_closure.complete||r.push({code:"COLLECTION_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"Collection recipe analysis requires a complete selected source closure."});for(let f of n.errors)r.push({code:RL(f.code),path:f.path,message:f.message});t.call&&o.push({fact:"invocation",path:t.call.source_file,reason:"The selected rendered component call supplies the portable invocation bindings.",source_range:t.call.source_range});let i=CL(e.files),s=n.collection_wiring,a=NL(e.file_path,e.target.source,i),c=a?i.get(a):null,l=a&&typeof c=="string"?IL(c,a,e.collection.slug):null;if(!a)r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation target does not resolve to a Snapshot source file."});else if(!l)r.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:a,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{o.push({fact:"pagination",path:a,reason:l.paginate?`listStrict consumes route searchParams with literal pageSize ${l.limit}.`:`listStrict is embedded and uses literal top-N ${l.limit}.`});let f=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(l.paginate&&f.length!==1||!l.paginate&&f.length!==0)&&r.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:l.paginate?"A paginated collection must receive the selected route searchParams exactly once.":"An embedded collection cannot carry a route searchParams binding.",source_range:t.call?.source_range})}s&&a!==s.list_container_file&&r.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation does not resolve to the proven collection list container."});let u=null;if(s&&l&&r.length===0){let f={source_slug:s.source_slug,list_mode:l.paginate?"page":"embedded",paginate:l.paginate,...l.paginate?{page_size:l.limit}:{top_n:l.limit},detail_prefix:s.detail_prefix,schema:s.schema.map(p=>({...p})),list_view:{...s.list_view},detail_view:{...s.detail_view},...s.title?{title:s.title}:{},...s.breadcrumb?{breadcrumb:{...s.breadcrumb}}:{},...s.required_fields?{required_fields:[...s.required_fields]}:{},...s.force_multi_media?{force_multi_media:[...s.force_multi_media]}:{},list_route_required:l.paginate},g=yL.safeParse(f);g.success?(u=g.data,o.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${s.detail_prefix}.`},{fact:"list-view",path:s.list_view.source_path,reason:`The list container renders ${s.list_view.export_name} with ${s.list_view.interface_name}.`},{fact:"detail-view",path:s.detail_view.source_path,reason:`The detail route renders ${s.detail_view.export_name} with ${s.detail_view.interface_name}.`},{fact:"schema",path:s.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):r.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${s.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=$E(r).sort(fp);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:o.sort(PL),related_entries:n}}function IL(e,t,n){let r;try{r=mp(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=kL(r);if(!o)return null;let i=up(o,f=>{if(!B.isCallExpression(f))return!1;let g=f.callee;return B.isMemberExpression(g)&&!g.computed&&B.isIdentifier(g.property,{name:"listStrict"})&&B.isMemberExpression(g.object)&&!g.object.computed&&B.isIdentifier(g.object.property,{name:"collections"})&&B.isIdentifier(g.object.object,{name:"cms"})&&B.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!B.isObjectExpression(s)||s.properties.some(f=>B.isSpreadElement(f)))return null;let a=s.properties.find(f=>B.isObjectProperty(f)&&!f.computed&&pc(f.key)==="pageSize");if(!a||!B.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>B.isObjectProperty(f)&&!f.computed&&pc(f.key)==="page"))return null;let l=s.properties.some(f=>B.isObjectProperty(f)&&!f.computed&&pc(f.key)==="category"),u=up(o,f=>B.isAwaitExpression(f)&&B.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=up(o,f=>{if(!B.isCallExpression(f))return!1;let g=f.callee;return B.isMemberExpression(g)&&!g.computed&&B.isIdentifier(g.property,{name:"categories"})&&B.isMemberExpression(g.object)&&!g.object.computed&&B.isIdentifier(g.object.property,{name:"collections"})&&B.isIdentifier(g.object.object,{name:"cms"})&&B.isStringLiteral(f.arguments[0],{value:n})}).length;return u===1&&(!l||d!==1)||u===0&&(l||d!==0)?null:{paginate:u===1,limit:a.value.value}}function kL(e){let t=e.program.body.find(n=>B.isExportDefaultDeclaration(n));return B.isExportDefaultDeclaration(t)&&(B.isFunctionDeclaration(t.declaration)||B.isFunctionExpression(t.declaration)||B.isArrowFunctionExpression(t.declaration))?t.declaration:null}function up(e,t){let n=[],r=o=>{if(!(o!==e&&hp(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)fc(s)&&r(s);else fc(i)&&r(i)}};return r(e),n}function RL(e){return e==="RELATED_COLLECTION_SCHEMA_UNPROVEN"?"COLLECTION_SCHEMA_UNPROVEN":e==="RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN"?"COLLECTION_LIST_CONTAINER_UNPROVEN":e==="RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN"||e==="RELATED_DETAIL_ENTRY_MISSING"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function CL(e){return e instanceof Map?e:new Map(Object.entries(e))}function NL(e,t,n){let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):_L(`${r}/${t}`);return[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`,`${o}/index.tsx`,`${o}/index.ts`,`${o}/index.jsx`,`${o}/index.js`].find(i=>n.has(i))??null}function _L(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function PL(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function AL(e){let t=new Map;for(let n of e.program.body){if(!B.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(B.isIdentifier(o.local)){if(B.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(B.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(B.isImportSpecifier(o)){let i=B.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{source:r,export_name:i,local_name:o.local.name})}}}return t}function TL(e,t,n,r,o,i){let s=BL(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(h,y)=>{if(u.has(h)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${h}`,message:`Portable invocation contains duplicate prop ${h}.`,source_range:s});return}u.add(h),c.push({propName:h,value:y}),(h==="type"||h==="variant")&&y.kind==="json-literal"&&(l[h]=y.value)};for(let h of t.attributes){if(B.isJSXSpreadAttribute(h)){let v=ur(h.argument);if(!v.ok||!jE(v.value)){a.push({code:"INVOCATION_SPREAD_UNRESOLVED",path:`${e.file_path}:spread`,message:"Portable invocation cannot prove the props supplied by a spread expression.",source_range:s});continue}for(let[_,P]of Object.entries(v.value)){if(!BE(_)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${_}`,message:`Portable invocation cannot encode prop ${_}.`,source_range:s});continue}g(_,dp(P))}continue}let y=ML(h.name);if(!y)continue;let x=h.value,E=x&&B.isJSXExpressionContainer(x)?x.expression:null;if(bL.has(y)){let v=x?dc(x):{ok:!0,value:!0};!v.ok||typeof v.value!="string"?a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original block identity.",source_range:s}):d=v.value;continue}if(EL.has(y)){let v=x?dc(x):{ok:!0,value:!0};!v.ok||typeof v.value!="number"||!Number.isSafeInteger(v.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=v.value;continue}if(!BE(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(xL.has(y)){let v=x?dc(x):{ok:!0,value:!0};v.ok&&typeof v.value=="string"?d=v.value:E&&ME(E,o)&&a.push({code:"INVOCATION_BLOCK_ID_UNRESOLVED",path:`${e.file_path}:${y}`,message:"A target block identity cannot be supplied by route search params.",source_range:s}),g(y,{kind:"target-block-id"});continue}if(E&&ME(E,o)){g(y,{kind:"route-search-params"});continue}let b=x?dc(x):{ok:!0,value:!0};if(!b.ok){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot prove a JSON-literal value for ${y}.`,source_range:s});continue}g(y,dp(b.value))}let p=OL(n);return p.ok?p.value!==null&&g("children",dp(p.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:p.message,source_range:s}),{call:{source_file:e.file_path,component_source:r.source,export_name:r.export_name,local_name:r.local_name,ordinal:i,source_range:s},bindings:c,original_block_id:d??e.target.original_block_id??null,original_order:f,semantic_props:l,errors:a}}function wL(e,t){if(e.length===1)return e[0]??null;if(!t)return null;let n=e.filter(r=>r.original_block_id===t);return n.length===1?n[0]??null:null}function dc(e){return e===null?{ok:!0,value:!0}:B.isStringLiteral(e)?{ok:!0,value:e.value}:B.isJSXExpressionContainer(e)?ur(e.expression):{ok:!1}}function ur(e){if(!e)return{ok:!1};if(B.isStringLiteral(e))return{ok:!0,value:e.value};if(B.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(B.isBooleanLiteral(e))return{ok:!0,value:e.value};if(B.isNullLiteral(e))return{ok:!0,value:null};if(B.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(B.isTSAsExpression(e)||B.isTSTypeAssertion(e)||B.isTSNonNullExpression(e))return ur(e.expression);if(B.isUnaryExpression(e)){let t=ur(e.argument);return!t.ok||e.operator==="+"&&typeof t.value=="number"?t:e.operator==="-"&&typeof t.value=="number"?{ok:!0,value:-t.value}:e.operator==="!"&&typeof t.value=="boolean"?{ok:!0,value:!t.value}:{ok:!1}}if(B.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=ur(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(B.isObjectExpression(e)){let t={};for(let n of e.properties){if(B.isSpreadElement(n)){let i=ur(n.argument);if(!i.ok||!jE(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!B.isObjectProperty(n)||n.computed)return{ok:!1};let r=pc(n.key);if(!r)return{ok:!1};let o=ur(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function OL(e){if(e.children.length===0)return{ok:!0,value:null};let t=[];for(let n of e.children){if(B.isJSXText(n)){n.value&&t.push(n.value);continue}if(B.isJSXExpressionContainer(n)){let r=ur(n.expression);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value);continue}return{ok:!1,message:"Portable invocation cannot move JSX child components as JSON props."}}return t.length===0?{ok:!0,value:null}:{ok:!0,value:t.length===1?t[0]:t}}function pp(e,t,n){let r=hp(e)?new Set([...t,...FL(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)fc(i)&&pp(i,r,n);else fc(o)&&pp(o,r,n)}function FL(e){if(!hp(e))return[];let t=[];for(let n of e.params)Ki(n,t);return t}function Ki(e,t){if(B.isIdentifier(e)){t.push(e.name);return}if(B.isAssignmentPattern(e)){Ki(e.left,t);return}if(B.isObjectPattern(e)){for(let n of e.properties)B.isRestElement(n)?Ki(n.argument,t):B.isObjectProperty(n)&&Ki(n.value,t);return}if(B.isArrayPattern(e))for(let n of e.elements)n&&Ki(n,t)}function ME(e,t){return B.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):B.isMemberExpression(e)&&!e.computed&&B.isIdentifier(e.property)&&e.property.name==="searchParams"&&B.isIdentifier(e.object)&&t.names.has(e.object.name)}function dp(e){return{kind:"json-literal",value:e}}function jE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function BE(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function LL(e){if(B.isJSXIdentifier(e))return e.name;if(!B.isJSXMemberExpression(e))return null;let t=gp(e.object);return t?`${t}.${e.property.name}`:null}function gp(e){if(B.isJSXIdentifier(e))return e.name;if(!B.isJSXMemberExpression(e))return null;let t=gp(e.object);return t?`${t}.${e.property.name}`:null}function DL(e,t){if(B.isJSXIdentifier(e))return t.get(e.name)??null;if(!B.isJSXMemberExpression(e))return null;let n=gp(e.object);if(!n)return null;let r=t.get(n);return!r||r.export_name!=="*"?null:{source:r.source,export_name:e.property.name,local_name:`${n}.${e.property.name}`}}function ML(e){return B.isJSXIdentifier(e)?e.name:B.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function pc(e){return B.isIdentifier(e)?e.name:B.isStringLiteral(e)||B.isNumericLiteral(e)?String(e.value):null}function hp(e){return B.isFunctionDeclaration(e)||B.isFunctionExpression(e)||B.isArrowFunctionExpression(e)}function fc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function BL(e){return{start_offset:e.start??0,end_offset:e.end??e.start??0,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function $E(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function fp(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import yp from"@babel/generator";import{parse as jL}from"@babel/parser";import $L from"@babel/traverse";import*as rt from"@babel/types";var xp=$L,VL=typeof xp=="function"?xp:xp.default,UL=typeof yp=="function"?yp:yp.default,zE="components/site/generated/{{$INSTANCE}}/",HE=new Set([".tsx",".ts",".jsx",".js"]),VE=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),KL=new Set(["data-site-block-order","data-vcp-order"]);function JL(e){let t=[],n=new Map,r=new Map;/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(e.instance_base_name)||t.push({code:"SOURCE_INPUT_INVALID",path:"instance_base_name",message:"The portable instance base name is not safe."});for(let b of e.source_files){let v=$n(b.path);if(!v||n.has(v)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(v,{...b,path:v})}for(let b of e.ownership){let v=$n(b.path);if(!v||r.has(v)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(v,{...b,path:v})}let o=$n(e.entry_file);n.get(o)?r.get(o)?.ownership!=="private"&&t.push({code:"SOURCE_ENTRY_NOT_PRIVATE",path:o,message:"The selected portable source entry must be private source."}):t.push({code:"SOURCE_ENTRY_NOT_FOUND",path:e.entry_file,message:"The selected portable source entry is not present."});for(let b of n.keys())r.has(b)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:b,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(b=>r.get(b)?.ownership==="private").sort((b,v)=>b.localeCompare(v)),a=s.map(b=>({source_path:b,path_template:QL(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=XL(e.source_mapping??[],c,t),u=zL(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let b of s){let v=n.get(b);if(!v)continue;let _=WL(b,v.content,r,c,d,f,t);_!==null&&g.push({path_template:c.get(b),content:_,...v.role?{role:v.role}:{}})}let p=JE(t).sort(XE);if(p.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:p};let h=g.map(b=>{let v=a.find(P=>P.path_template===b.path_template)?.source_path,_=n.get(v)?.content??"";return{source_path:v,path_template:b.path_template,original_byte_size:UE(_),output_byte_size:UE(b.content),original_line_count:KE(_),output_line_count:KE(b.content)}}),y=[...f.values()].map(b=>({...b,normalized:!0})).sort((b,v)=>b.source_path.localeCompare(v.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=HL(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let E=JE(t).sort(XE);return E.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:E}:{complete:!0,entry_path_template:x,files:g.sort((b,v)=>b.path_template.localeCompare(v.path_template)),source_path_mappings:h.sort((b,v)=>b.path_template.localeCompare(v.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(rD),block_metadata:y,errors:[]}}function XL(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=$n(s.generated_path),c=$n(s.source_file),l=a,u=t.get(a);if(!a||a!==s.generated_path||!c||c!==s.source_file||!s.structural_path||r.has(l)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`source_mapping.${i}`,message:"Portable selected-source mappings require unique safe paths and structural identities."});continue}if(r.add(l),!u){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:s.generated_path,message:"A selected-source mapping must resolve to one private normalized entry path."});continue}o.push({...s,path_template:u})}return o.sort((i,s)=>i.path_template.localeCompare(s.path_template)||i.source_file.localeCompare(s.source_file)||i.structural_path.localeCompare(s.structural_path))}function zL(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=$n(a.source_path);if(!/^[a-z][a-z0-9-]{0,127}$/u.test(a.key)||!c||r.has(a.key)||o.has(c)){n.push({code:"SOURCE_REQUIRED_PATH_INVALID",path:`required_source_paths.${s}`,message:"Required portable source paths must use unique safe keys and source identities."});continue}r.add(a.key),o.add(c);let l=t.get(c);if(!l){n.push({code:"SOURCE_REQUIRED_PATH_UNMAPPED",path:a.source_path,message:"A required portable source identity must map to exactly one private package path."});continue}i.push({key:a.key,source_path:c,path_template:l})}return i.sort((s,a)=>s.key.localeCompare(a.key)||s.source_path.localeCompare(a.source_path))}function HL(e,t,n){if(e.adds_dom!==!1)return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.source_file,message:"A managed-root thin entry must not add DOM."}),null;let r=t.get($n(e.component_source));if(!r)return n.push({code:"SOURCE_THIN_ENTRY_TARGET_MISSING",path:e.component_source,message:"The managed-root thin entry target is not private materialized source."}),null;if(!/^(?:default|[A-Za-z_$][A-Za-z0-9_$]*)$/u.test(e.component_export))return n.push({code:"SOURCE_THIN_ENTRY_INVALID",path:e.component_export,message:"The managed-root thin entry export is not a safe export name."}),null;let o=`${zE}__managed-root-entry.tsx`,i=WE(o,r,"./component"),s=e.component_export==="default"?`import Root from ${JSON.stringify(i)};`:`import { ${e.component_export} as Root } from ${JSON.stringify(i)};`;return{path_template:o,role:"managed-root-thin-entry",content:`${s}
|
|
15
15
|
export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
|
|
16
16
|
return <Root {...props} />;
|
|
17
17
|
}
|
|
18
|
-
`}}function
|
|
19
|
-
`).length}function ME(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function BE(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function qL(e,t){return e.source_path.localeCompare(t.source_path)||e.target_path.localeCompare(t.target_path)||e.original_specifier.localeCompare(t.original_specifier)}import{createHash as eD}from"node:crypto";import Xi from"node:path";import yp from"@babel/generator";import{parse as tD}from"@babel/parser";import nD from"@babel/traverse";import*as F from"@babel/types";import{SiteEditSourcePathSchema as rD}from"@vcp-dev/contracts";var xp=nD,YE=typeof xp=="function"?xp:xp.default,oD=typeof yp=="function"?yp:yp.default,XE=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]);function iD(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"?t.entry_file:t.source_file;if(!qE(r))return Tt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!rD.safeParse(t.source_file).success)return Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected root source is outside the allowed Snapshot source paths.");if(t.call_chain.length>1)return Tt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Tt("SOURCE_NOT_PORTABLE",t.source_file,"The selected root has an incomplete invocation binding set.");if(t.strategy==="reuse-entry"){if(t.entry_file!==t.source_file)return Tt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=vp(n,t.source_file);return i===null||!GE(t,i)?Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):Ep({entryFile:r,entryContent:i,files:n,selection:t})}let o=vp(n,t.source_file);if(o===null||!GE(t,o))return Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected source is missing or does not match its pinned hash.");if(t.strategy==="managed-thin-entry"){let i={generated_path:r,source_file:t.source_file,structural_path:t.structural_path};return Ep({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}return n.has(r)?Tt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):sD(t,o,n)}function sD(e,t,n){let r;try{r=tD(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(N){return Tt("SOURCE_PARSE_FAILED",e.source_file,N instanceof Error?N.message:String(N))}let o=aD(r,e);if(o.length!==1)return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(N=>N.isFunction());if(!s||!yD(s.node))return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=mD(a);if(!c.ok)return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let l={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},u=cD(a,e);if(!u.ok)return{complete:!1,errors:[u.error]};if(lD(i,i.node,a,u.value,e,c.translationBinding??null,l),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(N=>F.isVariableDeclaration(N)&&N.declarations.some(A=>F.isIdentifier(A.id,{name:c.translationBinding}))))return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let d=bD(r,"__vcpPortableProps"),f=F.cloneNode(i.node,!0),g=[];for(let N of[...l.imports].sort(bp)){let A=dD(N,e.source_file,e.entry_file,n);if(!A.ok)return{complete:!1,errors:[A.error]};g.push(A.node)}let p=[...l.moduleDeclarations].sort(bp).map(N=>F.cloneNode(N,!0)),h=[...l.functionDeclarations].sort(bp).map(N=>F.cloneNode(N,!0)),y=F.returnStatement(f),x=[...l.props].filter(([N])=>!N.startsWith("@")).map(([N,A])=>F.variableDeclaration("const",[F.variableDeclarator(F.identifier(N),F.memberExpression(F.identifier(d),F.identifier(A)))]));l.propsObjectName&&x.push(F.variableDeclaration("const",[F.variableDeclarator(F.identifier(l.propsObjectName),F.identifier(d))]));let E=F.blockStatement([...x,...h,y]),b=l.props.size?[uD(d)]:[],v=F.functionDeclaration(F.identifier("PortableBlockEntry"),b,E),_=F.program([...g,...p,v,F.exportDefaultDeclaration(F.identifier("PortableBlockEntry"))]);_.directives=r.program.directives.map(N=>F.cloneNode(N,!0));let P=oD(F.file(_),{jsescOption:{minimal:!0}}).code,R={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return Ep({entryFile:e.entry_file,entryContent:P,files:n,selection:e,sourceMapping:R,invocationBindings:xD(e,l.props)})}function aD(e,t){let n=[];return YE(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function cD(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Multiple component parameters are not a proven portable invocation surface.")};let r=new Map,o=n[0];if(!o)return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}};if(F.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!F.isObjectPattern(o))return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!F.isObjectProperty(i)||i.computed||!(F.isIdentifier(i.key)||F.isStringLiteral(i.key))||!(F.isIdentifier(i.value)||F.isAssignmentPattern(i.value)&&F.isIdentifier(i.value.left)))return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=F.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=F.isIdentifier(a)?a.name:F.isAssignmentPattern(a)&&F.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function lD(e,t,n,r,o,i,s){let a=new Set,c=d=>{let f=d.node.name,g=d.scope.getBinding(f);if(!g){XE.has(f)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${f}.`));return}if(!HE(g.path.node,t)){if(r.bindingByLocalName.has(f)&&g.scope===n.scope){let p=r.bindingByLocalName.get(f);WE(o,p)?s.props.set(f,p):s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${p} has no proven invocation binding.`));return}if(r.propsParameter&&g.path.node===r.propsParameter&&d.parentPath?.isMemberExpression()&&d.parentPath.node.object===d.node){let p=d.parentPath.node,h=!p.computed&&F.isIdentifier(p.property)?p.property.name:p.computed&&F.isStringLiteral(p.property)?p.property.value:null;h&&WE(o,h)?(s.propsObjectName=f,s.props.set(`@${f}.${h}`,h)):s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${f}.`));return}a.has(g)||(a.add(g),zE(g,n,o,s,c,l))}},l=(d,f)=>{let g=QE(d);if(!g||/^[a-z]/u.test(g.name))return;let p=f.scope.getBinding(g.name);if(!p){XE.has(g.name)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${g.name} has no proven import or declaration.`));return}a.has(p)||HE(p.path.node,t)||(a.add(p),zE(p,n,o,s,c,l))};(d=>{d.isIdentifier()&&d.isReferencedIdentifier()&&c(d),d.isJSXElement()&&l(d.node.openingElement.name,d),d.traverse({ReferencedIdentifier(f){c(f)},JSXOpeningElement(f){l(f.node.name,f)},CallExpression(f){gD(f,i)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),f.stop()},UpdateExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),f.stop()},NewExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),f.stop()}})})(e)}function zE(e,t,n,r,o,i){let s=e.path;if(hD(s,t)||s.isFunctionDeclaration()&&s.node===t.node){r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}let a=s.isImportDeclaration()?s:s.findParent(u=>u.isImportDeclaration());if(a?.isImportDeclaration()){r.imports.add(a.node);return}let c=s.isVariableDeclarator()?s:s.findParent(u=>u.isVariableDeclarator());if(c?.isVariableDeclarator()){let u=c.parentPath,d=c.get("init");if(!u?.isVariableDeclaration()||u.node.kind!=="const"||!d.node||!fc(d.node)){r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}(u.findParent(p=>p.isFunction())===t?r.functionDeclarations:r.moduleDeclarations).add(F.variableDeclaration("const",[F.cloneNode(c.node,!0)])),d.isIdentifier()&&d.isReferencedIdentifier()&&o(d),d.traverse({ReferencedIdentifier(p){p.isIdentifier()&&o(p)},JSXOpeningElement(p){i(p.node.name,p)}});return}let l=s.isFunctionDeclaration()?s:s.findParent(u=>u.isFunction());if(l?.isFunctionDeclaration()&&Sp(l.node)){(l.findParent(d=>d.isFunction())===t?r.functionDeclarations:r.moduleDeclarations).add(F.cloneNode(l.node,!0)),l.traverse({ReferencedIdentifier(d){d.isIdentifier()&&o(d)},JSXOpeningElement(d){i(d.node.name,d)}});return}r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function uD(e){let t=F.identifier(e);return t.typeAnnotation=F.tsTypeAnnotation(F.tsTypeReference(F.identifier("Record"),F.tsTypeParameterInstantiation([F.tsStringKeyword(),F.tsAnyKeyword()]))),t}function Ep(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=Ui({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>ft(ED(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=vp(t,i.path);if(s===null)return Tt("SOURCE_NOT_PORTABLE",i.path,"A closed dependency is not valid UTF-8 source content.");r.push({path:i.path,content:s})}let o=e.sourceMapping??{generated_path:e.entryFile,source_file:e.selection.source_file,structural_path:e.selection.structural_path};return{complete:!0,entry_file:e.entryFile,source_files:r.sort((i,s)=>i.path.localeCompare(s.path)),source_mapping:[o],invocation_bindings:e.invocationBindings??e.selection.invocation?.bindings??[],selected_root_ref:e.selection.root_ref}}function dD(e,t,n,r){let o=F.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=pD(t,i,r);if(!s)return{ok:!1,error:ft("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=fD(n,s)}return{ok:!0,node:o}}function pD(e,t,n){let r=t.startsWith("@/")?t.slice(2):Xi.posix.normalize(Xi.posix.join(Xi.posix.dirname(e),t));if(!qE(r))return null;let o=/\.[a-z0-9]+$/iu.test(r)?[r]:[".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}${s}`).concat([".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}/index${s}`)),i=[...new Set(o.filter(s=>n.has(s)))];return i.length===1?i[0]:null}function fD(e,t){let n=Xi.posix.relative(Xi.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function mD(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!F.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!F.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(l=>l.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!F.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!F.isIdentifier(c.node.id)){r=!0,o.stop();return}t=c.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function Sp(e){if(!e.body||e.body.body.length!==1)return!1;let t=e.body.body[0];return!F.isReturnStatement(t)||!t.argument?!1:fc(t.argument)}function gD(e,t){let n=e.node.callee;if(F.isImport(n))return!1;if(t&&F.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(s=>F.isStringLiteral(s))){let s=e.scope.getBinding(t),a=s?.path.isVariableDeclarator()?s.path:s?.path.findParent(l=>l.isVariableDeclarator()),c=a?.isVariableDeclarator()?a.node.init:null;return!!(F.isCallExpression(c)&&ZE(c))}if(!F.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);if(!r)return!1;if(r.path.isFunctionDeclaration())return Sp(r.path.node);let o=r.path.isVariableDeclarator()?r.path:r.path.findParent(s=>s.isVariableDeclarator()),i=o?.isVariableDeclarator()?o.node.init:null;return F.isArrowFunctionExpression(i)?F.isBlockStatement(i.body)?i.body.body.length===1&&F.isReturnStatement(i.body.body[0])&&!!i.body.body[0].argument&&fc(i.body.body[0].argument):fc(i.body):F.isFunctionExpression(i)?Sp({...F.functionDeclaration(null,i.params,i.body),async:i.async,generator:i.generator}):!1}function fc(e){let t=!0;return F.traverseFast(e,n=>{(F.isCallExpression(n)&&!ZE(n)||F.isOptionalCallExpression(n)||F.isNewExpression(n)||F.isAwaitExpression(n)||F.isAssignmentExpression(n)||F.isUpdateExpression(n)||F.isYieldExpression(n)||F.isTaggedTemplateExpression(n))&&(t=!1)}),t}function ZE(e){return F.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&F.isStringLiteral(e.arguments[0])}function QE(e){return F.isJSXIdentifier(e)?F.isValidIdentifier(e.name)?F.identifier(e.name):null:F.isJSXMemberExpression(e)?QE(e.object):null}function hD(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>F.isObjectPattern(n)&&n.properties.some(r=>F.isObjectProperty(r)&&F.isIdentifier(r.value,{name:e.node.name}))))}function HE(e,t){return e===t||typeof e.start=="number"&&typeof e.end=="number"&&typeof t.start=="number"&&typeof t.end=="number"&&e.start>=t.start&&e.end<=t.end}function yD(e){return F.isFunction(e)}function WE(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function xD(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function bD(e,t){let n=new Set;YE(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function bp(e,t){return(e.start??0)-(t.start??0)}function vp(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function GE(e,t){let n=eD("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function qE(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function ED(e){return e==="SOURCE_PARSE_FAILED"?"SOURCE_PARSE_FAILED":e==="SOURCE_ENTRY_UNRESOLVED"?"SOURCE_ENTRY_NOT_FOUND":e==="SOURCE_FILE_UNRESOLVED"||e==="SOURCE_ASSET_UNRESOLVED"?"SOURCE_IMPORT_UNRESOLVED":"SOURCE_NOT_PORTABLE"}function Tt(e,t,n){return{complete:!1,errors:[ft(e,t,n)]}}function ft(e,t,n){return{code:e,path:t,message:n}}import SD from"node:path";import{GeneratedSiteCapabilitiesSchema as vD,FormDefinitionIdSchema as ID,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as kD,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as RD,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as CD,SiteEditMaterializationExportSchema as ND,SiteEditMaterializationSchema as _D}from"@vcp-dev/contracts";var mc="components/site/generated",PD=/^[a-z][a-z0-9._-]{0,127}$/,gc=/^[a-z][a-z0-9._-]{0,127}$/,AD=new Set(["collection-detail-view","i18n-companion","client-importer"]);function TD(e){if(!Io(e))return Me("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!PD.test(e.instanceId))return Me("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=vD.safeParse(e.trustedHostPolicy);if(!t.success)return Me("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return Me("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!LD(e.existingSources))return Me("PORTABLE_INPUT_INVALID","Portable materialization requires a read-only existing source index.","existingSources");if(e.trustedManagedImports!==void 0&&(!Array.isArray(e.trustedManagedImports)||e.trustedManagedImports.some(p=>{if(typeof p!="string")return!0;let h=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(p)?.[1];return!ID.safeParse(h).success||!Ip(e.existingSources,`${p.slice(2)}.tsx`)})))return Me("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=wD(e.resolved);if(!n.ok)return n;let r=_D.safeParse(n.materialization);if(!r.success)return Me("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=OD(n.relatedEntries,r.data);if(!o.ok)return o;let i=FD(e.entryConsumers,o.data,r.data);if(!i.ok)return i;let s=SD.posix.join(mc,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let h=Qo({pathTemplate:p.pathTemplate,generatedRoot:mc,instanceName:e.instanceId,instanceRoot:s});if(!h.ok)return kp(h.error);if(c.has(h.data))return Me("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${h.data}`,h.data);c.add(h.data),a.push({kind:"create-only",path:h.data,content:p.content,...p.role?{role:p.role}:{},sourcePathTemplate:p.pathTemplate})}if(a.length>RD)return Me("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let p of a){let h=Buffer.byteLength(p.content,"utf8");if(h>kD)return Me("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=h}if(l>CD)return Me("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=eS(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let p of o.data){let h=eS(p.pathTemplate,p.export,c,e.instanceId,s);if(!h.ok)return h;d.push({...p,path:h.data.path}),f.push(h.data)}if(Ip(e.existingSources,s)||a.some(p=>Ip(e.existingSources,p.path)))return Me("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=Hl({files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((p,h)=>p.path.localeCompare(h.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:mc,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,h)=>p.path.localeCompare(h.path)),entryConsumers:i.data,files:a}}):kp(g.error)}function wD(e){if(!Io(e))return Me("PORTABLE_INPUT_INVALID","Resolved portable materialization must be an object.","resolved");let t=e.relatedEntries,n=e.portable;if(t!==void 0&&!Array.isArray(t))return Me("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!Io(n))return Me("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return Me("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?Me("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function OD(e,t){let n=new Set(t.files.map(a=>a.pathTemplate)),r=new Set((t.dataRequirements??[]).map(a=>a.key)),o=new Set,i=new Set,s=[];for(let[a,c]of e.entries()){if(!Io(c))return Me("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let l=c.key,u=c.requirementKey,d=c.pathTemplate,f=c.purpose,g=ND.safeParse(c.export);if(typeof l!="string"||!gc.test(l)||typeof u!="string"||!gc.test(u)||typeof d!="string"||typeof f!="string"||!AD.has(f)||!g.success)return Me("PORTABLE_INPUT_INVALID","Every related entry must have a strict key, purpose, path and export.",`resolved.relatedEntries[${a}]`);if(o.has(l)||i.has(d))return Me("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return Me("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return Me("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return Me("PORTABLE_REQUIREMENT_UNRESOLVED","Every related entry must reference a resolved managed requirement.",u);o.add(l),i.add(d),s.push({key:l,pathTemplate:d,export:g.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function FD(e,t,n){let r=new Map(t.map(c=>[c.key,c])),o=new Set((n.dataRequirements??[]).map(c=>c.key)),i=new Set,s=[];for(let[c,l]of e.entries()){if(!Io(l))return Me("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${c}]`);let u=l.entry_key,d=l.requirement_key,f=l.kind,g=l.consumer_path;if(typeof u!="string"||!gc.test(u)||typeof d!="string"||!gc.test(d)||typeof g!="string"||!g.trim()||f!=="route"&&f!=="capability")return Me("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${c}]`);let p=r.get(u);if(!p)return Me("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",u);if(i.has(u))return Me("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",u);if(p.requirementKey!==d)return Me("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",u);if(!o.has(d))return Me("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",d);i.add(u),s.push({entry_key:u,requirement_key:d,kind:f,consumer_path:g})}let a=t.find(c=>!i.has(c.key));return a?Me("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",a.key):{ok:!0,data:s.sort((c,l)=>c.entry_key.localeCompare(l.entry_key)||c.consumer_path.localeCompare(l.consumer_path))}}function eS(e,t,n,r,o){let i=Qo({pathTemplate:e,generatedRoot:mc,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:Me("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):kp(i.error)}function Ip(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function LD(e){return Array.isArray(e)||e instanceof Map||Io(e)}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kp(e){return{ok:!1,error:e}}function Me(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import tS from"node:path";import{SiteEditSourcePathSchema as Rp}from"@vcp-dev/contracts";function DD(e){let t=e.resolvedBoundary;if(!e.routeId.trim()||!Number.isSafeInteger(e.documentVersion)||e.documentVersion<0||e.binding.documentVersion!==e.documentVersion||e.binding.composition.routeId!==e.routeId||t.ownerFile!==e.binding.ownerFile||t.sourceHash!==e.binding.ownerSourceHash||(t.placement==="before"?t.afterBlockKey:t.beforeBlockKey)!==e.binding.blockKey||!Rp.safeParse(e.entryFile).success||!Rp.safeParse(t.ownerFile).success||t.anchorLocator.file!==t.ownerFile||t.parentLocator!==null&&t.parentLocator.file!==t.ownerFile||!/^sha256:[a-f0-9]{64}$/u.test(t.sourceHash))return st("INVALID_TARGET","The resolved Portable boundary is not a valid source-owner boundary.");let n=e.files.get(t.ownerFile);if(n===void 0)return st("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ve(n)!==t.sourceHash)return st("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=$D(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?st("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):MD(e,n):jD(e,n))}function MD(e,t){let n=Ke(e.entryFile,t);if(!n.ok)return st("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=nn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return st("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=BD(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return st("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=su({routeId:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,documentVersion:e.documentVersion,source:t,anchor:{componentName:o,relation:e.resolvedBoundary.placement,sourceRange:e.resolvedBoundary.anchorLocator.sourceRange},component:e.component,invocation:e.invocation});if(!i.ok)return st(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return st("INVALID_TARGET","The route planner did not preserve the resolved owner boundary.",e.resolvedBoundary.ownerFile);let s=i.plan.rewriteStep,a=s.kind==="insert-child"&&s.anchorLocator?.strategy==="source-range"?s.anchorLocator.sourceRange:null;return s.kind==="insert-child"&&(!a||!Np(a,e.resolvedBoundary.anchorLocator.sourceRange))?st("INVALID_TARGET","The route planner selected a different anchor than the resolved boundary.",e.entryFile):{ok:!0,patches:[{path:i.patch.path,source:i.patch.source,baseContentHash:i.patch.expectedSourceHash}]}}function BD(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Np(o.anchorSourceRange,t)?[]:nS(o.members).filter(i=>i.sourceRange!==null&&Np(i.sourceRange,t)));return r.length===1?r[0].label:null}function nS(e){return e.flatMap(t=>[t,...nS(t.children)])}function jD(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return st("UNSUPPORTED_OPERATION","A shared owner root without a JSX parent has no safe sibling boundary.",n.ownerFile);if(r.kind!=="jsx-element"&&r.kind!=="jsx-fragment")return st("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return st(o.error.code,o.error.message,n.ownerFile);let i=VD(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Kt({source:t,locator:Cp(r),anchorLocator:Cp(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return st("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=Jt({source:s.source,moduleSpecifier:UD(n.ownerFile,e.component.source),imports:[e.component.exportName==="default"?{kind:"default",local:e.component.localName}:{kind:"named",imported:e.component.exportName,...e.component.localName===e.component.exportName?{}:{local:e.component.localName}}]});return a.ok?{ok:!0,patches:[{path:n.ownerFile,source:a.source,baseContentHash:n.sourceHash}]}:st("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function $D(e){return!Rp.safeParse(e.component.source).success||e.component.source===e.resolvedBoundary.ownerFile||e.component.exportName!=="default"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e.component.exportName)?st("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function VD(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Ke(t,e);if(!o.ok)return st("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=xe(o.module.ast,Cp(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?st("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Cp(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function UD(e,t){let n=tS.posix.relative(tS.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Np(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function st(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{SiteEditPageBlockTargetSchema as KD,SiteEditSourcePathSchema as _p,SiteIdSchema as JD,SnapshotIdSchema as XD}from"@vcp-dev/contracts";async function zD(e){if(!JD.safeParse(e.site_id).success||!XD.safeParse(e.base_snapshot_id).success||!KD.safeParse(e.target).success)return kn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!GD(e.composition,e.target.composition))return kn("INVALID_TARGET","The target selector does not match the requested composition.");let t=new Map,n=new Map;for(let[u,d]of e.files){if(!WD(u))return kn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:HD(u,d);f!==null&&(n.set(u,f),_p.safeParse(u).success&&t.set(u,f))}let r;try{r=pa({files:n})}catch{return kn("INVALID_TARGET","Snapshot composition inventory is invalid.")}let o=r.find(u=>u.context.routeId===e.composition.routeId&&u.context.effectiveTemplateId===e.composition.templateId);if(!o)return kn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return kn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Bs(o.entryFile,i,async u=>{if(!_p.safeParse(u).success)throw new Error("Unsafe imported source path");let d=t.get(u);if(d===void 0)throw new Error("Source file unavailable");return d},async u=>_p.safeParse(u).success&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return kn("INVALID_TARGET","The selected snapshot source graph is incomplete.");s.graph.routeId=e.composition.routeId,s.graph.composition={routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}};let a=nn({route:e.composition.routeId,composition:s.graph.composition,entryFile:o.entryFile,version:e.document_version,source:i,ast:s.entryModule.ast});if(!a.ok)return kn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=ia({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return kn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=ai({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:c.roots});return l.diagnostics.length>0?{...kn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...ro(l,e.target,e.document_version,e.selection_ref),index:l}}function HD(e,t){if(!/\.(?:[cm]?[jt]sx?)$/i.test(e))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function WD(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function GD(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function kn(e,t){return{ok:!1,code:e,message:t}}import{createHash as YD}from"node:crypto";import Pp from"node:path";import Ap from"@babel/traverse";import*as at from"@babel/types";import{GeneratedSiteCapabilitiesSchema as ZD,SiteEditSourcePathSchema as QD}from"@vcp-dev/contracts";var qD=typeof Ap=="function"?Ap:Ap.default;function eM(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!ZD.safeParse(e.hostCapabilities).success)return Zt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!zi(t.descriptor.source.file)||!zi(t.ownerFile))return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=hc(n,t.descriptor.source.file),o=hc(n,t.ownerFile);if(r===null||o===null)return Zt("INVOCATION_TARGET_NOT_RENDERED",r===null?t.descriptor.source.file:t.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(ve(r)!==t.descriptor.source.contentHash||ve(r)!==t.sourceHash||ve(o)!==t.ownerSourceHash)return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=Ke(t.descriptor.source.file,r);if(!i.ok)return Zt("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=rS(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return Zt("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=oS(a.node);if(!c)return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The selected JSX element has no complete source range.");let l=[],u=t.root.callChain;for(let[p,h]of u.entries()){let y=hc(n,h.sourceFile);if(y===null||!zi(h.sourceFile))return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let x=Ke(h.sourceFile,y);if(!x.ok)return Zt("INVOCATION_PARSE_FAILED",h.sourceFile,x.diagnostic.message);let E=rS(x.module.ast,h.callLocator.sourceRange);if(E.length!==1)return Zt("INVOCATION_TARGET_AMBIGUOUS",h.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let b=nM(x.module.ast,E[0].node.openingElement.name,h.component,h.exportName);if(!b)return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"The statically proven component call no longer resolves through one exact import.");let v=u[p+1]?.sourceFile??t.descriptor.source.file,_=oM(h.sourceFile,b.source,n);if(!_||_!==v)return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let P=Ji({file_path:h.sourceFile,source:y,target:{source:b.source,export_name:b.exportName,local_name:b.localName},call_source_range:{start_line:h.callLocator.sourceRange.startLine,start_column:h.callLocator.sourceRange.startColumn}});if(!P.call||!P.complete)return{complete:!1,errors:P.errors.length>0?P.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:h.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};l.push({call:P.call,invocation:P,importTarget:b,importedFile:_})}let d={kind:"page-block",composition:sM(t.composition),blockKey:t.blockKey},f=tM(t,a,l,n,e.hostCapabilities);if(!f.ok)return{complete:!1,errors:[f.error]};let g=l[0]?.invocation??null;return{complete:!0,selection:{target:d,root_ref:t.root.rootRef,source_file:t.descriptor.source.file,structural_path:t.descriptor.source.structuralPath,content_hash:t.descriptor.source.contentHash,source_range:c,owner:t.descriptor.owner,call_chain:l.map(({call:p})=>p),strategy:f.strategy,entry_file:f.entryFile,entry_export:f.entryExport,invocation:g}}}function tM(e,t,n,r,o){let i=n.at(-1);if(i){let l=Ke(i.importedFile,hc(r,i.importedFile)??"");if(!l.ok)return{ok:!1,error:{code:"INVOCATION_PARSE_FAILED",path:i.importedFile,message:l.diagnostic.message}};let u=Nr({module:l.module,exportName:i.importTarget.exportName}),d=u.ok&&u.roots.length===1&&rM(u.roots[0].node,e.rootLocator.sourceRange),f=aM(e.ownerFile);if(n.length===1&&d&&f)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&d)return{ok:!0,strategy:"reuse-entry",entryFile:i.importedFile,entryExport:i.importTarget.exportName==="default"?{kind:"default"}:{kind:"named",name:i.importTarget.exportName}}}if(!oS(t.node))return{ok:!1,error:{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.descriptor.source.file,message:"Cannot derive a portable entry identity without an exact root range."}};let c=`components/site/portable/${YD("sha256").update(JSON.stringify([e.composition,e.blockKey,e.descriptor.source.file,e.descriptor.source.structuralPath,e.descriptor.source.contentHash,o?.host_contract_digest??null])).digest("hex").slice(0,24)}/page.tsx`;return!zi(c)||r.has(c)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:c,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:c,entryExport:{kind:"default"}}}function nM(e,t,n,r){let o=Tp(t);if(!o||o!==n)return null;let i=at.isJSXMemberExpression(t)?Tp(t.object):at.isJSXNamespacedName(t)?t.namespace.name:o,s=at.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(at.isImportDeclaration(a))for(let c of a.specifiers){if(at.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(at.isImportSpecifier(c)&&c.local.name===i){let l=iM(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(at.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function rS(e,t){let n=[];return qD(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.startLine&&o.start.column===t.startColumn&&o.end.line===t.endLine&&o.end.column===t.endColumn&&n.push(r)}}),n}function oS(e){let t=e.loc;return typeof e.start!="number"||typeof e.end!="number"||!t?null:{start_offset:e.start,end_offset:e.end,start_line:t.start.line,start_column:t.start.column,end_line:t.end.line,end_column:t.end.column}}function rM(e,t){let n=e.loc;return!!(n&&n.start.line===t.startLine&&n.start.column===t.startColumn&&n.end.line===t.endLine&&n.end.column===t.endColumn)}function hc(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function oM(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Pp.posix.normalize(Pp.posix.join(Pp.posix.dirname(e),t)):null;return!r||r===".."||r.startsWith("../")||r.startsWith("/")?null:(/\.(?:[cm]?[jt]sx?)$/u.test(r)?[r]:[".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}/index${i}`))).find(i=>zi(i)&&n.has(i))??null}function Tp(e){if(at.isJSXIdentifier(e))return e.name;if(at.isJSXMemberExpression(e)){let t=Tp(e.object);return t?`${t}.${e.property.name}`:null}return null}function iM(e){return at.isIdentifier(e)?e.name:e.value}function sM(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function zi(e){return QD.safeParse(e).success}function aM(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function Zt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import{createHash as cM}from"node:crypto";import lM from"@babel/traverse";import*as we from"@babel/types";var wp=lM,uM=typeof wp=="function"?wp:wp.default,dM=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),ko=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),pM=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,fM=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function mM(e){let t=Ke(e.file_path,e.source);if(!t.ok)return{complete:!1,references:[],errors:[{code:"MEDIA_SOURCE_PARSE_FAILED",file_path:e.file_path,message:t.diagnostic.message}]};let n=[],r=[],o=new Set,i=c=>{let l=sS(c.node),u=SM(e.source,l),d=`${l.start_offset}:${l.end_offset}:${c.kind}:${c.value??"<unknown>"}`;o.has(d)||(o.add(d),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:u,asset_key:c.assetKey??null,source_range:l,content_digest:vM(u),complete:c.complete}),c.complete||r.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:l}))},s=(c,l)=>{if(!l){i({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let u=e.media_manifest?.[l];if(u===void 0){let d=sS(c);r.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${l} is not available in the supplied snapshot.`,source_range:d})}i({node:c,kind:"manifest",source:"media-manifest",value:u??null,assetKey:l,complete:u!==void 0})};uM(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;gM(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=aS(c.node.name),u=fM.test(l);for(let d of c.node.attributes){if(we.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=yM(d);if(!f||!hM(f,u))continue;let g=dr(d.value);i({node:d.value??d,kind:iS(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=bc(c.node.key);if(!l||!ko.has(l)&&!(EM(c)&&cS(l))||ko.has(l)&&yc(c.node.value)&&xc(c.node.value))return;let u=dr(c.node.value);i({node:c.node.value,kind:iS(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(bM(c))for(let l of c.node.elements){if(!l||yc(l)&&xc(l))continue;let u=dr(l);(u.value!==null||!u.complete)&&i({node:l,kind:"array-item",source:"array-item",value:u.value,complete:u.complete})}},CallExpression(c){let l=c.node.callee;if(!we.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!we.isExpression(u)){s(c.node,null);return}let d=dr(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!xM(c.node.object))return;let l=c.node.computed?dr(c.node.property):we.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};s(c.node,l.complete?l.value:null)}});let a=IM(r).sort(kM);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function gM(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&dM.has(n)}function hM(e,t){return e!=="src"||t?ko.has(e):!1}function iS(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function yM(e){return we.isJSXIdentifier(e.name)?e.name.name.toLowerCase():we.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function aS(e){return we.isJSXIdentifier(e)?e.name:we.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${aS(e.object)}.${e.property.name}`}function bc(e){return we.isIdentifier(e)?e.name.toLowerCase():we.isStringLiteral(e)?e.value.toLowerCase():null}function xM(e){return we.isIdentifier(e,{name:"mediaAssets"})}function bM(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=bc(t.node.key);return n!==null&&ko.has(n)}return t?.isVariableDeclarator()&&we.isIdentifier(t.node.id)?pM.test(t.node.id.name):!1}function EM(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=bc(n.node.key);return r!==null&&ko.has(r)}function cS(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function yc(e){return we.isObjectExpression(e)||we.isArrayExpression(e)}function xc(e){if(we.isArrayExpression(e))return e.elements.some(n=>n!==null&&(yc(n)?xc(n):!0));let t=!1;for(let n of e.properties){if(!we.isObjectProperty(n))return!1;let r=bc(n.key);if(r!==null&&(ko.has(r)||cS(r))){t=!0;continue}yc(n.value)&&xc(n.value)&&(t=!0)}return t}function dr(e){return e?we.isStringLiteral(e)?{value:e.value,complete:!0}:we.isJSXExpressionContainer(e)?dr(e.expression):we.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:we.isTSAsExpression(e)||we.isTSTypeAssertion(e)||we.isParenthesizedExpression(e)?dr(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function sS(e){let t=e.start??0,n=e.end??t;return{start_offset:t,end_offset:n,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function SM(e,t){return e.slice(t.start_offset,t.end_offset)}function vM(e){return`sha256:${cM("sha256").update(e).digest("hex")}`}function IM(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.file_path}:${n.source_range?.start_offset??-1}`;return t.has(r)?!1:(t.add(r),!0)})}function kM(e,t){return e.file_path.localeCompare(t.file_path)||(e.source_range?.start_offset??0)-(t.source_range?.start_offset??0)||e.code.localeCompare(t.code)}export{ge as FileHistoryStoreError,li as PageTemplateManagedSourceError,ic as PreviewFileSystemSiteEditEngineRuntime,tg as SITE_EDIT_RAW_COLOR_LITERAL_RE,rc as SnapshotSiteEditEngineRuntime,xL as analyzePortableCollectionInvocation,Ji as analyzePortableInvocation,ap as analyzePortableRelatedEntries,Kl as auditGeneratedCode,AF as auditPortableDependencies,ai as buildPageBlockIndex,qr as buildPortableInvocation,TD as buildPortableMaterializationPlan,Ui as buildPortableSourceClosure,Po as checkComponentI18nHostCompatibility,sc as classifyPortableDependencyOwnership,yh as computeManagedPageTemplatePaths,IF as createPreviewSiteEditEngineRuntime,bF as createSiteEditEngineRuntime,mh as decodePageTemplateKey,GF as discoverPortableCollectionSourceRelation,Ru as encodePageTemplateId,iD as extractPortableBlockEntry,ZS as instrumentSiteEditRuntimeAttributes,xh as isManagedPageTemplateSourcePath,kN as normalizePortableBlockMetadata,$L as normalizePortableSource,Pm as openFileHistoryStore,LS as parseSourceModule,DD as planPortableBlockPatch,su as planPortableRouteCompositionPatch,ni as planRouteCompositionRewrite,DS as resolveImportBase,uP as resolveManagedPageTemplateComposition,aa as resolvePageBlockBoundary,zD as resolvePageBlockFromSnapshot,ro as resolvePageBlockTarget,nn as resolvePageCompositionProjection,eM as resolvePortableBlockSelection,RF as resolvePortableDependencyOwnership,BF as resolvePortableSourcePath,da as scanManagedPageTemplateCandidates,mM as scanPortableMediaReferences,pa as scanSiteEditCompositionsFromFiles,Zo as scanSiteEditThemeStyleViolations,yL as selectPortablePageUnitInvocation};
|
|
18
|
+
`}}function WL(e,t,n,r,o,i,s){if(!nD(e))return t;let a;try{a=jL(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch(l){return s.push({code:"SOURCE_PARSE_FAILED",path:e,message:l instanceof Error?l.message:String(l)}),null}let c=l=>{let u=l.value,d=GL(e,u,n.keys());if(d.status==="external")return;if(d.status==="unresolved"){s.push({code:"SOURCE_IMPORT_UNRESOLVED",path:e,specifier:u,message:`The local import ${u} cannot be resolved.`});return}if(d.status==="ambiguous"){s.push({code:"SOURCE_IMPORT_AMBIGUOUS",path:e,specifier:u,message:`The local import ${u} resolves to multiple files.`});return}let f=n.get(d.path);if(!f){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The local import target ${d.path} has no ownership decision.`});return}if(f.ownership==="private"){let h=r.get(d.path);if(!h){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=WE(r.get(e),h,u);return}if(f.ownership!=="platform-managed"&&f.ownership!=="host-public"){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The import target ${d.path} is not portable source.`});return}let g=YL(d.path,u);l.value=g;let p=f.requirement_key??"host-public";if(!/^[a-z][a-z0-9._-]{0,127}$/u.test(p)){s.push({code:"SOURCE_MANAGED_REBIND_INVALID",path:e,specifier:u,message:"Managed import rebinding requires a safe requirement key."});return}o.push({source_path:e,original_specifier:u,target_path:d.path,rebound_specifier:g,requirement_key:p})};return VL(a,{ImportDeclaration(l){c(l.node.source)},ExportNamedDeclaration(l){l.node.source&&c(l.node.source)},ExportAllDeclaration(l){c(l.node.source)},CallExpression(l){let u=l.node.callee,d=l.node.arguments[0];(rt.isImport(u)||rt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&rt.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=qL(l.node.name);if(!u||!VE.has(u)&&!KL.has(u))return;let d=l.parentPath.parentPath?.node,f=typeof d?.start=="number"?d.start:l.node.start??0,g=`${e}:${f}`,p=i.get(g)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};VE.has(u)?(p.original_block_attribute=u,p.original_block_id=eD(l.node.value)):p.original_order=tD(l.node.value),i.set(g,p),l.remove()}}),UL(a,{jsescOption:{minimal:!0}}).code}function GL(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):$n(`${ZE(e)}/${t}`),o=[r,`${r}.tsx`,`${r}.ts`,`${r}.jsx`,`${r}.js`,`${r}.json`,`${r}.css`,`${r}/index.tsx`,`${r}/index.ts`,`${r}/index.jsx`,`${r}/index.js`,`${r}/index.json`],i=new Set(n),s=[...new Set(o.filter(a=>i.has(a)))];return s.length===0?t.startsWith(".")?{status:"unresolved"}:{status:"external"}:s.length>1&&!i.has(r)?{status:"ambiguous"}:{status:"resolved",path:s[0]}}function WE(e,t,n){let r=ZE(e),o=ZL(r,t),i=o.startsWith(".")?o:`./${o}`;return GE(n)?i:YE(i)}function YL(e,t){let n=`@/${e}`;return GE(t)?n:YE(n)}function ZL(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);for(;n.length>0&&n[0]===r[0];)n.shift(),r.shift();return`${"../".repeat(n.length)}${r.join("/")}`||"."}function QL(e){let t=$n(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${zE}${r}`}function qL(e){return rt.isJSXIdentifier(e)?e.name:rt.isJSXNamespacedName(e)&&rt.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function eD(e){return e?rt.isStringLiteral(e)?e.value:rt.isJSXExpressionContainer(e)&&rt.isStringLiteral(e.expression)?e.expression.value:null:null}function tD(e){if(!e)return null;if(rt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return rt.isJSXExpressionContainer(e)&&rt.isNumericLiteral(e.expression)?e.expression.value:null}function nD(e){return[...HE].some(t=>e.endsWith(t))}function GE(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function YE(e){for(let t of HE)if(e.endsWith(t))return e.slice(0,-t.length);return e}function $n(e){let t=[];for(let n of e.replace(/\\/gu,"/").split("/"))if(!(!n||n===".")){if(n===".."){if(t.length===0)return"";t.pop();continue}t.push(n)}return t.join("/")}function ZE(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function UE(e){return new TextEncoder().encode(e).byteLength}function KE(e){return e.length===0?0:e.split(`
|
|
19
|
+
`).length}function JE(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function XE(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function rD(e,t){return e.source_path.localeCompare(t.source_path)||e.target_path.localeCompare(t.target_path)||e.original_specifier.localeCompare(t.original_specifier)}import{createHash as oD}from"node:crypto";import Xi from"node:path";import bp from"@babel/generator";import{parse as iD}from"@babel/parser";import sD from"@babel/traverse";import*as F from"@babel/types";import{SiteEditSourcePathSchema as aD}from"@vcp-dev/contracts";var Ep=sD,rS=typeof Ep=="function"?Ep:Ep.default,cD=typeof bp=="function"?bp:bp.default,QE=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]);function lD(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"?t.entry_file:t.source_file;if(!sS(r))return Tt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!aD.safeParse(t.source_file).success)return Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected root source is outside the allowed Snapshot source paths.");if(t.call_chain.length>1)return Tt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Tt("SOURCE_NOT_PORTABLE",t.source_file,"The selected root has an incomplete invocation binding set.");if(t.strategy==="reuse-entry"){if(t.entry_file!==t.source_file)return Tt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=kp(n,t.source_file);return i===null||!nS(t,i)?Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):vp({entryFile:r,entryContent:i,files:n,selection:t})}let o=kp(n,t.source_file);if(o===null||!nS(t,o))return Tt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The selected source is missing or does not match its pinned hash.");if(t.strategy==="managed-thin-entry"){let i={generated_path:r,source_file:t.source_file,structural_path:t.structural_path};return vp({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}return n.has(r)?Tt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):uD(t,o,n)}function uD(e,t,n){let r;try{r=iD(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(N){return Tt("SOURCE_PARSE_FAILED",e.source_file,N instanceof Error?N.message:String(N))}let o=dD(r,e);if(o.length!==1)return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(N=>N.isFunction());if(!s||!SD(s.node))return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=xD(a);if(!c.ok)return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component has hook calls whose order cannot be proven for an isolated root.");let l={imports:new Set,moduleDeclarations:new Set,functionDeclarations:new Set,props:new Map,propsObjectName:null,errors:[]},u=pD(a,e);if(!u.ok)return{complete:!1,errors:[u.error]};if(fD(i,i.node,a,u.value,e,c.translationBinding??null,l),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(N=>F.isVariableDeclaration(N)&&N.declarations.some(A=>F.isIdentifier(A.id,{name:c.translationBinding}))))return Tt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let d=ID(r,"__vcpPortableProps"),f=F.cloneNode(i.node,!0),g=[];for(let N of[...l.imports].sort(Sp)){let A=gD(N,e.source_file,e.entry_file,n);if(!A.ok)return{complete:!1,errors:[A.error]};g.push(A.node)}let p=[...l.moduleDeclarations].sort(Sp).map(N=>F.cloneNode(N,!0)),h=[...l.functionDeclarations].sort(Sp).map(N=>F.cloneNode(N,!0)),y=F.returnStatement(f),x=[...l.props].filter(([N])=>!N.startsWith("@")).map(([N,A])=>F.variableDeclaration("const",[F.variableDeclarator(F.identifier(N),F.memberExpression(F.identifier(d),F.identifier(A)))]));l.propsObjectName&&x.push(F.variableDeclaration("const",[F.variableDeclarator(F.identifier(l.propsObjectName),F.identifier(d))]));let E=F.blockStatement([...x,...h,y]),b=l.props.size?[mD(d)]:[],v=F.functionDeclaration(F.identifier("PortableBlockEntry"),b,E),_=F.program([...g,...p,v,F.exportDefaultDeclaration(F.identifier("PortableBlockEntry"))]);_.directives=r.program.directives.map(N=>F.cloneNode(N,!0));let P=cD(F.file(_),{jsescOption:{minimal:!0}}).code,R={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return vp({entryFile:e.entry_file,entryContent:P,files:n,selection:e,sourceMapping:R,invocationBindings:vD(e,l.props)})}function dD(e,t){let n=[];return rS(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function pD(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Multiple component parameters are not a proven portable invocation surface.")};let r=new Map,o=n[0];if(!o)return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}};if(F.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!F.isObjectPattern(o))return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!F.isObjectProperty(i)||i.computed||!(F.isIdentifier(i.key)||F.isStringLiteral(i.key))||!(F.isIdentifier(i.value)||F.isAssignmentPattern(i.value)&&F.isIdentifier(i.value.left)))return{ok:!1,error:ft("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=F.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=F.isIdentifier(a)?a.name:F.isAssignmentPattern(a)&&F.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function fD(e,t,n,r,o,i,s){let a=new Set,c=d=>{let f=d.node.name,g=d.scope.getBinding(f);if(!g){QE.has(f)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${f}.`));return}if(!eS(g.path.node,t)){if(r.bindingByLocalName.has(f)&&g.scope===n.scope){let p=r.bindingByLocalName.get(f);tS(o,p)?s.props.set(f,p):s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${p} has no proven invocation binding.`));return}if(r.propsParameter&&g.path.node===r.propsParameter&&d.parentPath?.isMemberExpression()&&d.parentPath.node.object===d.node){let p=d.parentPath.node,h=!p.computed&&F.isIdentifier(p.property)?p.property.name:p.computed&&F.isStringLiteral(p.property)?p.property.value:null;h&&tS(o,h)?(s.propsObjectName=f,s.props.set(`@${f}.${h}`,h)):s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${f}.`));return}a.has(g)||(a.add(g),qE(g,n,o,s,c,l))}},l=(d,f)=>{let g=iS(d);if(!g||/^[a-z]/u.test(g.name))return;let p=f.scope.getBinding(g.name);if(!p){QE.has(g.name)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${g.name} has no proven import or declaration.`));return}a.has(p)||eS(p.path.node,t)||(a.add(p),qE(p,n,o,s,c,l))};(d=>{d.isIdentifier()&&d.isReferencedIdentifier()&&c(d),d.isJSXElement()&&l(d.node.openingElement.name,d),d.traverse({ReferencedIdentifier(f){c(f)},JSXOpeningElement(f){l(f.node.name,f)},CallExpression(f){bD(f,i)||s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),f.stop()},UpdateExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),f.stop()},NewExpression(f){s.errors.push(ft("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),f.stop()}})})(e)}function qE(e,t,n,r,o,i){let s=e.path;if(ED(s,t)||s.isFunctionDeclaration()&&s.node===t.node){r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}let a=s.isImportDeclaration()?s:s.findParent(u=>u.isImportDeclaration());if(a?.isImportDeclaration()){r.imports.add(a.node);return}let c=s.isVariableDeclarator()?s:s.findParent(u=>u.isVariableDeclarator());if(c?.isVariableDeclarator()){let u=c.parentPath,d=c.get("init");if(!u?.isVariableDeclaration()||u.node.kind!=="const"||!d.node||!mc(d.node)){r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}(u.findParent(p=>p.isFunction())===t?r.functionDeclarations:r.moduleDeclarations).add(F.variableDeclaration("const",[F.cloneNode(c.node,!0)])),d.isIdentifier()&&d.isReferencedIdentifier()&&o(d),d.traverse({ReferencedIdentifier(p){p.isIdentifier()&&o(p)},JSXOpeningElement(p){i(p.node.name,p)}});return}let l=s.isFunctionDeclaration()?s:s.findParent(u=>u.isFunction());if(l?.isFunctionDeclaration()&&Ip(l.node)){(l.findParent(d=>d.isFunction())===t?r.functionDeclarations:r.moduleDeclarations).add(F.cloneNode(l.node,!0)),l.traverse({ReferencedIdentifier(d){d.isIdentifier()&&o(d)},JSXOpeningElement(d){i(d.node.name,d)}});return}r.errors.push(ft("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function mD(e){let t=F.identifier(e);return t.typeAnnotation=F.tsTypeAnnotation(F.tsTypeReference(F.identifier("Record"),F.tsTypeParameterInstantiation([F.tsStringKeyword(),F.tsAnyKeyword()]))),t}function vp(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=Ui({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>ft(kD(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=kp(t,i.path);if(s===null)return Tt("SOURCE_NOT_PORTABLE",i.path,"A closed dependency is not valid UTF-8 source content.");r.push({path:i.path,content:s})}let o=e.sourceMapping??{generated_path:e.entryFile,source_file:e.selection.source_file,structural_path:e.selection.structural_path};return{complete:!0,entry_file:e.entryFile,source_files:r.sort((i,s)=>i.path.localeCompare(s.path)),source_mapping:[o],invocation_bindings:e.invocationBindings??e.selection.invocation?.bindings??[],selected_root_ref:e.selection.root_ref}}function gD(e,t,n,r){let o=F.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=hD(t,i,r);if(!s)return{ok:!1,error:ft("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=yD(n,s)}return{ok:!0,node:o}}function hD(e,t,n){let r=t.startsWith("@/")?t.slice(2):Xi.posix.normalize(Xi.posix.join(Xi.posix.dirname(e),t));if(!sS(r))return null;let o=/\.[a-z0-9]+$/iu.test(r)?[r]:[".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}${s}`).concat([".tsx",".ts",".jsx",".js",".json",".css",".svg"].map(s=>`${r}/index${s}`)),i=[...new Set(o.filter(s=>n.has(s)))];return i.length===1?i[0]:null}function yD(e,t){let n=Xi.posix.relative(Xi.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function xD(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!F.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!F.isStringLiteral(o.node.arguments[0])){r=!0,o.stop();return}let s=o.scope.getBinding(i.name),a=s?.path.findParent(l=>l.isImportDeclaration());if(!s?.path.isImportSpecifier()||!a?.isImportDeclaration()||a.node.source.value!=="next-intl"||!F.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!F.isIdentifier(c.node.id)){r=!0,o.stop();return}t=c.node.id.name}}),r||n>1?{ok:!1}:t?{ok:!0,translationBinding:t}:{ok:!0}}function Ip(e){if(!e.body||e.body.body.length!==1)return!1;let t=e.body.body[0];return!F.isReturnStatement(t)||!t.argument?!1:mc(t.argument)}function bD(e,t){let n=e.node.callee;if(F.isImport(n))return!1;if(t&&F.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(s=>F.isStringLiteral(s))){let s=e.scope.getBinding(t),a=s?.path.isVariableDeclarator()?s.path:s?.path.findParent(l=>l.isVariableDeclarator()),c=a?.isVariableDeclarator()?a.node.init:null;return!!(F.isCallExpression(c)&&oS(c))}if(!F.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);if(!r)return!1;if(r.path.isFunctionDeclaration())return Ip(r.path.node);let o=r.path.isVariableDeclarator()?r.path:r.path.findParent(s=>s.isVariableDeclarator()),i=o?.isVariableDeclarator()?o.node.init:null;return F.isArrowFunctionExpression(i)?F.isBlockStatement(i.body)?i.body.body.length===1&&F.isReturnStatement(i.body.body[0])&&!!i.body.body[0].argument&&mc(i.body.body[0].argument):mc(i.body):F.isFunctionExpression(i)?Ip({...F.functionDeclaration(null,i.params,i.body),async:i.async,generator:i.generator}):!1}function mc(e){let t=!0;return F.traverseFast(e,n=>{(F.isCallExpression(n)&&!oS(n)||F.isOptionalCallExpression(n)||F.isNewExpression(n)||F.isAwaitExpression(n)||F.isAssignmentExpression(n)||F.isUpdateExpression(n)||F.isYieldExpression(n)||F.isTaggedTemplateExpression(n))&&(t=!1)}),t}function oS(e){return F.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&F.isStringLiteral(e.arguments[0])}function iS(e){return F.isJSXIdentifier(e)?F.isValidIdentifier(e.name)?F.identifier(e.name):null:F.isJSXMemberExpression(e)?iS(e.object):null}function ED(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>F.isObjectPattern(n)&&n.properties.some(r=>F.isObjectProperty(r)&&F.isIdentifier(r.value,{name:e.node.name}))))}function eS(e,t){return e===t||typeof e.start=="number"&&typeof e.end=="number"&&typeof t.start=="number"&&typeof t.end=="number"&&e.start>=t.start&&e.end<=t.end}function SD(e){return F.isFunction(e)}function tS(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function vD(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function ID(e,t){let n=new Set;rS(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function Sp(e,t){return(e.start??0)-(t.start??0)}function kp(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function nS(e,t){let n=oD("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function sS(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function kD(e){return e==="SOURCE_PARSE_FAILED"?"SOURCE_PARSE_FAILED":e==="SOURCE_ENTRY_UNRESOLVED"?"SOURCE_ENTRY_NOT_FOUND":e==="SOURCE_FILE_UNRESOLVED"||e==="SOURCE_ASSET_UNRESOLVED"?"SOURCE_IMPORT_UNRESOLVED":"SOURCE_NOT_PORTABLE"}function Tt(e,t,n){return{complete:!1,errors:[ft(e,t,n)]}}function ft(e,t,n){return{code:e,path:t,message:n}}import RD from"node:path";import{GeneratedSiteCapabilitiesSchema as CD,FormDefinitionIdSchema as ND,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as _D,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as PD,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as AD,SiteEditMaterializationExportSchema as TD,SiteEditMaterializationSchema as wD}from"@vcp-dev/contracts";var gc="components/site/generated",OD=/^[a-z][a-z0-9._-]{0,127}$/,hc=/^[a-z][a-z0-9._-]{0,127}$/,FD=new Set(["collection-detail-view","i18n-companion","client-importer"]);function LD(e){if(!Io(e))return Be("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!OD.test(e.instanceId))return Be("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=CD.safeParse(e.trustedHostPolicy);if(!t.success)return Be("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return Be("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!jD(e.existingSources))return Be("PORTABLE_INPUT_INVALID","Portable materialization requires a read-only existing source index.","existingSources");if(e.trustedManagedImports!==void 0&&(!Array.isArray(e.trustedManagedImports)||e.trustedManagedImports.some(p=>{if(typeof p!="string")return!0;let h=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(p)?.[1];return!ND.safeParse(h).success||!Rp(e.existingSources,`${p.slice(2)}.tsx`)})))return Be("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=DD(e.resolved);if(!n.ok)return n;let r=wD.safeParse(n.materialization);if(!r.success)return Be("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=MD(n.relatedEntries,r.data);if(!o.ok)return o;let i=BD(e.entryConsumers,o.data,r.data);if(!i.ok)return i;let s=RD.posix.join(gc,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let h=Qo({pathTemplate:p.pathTemplate,generatedRoot:gc,instanceName:e.instanceId,instanceRoot:s});if(!h.ok)return Cp(h.error);if(c.has(h.data))return Be("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${h.data}`,h.data);c.add(h.data),a.push({kind:"create-only",path:h.data,content:p.content,...p.role?{role:p.role}:{},sourcePathTemplate:p.pathTemplate})}if(a.length>PD)return Be("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let p of a){let h=Buffer.byteLength(p.content,"utf8");if(h>_D)return Be("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=h}if(l>AD)return Be("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=aS(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let p of o.data){let h=aS(p.pathTemplate,p.export,c,e.instanceId,s);if(!h.ok)return h;d.push({...p,path:h.data.path}),f.push(h.data)}if(Rp(e.existingSources,s)||a.some(p=>Rp(e.existingSources,p.path)))return Be("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=Wl({files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((p,h)=>p.path.localeCompare(h.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:gc,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,h)=>p.path.localeCompare(h.path)),entryConsumers:i.data,files:a}}):Cp(g.error)}function DD(e){if(!Io(e))return Be("PORTABLE_INPUT_INVALID","Resolved portable materialization must be an object.","resolved");let t=e.relatedEntries,n=e.portable;if(t!==void 0&&!Array.isArray(t))return Be("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!Io(n))return Be("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return Be("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?Be("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function MD(e,t){let n=new Set(t.files.map(a=>a.pathTemplate)),r=new Set((t.dataRequirements??[]).map(a=>a.key)),o=new Set,i=new Set,s=[];for(let[a,c]of e.entries()){if(!Io(c))return Be("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let l=c.key,u=c.requirementKey,d=c.pathTemplate,f=c.purpose,g=TD.safeParse(c.export);if(typeof l!="string"||!hc.test(l)||typeof u!="string"||!hc.test(u)||typeof d!="string"||typeof f!="string"||!FD.has(f)||!g.success)return Be("PORTABLE_INPUT_INVALID","Every related entry must have a strict key, purpose, path and export.",`resolved.relatedEntries[${a}]`);if(o.has(l)||i.has(d))return Be("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return Be("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return Be("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return Be("PORTABLE_REQUIREMENT_UNRESOLVED","Every related entry must reference a resolved managed requirement.",u);o.add(l),i.add(d),s.push({key:l,pathTemplate:d,export:g.data,purpose:f,requirementKey:u})}return{ok:!0,data:s}}function BD(e,t,n){let r=new Map(t.map(c=>[c.key,c])),o=new Set((n.dataRequirements??[]).map(c=>c.key)),i=new Set,s=[];for(let[c,l]of e.entries()){if(!Io(l))return Be("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${c}]`);let u=l.entry_key,d=l.requirement_key,f=l.kind,g=l.consumer_path;if(typeof u!="string"||!hc.test(u)||typeof d!="string"||!hc.test(d)||typeof g!="string"||!g.trim()||f!=="route"&&f!=="capability")return Be("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${c}]`);let p=r.get(u);if(!p)return Be("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",u);if(i.has(u))return Be("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",u);if(p.requirementKey!==d)return Be("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",u);if(!o.has(d))return Be("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",d);i.add(u),s.push({entry_key:u,requirement_key:d,kind:f,consumer_path:g})}let a=t.find(c=>!i.has(c.key));return a?Be("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",a.key):{ok:!0,data:s.sort((c,l)=>c.entry_key.localeCompare(l.entry_key)||c.consumer_path.localeCompare(l.consumer_path))}}function aS(e,t,n,r,o){let i=Qo({pathTemplate:e,generatedRoot:gc,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:Be("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):Cp(i.error)}function Rp(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jD(e){return Array.isArray(e)||e instanceof Map||Io(e)}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cp(e){return{ok:!1,error:e}}function Be(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import cS from"node:path";import{SiteEditSourcePathSchema as Np}from"@vcp-dev/contracts";function $D(e){let t=e.resolvedBoundary;if(!e.routeId.trim()||!Number.isSafeInteger(e.documentVersion)||e.documentVersion<0||e.binding.documentVersion!==e.documentVersion||e.binding.composition.routeId!==e.routeId||t.ownerFile!==e.binding.ownerFile||t.sourceHash!==e.binding.ownerSourceHash||(t.placement==="before"?t.afterBlockKey:t.beforeBlockKey)!==e.binding.blockKey||!Np.safeParse(e.entryFile).success||!Np.safeParse(t.ownerFile).success||t.anchorLocator.file!==t.ownerFile||t.parentLocator!==null&&t.parentLocator.file!==t.ownerFile||!/^sha256:[a-f0-9]{64}$/u.test(t.sourceHash))return st("INVALID_TARGET","The resolved Portable boundary is not a valid source-owner boundary.");let n=e.files.get(t.ownerFile);if(n===void 0)return st("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(ve(n)!==t.sourceHash)return st("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=JD(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?st("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):VD(e,n):KD(e,n))}function VD(e,t){let n=Je(e.entryFile,t);if(!n.ok)return st("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=nn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return st("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=UD(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return st("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=au({routeId:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,documentVersion:e.documentVersion,source:t,anchor:{componentName:o,relation:e.resolvedBoundary.placement,sourceRange:e.resolvedBoundary.anchorLocator.sourceRange},component:e.component,invocation:e.invocation});if(!i.ok)return st(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return st("INVALID_TARGET","The route planner did not preserve the resolved owner boundary.",e.resolvedBoundary.ownerFile);let s=i.plan.rewriteStep,a=s.kind==="insert-child"&&s.anchorLocator?.strategy==="source-range"?s.anchorLocator.sourceRange:null;return s.kind==="insert-child"&&(!a||!Pp(a,e.resolvedBoundary.anchorLocator.sourceRange))?st("INVALID_TARGET","The route planner selected a different anchor than the resolved boundary.",e.entryFile):{ok:!0,patches:[{path:i.patch.path,source:i.patch.source,baseContentHash:i.patch.expectedSourceHash}]}}function UD(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Pp(o.anchorSourceRange,t)?[]:lS(o.members).filter(i=>i.sourceRange!==null&&Pp(i.sourceRange,t)));return r.length===1?r[0].label:null}function lS(e){return e.flatMap(t=>[t,...lS(t.children)])}function KD(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return st("UNSUPPORTED_OPERATION","A shared owner root without a JSX parent has no safe sibling boundary.",n.ownerFile);if(r.kind!=="jsx-element"&&r.kind!=="jsx-fragment")return st("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=qr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return st(o.error.code,o.error.message,n.ownerFile);let i=XD(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Kt({source:t,locator:_p(r),anchorLocator:_p(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return st("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=Jt({source:s.source,moduleSpecifier:zD(n.ownerFile,e.component.source),imports:[e.component.exportName==="default"?{kind:"default",local:e.component.localName}:{kind:"named",imported:e.component.exportName,...e.component.localName===e.component.exportName?{}:{local:e.component.localName}}]});return a.ok?{ok:!0,patches:[{path:n.ownerFile,source:a.source,baseContentHash:n.sourceHash}]}:st("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function JD(e){return!Np.safeParse(e.component.source).success||e.component.source===e.resolvedBoundary.ownerFile||e.component.exportName!=="default"&&!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e.component.exportName)?st("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function XD(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Je(t,e);if(!o.ok)return st("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=xe(o.module.ast,_p(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?st("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function _p(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e.sourceRange,...e.structuralPath&&e.componentName?{expectedIdentity:{file:e.file,component:e.componentName,structuralPath:e.structuralPath}}:{}}}function zD(e,t){let n=cS.posix.relative(cS.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Pp(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function st(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{SiteEditPageBlockTargetSchema as HD,SiteIdSchema as WD,SnapshotIdSchema as GD}from"@vcp-dev/contracts";async function YD(e){if(!WD.safeParse(e.site_id).success||!GD.safeParse(e.base_snapshot_id).success||!HD.safeParse(e.target).success)return Rn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!QD(e.composition,e.target.composition))return Rn("INVALID_TARGET","The target selector does not match the requested composition.");let t=new Map,n=new Map;for(let[u,d]of e.files){if(!Ap(u))return Rn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:ZD(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=fa({files:n})}catch{return Rn("INVALID_TARGET","Snapshot composition inventory is invalid.")}let o=r.find(u=>u.context.routeId===e.composition.routeId&&u.context.effectiveTemplateId===e.composition.templateId);if(!o)return Rn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Rn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Bs(o.entryFile,i,async u=>{if(!Ap(u)||!/\.(?:[cm]?[jt]sx?)$/i.test(u))throw new Error("Unsafe imported source path");let d=t.get(u);if(d===void 0)throw new Error("Source file unavailable");return d},async u=>Ap(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Rn("INVALID_TARGET","The selected snapshot source graph is incomplete.");s.graph.routeId=e.composition.routeId,s.graph.composition={routeId:e.composition.routeId,...e.composition.templateId!==void 0?{effectiveTemplateId:e.composition.templateId}:{}};let a=nn({route:e.composition.routeId,composition:s.graph.composition,entryFile:o.entryFile,version:e.document_version,source:i,ast:s.entryModule.ast});if(!a.ok)return Rn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=sa({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Rn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=ai({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection,documentVersion:e.document_version,roots:c.roots});return l.diagnostics.length>0?{...Rn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...ro(l,e.target,e.document_version,e.selection_ref),index:l}}function ZD(e,t){if(!/\.(?:[cm]?[jt]sx?)$/i.test(e))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function Ap(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function QD(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Rn(e,t){return{ok:!1,code:e,message:t}}import{createHash as qD}from"node:crypto";import Tp from"node:path";import wp from"@babel/traverse";import*as at from"@babel/types";import{GeneratedSiteCapabilitiesSchema as eM,SiteEditSourcePathSchema as tM}from"@vcp-dev/contracts";var nM=typeof wp=="function"?wp:wp.default;function rM(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!eM.safeParse(e.hostCapabilities).success)return Zt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!zi(t.descriptor.source.file)||!zi(t.ownerFile))return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=yc(n,t.descriptor.source.file),o=yc(n,t.ownerFile);if(r===null||o===null)return Zt("INVOCATION_TARGET_NOT_RENDERED",r===null?t.descriptor.source.file:t.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(ve(r)!==t.descriptor.source.contentHash||ve(r)!==t.sourceHash||ve(o)!==t.ownerSourceHash)return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=Je(t.descriptor.source.file,r);if(!i.ok)return Zt("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=uS(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return Zt("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=dS(a.node);if(!c)return Zt("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The selected JSX element has no complete source range.");let l=[],u=t.root.callChain;for(let[p,h]of u.entries()){let y=yc(n,h.sourceFile);if(y===null||!zi(h.sourceFile))return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let x=Je(h.sourceFile,y);if(!x.ok)return Zt("INVOCATION_PARSE_FAILED",h.sourceFile,x.diagnostic.message);let E=uS(x.module.ast,h.callLocator.sourceRange);if(E.length!==1)return Zt("INVOCATION_TARGET_AMBIGUOUS",h.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let b=iM(x.module.ast,E[0].node.openingElement.name,h.component,h.exportName);if(!b)return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"The statically proven component call no longer resolves through one exact import.");let v=u[p+1]?.sourceFile??t.descriptor.source.file,_=aM(h.sourceFile,b.source,n);if(!_||_!==v)return Zt("INVOCATION_TARGET_NOT_RENDERED",h.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let P=Ji({file_path:h.sourceFile,source:y,target:{source:b.source,export_name:b.exportName,local_name:b.localName},call_source_range:{start_line:h.callLocator.sourceRange.startLine,start_column:h.callLocator.sourceRange.startColumn}});if(!P.call||!P.complete)return{complete:!1,errors:P.errors.length>0?P.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:h.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};l.push({call:P.call,invocation:P,importTarget:b,importedFile:_})}let d={kind:"page-block",composition:lM(t.composition),blockKey:t.blockKey},f=oM(t,a,l,n,e.hostCapabilities);if(!f.ok)return{complete:!1,errors:[f.error]};let g=l[0]?.invocation??null;return{complete:!0,selection:{target:d,root_ref:t.root.rootRef,source_file:t.descriptor.source.file,structural_path:t.descriptor.source.structuralPath,content_hash:t.descriptor.source.contentHash,source_range:c,owner:t.descriptor.owner,call_chain:l.map(({call:p})=>p),strategy:f.strategy,entry_file:f.entryFile,entry_export:f.entryExport,invocation:g}}}function oM(e,t,n,r,o){let i=n.at(-1);if(i){let l=Je(i.importedFile,yc(r,i.importedFile)??"");if(!l.ok)return{ok:!1,error:{code:"INVOCATION_PARSE_FAILED",path:i.importedFile,message:l.diagnostic.message}};let u=Nr({module:l.module,exportName:i.importTarget.exportName}),d=u.ok&&u.roots.length===1&&sM(u.roots[0].node,e.rootLocator.sourceRange),f=uM(e.ownerFile);if(n.length===1&&d&&f)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&d)return{ok:!0,strategy:"reuse-entry",entryFile:i.importedFile,entryExport:i.importTarget.exportName==="default"?{kind:"default"}:{kind:"named",name:i.importTarget.exportName}}}if(!dS(t.node))return{ok:!1,error:{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.descriptor.source.file,message:"Cannot derive a portable entry identity without an exact root range."}};let c=`components/site/portable/${qD("sha256").update(JSON.stringify([e.composition,e.blockKey,e.descriptor.source.file,e.descriptor.source.structuralPath,e.descriptor.source.contentHash,o?.host_contract_digest??null])).digest("hex").slice(0,24)}/page.tsx`;return!zi(c)||r.has(c)?{ok:!1,error:{code:"INVOCATION_TARGET_AMBIGUOUS",path:c,message:"The deterministic in-memory Portable entry path collides with an existing Snapshot file."}}:{ok:!0,strategy:"extract-jsx",entryFile:c,entryExport:{kind:"default"}}}function iM(e,t,n,r){let o=Op(t);if(!o||o!==n)return null;let i=at.isJSXMemberExpression(t)?Op(t.object):at.isJSXNamespacedName(t)?t.namespace.name:o,s=at.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(at.isImportDeclaration(a))for(let c of a.specifiers){if(at.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(at.isImportSpecifier(c)&&c.local.name===i){let l=cM(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(at.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function uS(e,t){let n=[];return nM(e,{JSXElement(r){let o=r.node.loc;o&&o.start.line===t.startLine&&o.start.column===t.startColumn&&o.end.line===t.endLine&&o.end.column===t.endColumn&&n.push(r)}}),n}function dS(e){let t=e.loc;return typeof e.start!="number"||typeof e.end!="number"||!t?null:{start_offset:e.start,end_offset:e.end,start_line:t.start.line,start_column:t.start.column,end_line:t.end.line,end_column:t.end.column}}function sM(e,t){let n=e.loc;return!!(n&&n.start.line===t.startLine&&n.start.column===t.startColumn&&n.end.line===t.endLine&&n.end.column===t.endColumn)}function yc(e,t){let n=e.get(t);if(typeof n=="string")return n;if(!(n instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{return null}}function aM(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Tp.posix.normalize(Tp.posix.join(Tp.posix.dirname(e),t)):null;return!r||r===".."||r.startsWith("../")||r.startsWith("/")?null:(/\.(?:[cm]?[jt]sx?)$/u.test(r)?[r]:[".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}${i}`).concat([".tsx",".ts",".jsx",".js",".mts",".cts"].map(i=>`${r}/index${i}`))).find(i=>zi(i)&&n.has(i))??null}function Op(e){if(at.isJSXIdentifier(e))return e.name;if(at.isJSXMemberExpression(e)){let t=Op(e.object);return t?`${t}.${e.property.name}`:null}return null}function cM(e){return at.isIdentifier(e)?e.name:e.value}function lM(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function zi(e){return tM.safeParse(e).success}function uM(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function Zt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import{createHash as dM}from"node:crypto";import pM from"@babel/traverse";import*as we from"@babel/types";var Fp=pM,fM=typeof Fp=="function"?Fp:Fp.default,mM=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),ko=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),gM=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,hM=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function yM(e){let t=Je(e.file_path,e.source);if(!t.ok)return{complete:!1,references:[],errors:[{code:"MEDIA_SOURCE_PARSE_FAILED",file_path:e.file_path,message:t.diagnostic.message}]};let n=[],r=[],o=new Set,i=c=>{let l=fS(c.node),u=kM(e.source,l),d=`${l.start_offset}:${l.end_offset}:${c.kind}:${c.value??"<unknown>"}`;o.has(d)||(o.add(d),n.push({file_path:e.file_path,occurrence:n.length,kind:c.kind,source:c.source,value:c.value,expression:u,asset_key:c.assetKey??null,source_range:l,content_digest:RM(u),complete:c.complete}),c.complete||r.push({code:"MEDIA_VALUE_UNKNOWN",file_path:e.file_path,message:"The media expression cannot be resolved without executing user code.",source_range:l}))},s=(c,l)=>{if(!l){i({node:c,kind:"manifest",source:"media-manifest",value:null,complete:!1});return}let u=e.media_manifest?.[l];if(u===void 0){let d=fS(c);r.push({code:"MEDIA_MANIFEST_KEY_UNKNOWN",file_path:e.file_path,message:`The media manifest key ${l} is not available in the supplied snapshot.`,source_range:d})}i({node:c,kind:"manifest",source:"media-manifest",value:u??null,assetKey:l,complete:u!==void 0})};fM(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;xM(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=mS(c.node.name),u=hM.test(l);for(let d of c.node.attributes){if(we.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=EM(d);if(!f||!bM(f,u))continue;let g=dr(d.value);i({node:d.value??d,kind:pS(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=Ec(c.node.key);if(!l||!ko.has(l)&&!(IM(c)&&gS(l))||ko.has(l)&&xc(c.node.value)&&bc(c.node.value))return;let u=dr(c.node.value);i({node:c.node.value,kind:pS(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(vM(c))for(let l of c.node.elements){if(!l||xc(l)&&bc(l))continue;let u=dr(l);(u.value!==null||!u.complete)&&i({node:l,kind:"array-item",source:"array-item",value:u.value,complete:u.complete})}},CallExpression(c){let l=c.node.callee;if(!we.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!we.isExpression(u)){s(c.node,null);return}let d=dr(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!SM(c.node.object))return;let l=c.node.computed?dr(c.node.property):we.isIdentifier(c.node.property)?{value:c.node.property.name,complete:!0}:{value:null,complete:!1};s(c.node,l.complete?l.value:null)}});let a=CM(r).sort(NM);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function xM(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&mM.has(n)}function bM(e,t){return e!=="src"||t?ko.has(e):!1}function pS(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function EM(e){return we.isJSXIdentifier(e.name)?e.name.name.toLowerCase():we.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function mS(e){return we.isJSXIdentifier(e)?e.name:we.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${mS(e.object)}.${e.property.name}`}function Ec(e){return we.isIdentifier(e)?e.name.toLowerCase():we.isStringLiteral(e)?e.value.toLowerCase():null}function SM(e){return we.isIdentifier(e,{name:"mediaAssets"})}function vM(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=Ec(t.node.key);return n!==null&&ko.has(n)}return t?.isVariableDeclarator()&&we.isIdentifier(t.node.id)?gM.test(t.node.id.name):!1}function IM(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=Ec(n.node.key);return r!==null&&ko.has(r)}function gS(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function xc(e){return we.isObjectExpression(e)||we.isArrayExpression(e)}function bc(e){if(we.isArrayExpression(e))return e.elements.some(n=>n!==null&&(xc(n)?bc(n):!0));let t=!1;for(let n of e.properties){if(!we.isObjectProperty(n))return!1;let r=Ec(n.key);if(r!==null&&(ko.has(r)||gS(r))){t=!0;continue}xc(n.value)&&bc(n.value)&&(t=!0)}return t}function dr(e){return e?we.isStringLiteral(e)?{value:e.value,complete:!0}:we.isJSXExpressionContainer(e)?dr(e.expression):we.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:we.isTSAsExpression(e)||we.isTSTypeAssertion(e)||we.isParenthesizedExpression(e)?dr(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function fS(e){let t=e.start??0,n=e.end??t;return{start_offset:t,end_offset:n,start_line:e.loc?.start.line??1,start_column:e.loc?.start.column??0,end_line:e.loc?.end.line??e.loc?.start.line??1,end_column:e.loc?.end.column??e.loc?.start.column??0}}function kM(e,t){return e.slice(t.start_offset,t.end_offset)}function RM(e){return`sha256:${dM("sha256").update(e).digest("hex")}`}function CM(e){let t=new Set;return e.filter(n=>{let r=`${n.code}:${n.file_path}:${n.source_range?.start_offset??-1}`;return t.has(r)?!1:(t.add(r),!0)})}function NM(e,t){return e.file_path.localeCompare(t.file_path)||(e.source_range?.start_offset??0)-(t.source_range?.start_offset??0)||e.code.localeCompare(t.code)}export{ge as FileHistoryStoreError,li as PageTemplateManagedSourceError,sc as PreviewFileSystemSiteEditEngineRuntime,sg as SITE_EDIT_RAW_COLOR_LITERAL_RE,oc as SnapshotSiteEditEngineRuntime,vL as analyzePortableCollectionInvocation,Ji as analyzePortableInvocation,lp as analyzePortableRelatedEntries,Jl as auditGeneratedCode,FF as auditPortableDependencies,ai as buildPageBlockIndex,qr as buildPortableInvocation,LD as buildPortableMaterializationPlan,Ui as buildPortableSourceClosure,Po as checkComponentI18nHostCompatibility,ac as classifyPortableDependencyOwnership,kh as computeManagedPageTemplatePaths,NF as createPreviewSiteEditEngineRuntime,IF as createSiteEditEngineRuntime,Sh as decodePageTemplateKey,qF as discoverPortableCollectionSourceRelation,Nu as encodePageTemplateId,lD as extractPortableBlockEntry,rv as instrumentSiteEditRuntimeAttributes,Rh as isManagedPageTemplateSourcePath,AN as normalizePortableBlockMetadata,JL as normalizePortableSource,Fm as openFileHistoryStore,VS as parseSourceModule,$D as planPortableBlockPatch,au as planPortableRouteCompositionPatch,ni as planRouteCompositionRewrite,US as resolveImportBase,mP as resolveManagedPageTemplateComposition,ca as resolvePageBlockBoundary,YD as resolvePageBlockFromSnapshot,ro as resolvePageBlockTarget,nn as resolvePageCompositionProjection,rM as resolvePortableBlockSelection,PF as resolvePortableDependencyOwnership,UF as resolvePortableSourcePath,pa as scanManagedPageTemplateCandidates,yM as scanPortableMediaReferences,fa as scanSiteEditCompositionsFromFiles,Zo as scanSiteEditThemeStyleViolations,SL as selectPortablePageUnitInvocation};
|