@vcp-dev/site-edit-engine 0.11.24 → 0.11.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,21 +1,53 @@
1
- import*as Rk from"@babel/parser";import*as Pt from"@babel/types";import*as ar from"node:path";var Wl=[".tsx",".ts",".jsx",".js"],Ck=Wl.map(e=>`/index${e}`),Nk=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 Qm(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&Nk.has(n[1].toLowerCase())}function eg(e){let t=[];for(let n of e.program.body)Pt.isImportDeclaration(n)&&typeof n.source.value=="string"&&Qe(n.source.value)&&t.push(n.source.value),Pt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&Qe(n.source.value)&&t.push(n.source.value),Pt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&Qe(n.source.value)&&t.push(n.source.value);return Pt.traverseFast(e.program,n=>{let r=Pt.isImportExpression(n)?n.source:Pt.isCallExpression(n)&&Pt.isImport(n.callee)?n.arguments[0]:null;Pt.isStringLiteral(r)&&Qe(r.value)&&t.push(r.value)}),t}function Qe(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Nn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=ar.dirname(e);return ar.join(n,t).replace(/\\/g,"/")}async function Pk(e,t){for(let n of tg(e))if(await t(n))return n;return null}function tg(e){return[...Wl.some(t=>e.endsWith(t))?[e]:[],...Wl.map(t=>`${e}${t}`),...Ck.map(t=>`${e}${t}`)]}function cr(e,t,n){let r=Nn(e,t);if(!Qe(t)||!ng(e,t,r))return null;for(let o of tg(r))if(n.has(o))return o;return null}async function Xr(e,t,n){let r=await Js(e,t,n);return r.ok?r.path:null}async function Js(e,t,n){let r=Nn(e,t);try{if(!ng(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 Pk(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 ng(e,t,n){if(!Qe(t)||t.includes("\0")||t.includes("\\")||ar.posix.isAbsolute(n))return!1;let r=ar.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!ar.posix.isAbsolute(e)}import{createHash as Tk}from"node:crypto";import*as rg from"@babel/parser";function zr(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function te(e,t,n,r,o){return{ok:!1,source:e,diagnostic:zr(t,n,r,o)}}function Gl(e,t,n,r,o){return{ok:!1,source:e,diagnostic:zr(t,n,r,o)}}var Ak={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Pn(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:rg.parse(t,{sourceType:"module",plugins:Ak[n]})}}catch(r){return{ok:!1,source:t,diagnostic:zr("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Yl(e,t){return Pn({source:e,profile:og(t.kind)})}function gi(e,t){return Pn({source:e,profile:og(t)})}function og(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 De=(e,t)=>{let n=Pn({source:t,profile:Hr({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${Tk("sha256").update(t).digest("hex")}`,ast:n.ast,imports:eg(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function wk(e,t){return De(e,t)}function Ok(e,t){return Nn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as Lk,parseComponentI18nResourcesJson as Fk,resolveSiteTextDirection as Dk,SiteLocaleSchema as Mk}from"@vcp-dev/contracts";var Bk=["i18next","react-i18next"],jk="components/ui/site-locale-provider.tsx",$k="components/ui/component-i18n-provider.tsx",ig="app/layout.tsx";async function hi(e){let t=e.files.filter(f=>f.path.endsWith(Lk));if(t.length===0)return{ok:!0};for(let f of["package.json",ig,jk,$k])if(!await e.exists(f))return lr(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return lr("Target snapshot package.json is invalid.")}let r=sg(n)&&sg(n.dependencies)?n.dependencies:{},o=Bk.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return lr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(ig),s=Zl(i,"html","lang"),a=Zl(i,"html","dir"),c=Zl(i,"SiteLocaleProvider","locale"),l=Mk.safeParse(s);if(!l.success||!a||!c||s!==c||a!==Dk(l.data))return lr("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 lr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return lr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=Fk(f.content);if(!g.success)return lr(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return lr(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Zl(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 sg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lr(e){return{ok:!1,message:e}}import Ql from"@babel/generator";import*as fg from"@babel/parser";import eu from"@babel/traverse";import*as He from"@babel/types";import{computeSiteEditSourceIdentityKey as Vk}from"@vcp-dev/contracts";var ag="data-vcp-ui-component",Xs="components/ui";function Hn(e){if(!e)return!1;let t=ql(e);return t===Xs||t.startsWith(`${Xs}/`)||t.includes(`/${Xs}/`)||t.endsWith(`/${Xs}`)}function Wr(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Hn(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Hn(ql(`${Uk(t)}/${e}`)):Hn(e):!1}function ql(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 Uk(e){let t=ql(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as N$}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as A$,isSiteEditRuntimeTextTag as T$}from"@vcp-dev/contracts/site-edit-runtime-capability";var cg={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 Kk=typeof Ql=="function"?Ql:Ql.default,Jk=typeof eu=="function"?eu:eu.default,Xk=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),zk="suppressHydrationWarning",Hk=new Set(["SiteEditBootstrap"]);function Wk(e){let t=Zk(e.file,e.projectRoot);if(!Yk(e.source)||Hn(t))return{code:e.source,elements:[]};let n=e.attributes??cg,r=fg.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=Qk(r,t);return Jk(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!t_(c)||pg(a,n.key))return;let l=r_(s)??"default",u=i_(s),d=Vk(t,l,u),f=Hs(c)??"unknown",g=qk(c)?"jsx":"component-call";if(g==="component-call"&&!o_(s.node.children)&&Hk.has(f))return;let p=g==="component-call"&&e_(f,i);n_(a,n.key,d),p&&lg(a,ag),Gk(s)&&lg(a,zk),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Kk(r,{jsescOption:{minimal:!0}}).code,elements:o}}function Gk(e){return!e.findParent(t=>t.isJSXElement())}function Yk(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function Zk(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 qk(e){return He.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Hs(e){return He.isJSXIdentifier(e)?e.name:He.isJSXMemberExpression(e)?gg(e):null}function Qk(e,t){let n=new Set;for(let r of e.program.body)if(!(!He.isImportDeclaration(r)||!Wr(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function e_(e,t){let n=e.split(".")[0]??e;return t.has(n)}function t_(e){let t=Hs(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!Xk.has(t)}function pg(e,t){return e.attributes.some(n=>He.isJSXAttribute(n)&&He.isJSXIdentifier(n.name,{name:t}))}function n_(e,t,n){mg(e,He.jsxAttribute(He.jsxIdentifier(t),He.stringLiteral(n)))}function lg(e,t){pg(e,t)||mg(e,He.jsxAttribute(He.jsxIdentifier(t),null))}function mg(e,t){let n=e.attributes.findIndex(r=>He.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function gg(e){return`${He.isJSXIdentifier(e.object)?e.object.name:gg(e.object)}.${e.property.name}`}function r_(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&He.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 o_(e){return e.some(t=>He.isJSXElement(t)||He.isJSXFragment(t))}var ug=new WeakMap,zs=new WeakMap,tu=new WeakMap;function i_(e){let t=ug.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=s_(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return ug.set(e.node,o),o}function s_(e){let t=Hs(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${dg(e,t)}`:`${t}#${dg(e,t)}`}function dg(e,t){let n=hg(e)??e.getFunctionParent();if(!n)return 0;let r=tu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=tu.get(n.node);o||(o=new Map,tu.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()?Ws(n):a_(n);for(let c of a)if(Hs(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 a_(e){let t=zs.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!hg(r)&&n.push(r)}}),zs.set(e.node,n),n}function hg(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 Ws(e){let t=zs.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(...Ws(o));continue}o.isJSXExpressionContainer()&&n.push(...Gr(o.get("expression")))}return zs.set(e.node,n),n}function Gr(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Ws(e);if(e.isParenthesizedExpression())return Gr(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Gr(e.get("right"));if(e.isConditionalExpression())return[...Gr(e.get("consequent")),...Gr(e.get("alternate"))];if(e.isCallExpression()&&l_(e.node)){let t=e.get("arguments")[0];return c_(t)}return[]}function c_(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Ws(t);if(t.isParenthesizedExpression())return Gr(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?Gr(r):[]}return[]}function l_(e){return He.isMemberExpression(e.callee)&&He.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as RM,SiteEditPatchPlanSchema as CM}from"@vcp-dev/contracts";function Yr(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 Gs(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 Ys(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 Zs(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:u_(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 qs(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:Yr(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 u_(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 MD,computeSiteEditCompositionKey as BD,getSiteEditSourceDeleteProtectionReason as jD,isSiteEditTextSourcePath as $D,parseSiteEditRepeatInstanceKey as UD,SITE_EDIT_SOURCE_DELETE_CAPABILITY as VD,stripSiteEditRepeatInstanceKeys as Vt}from"@vcp-dev/contracts";import ll from"node:path";import{parse as KD}from"yaml";import su from"node:path";import{TextDecoder as f_}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as bg,SITE_EDIT_SOURCE_ALLOWED_DIRS as xg,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Eg,SiteEditCompositionContextSchema as p_,SiteEditSourceFileResponseSchema as nu,SiteEditSourceLocationSchema as m_,SiteEditSourcePathSchema as Qs,SiteEditSourceTreeResponseSchema as g_,isSiteEditTextSourcePath as h_}from"@vcp-dev/contracts";import{createHash as d_}from"node:crypto";var yi=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 _e(e){return`sha256:${d_("sha256").update(e).digest("hex")}`}var y_=[...Eg,...bg,...xg];function au(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return p_.parse(e.composition)}var ru=2e3,ou=12,iu=24*1024*1024,yg=512*1024,b_=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),x_={".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"},E_={".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"},S_=new f_("utf-8",{fatal:!0});async function ea(e,t={}){let n=au(t),{files:r,truncated:o}=await N_(e,t),i=T_(r.map(s=>s.metadata));return g_.parse({composition:n,nodes:i,defaultPath:w_(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function ta(e,t,n={}){let r=au(n),o=Qs.parse(t.path),i=await I_(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(lu(o)){let a=Ig(o),c=await __(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return nu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await cu(e,o);return s.ok?nu.parse({composition:r,path:o,kind:"text",language:kg(o),sizeBytes:s.sizeBytes,contentHash:_e(s.content),readonly:!1,content:s.content}):nu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function cu(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=v_(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 v_(e){if(e.includes(0))return null;try{return S_.decode(e)}catch{return null}}async function I_(e,t,n){if(!R_(t,n))return null;let r=await k_(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function k_(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Sg(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(lu(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function __(e,t){if(!b_.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>yg)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>yg?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function R_(e,t){return Eg.some(n=>n===e)||bg.some(n=>n===e)||xg.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Qs.safeParse(n);return r.success&&r.data===e})}function na(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return m_.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 Sg(e){return Array.isArray(e)?{files:e}:e}function C_(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function N_(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Sg(await e.listFiles({roots:P_(t),maxFiles:ru+1,maxDepth:ou,maxTotalBytes:iu+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=Qs.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>ou){o.add("max-depth");continue}if(r.size>=ru){o.add("max-files");break}if(i+a.sizeBytes>iu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:A_(l,a.sizeBytes,au(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:C_([...o]),maxFiles:ru,maxDepth:ou,maxTotalBytes:iu}}:{}}}function P_(e){let t=new Set(y_);for(let n of e.routeEntryFiles??[]){let r=Qs.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function A_(e,t,n){return lu(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Ig(e),readonly:!0}:{composition:n,path:e,kind:"text",language:kg(e),sizeBytes:t,readonly:!1}}function T_(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 vg(t)}function vg(e){return e.map(t=>t.kind==="directory"?{...t,children:vg(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function w_(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 lu(e){return!h_(e)}function Ig(e){let t=su.posix.extname(e).toLowerCase();return!t&&su.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":x_[t]??"application/octet-stream"}function kg(e){let t=su.posix.extname(e).toLowerCase();return E_[t]??"plaintext"}import*as qr from"@babel/types";import uu from"@babel/traverse";import*as An from"@babel/types";function Ze(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(An.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(An.isIdentifier(s)&&s.name==="Fragment"||An.isStringLiteral(s)&&s.value==="Fragment")&&_g(i.parentPath)}if(!An.isJSXMemberExpression(t)||!An.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!An.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())&&_g(r.parentPath)}function _g(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var ur=typeof uu=="function"?uu:uu.default,ra=new WeakMap,oa=new WeakMap;function Tn(e,t){let n=Yl(e,t);if(!n.ok)return Gl(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Ie(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}}:Gl(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Ie(e,t){return t.kind==="jsx-node"?Pg(e,t):t.kind==="jsx-attribute"?B_(e,t):t.kind==="value"?j_(e,t):t.kind==="expression"?$_(e,t):t.kind==="directive"?U_(e,t):t.kind==="export"?V_(e,t):{ok:!1,diagnostic:zr("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Pg(e,t){return t.strategy==="source-range"?O_(e,t):L_(e,t)}function O_(e,t){let n=null;if(ur(e,{JSXElement(o){if(!Zr(o.node,t.sourceRange))return;let i=lt("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Zr(o.node,t.sourceRange))return;let i=lt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Zr(o.node,t.sourceRange))return;let i=lt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Zr(o.node,t.sourceRange))return;let i=lt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return pt("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!eR(r.path,t.expectedIdentity)?pt("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function L_(e,t){if(t.structuralPath===""){let r=D_(e,t.component);if(r){let o=M_(r);if(o)return o}}let n=null;return ur(e,{JSXElement(r){if(xi(r)!==t.component||fu(r)!==t.structuralPath)return;let i=lt("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(xi(r)!==t.component||fu(r)!==t.structuralPath)return;let i=lt("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=F_(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:pt("jsx-node","locator-miss","JSX node not found for structural-path locator")}function F_(e,t,n){let r=null;return ur(e,{JSXElement(o){if(xi(o)!==t||!Zr(o.node,n))return;let i=lt("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(xi(o)!==t||!Zr(o.node,n))return;let i=lt("jsx-node",o);i&&(r=i,o.stop())}}),r}function D_(e,t){let n=null;return ur(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 M_(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 pt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?pt("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 pt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function B_(e,t){let n=Pg(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>tR(c,t.name));if(!s||!s.isJSXAttribute())return pt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=lt("jsx-attribute",s);return a?{ok:!0,match:a}:pt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function j_(e,t){let n=K_(e,t);if(!n.ok)return n;let r=J_(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Gn(r.match.path.node.loc,t.expectedRange)?pt("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function $_(e,t){let n=null;return ur(e,{Identifier(r){if(!Y_(r))return;let o=Cg(r);if(!o||!Ng(o,t))return;let i=lt("expression",r);i&&(t.expectedRange&&!Gn(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Cg(r);if(!o||!Ng(o,t))return;let i=lt("expression",r);i&&(t.expectedRange&&!Gn(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:pt("expression","locator-miss","Expression not found")}function U_(e,t){let n=null;return ur(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Gn(i.node.loc,t.expectedRange))return;let s=lt("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:pt("directive","locator-miss",`Directive '${t.value}' not found`)}function V_(e,t){let n=null;return ur(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let f=lt("export",c);if(!f||t.expectedRange&&!Gn(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=pu(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=lt("export",u);if(!d||t.expectedRange&&!Gn(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=pu(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Gn(s.node.loc,t.expectedRange))return;let a=lt("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=lt("export",o);i&&(t.expectedRange&&!Gn(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:pt("export","export-not-found",`Export '${Q_(t)}' not found`)}function K_(e,t){let n=null;return ur(e,{Expression(r){if(n||t.root.kind!=="expression"||!Zr(r.node,t.root.sourceRange))return;let o=lt("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=lt("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=lt("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=pu(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=lt("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=lt("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:pt("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 J_(e,t){let n=du(e);for(let o of t){if(n=du(n),o.kind==="property"){if(!n.isObjectExpression())return pt("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return pt("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>nR(l,o.name));if(!c||!c.isObjectProperty())return pt("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return pt("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return pt("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return pt("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=du(n);let r=lt("value",n);return r?{ok:!0,match:r}:pt("value","locator-miss","Resolved value has no source range")}function du(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function lt(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 Zr(e,t){return Gn(e.loc,t)}function Gn(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 fu(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!Ze(n)){let o=Tg(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Rg(n,o)}`):t.unshift(`${o}#${Rg(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||W_(n.parentPath)&&!G_(n.parentPath))break;n=n.parentPath}return t.join("/")}function Rg(e,t){let n=Ag(e)??e.getFunctionParent();if(!n)return 0;let r=ra.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=ra.get(n.node)?.get(t);if(!i){let a=ra.get(n.node);a||(a=new Map,ra.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?bi(n):X_(n);for(let a of s)if(Tg(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function X_(e){let t=oa.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Ag(r)&&n.push(r)}}),oa.set(e.node,n),n}function Ag(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function bi(e){let t=oa.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(Ze(o)){n.push(...bi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...bi(o));continue}o.isJSXExpressionContainer()&&n.push(...Wn(o.get("expression")))}return oa.set(e.node,n),n}function Wn(e){if(e.isJSXElement())return Ze(e)?bi(e):[e];if(e.isJSXFragment())return bi(e);if(e.isParenthesizedExpression())return Wn(e.get("expression"));if(e.isLogicalExpression()&&z_(e.node.operator))return Wn(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(...Wn(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Wn(a));break}}return i}else if(o.node&&o.isExpression())return Wn(o)}}}}return e.isConditionalExpression()?[...Wn(e.get("consequent")),...Wn(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Wn(t)):[]}function z_(e){return e==="&&"||e==="||"||e==="??"}function Tg(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?H_(e.name):null}function H_(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 xi(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 W_(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function G_(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 Y_(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Cg(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 Ng(e,t){return e.base===t.base&&Z_(e.path,t.path??[])}function Z_(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 q_(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function Q_(e){return e.exportKind==="named"?e.name:e.exportKind}function pt(e,t,n,r){return{ok:!1,diagnostic:zr(t,n,e,r)}}function eR(e,t){return xi(e)!==t.component?!1:fu(e)===t.structuralPath}function tR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function pu(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function nR(e,t){return e.isObjectProperty()?q_(e.node)===t:!1}import*as Og from"@babel/parser";import{arrayExpression as aR,booleanLiteral as cR,identifier as lR,jsxAttribute as uR,jsxExpressionContainer as dR,jsxIdentifier as fR,nullLiteral as pR,numericLiteral as mR,objectExpression as gR,objectProperty as hR,stringLiteral as gu}from"@babel/types";import mu from"@babel/generator";var rR=typeof mu=="function"?mu:mu.default;function oR(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 iR(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 sR(e,t){return e.split(`
3
- `).map(r=>iR(r,t)).join(`
4
- `)}function ia(e){let{ast:t,source:n}=e;try{let r=oR(n),i=rR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=sR(i,r)),{ok:!0,source:i}}catch(r){return te(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function wg(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 Ei(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:wg(e),afterSourceHash:wg(t),inverse:n.inverse}}}function Be(e,t,n){let r=ia({ast:e,source:t});return r.ok?Ei(t,r.source,n):r}function We(e,t){let n=gi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function sa(e,t){return ia({ast:e,source:t})}function yR(e,t,n){let r=Ie(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function ko(e,t,n){let r=yR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:te(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function dr(e){return typeof e=="string"?gu(e):typeof e=="number"?mR(e):typeof e=="boolean"?cR(e):e===null?pR():Array.isArray(e)?aR(e.map(t=>dr(t))):gR(Object.entries(e).map(([t,n])=>{let r=hR(hu(t),dr(n));return t==="__proto__"&&(r.computed=!0),r}))}function bR(e){return typeof e=="string"?gu(e):dR(dr(e))}function Si(e,t){return uR(fR(e),bR(t))}function aa(e,t){try{let r=Og.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:te(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:te(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function hu(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?lR(e):gu(e)}function ca(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=We(t,"jsx-node");if(!i.ok)return i.result;let s=Ie(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=xR(s.match.path)[r];if(!c)return te(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?[qr.jsxText(d)]:[],qr.jsxExpressionContainer(qr.stringLiteral("")),...f?[qr.jsxText(f)]:[]]);break}let u=ER(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};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 Be(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function xR(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=SR(r.get("expression"));o.length>0&&t.push(...o)}}return t}function ER(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function SR(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 yu}from"@babel/types";function Qr(e){let{source:t,locator:n}=e,r=We(t,"jsx-node");if(!r.ok)return r.result;let o=Ie(r.ast,n);return o.ok?(vR(o.match.path),Be(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function vR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(yu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(yu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(yu());return}e.remove()}import{cloneNode as IR}from"@babel/types";function _o(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=Ie(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=aa(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(IR(r.node,!0)),Be(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as LR}from"@babel/types";import bu from"@babel/traverse";import*as he from"@babel/types";function vi(e,t,n){return`${e}::${t}::${n}`}var U={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 kR=typeof bu=="function"?bu:bu.default;function an(e,t,n,r){if(!e.ok)return e;let o=sn(n,t);if(!o)return e;let i=_R(t,o,r);return i?{...e,selectionRef:i}:e}function _R(e,t,n){let r=RR(e,t);if(!r)return;let o=n.sourceLocator?Lg(n.sourceLocator):void 0,i=n.targetParentLocator?Lg(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??NR(r)??i?.component??o?.component;if(!(!s||!a))return{key:vi(s,a,PR(r))}}function Lg(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function RR(e,t){let n=$g(e,t);return!n||n.node.type!=="JSXElement"?null:n}function $g(e,t){let n=null;return kR(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function sn(e,t){if(!e)return null;if(he.isJSXElement(e))return OR(t,e)?Fg(e.children,t):e;if(he.isJSXFragment(e))return Fg(e.children,t);if(he.isJSXExpressionContainer(e)||he.isParenthesizedExpression(e)||he.isTSAsExpression(e)||he.isTSSatisfiesExpression(e)||he.isTSTypeAssertion(e)||he.isTSNonNullExpression(e))return sn(e.expression,t);if(he.isLogicalExpression(e))return sn(e.right,t);if(he.isConditionalExpression(e))return sn(e.consequent,t)??sn(e.alternate,t);if(he.isCallExpression(e)||he.isOptionalCallExpression(e))return Ug(e)?CR(e.arguments[0],t):null;if(he.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=sn(n,t);if(r)return r}return null}function Fg(e,t){for(let n of e){let r=sn(n,t);if(r)return r}return null}function CR(e,t){return!e||!he.isArrowFunctionExpression(e)&&!he.isFunctionExpression(e)?null:he.isBlockStatement(e.body)?Ii(e.body.body,t):sn(e.body,t)}function Ii(e,t){for(let n of e){if(he.isReturnStatement(n)){let r=sn(n.argument,t);if(r)return r;continue}if(he.isBlockStatement(n)){let r=Ii(n.body,t);if(r)return r;continue}if(he.isIfStatement(n)){let r=Dg(n.consequent,t);if(r)return r;let o=n.alternate?Dg(n.alternate,t):null;if(o)return o;continue}if(he.isSwitchStatement(n))for(let r of n.cases){let o=Ii(r.consequent,t);if(o)return o}}return null}function Dg(e,t){return he.isBlockStatement(e)?Ii(e.body,t):Ii([e],t)}function NR(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(he.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&he.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 Mg=new WeakMap,Bg=new WeakMap,xu=new WeakMap;function PR(e){let t=Mg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=AR(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Mg.set(e.node,o),o}function AR(e){let t=Vg(e.node.openingElement.name);return!t||Ze(e)?null:/^[A-Z]/.test(t)?`component:${t}#${jg(e,t)}`:`${t}#${jg(e,t)}`}function jg(e,t){let n=TR(e);if(!n)return 0;let r=xu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=xu.get(n.node);o||(o=new Map,xu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of eo(n))if(Vg(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 TR(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(Ze(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function eo(e){let t=Bg.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(Ze(o)){n.push(...eo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...eo(o));continue}o.isJSXExpressionContainer()&&n.push(...wn(o.get("expression")))}return Bg.set(e.node,n),n}function wn(e){if(e.isJSXElement())return Ze(e)?eo(e):[e];if(e.isJSXFragment())return eo(e);if(e.isParenthesizedExpression())return wn(e.get("expression"));if(e.isLogicalExpression())return wn(e.get("right"));if(e.isConditionalExpression())return[...wn(e.get("consequent")),...wn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:wn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Ug(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?wR(n):[]}return[]}function wR(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return Ze(t)?eo(t):[t];if(t.isJSXFragment())return eo(t);if(t.isParenthesizedExpression())return wn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return wn(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(...wn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...wn(o)),n}return n}function Ug(e){let t=e.callee;return(he.isMemberExpression(t)||he.isOptionalMemberExpression(t))&&he.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function OR(e,t){let n=$g(e,t);return n?Ze(n):!1}function Vg(e){return he.isJSXIdentifier(e)?e.name:he.isJSXMemberExpression(e)?Kg(e):he.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Kg(e){return`${he.isJSXIdentifier(e.object)?e.object.name:Kg(e.object)}.${e.property.name}`}function fr(e,t){if(t.parentPath===e&&t.listKey==="children"&&Eu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Eu(n))return null;let r=n;for(;r&&r!==e;){if(!Eu(r)||!Ze(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Eu(e){return e.isJSXElement()||e.isJSXFragment()}function cn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return te(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 x=c.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return te(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=aa(t,r.jsx);if(!u.ok)return u.result;let d=LR(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},p=x=>s?an(x,a.ast,d,g):x;if(o==="append")return f.push(d),p(Be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),p(Be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return te(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let m=Ie(a.ast,i);if(!m.ok)return{ok:!1,source:t,diagnostic:m.diagnostic};let y=fr(c.match.path,m.match.path);if(!y)return te(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");l=y;let b=l.node.children,S=b.findIndex(x=>x===m.match.path.node);return S===-1?te(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?S:S+1,0,d),p(Be(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Jg from"@babel/parser";import{cloneNode as FR}from"@babel/types";function la(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=DR(t,r);if(!c.ok)return c.result;let l=Ie(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return te(t,"unsupported-syntax","insert-jsx-expression-child target must be a JSXElement or JSXFragment","jsx-node");if(l.match.path.isJSXElement()){let b=l.match.path.node;if(!b.closingElement||b.openingElement.selfClosing)return te(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let b=Ie(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=fr(l.match.path,b.match.path);if(!S)return te(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=S,d=b.match.path.node}else if(o==="before"||o==="after")return te(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=FR(c.node,!0),g=u.node.children,p={...s,targetParentLocator:n},m=b=>s?an(b,a.ast,f,p):b;if(o==="append")return g.push(f),m(Be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),m(Be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(b=>b===d);return y===-1?te(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),m(Be(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function DR(e,t){try{let r=Jg.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:te(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:te(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as MR,nullLiteral as Su}from"@babel/types";import*as pr from"@babel/types";import*as Xg from"@babel/types";function ki(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Xg.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function to(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=We(t,"jsx-node");if(!a.ok)return a.result;let c=Ie(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Ie(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return te(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 x=l.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return te(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let x=Ie(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=x.match.path.isJSXElement()?ki(x.match.path,l.match.path):x.match.path,k=fr(l.match.path,E);if(!k)return te(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=k,d=E}else if(o==="before"||o==="after")return te(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return te(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?ki(c.match.path,l.match.path):c.match.path,p=MR(g.node,!0);if(!pr.isJSXElement(p)&&!pr.isJSXExpressionContainer(p)&&!pr.isJSXFragment(p)&&!pr.isJSXText(p))return te(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let m=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 te(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");BR(g);let y=u.node.children,b={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(p),an(sa(a.ast,t),a.ast,p,b);if(o==="prepend")return y.unshift(p),an(sa(a.ast,t),a.ast,p,b);let S=f-(m!==-1&&m<f?1:0);return y.splice(o==="before"?S:S+1,0,p),an(sa(a.ast,t),a.ast,p,b)}function BR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Su());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Su());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Su());return}e.remove()}import*as zg from"@babel/parser";import{cloneNode as jR,nullLiteral as vu}from"@babel/types";function ua(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=We(t,"jsx-node");if(!c.ok)return c.result;let l=$R(t,s);if(!l.ok)return l.result;let u=Ie(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Ie(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return te(t,"unsupported-syntax","move-repeat-template-child target parent must be a JSXElement or JSXFragment","jsx-node");if(d.match.path.isJSXElement()){let x=d.match.path.node;if(!x.closingElement||x.openingElement.selfClosing)return te(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let f=d.match.path,g=null;if(i){let x=Ie(c.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=fr(d.match.path,x.match.path);if(!E)return te(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=E,g=x.match.path.node}else if(o==="before"||o==="after")return te(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return te(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let p=f.node,m=jR(l.node,!0);UR(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},b=p.children;if(o==="append")return b.push(m),an(Be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);if(o==="prepend")return b.unshift(m),an(Be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y);let S=b.findIndex(x=>x===g);return S===-1?te(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?S:S+1,0,m),an(Be(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,m,y))}function $R(e,t){try{let r=zg.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:te(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:te(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function UR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(vu());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(vu());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(vu());return}e.remove()}import{SiteEditSetPropsParamsSchema as VR,classifySiteEditPropertyName as KR}from"@vcp-dev/contracts";import*as Ro from"@babel/types";function da(e){let t=VR.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return te(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=We(e.source,"jsx-node");if(!n.ok)return n.result;let r=ko(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=KR(a.name);if(c.owner!=="generic")return te(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(Ro.isJSXAttribute),s=new Map;for(let a of i){let c=JR(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 te(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=Si(a.name,a.value).value;c?c.value=l:o.attributes.push(Si(a.name,a.value))}return Be(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function JR(e){return Ro.isJSXIdentifier(e.name)?e.name.name:Ro.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as XR}from"@vcp-dev/contracts";import*as oe from"@babel/types";var Hg=["prefetch","replace","scroll","locale","onNavigate"],zR=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function HR(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>oe.isJSXAttribute(n)&&oe.isJSXIdentifier(n.name)&&zR.test(n.name.name)))return!0;t=t.parentPath}return!1}function fa(e){let t=We(e.source,"jsx-node");if(!t.ok)return t.result;let n=ko(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=XR.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Yn(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=eC(s.name);if(!a)return Yn(e.source,"Unsupported JSX link tag");if(s.attributes.some(oe.isJSXSpreadAttribute))return Yn(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let p of s.attributes){if(!oe.isJSXAttribute(p))continue;let m=ku(p);if(!m)return Yn(e.source,"Unsupported JSX attribute name");let y=c.get(m)??[];y.push(p),c.set(m,y)}if([...c.values()].some(p=>p.length>1))return Yn(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!QR(l))return Yn(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:YR(o,s.name);if(!u&&!d)return Yn(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&HR(o))return Yn(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=ZR(t.ast,o);if(!p.ok)return Yn(e.source,p.reason);f=p.localName}if(d&&e.link.kind!=="internal-route"){let p=oe.jsxIdentifier("a");s.name=p,i.closingElement&&(i.closingElement.name=oe.jsxIdentifier("a")),qR(t.ast,d,o)}else f&&u&&(s.name=oe.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=oe.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Hg.forEach(p=>g.add(p))):(g.add("href"),e.link.kind==="native-link"&&Hg.forEach(p=>g.add(p))),s.attributes=s.attributes.filter(p=>{if(!oe.isJSXAttribute(p))return!0;let m=ku(p);return!m||!g.has(m)}),e.link.kind!=="none"&&s.attributes.push(oe.jsxAttribute(oe.jsxIdentifier("href"),oe.stringLiteral(e.link.href))),WR(s,e.changes),Be(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function WR(e,t){for(let n of t){let r=e.attributes.find(s=>oe.isJSXAttribute(s)&&ku(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?oe.stringLiteral(n.value):oe.jsxExpressionContainer(Iu(n.value)),i=oe.jsxAttribute(oe.jsxIdentifier(n.name),o);r&&oe.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Iu(e){return e===null?oe.nullLiteral():typeof e=="string"?oe.stringLiteral(e):typeof e=="number"?oe.numericLiteral(e):typeof e=="boolean"?oe.booleanLiteral(e):Array.isArray(e)?oe.arrayExpression(e.map(t=>Iu(t))):typeof e=="object"?oe.objectExpression(Object.entries(e).map(([t,n])=>oe.objectProperty(oe.isValidIdentifier(t)?oe.identifier(t):oe.stringLiteral(t),Iu(n)))):oe.nullLiteral()}function GR(e){return oe.isImportDefaultSpecifier(e)||oe.isImportSpecifier(e)&&e.importKind!=="type"&&(oe.isIdentifier(e.imported,{name:"default"})||oe.isStringLiteral(e.imported,{value:"default"}))}function Wg(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(oe.isIdentifier(e.node.imported,{name:"default"})||oe.isStringLiteral(e.node.imported,{value:"default"}))}function YR(e,t){if(!oe.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Wg(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function ZR(e,t){let n=e.program.body.filter(c=>oe.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(GR);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=oe.importDefaultSpecifier(oe.identifier(s));if(r)r.specifiers.unshift(a);else{let c=oe.importDeclaration([a],oe.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&oe.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function qR(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Wg(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 QR(e){return!e.value||oe.isStringLiteral(e.value)}function eC(e){return oe.isJSXIdentifier(e)?e.name:null}function ku(e){return oe.isJSXIdentifier(e.name)?e.name.name:null}function Yn(e,t){return te(e,"unsupported-syntax",t,"jsx-node")}import*as xt from"@babel/types";import{classifySiteEditPropertyName as Gg}from"@vcp-dev/contracts";function pa(e){let t=Gg(e.name),n=Gg(e.property);if(t.owner!=="generic"||n.owner!=="generic")return te(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Yg(e.object))return te(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return te(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=We(e.source,"jsx-node");if(!r.ok)return r.result;let o=ko(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>xt.isJSXAttribute(l)&&nC(l)===e.name);if(s.length>1)return te(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=tC(e.object,e.property),c=s[0];if(c)c.value=xt.jsxExpressionContainer(a);else{let l=Si(e.name,"");l.value=xt.jsxExpressionContainer(a),i.attributes.push(l)}return Be(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function tC(e,t){return Yg(t)?xt.memberExpression(xt.identifier(e),xt.identifier(t)):xt.memberExpression(xt.identifier(e),xt.stringLiteral(t),!0)}function Yg(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function nC(e){return xt.isJSXIdentifier(e.name)?e.name.name:xt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as oC,identifier as _i,importDeclaration as iC,importDefaultSpecifier as sC,importNamespaceSpecifier as aC,importSpecifier as cC,isImportDefaultSpecifier as Zg,isImportNamespaceSpecifier as qg,isImportSpecifier as Qg,stringLiteral as lC}from"@babel/types";function ln(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!bC(y));if(o!==-1){let y=r[o],b=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return te(t,"unsupported-syntax",`Unsupported import spec kind: ${String(b)}`)}let i=gC(r);if(!i.ok)return te(t,"unsupported-syntax",i.message);let s=We(t);if(!s.ok)return s.result;let{ast:a}=s,c=a.program,l=c.body.filter(y=>y.type==="ImportDeclaration"&&y.source.value===n),u=new Set(l.flatMap(y=>y.specifiers.flatMap(b=>{let S=xC(y,b);return S?[S]:[]}))),d=i.imports.filter(y=>!u.has(ih(y)));if(d.length===0)return Ei(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=hC(c.body),g=d.find(y=>f.has(_u(y)));if(g)return te(t,"unsupported-syntax",`Import local binding already exists: ${_u(g)}`);let p=mC(d);if(p.reduce((y,b)=>y+b.length,0)!==d.length)return te(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of p){if(!rh(th(y)))return te(t,"unsupported-syntax","Unsupported import specifier combination");let b=l.find(S=>uC(S,y));if(b)dC(b,y);else{let S=iC(eh(y),lC(n));yC(c.body,S),l.push(S)}}return Be(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function uC(e,t){return e.importKind==="type"?!1:rh(pC(fC(e),th(t)))}function dC(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Ru(o)));for(let o of eh(t)){let i=Ru(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return oh(e.specifiers),{changed:n}}function eh(e){let t=e.map(n=>{switch(n.kind){case"named":return cC(n.local?_i(n.local):_i(n.imported),_i(n.imported));case"default":return sC(_i(n.local));case"namespace":return aC(_i(n.local));default:return n}});return oh(t),t}function th(e){let t=nh();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 fC(e){let t=nh();for(let n of e.specifiers)Zg(n)?t.defaultLocals.add(n.local.name):qg(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function nh(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function pC(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function rh(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function oh(e){let t=[...e.filter(n=>Zg(n)),...e.filter(n=>qg(n)),...e.filter(n=>Qg(n))];e.splice(0,e.length,...t)}function mC(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 gC(e){let t=new Map,n=new Map;for(let r of e){let o=ih(r);if(t.has(o))continue;let i=_u(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 hC(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(oC(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 yC(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 bC(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 ih(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 _u(e){return e.kind==="named"?e.local??e.imported:e.local}function xC(e,t){return e.importKind==="type"||Qg(t)&&t.importKind==="type"?null:Ru(t)}function Ru(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 Co(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!SC(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return te(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=We(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 Ei(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),Be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>EC(u,d))),l.specifiers.length===0&&a.body.splice(c,1),Be(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function EC(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 SC(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 Ri(e){let{source:t,locator:n,next:r}=e,o=ya(t,n);return o.ok?(o.path.replaceWith(dr(r)),Be(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function ma(e){let{source:t,locator:n,index:r,value:o}=e,i=ya(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?te(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?te(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,dr(o)),Be(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):te(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ga(e){let{source:t,locator:n,index:r}=e,o=ya(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?te(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?te(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),Be(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):te(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function ha(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=ya(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return te(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return te(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 te(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),Be(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function ya(e,t){let n=We(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Ie(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 It from"@babel/types";function ba(e){let t=We(e.source,"value");if(!t.ok)return t.result;let n=Ie(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return te(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>It.isSpreadElement(a)||It.isObjectProperty(a)&&a.computed))return te(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>It.isObjectProperty(a)&&vC(a.key)===e.name);if(o.length>1)return te(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?It.unaryExpression("void",It.numericLiteral(0)):dr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=It.objectProperty(hu(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return Be(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function vC(e){return It.isIdentifier(e)?e.name:It.isStringLiteral(e)?e.value:It.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as IC,isSiteEditRuntimeVoidElementTag as kC}from"@vcp-dev/contracts/site-edit-runtime-capability";function No(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function _C(e,t,n){let r=No(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(E=>({kind:E.kind,message:E.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,f=!d&&kC(u),g=d||IC(u),p=d&&i.childKeys.length>0&&!i.isPublicUiComponent,m=i.textSegments.length>0&&i.textSegments.some(E=>E.editable);f&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(E=>E.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=m&&(!a||i.importedFrom==="next/link"),b=!i.isPublicUiComponent&&!f&&g&&(!a||p);return{composition:r,key:e,canUpdateText:y,canInsertChild:b,canMove:!l,canRemove:!l,constraints:s}}function xa(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,_C(r,e,t));return n}function Cu(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:_e(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=RC(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:_e(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:ah(r),version:{documentVersion:e.route.graph.version,contentHash:_e(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",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?CC(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:sh(e.route.source,o),valueRaw:s?sh(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:ah(o),diagnostics:[]}}function ch(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 RC(e,t){let n=Pn({source:e,profile:Hr({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Ie(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:NC(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function CC(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function lh(e){let t=Pn({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 sh(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function ah(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 NC(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function uh(){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 PC}from"node:crypto";import Ea from"node:fs/promises";import Nu from"node:path";import{setTimeout as AC}from"node:timers/promises";var TC={async mkdir(e,t){await Ea.mkdir(e,t)},async writeFile(e,t,n){await Ea.writeFile(e,t,n)},async rename(e,t){await Ea.rename(e,t)},async rm(e,t){await Ea.rm(e,t)}},wC=new Set(["EACCES","EBUSY","EPERM"]),OC=[10,20,40,80,160];async function LC(e,t,n){for(let r of OC)try{await e.rename(t,n);return}catch(o){if(!FC(o))throw o;await AC(r)}await e.rename(t,n)}function FC(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&wC.has(e.code)}async function Sa(e,t,n=TC){let r=Nu.dirname(e),o=Nu.basename(e),i=Nu.join(r,`.${o}.${process.pid}.${PC()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await LC(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Pu from"@babel/traverse";import*as P from"@babel/types";import*as Le from"@babel/types";function On(e,t={}){if(Le.isTSAsExpression(e)||Le.isTSSatisfiesExpression(e)||Le.isTSNonNullExpression(e)||Le.isTypeCastExpression(e)||Le.isParenthesizedExpression(e))return On(e.expression,t);if(Le.isStringLiteral(e))return{status:"resolved",value:e.value};if(Le.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Le.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Le.isNullLiteral(e))return{status:"resolved",value:null};if(Le.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(Le.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Le.isUnaryExpression(e)&&e.operator==="void"&&Le.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Le.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Le.isSpreadElement(r))return{status:"unresolved"};let o=On(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Le.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Le.isObjectProperty(r)||r.computed||!Le.isExpression(r.value))return{status:"unresolved"};let o=DC(r.key);if(o===null)return{status:"unresolved"};let i=On(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 Le.isMemberExpression(e)||Le.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function DC(e){return Le.isIdentifier(e)?e.name:Le.isStringLiteral(e)?e.value:Le.isNumericLiteral(e)?String(e.value):null}var MC=typeof Pu=="function"?Pu:Pu.default;function At(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 BC(e){return/^[A-Z]/.test(e)}function Lu(e){let t=e.openingElement;return P.isJSXIdentifier(t.name)?t.name.name==="Fragment":P.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function Ao(e){return P.isJSXFragment(e)}function fh(e){return P.isJSXIdentifier(e.name)?e.name.name:P.isJSXMemberExpression(e.name)?ph(e.name):P.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function ph(e){return P.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:P.isJSXMemberExpression(e.object)?`${ph(e.object)}.${e.property.name}`:e.property.name}function jC(e){return e.split(".")[0]??e}function $C(e){let t=e;for(;t;){let n=t.node;if(P.isFunctionDeclaration(n)&&n.id||P.isVariableDeclarator(n)&&P.isIdentifier(n.id))return n.id.name;if(P.isExportDefaultDeclaration(n)){let r=n.declaration;if(P.isFunctionDeclaration(r)&&r.id)return r.id.name;if(P.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function UC(){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 VC(e){let t=new Map;for(let n of e.program.body){if(!P.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(P.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(P.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(P.isImportSpecifier(o)){let i=P.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Zn(e,t=[]){if(P.isIdentifier(e))return t.push(e.name),t;if(P.isObjectPattern(e)){for(let n of e.properties)P.isObjectProperty(n)?Zn(n.value,t):P.isRestElement(n)&&Zn(n.argument,t);return t}if(P.isArrayPattern(e)){for(let n of e.elements)n&&(P.isRestElement(n)?Zn(n.argument,t):Zn(n,t));return t}return P.isAssignmentPattern(e)?(Zn(e.left,t),t):(P.isRestElement(e)&&Zn(e.argument,t),t)}function yn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ci(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 KC(e,t,n){e.set(t,{resolved:!0,value:n})}function Fu(e,t){e.set(t,{resolved:!1})}function mh(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 ht(e,t,n){if(P.isTSAsExpression(e)||P.isTSSatisfiesExpression(e)||P.isTSNonNullExpression(e)||P.isTypeCastExpression(e)||P.isParenthesizedExpression(e))return ht(e.expression,t,n);if(P.isLogicalExpression(e))return va([ht(e.left,t,n),ht(e.right,t,n)]);if(P.isBinaryExpression(e))return va([P.isExpression(e.left)?ht(e.left,t,n):null,P.isExpression(e.right)?ht(e.right,t,n):null]);if(P.isConditionalExpression(e))return va([ht(e.consequent,t,n),ht(e.alternate,t,n)]);if(P.isTemplateLiteral(e))return va(e.expressions.filter(P.isExpression).map(i=>ht(i,t,n)));if(P.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!P.isMemberExpression(e)&&!P.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;P.isMemberExpression(o)||P.isOptionalMemberExpression(o);){if(o.computed)if(P.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(P.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&P.isExpression(o.property)){let i=mr(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(!P.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return P.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:yn(e,t),base:o.name,path:r}:null}function va(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 Du(e,t,n){if(P.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&P.isExpression(r)?ht(r,t,n):null}return P.isCallExpression(e)&&P.isMemberExpression(e.callee)&&!e.callee.computed&&P.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&P.isExpression(e.callee.object)?Du(e.callee.object,t,n):ht(e,t,n)}function mr(e,t){if(P.isStringLiteral(e)||P.isNumericLiteral(e)||P.isBooleanLiteral(e))return e.value;if(P.isNullLiteral(e))return null;if(P.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(P.isIdentifier(e)){let n=Ci(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return;let o=mr(r,t);if(o===void 0)return;n.push(o)}return n}if(P.isObjectExpression(e)){let n={};for(let r of e.properties){if(!P.isObjectProperty(r)||r.computed||!P.isExpression(r.value))return;let o=null;if(P.isIdentifier(r.key)?o=r.key.name:P.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!P.isIdentifier(r.value))return;let s=Ci(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=mr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(P.isMemberExpression(e)){let n=ht(e,"",t);if(!n)return;let r=Ci(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=mh(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(P.isCallExpression(e))return hh(e,t)??void 0}function gh(e,t,n){let r=ht(e,n,t);if(!r)return P.isMemberExpression(e)||P.isBinaryExpression(e)||P.isLogicalExpression(e)||P.isConditionalExpression(e)||P.isCallExpression(e)?{value:yn(e,n),source:null}:null;let o=Ci(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?mh(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 Au(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:UC(),parentStack:[],valueScopes:i,importMap:o}}function wu(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Zn(o.id))Fu(n,s);if(!P.isIdentifier(o.id)||!o.init||!P.isExpression(o.init))continue;let i=mr(o.init,t);i!==void 0&&KC(n,o.id.name,i)}}function JC(e){let t=[];for(let n of e){if(P.isVariableDeclaration(n)){t.push(n);continue}P.isExportNamedDeclaration(n)&&n.declaration&&P.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function XC(e,t,n){let r=[],o=0;for(let i of e)if(P.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:At(i),editable:!0,source:null})}else if(P.isJSXExpressionContainer(i)&&P.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:At(i),editable:!0,source:null});else if(P.isJSXExpressionContainer(i)&&P.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:At(i),editable:!0,source:null}):r.push({index:o++,value:yn(s,n),sourceRange:At(i),editable:!0,source:ht(s,n,t)})}else if(P.isJSXExpressionContainer(i)&&P.isExpression(i.expression)){let s=gh(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:At(i),editable:!0,source:s.source})}return r}function zC(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!P.isJSXAttribute(i))continue;let s=WC(i.name);if(!s)continue;let a=yn(i,n);if(P.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:At(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:At(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(P.isJSXExpressionContainer(i.value)&&P.isExpression(i.value.expression)){let c=mr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?hh(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:At(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=gh(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:tN(c),sourceRange:At(i),source:ht(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=GC(i.value.expression,t),d=ht(i.value.expression,n,t),f=l?.value??yn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:At(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function HC(e,t,n){return e.attributes.flatMap((r,o)=>!P.isJSXSpreadAttribute(r)||!P.isExpression(r.argument)?[]:[{raw:yn(r.argument,n),sourceRange:At(r),order:o,source:ht(r.argument,n,t)}])}function WC(e){return P.isJSXIdentifier(e)?e.name:P.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function GC(e,t){return On(e,{resolveIdentifier(n){let r=Ci(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=mr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function hh(e,t){let n=Po(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Po(e,t){if(P.isStringLiteral(e))return[e.value];if(P.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(P.isNullLiteral(e))return[];if(P.isBooleanLiteral(e))return e.value?null:[];if(P.isIdentifier(e)||P.isMemberExpression(e)){if(P.isIdentifier(e)&&e.name==="undefined")return[];let n=mr(e,t);return typeof n=="string"?[n]:null}if(P.isConditionalExpression(e)){let n=Po(e.consequent,t),r=Po(e.alternate,t);return!n||!r?null:[...n,...r]}if(P.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=mr(e.left,t);return n===!1||n===null?[]:Po(e.right,t)}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return null;let o=Po(r,t);if(!o)return null;n.push(...o)}return n}if(P.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!P.isObjectProperty(r))return null;let o=ZC(r.key);if(!o)return null;n.push(o)}return n}if(P.isCallExpression(e)){let n=YC(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!P.isExpression(o))return null;let i=Po(o,t);if(!i)return null;r.push(...i)}return r}return null}function YC(e){return P.isIdentifier(e)?e.name:P.isMemberExpression(e)&&P.isIdentifier(e.property)?e.property.name:null}function ZC(e){return P.isIdentifier(e)?e.name:P.isStringLiteral(e)?e.value:null}function qC(e,t){let n=e.attributes.find(r=>P.isJSXAttribute(r)&&P.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!P.isJSXAttribute(n)||!P.isJSXExpressionContainer(n.value)?null:n.value.expression}function QC(e,t){for(let n of t){let r=qC(e,n);if(r)return r}return null}function eN(e){return P.isJSXIdentifier(e.name)?e.name.name:null}function tN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function nN(e){if(!P.isCallExpression(e)&&!P.isOptionalCallExpression(e))return null;let t=e.callee;return!P.isMemberExpression(t)&&!P.isOptionalMemberExpression(t)||!P.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!P.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Tu(e){return P.isArrowFunctionExpression(e)||P.isFunctionExpression(e)}function rN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function oN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function dh(e,t,n,r){if(!e||!P.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:yn(e,n),collectionSource:Du(e,n,r)};if(t){let i=t.params[0],s=t.params[1];P.isIdentifier(i)&&(o.itemParamName=i.name),P.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function qn(e,t,n){if(!e)return[];if(P.isJSXElement(e)){if(Lu(e))return Ca(e.children,t,n);let r=_a(e,t,n);return r?[r]:[]}return Ao(e)?Ra(e,t,n):P.isParenthesizedExpression(e)?qn(e.expression,t,n):P.isExpression(e)?Na(e,t,n):[]}function Ia(e,t,n){let r=new Map;for(let o of e.params)for(let i of Zn(o))Fu(r,i);t.valueScopes.push(r);try{if(!P.isBlockStatement(e.body))return qn(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return yh(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function yh(e,t,n){let r=[];for(let o of e){if(P.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){wu([o],t,i);for(let s of o.declarations)P.isIdentifier(s.id)&&(P.isJSXElement(s.init)||P.isJSXFragment(s.init))&&r.push(...qn(s.init,t,n))}continue}r.push(...Ou(o,t,n))}return r}function Ou(e,t,n){if(P.isReturnStatement(e))return e.argument?qn(e.argument,t,n):[];if(P.isBlockStatement(e))return no(e.body,t,n);if(P.isIfStatement(e)){let r=P.isBlockStatement(e.consequent)?no(e.consequent.body,t,n):Ou(e.consequent,t,n),o=e.alternate?P.isBlockStatement(e.alternate)?no(e.alternate.body,t,n):Ou(e.alternate,t,n):[];return[...r,...o]}if(P.isSwitchStatement(e))return no(e.cases.flatMap(r=>r.consequent),t,n);if(P.isTryStatement(e)){let r=no(e.block.body,t,n);return e.handler&&r.push(...no(e.handler.body.body,t,n)),e.finalizer&&r.push(...no(e.finalizer.body,t,n)),r}return[]}function no(e,t,n){let r=new Map;t.valueScopes.push(r);try{return yh(e,t,n)}finally{t.valueScopes.pop()}}function ka(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:At(r),sourceCandidates:i&&i.length>0?i:void 0})}function iN(e,t,n,r){let o=QC(e.openingElement,["items","dataSource","data"]),i={key:t,tag:fh(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!P.isJSXAttribute(s))continue;let a=eN(s);if(!a||!P.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!P.isJSXEmptyExpression(c)){if(rN(a)&&Tu(c)){let l=Ia(c,n,r),u=dh(o,c,r,n);ka(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(oN(a)){let l=Tu(c)?Ia(c,n,r):qn(c,n,r);ka(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!P.isJSXExpressionContainer(s)||!Tu(s.expression))continue;let a=Ia(s.expression,n,r),c=dh(o,s.expression,r,n);ka(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function _a(e,t,n){let r=fh(e.openingElement);if(r==="Fragment"||Lu(e))return Ca(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=BC(r),a;if(s){let E=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${E}`}else{let E=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${E}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=vi(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=XC(e.children,t,n),p=zC(e.openingElement,t,n),m=HC(e.openingElement,t,n),y,b,S=!1;if(s){let E=t.importMap.get(r)??t.importMap.get(jC(r));E&&(y=E.specifier,b=E.exportName,S=Wr(E.specifier,t.file))}let x={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:At(e),parentKey:i,childKeys:[],textSegments:g,attributes:p.length>0?p:void 0,attributeSpreads:m.length>0?m:void 0,boundaryKind:f,isOpaque:s,...S?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:b};return t.elements.set(u,x),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),iN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),sN(e.children,t,n),t.parentStack.pop()),u}function Ra(e,t,n){return Ca(e.children,t,n)}function Ca(e,t,n){let r=[];for(let o of e)if(P.isJSXElement(o))if(Lu(o))r.push(...Ca(o.children,t,n));else{let i=_a(o,t,n);i&&r.push(i)}else Ao(o)?r.push(...Ra(o,t,n)):P.isJSXExpressionContainer(o)&&r.push(...Na(o.expression,t,n));return r}function sN(e,t,n){for(let r of e)P.isJSXElement(r)?_a(r,t,n):Ao(r)?Ra(r,t,n):P.isJSXExpressionContainer(r)&&Na(r.expression,t,n)}function aN(e){return e==="&&"||e==="||"||e==="??"}function Na(e,t,n){if(P.isJSXEmptyExpression(e))return[];let r=nN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:yn(r.collection,n),collectionSource:Du(r.collection,n,t)};if(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];P.isIdentifier(u)&&(c.itemParamName=u.name),P.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:At(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a))&&l.childKeys.push(...Ia(a,t,n)),l.childKeys}if(P.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:yn(e.test,n),conditionSource:ht(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:At(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qn(e.consequent,t,n)),s.childKeys.push(...qn(e.alternate,t,n)),s.childKeys}if(P.isLogicalExpression(e)&&aN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:yn(e.left,n),conditionSource:ht(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:At(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...qn(e.right,t,n)),s.childKeys}if(P.isParenthesizedExpression(e))return Na(e.expression,t,n);if(P.isJSXElement(e)){let o=_a(e,t,n);return o?[o]:[]}return Ao(e)?Ra(e,t,n):[]}function cN(e){let t=e.argument;return t&&(P.isExpression(t)||Ao(t))?t:null}function Ni(e,t){let n=[];for(let r of e){if(P.isReturnStatement(r)){let o=cN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(P.isIfStatement(r)){let o=P.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...Ni(o,r.test)),r.alternate){let i=P.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ni(i,r.test))}continue}if(P.isSwitchStatement(r))for(let o of r.cases){let i=o.test?P.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...Ni(o.consequent,i))}}return n}function Pa(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function bh(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(f=>f.specifier);if(!P.traverseFast(r,f=>{if(P.isJSXElement(f)||P.isJSXFragment(f))return P.traverseFast.stop}))return{graph:Pa(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=VC(r);MC(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=$C(f);if(!g)return;let p=f.node,m=[];if(P.isArrowFunctionExpression(p))P.isExpression(p.body)||Ao(p.body)?m=[{argument:p.body,statement:P.returnStatement(P.isExpression(p.body)?p.body:null)}]:P.isBlockStatement(p.body)&&(m=Ni(p.body.body));else{let k=p.body;P.isBlockStatement(k)&&(m=Ni(k.body))}if(m.length===0){f.skip();return}let y=new Map;wu(JC(r.program.body),Au(t,g,s,a,u,[y]),y);let b=new Map;for(let k of p.params)for(let v of Zn(k))Fu(b,v);let S=P.isBlockStatement(p.body)?p.body.body:[],x=m[0]?.statement??null;for(let k of S){if(x&&k===x)break;P.isVariableDeclaration(k)&&wu([k],Au(t,g,s,a,u,[y,b]),b)}let E=Au(t,g,s,a,u,[y,b]);for(let k of m){let v=qn(k.argument,E,n);for(let I of v)c.includes(I)||c.push(I);if(k.condition){let I={kind:"conditional-branch",conditionExpression:yn(k.condition,n),conditionSource:ht(k.condition,n,E)};ka(E,"conditional-region","",k.statement,v,[I])}}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 Mu(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Aa(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function xh(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 Ta(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??De,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=b=>{let S=`${b.path}\0${b.code}\0${b.message}\0${JSON.stringify(b.details??{})}`;f.has(S)||(f.add(S),d.push(b))},p=[{file:e,source:t,depth:0,diagnosticEntryFile:e,importStack:[]},...(o.additionalEntries??[]).map(b=>({file:b.file,source:b.source,depth:0,diagnosticEntryFile:b.file,importStack:[]}))],m=new Set;for(;p.length>0;){let b=p.shift(),{file:S,source:x,depth:E,diagnosticEntryFile:k,importStack:v}=b;if(m.has(S))continue;m.add(S),c.set(S,x);let I=o.validationOnly&&E<i?o.validatedImports?.(S,x):void 0,N,A;if(I)N=Pa(S),A=I;else{let $=a(S,x);if(!$.ok){g(Aa($.diagnostic,k,v));continue}u.set(S,$.module);let W=o.validationOnly&&E<i?{graph:Pa(S),localImports:$.module.imports.map(ee=>ee.specifier)}:bh($.module);N=W.graph,A=W.localImports}let w=[...new Set([...N.elements.values()].map($=>$.importedFrom).filter($=>typeof $=="string"&&Qe($)))],L=w.length?await xh(w,$=>Js(S,$,r)):[],B=new Map(w.map(($,W)=>[$,L[W]]));for(let $ of N.elements.values())if($.importedFrom&&Qe($.importedFrom)){let W=$.importedFrom,ee=B.get(W);ee.ok?($.importedFrom=ee.path,Hn(ee.path)&&($.isPublicUiComponent=!0)):Wr(W,S)||g(Aa(ee.diagnostic,k,Mu(v,S,W,ee.diagnostic.path)))}if(l.set(S,N),E>=i)continue;let J=await xh(A,async $=>{if(Qm($))return null;let W=B.get($)??await Js(S,$,r);if(!W.ok)return Wr($,S)?null:{diagnostic:Aa(W.diagnostic,k,Mu(v,S,$,W.diagnostic.path))};let ee=W.path;if(m.has(ee)||Hn(ee))return null;let Ge=Mu(v,S,$,ee);try{let tt=await n(ee);return{entry:{file:ee,source:tt,depth:E+1,diagnosticEntryFile:k,importStack:Ge}}}catch(tt){return{diagnostic:Aa({path:ee,code:"import-read-failed",message:`Failed to read imported file: ${ee}`,details:{fromFile:S,specifier:$,reason:tt instanceof Error?tt.message:String(tt)}},k,Ge)}}});for(let $ of J)$&&"entry"in $?p.push($.entry):$&&g($.diagnostic)}let y=lN(e,l,s,(o.additionalEntries??[]).map(b=>b.file));return y.diagnostics=d,{graph:y,allSources:c,diagnostics:d,parsedModules:u,entryModule:u.get(e)??null}}function lN(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 Eh(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 BN}from"@vcp-dev/contracts";import{createHash as uN,randomUUID as Hu}from"node:crypto";import it from"node:fs/promises";import at from"node:path";var Ah=new WeakMap;function To(e){return Ah.get(e)?.()??e.readIndex()}var un=1,ju=1,dN=2,fN="index.json",pN="recovery.json",mN="transaction-journal.json",gN="document-version.json",La={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},be={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"},Ee=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Qn(){return{entries:new Map,blobSizes:new Map}}function wa(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)Th(n,r,t);return n}function Th(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 wh(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 Oh(e,t={}){let n=wN(e),r=DN(t.limits),o=Bu(n),i=ON(n),s=await Bt(i),a=await Bt(o)||s;a||(await kN(n),await _N(n)),a||await MN(n);let c=Qn(),l=await Da(n,c),u=new Set(a?(await Ua(n)).map(S=>S.stageId):[]);a||await _h(n,l.entryIds,c);let d=l.digest,f=wa(l.entryIds,c),g=async S=>{let{index:x,sizeBytes:E}=await Oi(n);if($h(x,S),x.digest!==d){let k=Qn();await Mh(n,x.entryIds,k,E),f=wa(x.entryIds,k),d=x.digest}return{...Va(x),totalBytes:f.objectBytes+E}},p=async S=>{Wu(S),await g(),await Ih(n,f,[S.entryId],S.blobIds,S.stageId),await Fa(n,S.stageId)},m=async(S,x)=>{let E=await g(x);Fh(S,E.entryIds.length);let k=Qn();for(let v of E.entryIds.slice(Math.min(E.cursor,S)+1,Math.max(E.cursor,S)+1))await Ai(n,v,k);return E},y=async()=>{if(await Bt(o)||s)throw new Ee(be.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},b={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Nh(n)},async writeDocumentVersion(S){if(await y(),!Number.isInteger(S)||S<0)throw new Ee(be.INVALID_SCHEMA,"document version must be a non-negative integer");let x=await Nh(n);S<=x||await Pi(Jh(n),{schemaVersion:1,version:Math.max(x,S)})},async stageAppend(S,x={}){await y();let E=await bN(S,r),k={schemaVersion:ju,stageId:Hu(),entryId:E.entryId,blobIds:E.blobs.map(v=>v.digest)};try{await xN(n,E),await SN(n,k,x.durableManifest!==!1)}catch(v){try{await p(k)}catch(I){throw new Ee(be.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:I})}throw v}return{stageId:k.stageId,entryId:k.entryId,blobIds:k.blobIds}},async discardStage(S){await y(),Vu(S);let x=await $u(n,S);x&&await p(x)},async previewStagedAppend(S,x){await y();let E=await g(x);return(await Sh(n,r,S,E,f)).transition},async previewCursor(S,x){await y();let E=await m(S,x);return Lh(E,E.entryIds,S)},async publishStagedAppend(S,x,E){if(await y(),Ba(S,"entryId"),E){Vu(E);let A=await $u(n,E);if(!A||A.entryId!==S)throw new Ee(be.INVALID_SCHEMA,"history stage does not match the published entry")}let k=await g(x),v=f,I=await Sh(n,r,S,k,v),N=await Ch({rootDir:n,previousDigest:I.current.digest,entryIds:I.entryIds,cursor:I.cursor,readback:async()=>Rh(n,I.usage),afterWrite:async()=>{E?await Fa(n,E):await IN(n,S),await Ih(n,I.usage,[...v.entries.keys()].filter(A=>!I.usage.entries.has(A)),[...v.blobs.keys()].filter(A=>!I.usage.blobs.has(A)))}});return f=I.usage,d=N.digest,N},async append(S){await y();let x=await g(),E=await b.stageAppend(S);try{return await b.publishStagedAppend(E.entryId,x.digest,E.stageId)}catch(k){throw await b.discardStage(E.stageId),k}},async readEntry(S){return Ba(S,"entryId"),Ai(n,S)},async readBlob(S){Ba(S,"blobId");let x=await zh(n,S),E=await Ti(x,be.NOT_FOUND,"blob");return Kh(E,S,x),E},async readIndex(){let S=Qn(),x=await Da(n,S);return f=wa(x.entryIds,S),d=x.digest,x},async readStatus(){let S=await Ma(n);return{canUndo:S.undoIds.length>0,canRedo:S.redoIds.length>0,undoDepth:S.undoIds.length,redoDepth:S.redoIds.length,cursor:S.cursor,recoveryRequired:await Bt(o)||await Bt(i)}},async readUndoRedoIds(){let S=await Ma(n);return{undoIds:S.undoIds,redoIds:S.redoIds,currentId:S.currentId}},async setCursor(S,x){await y();let E=await m(S,x),k=await Ch({rootDir:n,previousDigest:E.digest,entryIds:E.entryIds,cursor:S,readback:async()=>Rh(n,f)});return d=k.digest,k},async markRecoveryRequired(S){await Bt(o)||await Pi(Bu(n),{schemaVersion:un,reason:LN(S),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await it.rm(Bu(n),{force:!0})},async readTransactionJournal(){return await Bt(i)?Oa(i):null},async writeTransactionJournal(S){await y(),Xh(S);try{await Pi(i,S)}catch(E){let k=await Oa(i).catch(()=>null);if(k&&Buffer.from(jt(k)).equals(Buffer.from(jt(S))))return;throw k?new Ee(be.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:E}):E}let x=await Oa(i);if(!Buffer.from(jt(x)).equals(Buffer.from(jt(S))))throw new Ee(be.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(S){let x=await Bt(i)?await Oa(i):null;if(x&&x.transactionId!==S)throw new Ee(be.INVALID_SCHEMA,"transaction journal changed concurrently");try{await it.rm(i,{force:!0})}catch(E){if(!await Bt(i))return;throw E}if(await Bt(i))throw new Ee(be.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let E of u)await Fa(n,E),u.delete(E);await RN(n);let S=Qn(),x=await Da(n,S);await _h(n,x.entryIds,S),f=wa(x.entryIds,S),d=x.digest}};return Ah.set(b,()=>Ma(n)),b}async function Sh(e,t,n,r,o){Ba(n,"entryId");let i=Qn(),s=await Ai(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))wh(a,u);Th(a,s.id,i),c.push(s.id);let l=EN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Lh(r,l.entryIds,l.cursor)}}function Lh(e,t,n){return Fh(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:hN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function hN(e,t){return gr(jt({schemaVersion:un,entryIds:e,cursor:t}))}function Fh(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new Ee(be.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function yN(e){if(!bn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!Jt(e.expectedIndexDigest)||!Jt(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!Jt(n)?!1:t===-1?n===null:Jt(n)}async function bN(e,t){if(!e.kind.trim())throw new Ee(be.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new Ee(be.INVALID_JSON,"history blob name must not be empty");let l=TN(c.data),u=gr(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:un,kind:e.kind,manifest:e.manifest,blobs:r},i=jt({...o}),s=gr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new Ee(be.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function xN(e,t){let n=qu(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=>vh(Qu(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},td(e,c.digest))),vh(n,jt(r),{kind:"entry",digest:t.entryId},ed(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function vh(e,t,n,r){let o=await Xu(e)??(r?await Xu(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new Ee(n.kind==="blob"?be.BLOB_CORRUPT:be.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Uh(e,t)}function EN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+jt(jh(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new Ee(be.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");wh(n,r.shift()),o-=1}}async function SN(e,t,n){Wu(t);let r=Zu(e,t.stageId);if(n){await Pi(r,t);return}await AN(r,t)}async function $u(e,t){let n=await Xu(Zu(e,t));if(n===null)return null;let r=Li(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Wu(r);if(o.stageId!==t)throw new Ee(be.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ua(e){let t=[];for(let n of await $a(Yu(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Vu(r);let o=await $u(e,r);o&&t.push(o)}return t}async function Ih(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 Ua(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 kh(qu(e,a),ed(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await kh(Qu(e,a),td(e,a));await zu(Fi(e)),await zu(Di(e))}async function Fa(e,t){await Uu(Zu(e,t)),await vN(e)}async function vN(e){try{await it.rmdir(Yu(e))}catch(t){if(Mi(t)||bn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function IN(e,t){for(let n of await Ua(e))n.entryId===t&&await Fa(e,n.stageId)}async function Uu(e){if(await it.rm(e,{force:!0}),await Bt(e))throw new Ee(be.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function kh(e,t){await Uu(e),await Uu(t)}function Wu(e){if(!bn(e)||e.schemaVersion!==ju||typeof e.stageId!="string"||!Dh(e.stageId)||!Jt(e.entryId))throw new Ee(be.INVALID_SCHEMA,"history stage schema is invalid");let t=Vh(e.blobIds,"history stage blobIds");return{schemaVersion:ju,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Vu(e){if(!Dh(e))throw new Ee(be.INVALID_PATH,"history stageId must be a UUID")}function Dh(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 _h(e,t,n=Qn()){let r=new Set(t),o=new Set;for(let l of t){let u=await Ai(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ua(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Fi(e),s=await $a(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Ph(l.slice(0,-5));u&&!r.has(u)&&await ja(at.join(i,l))}let a=Di(e),c=await $a(a);for(let l of c){let u=Ph(l);u&&!o.has(u)&&await ja(at.join(a,l))}}async function Da(e,t=Qn()){let{index:n,sizeBytes:r}=await Oi(e),{totalBytes:o}=await Mh(e,n.entryIds,t,r);return{...Va(n),totalBytes:o}}async function Rh(e,t){let{index:n,sizeBytes:r}=await Oi(e);return{...Va(n),totalBytes:t.objectBytes+r}}async function Oi(e){let t=Gu(e),n=await Ti(t,be.NOT_FOUND,"index"),r=Li(Buffer.from(n).toString("utf8"),"index");return{index:CN(r),sizeBytes:n.byteLength}}async function Ma(e){return Va((await Oi(e)).index)}function Va(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:un,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Mh(e,t,n,r){let o=0,i=new Set;o+=r??(await Oi(e)).sizeBytes;for(let s of new Set(t)){let a=await Ai(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 Ai(e,t,n=Qn()){let r=n.entries.get(t);if(r)return r.entry;let o=await FN(e,t),i=await Ti(o,be.NOT_FOUND,"entry"),s=Li(Buffer.from(i).toString("utf8"),`entry ${t}`),a=NN(s);if(a.id!==t)throw new Ee(be.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(gr(jt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new Ee(be.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 zh(e,d),g=await Ti(f,be.NOT_FOUND,"blob");return Kh(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 b=g++;try{d[b]=await u(l[b])}catch(S){f.push({index:b,error:S})}}}),m=await Promise.allSettled(p),y=f.sort((b,S)=>b.index-S.index)[0];if(y)throw y.error;for(let b of m)if(b.status==="rejected")throw b.reason;for(let b=0;b<l.length;b++)n.blobSizes.set(l[b],d[b])}return n.entries.set(t,{entry:a,sizeBytes:i.byteLength}),a}async function Bh(e,t,n){await Pi(Gu(e),jh(t,n))}function jh(e,t){return{schemaVersion:un,digest:gr(jt({schemaVersion:un,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function $h(e,t){if(t!==void 0&&e.digest!==t)throw new Ee(be.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Ch(e){$h(await Ma(e.rootDir),e.previousDigest);let t=gr(jt({schemaVersion:un,entryIds:e.entryIds,cursor:e.cursor}));try{await Bh(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new Ee(be.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Da(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new Ee(be.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function kN(e){await it.mkdir(e,{recursive:!0}),await it.mkdir(Fi(e),{recursive:!0}),await it.mkdir(Di(e),{recursive:!0}),await it.mkdir(wi(e),{recursive:!0})}async function _N(e){await it.rm(wi(e),{recursive:!0,force:!0}),await it.mkdir(wi(e),{recursive:!0})}async function RN(e){let t=wi(e);await it.mkdir(t,{recursive:!0});for(let n of await $a(t))n!=="stages"&&await it.rm(at.join(t,n),{recursive:!0,force:!0})}function CN(e){if(!bn(e))throw new Ee(be.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==un)throw new Ee(be.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Vh(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new Ee(be.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!Jt(o))throw new Ee(be.INDEX_CORRUPT,"index digest is invalid");let i=gr(jt({schemaVersion:un,entryIds:t,cursor:r}));if(o!==i)throw new Ee(be.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:un,digest:o,entryIds:t,cursor:r}}function NN(e){if(!bn(e))throw new Ee(be.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==un)throw new Ee(be.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!Jt(t))throw new Ee(be.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new Ee(be.ENTRY_CORRUPT,"entry kind is invalid");let r=Ju(e.manifest,"entry.manifest"),o=PN(e.blobs);return{id:t,schemaVersion:un,kind:n,manifest:r,blobs:o}}function PN(e){if(!Array.isArray(e))throw new Ee(be.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!bn(t))throw new Ee(be.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new Ee(be.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!Jt(o))throw new Ee(be.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new Ee(be.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Pi(e,t){await Uh(e,jt(t))}async function AN(e,t){let n=at.dirname(e),r=at.basename(e),o=at.join(n,`.${r}.${process.pid}.${Hu()}.tmp`);await it.mkdir(n,{recursive:!0});try{await it.writeFile(o,jt(t),{flag:"wx"}),await it.rename(o,e)}finally{await ja(o)}}async function Uh(e,t){let n=at.dirname(e),r=at.basename(e),o=at.join(n,`.${r}.${process.pid}.${Hu()}.tmp`);await it.mkdir(n,{recursive:!0});try{let i=await it.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await it.rename(o,e),await zu(n)}finally{await ja(o)}}function jt(e){return Buffer.from(JSON.stringify(Ku(e)),"utf8")}function Ku(e){if(Array.isArray(e))return e.map(t=>Ku(t));if(bn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Ku(e[n]);return t}return e}function Li(e,t){try{return JSON.parse(e)}catch(n){throw new Ee(be.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ju(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=>Ju(n,t));if(bn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ju(o,t);return n}break}throw new Ee(be.INVALID_JSON,`${t} must be JSON-serializable`)}function Vh(e,t){if(!Array.isArray(e))throw new Ee(be.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!Jt(n))throw new Ee(be.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ba(e,t){if(!Jt(e))throw new Ee(be.INVALID_PATH,`${t} must be a sha256 digest`)}function Jt(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function gr(e){return`sha256:${uN("sha256").update(e).digest("hex")}`}function TN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Ti(e,t,n){try{return await it.readFile(e)}catch(r){throw new Ee(t,`${n} not found: ${e}`,{cause:r})}}async function Xu(e){try{return await it.readFile(e)}catch(t){if(Mi(t))return null;throw t}}function Kh(e,t,n){if(gr(e)!==t)throw new Ee(be.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Bt(e){try{return await it.access(e),!0}catch(t){if(Mi(t))return!1;throw t}}async function ja(e){try{await it.rm(e,{force:!0,recursive:!0})}catch{}}async function zu(e){try{let t=await it.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function $a(e){try{return await it.readdir(e)}catch(t){if(Mi(t))return[];throw t}}function wN(e){if(typeof e!="string"||e.trim().length===0)throw new Ee(be.INVALID_ROOT,"history store rootDir must be a non-empty string");return at.resolve(e)}function Gu(e){return at.join(e,fN)}function Bu(e){return at.join(e,pN)}function ON(e){return at.join(e,mN)}function Jh(e){return at.join(e,gN)}async function Nh(e){try{let t=await it.readFile(Jh(e),"utf8"),n=Li(t,"document version");if(!bn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new Ee(be.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Mi(t))return 0;throw t}}async function Oa(e){let t=await Ti(e,be.RECOVERY_PENDING,"transaction journal"),n=Li(Buffer.from(t).toString("utf8"),"transaction journal");return Xh(n),n}function Xh(e){if(!bn(e)||e.schemaVersion!==dN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!yN(e.historyTransition)||!Array.isArray(e.files))throw new Ee(be.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!bn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!Jt(t.preDigest)||t.postDigest!==null&&!Jt(t.postDigest))throw new Ee(be.INVALID_SCHEMA,"transaction journal file digest is invalid")}function LN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Fi(e){return at.join(e,"entries")}function Di(e){return at.join(e,"blobs")}function wi(e){return at.join(e,"tmp")}function Yu(e){return at.join(wi(e),"stages")}function Zu(e,t){return at.join(Yu(e),`${t}.json`)}function qu(e,t){return at.join(Fi(e),`${Wh(t)}.json`)}function Qu(e,t){return at.join(Di(e),Wh(t))}function ed(e,t){return at.join(Fi(e),`${t}.json`)}function td(e,t){return at.join(Di(e),t)}async function FN(e,t){return Hh(qu(e,t),ed(e,t))}async function zh(e,t){return Hh(Qu(e,t),td(e,t))}async function Hh(e,t){return await Bt(e)?e:await Bt(t)?t:e}function Wh(e){return e.slice(7)}function Ph(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return Jt(t)?t:null}function bn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mi(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function DN(e){return{maxEntries:e?.maxEntries??La.maxEntries,maxSessionBytes:e?.maxSessionBytes??La.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??La.maxEntryBytes}}async function MN(e){let t=Gu(e);await Bt(t)||await Bh(e,[],-1)}var jN={affectedCompositions:[]};function Qh(e){let t=null,n=new WeakMap;async function r(){return t??=$N(e),t}async function o(i){if(!i)return null;let s=nd(i);return s?UN(e,s):i}return{async prepareAppend(i){let s=await To(e),a=await e.stageAppend(Zh(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 To(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 To(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);Gh(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,wo(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(nd(c.at(-1))!==nd(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Gh(l,i.historyTransition),Object.assign(a,wo(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await To(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,wo(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(Zh(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,wo(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,wo(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 Gh(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 nd(e){return typeof e=="string"?e:e?.historyId}async function $N(e){let t=await To(e);return wo(t)}function wo(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function UN(e,t){let n=await e.readEntry(t),r=VN(n),o=r.provenance??jN;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 Yh(e,n,r.preSnapshots),postSnapshots:await Yh(e,n,r.postSnapshots)}}async function Yh(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(XN(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function Zh(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=KN(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 VN(e){if(!ty(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:ey(t.provenance)}:{},preSnapshots:qh(t.preSnapshots,"preSnapshots"),postSnapshots:qh(t.postSnapshots,"postSnapshots")}}function KN(e){if(e.provenance!==void 0)return ey(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function ey(e){let t=BN.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 qh(e,t){return e.map((n,r)=>{if(!ty(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&&!JN(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 JN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function XN(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function ty(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as zN}from"@vcp-dev/contracts";var ny={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 rd(){let e=zN.safeParse(ny);return e.success?e.data:null}import{randomBytes as HN}from"node:crypto";import Ka from"node:path";import{parse as ly}from"@babel/parser";import WN from"@babel/traverse";import*as uy from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as id,PageResourceArtifactSchema as GN,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as YN,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as ZN,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as qN,parseComponentI18nResourcesJson as QN}from"@vcp-dev/contracts";var sd="{{$INSTANCE}}",eP=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,tP=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,ad="components/site/generated",nP=/\.(?:tsx?|json)$/,rP=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,oP=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],iP=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),od=WN,sP=typeof od=="function"?od:od.default;async function cd(e){let t=GN.safeParse(e.artifact);if(!t.success)return st("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>HN(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=gP(r());if(!i)return st("Random instance suffix must be 8 lowercase hex chars.");let s=`${hP(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let x of n.pages){let E=x.final_route.slice(1);a.set(x.template_page_id,x.final_route),c.set(x.template_page_id,x.title),l.push({template_page_id:x.template_page_id,title:x.title,final_route:x.final_route,route_file_path:`app/${E}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,p=new Map,m=[],y=new Set(n.pages.flatMap(x=>x.components.map(E=>E.component_id)));for(let x of n.components){if(!y.has(x.component_id))continue;let E=ry({materialization:x.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!E.ok)return E;for(let k of E.files){let v=iy(k,d,u);if(v)return v}f.add(E.entry),p.set(E.entry,E.entryExport),g.set(x.component_id,E.entry)}for(let[x,E]of n.pages.entries()){let k=l[x],v=ry({materialization:E.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:k.route_file_path,pageTitle:k.title});if(!v.ok)return v;for(let I of v.files){let N=iy(I,d,u);if(N)return N}f.add(v.entry),p.set(v.entry,v.entryExport),m.push({entry:v.entry,declaredComponentIds:new Set(E.components.map(I=>I.component_id))})}let b=cP(u,f,s,g,m,p);if(!b.ok)return b;for(let x of u)if(await e.exists(x.file))return!x.file.startsWith("app/")&&o>1?cd({...e,randomHex:r,maxAttempts:o-1}):{ok:!1,code:"MATERIALIZATION_CONFLICT",message:`Page resource create-only target already exists: ${x.file}`,path:x.file};let S=lP(u);return S||(u.sort((x,E)=>x.file.localeCompare(E.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function ry(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:oy(o.pathTemplate,e.packageInstanceId);if(!s)return st("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=aP(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?dP(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??oy(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?st("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function aP(e,t,n,r){let o,i=e.replace(eP,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return st(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(tP,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return st(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(sd,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?st("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function oy(e,t){let n=`${ad}/${t}`;if(e.split(sd).length>2)return null;let o=e.replace(sd,t),i=`${ad}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Ka.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!nP.test(a)||rP.test(a)?null:a}function iy(e,t,n){return t.has(e.file)?st(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function cP(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${ad}/${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 st("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(id)&&!QN(g.content).success)return st("Materialization component i18n resources are invalid.",g.file);continue}try{let p=ly(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,p);for(let y of p.program.body)if((y.type==="ImportDeclaration"||y.type==="ExportAllDeclaration"||y.type==="ExportNamedDeclaration"&&y.source)&&y.source){let b=y.source.value,S=pP(g.file,b,s,a);if(!S.allowed)return st(`Materialization import is outside the controlled package: ${b}`,g.file);S.internalPath&&c.get(g.file).add(S.internalPath)}let m;if(sP(p,{Identifier(y){y.isReferencedIdentifier()&&iP.has(y.node.name)&&(m??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(m??="style element",y.stop())}}),m)return st(`Materialization source uses forbidden capability: ${m}`,g.file)}catch{return st("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return st("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return st("Materialization JSON files cannot be package entries.");for(let[g,p]of i){let m=l.get(g);if(!m||!uP(m,p))return st("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=cy(g.entry,c);for(let m of g.declaredComponentIds){let y=r.get(m);if(!y||!p.has(y))return st(`Page entry does not reach declared component: ${m}`,g.entry)}for(let m of p){let y=u.get(m);if(y&&!g.declaredComponentIds.has(y))return st(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let p of cy(g,c))d.add(p);if(d.size!==e.length)return st("Every materialization file must be reachable from a package entry.");let f=mP(e,l,c);return f||{ok:!0}}function lP(e){if(e.length>YN)return st("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>ZN)return st("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>qN?st("Page resource exceeds the aggregate content byte limit."):null}function uP(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 dP(e,t,n){let r;try{r=ly(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return st("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=sy(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&fP(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=sy(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 sy(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&uy.isExpression(t)?t:null}function fP(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function pP(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=ay(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:oP.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Ka.posix.normalize(Ka.posix.join(Ka.posix.dirname(e),t)),i=ay(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function ay(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 mP(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(id))continue;let i=o.file.slice(0,-id.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return st("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 st("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function cy(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 gP(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function hP(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function st(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as VP}from"node:crypto";import tr from"node:path";import{parse as KP}from"@babel/parser";import JP from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Xa,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as yy,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as XP,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as zP,SiteEditMaterializationSchema as HP,parseComponentI18nResourcesJson as WP}from"@vcp-dev/contracts";import{parse as wP}from"@babel/parser";import OP from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as LP,FormDefinitionIdSchema as FP}from"@vcp-dev/contracts";var fy={colorMixPolicy:"always",includeExtendedColorFunctions:!0},py=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,my=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,yP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,bP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,xP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,EP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,SP=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,vP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,IP=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,kP=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,_P=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,RP=/\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,CP=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,NP=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function ld(e,t){let n=Ja([...dn(e,yP),...dn(e,bP),...dn(e,xP),...dn(e,t.includeRgbBackgroundImage?EP:SP),...t.includeExtendedColorFunctions?[...dn(e,vP),...dn(e,IP)]:[]]),r=Ja([...dn(e,kP),...dn(e,_P)]).filter(o=>t.colorMixPolicy==="always"||py.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...dn(e,RP).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...dn(e,NP).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Ja(dn(e,my)),hardCodedSurfaceOccurrences:TP(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?PP(e):[]}}function PP(e){return Ja(dn(e,CP))}function dn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var dy=160,AP=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function TP(e){let t=new RegExp(my.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=AP.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>dy?`${g.slice(0,dy-1)}\u2026`:g})}return o}function Ja(e){return[...new Set(e)]}var DP=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],MP=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),gy=new Set(["require","module","exports","__dirname","__filename"]),ud=OP,BP=typeof ud=="function"?ud:ud.default;function fd(e,t={}){let n=[],r=jP(t.hostCapabilities),o=ld(e,t.style??fy),i;try{i=wP(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"&&UP(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 BP(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(dd(u.node))},OptionalMemberExpression(u){l(dd(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)&&FP.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&DP.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?$P(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||!MP.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:gy.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:gy.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function jP(e){if(e==null)return null;let t=LP.safeParse(e);return t.success?t.data:null}function $P(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)):hy(n)===hy(o)})}function hy(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function UP(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function dd(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?dd(e.object):null}var Iy="components/site/generated",by="{{$INSTANCE}}",za=5,GP=/^[a-z][a-z0-9-]{0,48}$/,YP=/^[a-f0-9]{8}$/,xy=/\.tsx?$/,ZP=/\.json$/,qP=/\.(?:tsx?|json)$/,QP=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,pd=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),md=JP,eA=typeof md=="function"?md:md.default;function tA(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>yy)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=hA(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=HP.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=pA(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Iy}.`,path:e.generatedRoot}};if(!ky(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=Sy(r.data.files),s=Sy(e.controlledFiles);if(!yA(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>yy)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>XP)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>zP?{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 nA(e){let t=tA(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=ky(e.manifest.instanceBaseName),o=Math.max(1,Math.min(za,e.maxAttempts??za));for(let i=0;i<o;i+=1){let s=mA(e.instanceNameGenerator?.()??VP(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=Ry(n,a),l=rA({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await iA(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 gd(e){let t=Math.max(1,Math.min(za,e.maxAttempts??za));for(let n=0;n<t;n+=1){let r=await nA({...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 rA(e){let t=oA(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Bi({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=Bi({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=hd({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 oA(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 iA(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Bi(e){if(e.pathTemplate.split(by).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(by,e.instanceName),n=gA(t);return n?Ry(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||!qP.test(n)||QP.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 hd(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(ZP.test(g.path)){if(g.path.endsWith(Xa)){let b=WP(g.content);if(!b.success)return er("MATERIALIZATION_DATA_UNSUPPORTED",b.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return er("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let p;try{p=KP(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 m=fd(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),y=aA(m.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,p)}for(let g of t){if(!xy.test(g.path))continue;let p=c.get(g.path),m=null;if(eA(p,{ImportDeclaration(y){let b=Ey({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!b.allowed)m??={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(!b.internalPath&&!cA(y.node.source.value,i,s))m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"External prefab imports must be declared and available in the target host.",file:g.path},y.stop();else if(b.internalPath&&(l.get(g.path).add(b.internalPath),b.internalPath.endsWith(Xa))){let S=uA({importer:g.path,imported:b.internalPath,source:y.node.source.value,ast:p});S.ok?u.get(b.internalPath).add(g.path):(m??=S.error,y.stop())}},ExportAllDeclaration(y){m??={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 b=Ey({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!b.allowed||!b.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(m??={code:"MATERIALIZATION_IMPORT_FORBIDDEN",message:"Static prefab re-exports must resolve within the controlled instance.",file:g.path},y.stop()):b.internalPath&&l.get(g.path).add(b.internalPath)}},CallExpression(y){if(y.node.callee.type==="Import"){m??={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"&&(m??={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"&&(m??={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"&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let b=vy(y.node);b&&pd.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let b=vy(y.node);b&&pd.has(b)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&pd.has(y.node.name)&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){!e.preserveCapturedStyles||y.node.name.type!=="JSXIdentifier"||y.node.name.name!=="style"||sA(y.node.value)||(m??={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"&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&Ha(y.node.value)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&Ha(y.node.value.cooked??y.node.value.raw)&&(m??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},JSXElement(y){let b=y.node.openingElement.name;e.preserveCapturedStyles&&b.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(b.name.toLowerCase())&&(m??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},y.stop())}}),m)return{ok:!1,error:m}}if(r.length===0)return er("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 er("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!xy.test(g.path))return er("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let p=c.get(g.path);if(!p)return er("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!dA(p,g.export))return er("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 er("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 fA(g.path,l))f.add(p);return f.size!==t.length?er("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Ha(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function sA(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Ha(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Ha(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function aA(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 Ey(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=tr.posix.normalize(tr.posix.join(tr.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 cA(e,t,n){if(n===null)return!0;let r=lA(e);return r===null||t.has(r)&&n.has(r)}function lA(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 uA(e){let t=tr.posix.dirname(e.importer),n=tr.posix.dirname(e.imported),r=tr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=tr.posix.basename(e.imported).slice(0,-Xa.length),i=`./${r}${Xa}`;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 dA(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 fA(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 er(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function pA(e){let t=_y(e);return t===Iy?t:null}function mA(e){let t=e.trim().toLowerCase();return YP.test(t)?t:null}function ky(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 GP.test(t)?t:null}function _y(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=tr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function gA(e){let t=_y(e);return!t||t!==e?null:t}function Ry(...e){return tr.posix.join(...e)}function Sy(e){return new Set(e.map(t=>t.pathTemplate))}function hA(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 yA(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function vy(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 Kd}from"node:crypto";import Dd from"@babel/traverse";function yd(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}}function Wa(e){if(e.node.alternate||!bA(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,c=a.type==="Identifier"?a.name:a.value,l=s.path.parentPath;return!!(c==="notFound"&&l?.isImportDeclaration()&&l.node.importKind!=="type"&&l.node.source.value==="next/navigation")}function bA(e){let t=Cy(e);return e.traverse({enter(n){Cy(n)||(t=!1,n.stop())}}),t}function Cy(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as VA}from"node:crypto";import By from"node:path";import*as Fo from"@babel/parser";import Rd from"@babel/traverse";import Cd from"@babel/generator";import*as de from"@babel/types";import vd from"@babel/generator";import{parse as PA}from"@babel/parser";import Id from"@babel/traverse";import*as Pe from"@babel/types";import{PortableInvocationBindingSchema as AA}from"@vcp-dev/contracts";import bd from"@babel/traverse";import*as Ae from"@babel/types";var Ny=typeof bd=="function"?bd:bd.default;function Xt(e){let t=Ay(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Py(t,e.allowNonRenderingGuards):hr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function yr(e){let t=xA(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Py(t.definition):t.kind==="imported"?!e.imported?.module&&!Qe(t.specifier)?hr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?Xt({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):hr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):hr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):hr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Py(e,t=!1){let n=kA(e.module.ast,e.node);if(!n)return hr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=Ty(n,t);if(!r){let s=RA(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:hr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=wy(r);return Ya(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:hr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function xA(e,t,n){let r={kind:"unresolved"};return Ny(e.ast,{JSXElement(o){if(!vA(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Ae.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(EA(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=SA(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function EA(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function SA(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&Sd(t.node)?t.node:null}function vA(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function Ay(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=cr(e.file,u,n),g=f?n.get(f):void 0;return g?Ay(g,d,n,i):null},a=u=>{let d=IA(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Ae.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Ae.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Ae.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,Ga(g.imported))}}return null};for(let u of e.ast.program.body){if(Ae.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(Sd(d))return{node:d,name:NA(d)??"default",module:e};if(Ae.isIdentifier(d))return a(d.name)}if(!(!Ae.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=CA(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Ae.isExportSpecifier(d)&&d.exportKind!=="type"&&Ga(d.exported)===t)return u.source?s(u.source.value,Ga(d.local)):a(Ga(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Ae.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 IA(e,t){for(let n of e.ast.program.body){let r=Ae.isExportNamedDeclaration(n)?n.declaration:n;if(Ae.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Ae.isVariableDeclaration(r)){for(let o of r.declarations)if(Ae.isIdentifier(o.id)&&o.id.name===t&&Sd(o.init))return{node:o.init,name:t}}}return null}function kA(e,t){let n=null;return Ny(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function Ty(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||_A(i)||t&&i.isIfStatement()&&Wa(i))?null:o.get("argument")}function _A(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Ae.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function RA(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=xd(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Ae.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(c=>!Ae.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Ae.isJSXSpreadAttribute(c)||Ae.isJSXAttribute(c)&&Ae.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function xd(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>xd(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:xd(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Ya(e,t){if(wy(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&Ze(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Ya(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()||Ya(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Ya(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Ed(e){return["base","link","meta","script","style","title"].includes(e)}function wy(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Ae.isJSXIdentifier(o)&&Ed(o.name)?(t=!0,!0):Ze(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||!Ae.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=Ty(s);return a!==null&&n(a)}return!1};return n(e)&&t}function CA(e,t){return Ae.isFunctionDeclaration(e)?e.id?.name===t?t:null:Ae.isVariableDeclaration(e)&&e.declarations.some(n=>Ae.isIdentifier(n.id)&&n.id.name===t)?t:null}function Sd(e){return Ae.isFunctionDeclaration(e)||Ae.isFunctionExpression(e)||Ae.isArrowFunctionExpression(e)}function NA(e){return"id"in e&&e.id&&Ae.isIdentifier(e.id)?e.id.name:null}function Ga(e){return Ae.isIdentifier(e)?e.name:e.value}function hr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var kd=typeof vd=="function"?vd:vd.default,Oy=typeof Id=="function"?Id:Id.default,Fy=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),TA=new Set(["sourceOrder","source_order","originalOrder","original_order"]),wA=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"]),OA=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,LA=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function xr(e){if(!My(e)||!Array.isArray(e.bindings))return br("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=BA(e);if(!t||!LA.test(t))return br("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Dy(e.targetBlockId);if(!n.ok)return n;let r=jA(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!OA.test(o))return br("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=AA.safeParse(f);if(!g.success)return br("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 br("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${d}.propName`);if(a.add(p.propName),TA.has(p.propName))return br("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${d}`);if(Fy.has(p.propName)&&p.value.kind!=="target-block-id")return br("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 br("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(Pe.jsxAttribute(Pe.jsxIdentifier(p.propName),Pe.jsxExpressionContainer(DA(p.value,n.value,o))))}let u=Pe.jsxElement(Pe.jsxOpeningElement(MA(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:kd(u,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,searchParamsIdentifier:c?o:null}}}function FA(e){if(!My(e)||e.jsx===void 0==(e.source===void 0))return Oo("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Dy(e.targetBlockId);if(!t.ok)return Oo("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Oo("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let g=De("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=PA(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return Oo("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=Xt({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});g.ok&&g.roots.length===1&&(s=g.roots[0],i.push(s.node))}else Oy(r,{JSXElement(g){Ly(g)||i.push(g.node)},JSXFragment(g){Ly(g)||i.push(g.node)}});if(i.length!==1)return Oo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=$A(a);if(!c)return Oo("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let l=0,u=0,d=g=>{let p=UA(g.node.name);!p||!wA.has(p)||(p==="data-site-block-id"||p==="data-vcp-block-id"||Fy.has(p)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):Oy(r,{JSXAttribute:d}),c.openingElement.attributes.push(Pe.jsxAttribute(Pe.jsxIdentifier("data-site-block-id"),Pe.stringLiteral(t.value)),Pe.jsxAttribute(Pe.jsxIdentifier("data-site-block-order"),Pe.jsxExpressionContainer(Pe.numericLiteral(e.targetOrder))));let f=n?kd(a,{jsescOption:{minimal:!0}}).code:kd(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:f,jsx:f,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:l,removedSourceOrderCount:u}}}function DA(e,t,n){return e.kind==="route-search-params"?Pe.identifier(n):e.kind==="target-block-id"?Pe.stringLiteral(t):_d(e.value)}function _d(e){return e===null?Pe.nullLiteral():typeof e=="string"?Pe.stringLiteral(e):typeof e=="number"?Pe.numericLiteral(e):typeof e=="boolean"?Pe.booleanLiteral(e):Array.isArray(e)?Pe.arrayExpression(e.map(t=>_d(t))):Pe.objectExpression(Object.entries(e).map(([t,n])=>Pe.objectProperty(Pe.stringLiteral(t),_d(n))))}function MA(e){let t=e.split("."),n=Pe.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Pe.jsxMemberExpression(n,Pe.jsxIdentifier(r));return n}function BA(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 Dy(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 jA(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 $A(e){if(Pe.isJSXElement(e))return e;let t=e.children.filter(Pe.isJSXElement),n=e.children.some(r=>Pe.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Ly(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function UA(e){return Pe.isJSXIdentifier(e)?e.name:null}function My(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function br(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Oo(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var Pd=typeof Cd=="function"?Cd:Cd.default,KA=typeof Rd=="function"?Rd:Rd.default;function Vi(e){let t=Jy(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Fd(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=zA(n,o),s=nT(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=JA(e);if(i){let p=Ad(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??(Za(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return ji("Route page composition does not expose a verifiable container boundary.");let d=Ui(l),f=$y(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?Ui(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return ji("Route page composition placement does not expose a verifiable anchor boundary.");let p=$y(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 Od(e){let t=De(e.entryFile,e.source);if(!t.ok)return Er("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=xn({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 Er("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&&Za(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+Vy(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 Er("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Er("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Vi({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=Ki({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 Er("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=cn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return Er("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=Xy({source:s,step:i.plan.serverParamsStep});if(!l.ok)return Er("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=ln({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}}:Er("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Vy(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Vy(r,t),0)}function Er(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function JA(e){let t=YA(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 Ki(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return ro(e.source,"Root expression rewrite requires an exact expression locator.");let t=gi(e.source,"value");if(!t.ok)return ro(e.source,t.diagnostic.message);let n=Ie(t.ast,e.locator);if(!n.ok)return ro(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return ro(e.source,"Resolved value locator does not point to an expression.");let o=Lo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return ro(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(de.nullLiteral()),{ok:!0,source:Pd(t.ast,{}).code};let i;try{i=Fo.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return ro(e.source,s instanceof Error?s.message:String(s))}return!de.isJSXElement(i)&&!de.isJSXFragment(i)?ro(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(XA(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Pd(t.ast,{}).code})}function XA(e,t,n,r){if(de.isNullLiteral(e)||r)return t;let o=de.isJSXFragment(e)?[...e.children]:[de.isJSXElement(e)?e:de.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return de.jsxFragment(de.jsxOpeningFragment(),de.jsxClosingFragment(),s)}function ro(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Ld(e){let t=Jy(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Zy(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(HA(n,o)){let m=Ad(e);return m.ok?e.operation==="remove-node"&&!jy(n,o.placementUnitKey)?ji("The last editable page unit cannot be deleted."):e.operation==="move-node"?ji("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:m.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:m.locator,sourceHash:m.sourceHash}}}:m.result}let s=Ui(o.sourceRange),a=Tn(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?[]:[$i(a.diagnostic)]}};if(Lo(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 m=Ad(e);return m.ok?jy(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}}}:ji("The last editable page unit cannot be deleted."):m.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||!GA(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=Fd(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=Ui(d),g=Tn(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?[]:[$i(g.diagnostic)]}};if(Lo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Uy("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let m=u.anchorSourceRange,y=u.anchorSourceHash;if(!m||!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 b=Ui(m),S=Tn(e.source,b);return!S.ok||!S.match.node?{ok:!1,error:{code:"UNRESOLVED_ROUTE_ANCHOR",message:S.ok===!1?S.diagnostic.message:"Route page composition target anchor could not be resolved.",diagnostics:S.ok?[]:[$i(S.diagnostic)]}}:Lo(e.source,S.match.node.start??null,S.match.node.end??null)!==y?Uy("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:b,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 jy(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function zA(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Za(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 HA(e,t){return e.container.kind!=="jsx-container"&&Za(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Ad(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Tn(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?[]:[$i(r.diagnostic)]}}}:Lo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Ky("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function $y(e,t,n,r){let o=Tn(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?[]:[$i(o.diagnostic)]}}}:Lo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Ky(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Ky(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ji(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Uy(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function $i(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Jy(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&&!WA(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 WA(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function GA(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function YA(e,t){let n=By.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=By.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ui(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Lo(e,t,n){return t==null||n==null?null:`sha256:${VA("sha256").update(e.slice(t,n)).digest("hex")}`}function Za(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 Xy(e){let t;try{t=Fo.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=ZA(t,e.step);return n.ok?{ok:!0,source:Pd(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function ZA(e,t){let n=Gy(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=wd(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."}:Hy(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=zy(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?Td():qA()),{ok:!0};let i=n.node.params[0],s=wd(i);return s?(QA(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function qA(){return de.objectPattern([de.objectProperty(de.identifier("searchParams"),de.identifier("searchParams"),!1,!0)])}function Td(){let t=Fo.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!de.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!de.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return de.cloneNode(n,!0)}function QA(e,t){let n=de.objectProperty(de.identifier("searchParams"),de.identifier("searchParams"),!1,!0),r=e.properties.findIndex(de.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Wy(e);if(!o){e.typeAnnotation=Td().typeAnnotation;return}if(!de.isTSTypeLiteral(o.typeAnnotation))return;let i=Td().typeAnnotation;if(!i||!de.isTSTypeAnnotation(i)||!de.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!eT(o.typeAnnotation)&&o.typeAnnotation.members.push(de.cloneNode(s,!0))}function eT(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Yy(t.key)==="searchParams")}function tT(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 nT(e){if(!e.invocation)return{ok:!0};let t=xr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return Nd(t.error.message);let n;if(t.plan.requiresRouteSearchParams){let r=rT(e.source,e.entryFile);if(!r.ok)return Nd(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=xr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return Nd(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function Nd(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function rT(e,t){let n;try{n=Fo.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=Gy(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=zy(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function zy(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=wd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Hy(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&&!oT(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function wd(e){return!e||de.isTSParameterProperty(e)?null:de.isObjectPattern(e)?e:de.isAssignmentPattern(e)&&de.isObjectPattern(e.left)?e.left:null}function Hy(e){for(let t of e.properties)if(!(!de.isObjectProperty(t)||t.computed||Yy(t.key)!=="searchParams"))return de.isIdentifier(t.value)?t.value.name:de.isAssignmentPattern(t.value)&&de.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function oT(e){let t=Wy(e);return t?de.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Wy(e){return e.typeAnnotation&&de.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Gy(e){let t=null;return KA(e,{ExportDefaultDeclaration(n){if(t)return;let r=tT(n,n.get("declaration"));r&&(t=r)}}),t}function Yy(e){return de.isIdentifier(e)?e.name:de.isStringLiteral(e)?e.value:null}var iT=typeof Dd=="function"?Dd:Dd.default;function xn(e){if(!e.ast)return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=pT(e.ast);if(!t)return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=gT(t);if(!n.ok)return En(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=yT(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(xT(r,t))return En(e,[yt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Bd(e,t,"virtual-route-root",r);if(bT(r)){let o=IT({input:e,source:e.source,expression:r});return Md(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!Ze(r)&&!Xi(r)){let o=Ud(r),i=eb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Md(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=ST(r);if(!o.ok)return En(e,[o.diagnostic]);let i=Do(o.path);if(i.unsupported)return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(ET(e.source,r,i.members))return Bd(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||Ze(r);if(i.members.length===0&&s)return Bd(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=eb({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Md(e,t,l,{kind:a,sourceKind:c},r)}return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Fd(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:yt("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:yt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function Zy(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:yt("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:yt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function tb(e){return e.ok?sT(e.projection):aT(e.projection)}function sT(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((m,y)=>nb(e,u,m,y,e.container.placementKey)),f=d.filter(({member:m})=>m.isBusinessMember).map(({sourceMember:m})=>lT(l,m,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:m})=>m)),o.set(l,f);let p=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:p,businessMemberKeys:f.map(m=>m.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:cT(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function aT(e){let t=e.diagnostics.map(uT);return{status:"unsupported",version:e.version,composition:e.composition,reason:dT(e.diagnostics),diagnostics:t}}function cT(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 nb(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)=>nb(e,t,a,c,i))]}function lT(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function uT(e){return{code:fT(e),message:e.message}}function dT(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 fT(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 pT(e){let t=null;return iT(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=mT(o.path);i&&(t=i,n.stop())}}),t}function mT(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 gT(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Ji(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:yt("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:yt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:yt("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(!hT(s)&&!Wa(s))return{ok:!1,diagnostic:yt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(rb(s)||ob(s))return{ok:!1,diagnostic:yt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Ji(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:yt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function hT(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(rb(o)||ob(o))return null;return r}function rb(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function ob(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function yT(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=Ji(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 bT(e){return e.isConditionalExpression()?qy(Ji(e.get("consequent")))&&qy(Ji(e.get("alternate"))):!1}function qy(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Ji(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 xT(e,t){if(e.isIdentifier())return Qy(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Qy(n.node.name,t)}return!1}function Qy(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 ET(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&$d(t)}function $d(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(!$d(t))return!1;continue}if(t.isJSXElement()&&!$d(t))return!1}return!0}function ST(e){return{ok:!0,path:e}}function Do(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Vd(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:fn(r.node.loc),businessMemberCount:0,parentSourceRange:fn(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=Do(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Xi(o)?Do(o):null;n||=i?.unsupported??!1,t.push({...Ud(o,i?.members),sourceRange:fn(r.node.loc),parentSourceRange:fn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Vd(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:fn(r.node.loc),businessMemberCount:1,parentSourceRange:fn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&Ze(r)){let o=Do(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Xi(r)?Do(r):null;n||=o?.unsupported??!1,t.push({...Ud(r,o?.members),parentSourceRange:fn(e.node.loc)})}}return{members:t,unsupported:n}}function Ud(e,t){let n=e.isJSXElement()&&Xi(e)?t??Do(e).members:[],r=e.isJSXElement()&&!Xi(e)&&!Ze(e);return{memberKey:Vd(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:fn(e.node.loc),businessMemberCount:r?1:ib(n),parentSourceRange:fn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:vT(e)}}function Xi(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function vT(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 ib(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function qa(e){return e.length===0?0:Math.max(1,ib(e))}function eb(e){let t=fn(e.containerPath.node.loc),n=Jd(e.source,e.containerPath.node.start,e.containerPath.node.end),r=pn(e.input,e.containerKind,e.sourceKind,t),o=pn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:qa(e.members)<=1,memberCount:qa(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function IT(e){let t=fn(e.expression.node.loc),n=Jd(e.source,e.expression.node.start,e.expression.node.end),r=pn(e.input,"virtual-route-root","atomic-expression",t),o=pn(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:pn(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 sb(e,t){let n=fn(t.node.loc),r=Jd(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Md(e,t,n,r,o){let i=sb(e,o);if(!i)return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=kT(e,n,s),c=yd(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:cb(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 kT(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,p,m=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:qa(p)<=1,memberCount:qa(p),sourceRange:f,sourceHash:f?jd(e.source,f):null,relation:l,containerSourceRange:m,containerSourceHash:m?jd(e.source,m):null,anchorSourceRange:g,anchorSourceHash:g?jd(e.source,g):null,members:p}),i=t.placementKey,s=t.members.map(l=>pn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",pn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=pn(e,i,"placement-unit",l.sourceRange);r.push(o("before",pn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",pn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Bd(e,t,n,r){let o=sb(e,r);if(!o)return En(e,[yt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=pn(e,n,"empty-container",void 0),s=pn(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=yd([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:cb(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 En(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 yt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function pn(e,t,n,r){return ab([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Vd(e,t,n){return ab(["member",e,String(t??-1),String(n??-1)])}function ab(e){return`pc_${Kd("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Jd(e,t,n){return t==null||n==null?null:`sha256:${Kd("sha256").update(e.slice(t,n)).digest("hex")}`}function jd(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:${Kd("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function fn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function cb(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 DT}from"node:crypto";import*as Sn from"@babel/types";function lb(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import Xd from"@babel/traverse";import*as Mo from"@babel/types";var RT=typeof Xd=="function"?Xd:Xd.default,CT=32;function Sr(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=CT)return null;let o=new Set(r).add(e.ast),i;if(RT(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=cr(e.file,d,n),p=g?n.get(g):void 0;return p?Sr(p,f,n,o):null},a=d=>{let f=i.scope.getBinding(d);if(!f||f.constantViolations.length)return null;let g=f.path.parentPath;return g?.isImportDeclaration()?g.node.importKind==="type"?null:f.path.isImportDefaultSpecifier()?s(g.node.source.value,"default"):f.path.isImportSpecifier()&&f.path.node.importKind!=="type"?s(g.node.source.value,Qa(f.path.node.imported)):null:f.path.isVariableDeclarator()?f.path.get("init"):f.path},c=[],l=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let f=d.get("declaration");c.push(f.isIdentifier()?a(f.node.name):f)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let f=d.get("declaration");f.node&&Object.hasOwn(Mo.getBindingIdentifiers(f.node),t)&&c.push(a(t));for(let g of d.node.specifiers)Mo.isExportSpecifier(g)&&g.exportKind!=="type"&&Qa(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Qa(g.local)):a(Qa(g.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&l.push(d.node.source.value);if(c.length)return c.length===1?c[0]:null;let u=l.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function Qa(e){return Mo.isIdentifier(e)?e.name:e.value}import*as Se from"@babel/types";var NT=32;function zt(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=NT)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return zi(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return zt(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Hd(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=Ht(e.node.property,e.node.computed),s=e.get("object"),a=zt(s,t,r);return i!==null&&a?nc(a,i,t,r):null}if(e.isConditionalExpression())return zi([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return zi([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?zt(i,t,r):null}if(e.isCallExpression()&&Se.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!Bo(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,c=new Map(t),l=e.get("arguments");for(let[g,p]of a.get("params").entries()){if(!p.isIdentifier())return null;let m=l[g];if(!m?.isExpression())return null;let y=zt(m,t,r);if(!y)return null;let b=p.scope.getBinding(p.node.name);if(!b)return null;c.set(b.identifier,y)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let f=d.isReturnStatement()?d.get("argument"):d;return f.node?zt(f,c,r):null}return[e]}function Hd(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return zi(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=zt(o,t,n);if(!i)return null;let s=zd(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&nc(a,c,t,n),i):null}function ec(e){if(!e.params.every(n=>Se.isIdentifier(n)||Se.isAssignmentPattern(n)&&Se.isIdentifier(n.left)&&oo(n.right)))return!1;if(!Se.isBlockStatement(e.body))return oo(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Se.isReturnStatement(t)&&!!t.argument&&oo(t.argument)}function Bo(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return ec(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Se.isArrowFunctionExpression(n)||Se.isFunctionExpression(n)?ec(n):!1}function oo(e){let t=!0;return Se.traverseFast(e,n=>{(Se.isCallExpression(n)&&!tc(n)||Se.isOptionalCallExpression(n)||Se.isNewExpression(n)||Se.isAwaitExpression(n)||Se.isAssignmentExpression(n)||Se.isUpdateExpression(n)||Se.isUnaryExpression(n,{operator:"delete"})||Se.isYieldExpression(n)||Se.isTaggedTemplateExpression(n))&&(t=!1)}),t}function tc(e){return Se.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Se.isStringLiteral(e.arguments[0])}function zi(e,t,n){let r=[];for(let o of e){let i=zt(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function nc(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(c=>!c.isObjectProperty()||c.node.computed))return null;let a=s.filter(c=>c.isObjectProperty()&&Ht(c.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>Se.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return zi(o,n,r)}function Wd(e,t){let n=zt(e,t);return!!(n?.length&&n.every(r=>Se.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function Ht(e,t){return!t&&Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)||Se.isNumericLiteral(e)?String(e.value):null}function zd(e,t){if(Se.isIdentifier(e))return e.name===t?[]:null;if(Se.isObjectPattern(e))for(let n of e.properties){if(!Se.isObjectProperty(n)||n.computed)continue;let r=Ht(n.key,!1),o=zd(n.value,t);if(r!==null&&o)return[r,...o]}if(Se.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=zd(r,t);if(o)return[String(n),...o]}return null}function ub(e,t=new Set,n){return db(e.get("callee"),t,n)}function db(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let l=i.node.source.value;if(!(l.startsWith(".")||l.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(y=>y.ast.program===u),f=d&&cr(d.file,l,n),g=f?n.get(f):void 0,p=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?Ht(r.path.node.imported,!1):null,m=g&&p&&i.node.importKind!=="type"?Sr(g,p,n):null;return m?jo(m,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=jo(s,o,n);if(a.kind!=="sources")return a;let c=[...a.sources];for(let l of r.constantViolations){if(!l.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=jo(l.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};c.push(...u.sources)}return{kind:"sources",sources:c,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=Ht(e.node.property,e.node.computed),o=e.get("object"),i=zt(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let c of i){if(!c.isObjectExpression())return{kind:"unknown"};if(r===null||c.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let l=c.get("properties").filter(d=>d.isObjectProperty()&&Ht(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=jo(l[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return jo(e,new Set(t).add(e.node),n)}function jo(e,t,n){if(e.isIdentifier())return db(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return jo(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function oc(e,t){return JSON.stringify([t,e])}var AT=new Set;function hb(e,t){let n=new Map,r=[],o=new Map,i=(p,m)=>JSON.stringify([p,m.loc?.start.line,m.loc?.start.column,m.loc?.end.line,m.loc?.end.column]);for(let p of e.graph.elements.values()){let m=p.sourceRange;o.set(JSON.stringify([p.sourceFile,m.startLine,m.startColumn,m.endLine,m.endColumn]),p)}let s=p=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:p}),a=(p,m)=>!gb(m)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===p);function c(p,m,y,b,S,x=AT){if(p.isIdentifier())return b&&rc(p,b)?b.children.some(k=>c(k.path,k.file,y,k.substitution,S,x)):u({path:p,file:m,active:y,substitution:b,unknownIsRelevant:S,aliases:x});if(p.isCallExpression()||p.isOptionalCallExpression()){let k=p,v=ub(k,x,e.parsedModules);return v.kind==="guard"||v.kind==="sources"&&v.sources.some(I=>c(I,[...e.parsedModules.values()].find(N=>N.ast.program===I.scope.getProgramParent().path.node)?.file??m,y,b,S,v.aliases))?!0:k.get("arguments").some(I=>c(I,m,y,b,S,x))||v.kind==="unknown"&&S}if(p.isJSXElement()){if(Ze(p))return p.get("children").some(L=>c(L,m,y,b,S,x));let k=o.get(i(m,p.node));if(k){if(t.has(k.identity.key))return!0;if(k.boundaryKind==="component-boundary"&&!k.isPublicUiComponent){let L=e.parsedModules.get(k.sourceFile);if(!L)return!1;let B=yr({module:L,componentName:k.tag,callSourceRange:k.sourceRange,...k.importedFrom?{imported:{file:k.importedFrom,module:e.parsedModules.get(k.importedFrom),exportName:k.exportName??k.tag,parsedModules:e.parsedModules}}:{}});return B.ok?B.metadataOnly?!1:l(B,p,k.sourceFile,y,b,x):B.diagnostic.code==="component-external-module-opaque"?Hi(p).some(J=>c(J,m,y,b,!1,x)):a(L.file,B.diagnostic.code)}return p.get("children").some(L=>c(L,m,y,b,S,x))}let v=p.node.openingElement.name;if(!Sn.isJSXIdentifier(v))return!1;if(/^[a-z]/.test(v.name))return p.get("children").some(L=>c(L,m,y,b,S,x));let I=e.parsedModules.get(m),N=p.node.loc;if(!I||!N)return!1;let A=FT({path:p,file:m,componentName:v.name,parsedModules:e.parsedModules}),w=yr({module:I,componentName:v.name,callSourceRange:{startLine:N.start.line,startColumn:N.start.column,endLine:N.end.line,endColumn:N.end.column},...A?{imported:A}:{}});return w.ok?w.metadataOnly?!1:l(w,p,m,y,b,x):w.diagnostic.code==="component-external-module-opaque"?Hi(p).some(L=>c(L,m,y,b,!1,x)):a(I.file,w.diagnostic.code)}if(p.isJSXFragment())return p.get("children").some(k=>c(k,m,y,b,S,x));if(p.isJSXExpressionContainer()||p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion())return c(p.get("expression"),m,y,b,S,x);let E=!1;return p.traverse({"CallExpression|OptionalCallExpression"(k){c(k,m,y,b,S,x)&&(E=!0),k.skip(),E&&k.stop()},ReferencedIdentifier(k){c(k,m,y,b,S,x)&&(E=!0),E&&k.stop()},JSXElement(k){c(k,m,y,b,S,x)&&(E=!0),k.skip(),E&&k.stop()},JSXFragment(k){c(k,m,y,b,S,x)&&(E=!0),k.skip(),E&&k.stop()}}),E?!0:S&&!io(p)}function l(p,m,y,b,S,x){let E=`${p.sourceFile}#${p.componentName}`;if(b.has(E))return!1;let k=new Set(b).add(E);return p.returnAlternatives?.some(v=>Hi(v).some(I=>c(I,p.sourceFile,k,null,!1,x)))||p.roots.some(v=>c(v,p.sourceFile,k,null,!1,x))?!0:fb(p.roots).kind==="none"?!1:mb(m).some(v=>c(v,y,k,S,!0,x))}function u(p){if(!p.path.isIdentifier())return p.unknownIsRelevant;let m=lb({path:p.path,aliases:p.aliases});return m.kind==="unbound"?p.unknownIsRelevant&&p.path.node.name!=="undefined":m.kind==="guard"||m.kind==="reassigned"?!0:m.kind==="not-alias"?p.unknownIsRelevant:c(m.initializer,p.file,p.active,p.substitution,p.unknownIsRelevant,m.aliases)?!0:Gd(m.initializer).isIdentifier()?!1:p.unknownIsRelevant&&!io(m.initializer)}let d=(p,m,y,b,S,x)=>{if(p.isIdentifier()){c(p,m,b,x,!1)&&s(m);return}if(p.isJSXElement()){if(Ze(p)){for(let v of p.get("children"))d(v,m,y,b,S,x);return}let E=o.get(i(m,p.node));if(!E)return;let k=E.identity.key;if(t.has(k)){S||s(m);let v=n.get(k)??[];v.push(oc(k,y)),n.set(k,v)}if(E.boundaryKind==="component-boundary"&&!E.isPublicUiComponent){let v=e.parsedModules.get(E.sourceFile);if(!v)return;let I=yr({module:v,componentName:E.tag,callSourceRange:E.sourceRange,...E.importedFrom?{imported:{file:E.importedFrom,module:e.parsedModules.get(E.importedFrom),exportName:E.exportName??E.tag,parsedModules:e.parsedModules}}:{}});if(!I.ok){if(I.diagnostic.code==="component-external-module-opaque"){Hi(p).some(J=>c(J,m,b,x,!1))&&s(m);return}[...t].some(J=>e.graph.elements.get(J)?.sourceFile===v.file)&&!gb(I.diagnostic.code)&&s(v.file);return}if(I.metadataOnly)return;let N=`${I.sourceFile}#${I.componentName}`;if(b.has(N)){s(v.file);return}let A=new Set(b).add(N);I.returnAlternatives?.some(J=>Hi(J).some($=>c($,I.sourceFile,A,x,!1)))&&s(I.sourceFile);let w=fb(I.roots),L=LT(p);if(w.kind==="unproven"||w.kind==="supported"&&L){for(let J of mb(p))if(c(J,m,A,x,!0)){s(m);break}}let B=w.kind==="supported"&&!L?{bindingNode:w.bindingNode,children:p.get("children").map(J=>({path:J,file:m,substitution:x}))}:null;for(let J of I.roots)d(J,I.sourceFile,[...y,k],A,S,B);return}for(let v of p.get("children"))d(v,m,y,b,S,x);return}if(p.isJSXFragment()){for(let E of p.get("children"))d(E,m,y,b,S,x);return}if(p.isJSXExpressionContainer()){let E=p.get("expression");if(x&&!E.isJSXEmptyExpression()){let k=Gd(E);if(rc(k,x)){for(let v of x.children)d(v.path,v.file,y,b,S,v.substitution);return}if(TT(E,x))for(let v of x.children)d(v.path,v.file,y,b,!1,v.substitution)}d(E,m,y,b,S,x);return}if(p.isParenthesizedExpression()||p.isTSAsExpression()||p.isTSNonNullExpression()||p.isTSTypeAssertion()){d(p.get("expression"),m,y,b,S,x);return}c(p,m,b,x,!1)&&s(m),p.traverse({JSXElement(E){d(E,m,y,b,!1,x),E.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=Xt({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!g.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let p of g.roots)d(p,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function Gd(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function io(e){let t=Gd(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||io(n)):t.isConditionalExpression()?io(t.get("consequent"))&&io(t.get("alternate")):t.isLogicalExpression()?io(t.get("left"))&&io(t.get("right")):!1}function rc(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function TT(e,t){if(rc(e,t))return!0;let n=!1;return e.traverse({Identifier(r){rc(r,t)&&(n=!0,r.stop())}}),n}function fb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?pb(n.get("left"),!0):pb(n,!1):{kind:"none"}}function pb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){Ln(i.get("value"))&&(r=!0);continue}let s=i.node.key;(Sn.isIdentifier(s)?s.name:Sn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&Ln(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>Ln(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>wT(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return Ln(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>OT(r))?{kind:"none"}:{kind:"unproven"}}return Ln(e)?{kind:"unproven"}:{kind:"none"}}function Ln(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?Ln(e.get("left")):e.isRestElement()?Ln(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?Ln(t.get("value")):t.isRestElement()?Ln(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?Ln(t):!1):!0}function wT(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function OT(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?Sn.isStringLiteral(n)&&n.value!=="children":Sn.isIdentifier(n)&&n.name!=="children"}function LT(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(Sn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&yb(t.get("argument")))return!0}return!1}function mb(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!Sn.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");yb(r)&&t.push(r)}}return t}function Hi(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function yb(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function FT(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=cr(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":Sn.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function gb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Eb(e){let t=[],n=[];return Sb(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Sb(e,t,n,r,o,i,s,a,c,l=[]){if(l.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){c.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(Ed(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=yr({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){c.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let f=d.sourceFile,g=`${f}#${d.componentName}`;if(s.has(g)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:f,structuralPath:e.identity.structuralPath});return}let p=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...l.length>1?{alternativeLocators:l.map(S=>({key:S.identity.key,structuralPath:S.identity.structuralPath,sourceRange:S.sourceRange}))}:{}}],m=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let b=[];for(let S of d.returnAlternatives??[]){let x=xb(S),E=x?bb(t.graph,f,x):[];if(E.length!==1){c.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:f});return}b.push(E[0])}for(let S of d.roots){let x=xb(S),E=x?bb(t.graph,f,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:f,structuralPath:e.identity.structuralPath});continue}Sb(E[0],t,p,m,d.roots.length>1?E[0]:o,d.roots.length>1?p:i,y,a,c,b)}}function bb(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 xb(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 ic(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Ib(e.projection.composition,e.composition)||e.graph.composition&&!Ib(e.graph.composition,e.composition))return{roots:[],diagnostics:[Wi("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Wi("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(Wi("route-member-not-addressable",e.entryFile));continue}let s=BT(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Wi(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=Eb({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=hb(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=oc(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(Wi("render-occurrence-unproven",i.element.sourceFile))}return{roots:MT(n,e.composition,o.occurrences),diagnostics:t}}function MT(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:DT("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(oc(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=vb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(vb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function vb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function BT(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 Ib(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Wi(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as jT,SiteEditPageBlockDescriptorSchema as $T,SiteEditSourcePathSchema as _b}from"@vcp-dev/contracts";function sc(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}),kb(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function kb(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}),kb(s,t,n,r,o))}}function Gi(e){let t=[],n={...e.graph,composition:e.composition},r=xa(sc(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=KT(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!_b.safeParse(a.sourceFile).success||!d||!f||!_b.safeParse(d).success){t.push(Yd("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Yd("block-key-ambiguous",a.sourceFile));continue}let g=_e(u.source),p=$T.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:JT(a,e),capabilities:UT(c,r),...VT(c,r)});if(!p.success){t.push(Yd("page-block-descriptor-invalid",a.sourceFile));continue}let m=p.data;o.push(m),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:m,root:a,ownerFile:d,ownerSourceHash:_e(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=jT.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 UT(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 VT(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 KT(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 JT(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 Yd(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Zd from"@babel/traverse";import{BlockRenderRefSchema as XT,SiteEditPageBlockPositionSchema as zT,SiteEditPageBlockTargetSchema as HT}from"@vcp-dev/contracts";var WT=typeof Zd=="function"?Zd:Zd.default;function $o(e,t,n,r){if(!HT.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&&(!XT.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 ac(e,t){if(!zT.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=Rb(n);if(!i)return $t("INVALID_TARGET","The operation owner call site is unavailable.");let s=Cb(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||!GT(Cb(u,Rb(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 Rb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Cb(e,t){if(!t)return;let n=De(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(WT(n.module.ast,{JSXElement(i){let s=qd(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=qd(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=qd(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 GT(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 qd(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 Ab from"node:path";import{SiteEditSourcePathSchema as sw}from"@vcp-dev/contracts";import cc from"node:path";import Qd from"@babel/traverse";import*as vr from"@babel/types";import{SiteEditSourcePathSchema as Nb,SiteEditPageBlockTargetSchema as YT}from"@vcp-dev/contracts";var ZT=typeof Qd=="function"?Qd:Qd.default;function Pb(e){if(!e.operationId)return ut("INVALID_PARAMS","An operationId is required.");if(!YT.safeParse(e.target).success)return ut("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 ut("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return ut("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return ut("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return ut("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Nb.safeParse(t).success)return ut("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return ut("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(_e(n)!==e.binding.ownerSourceHash)return ut("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||_e(r)!==e.binding.descriptor.source.contentHash)return ut("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 ut("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 ut("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return ut("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=QT(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?_o({source:n,locator:qT(e.binding),node:{jsx:i.value.jsx}}):cn({source:n,locator:ef(o.parentLocator),anchorLocator:ef(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return ut("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=ln({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return ut("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 qT(e){return ef(e.ownerLocator)}function ef(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 QT(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}>`}}:ut("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return ut("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=ew(t,e.component.source,r);if(!o)return ut("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=De(t,n);if(!i.ok)return ut("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=tw(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??rw(ow(e.component.exportName,o),nw(i.module.ast)),c=iw(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 ew(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?cc.posix.normalize(cc.posix.join(cc.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=>Nb.safeParse(i).success&&n.has(i))??null:null}function tw(e,t,n){for(let r of e)if(!(!vr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&vr.isImportDefaultSpecifier(o)||n!=="default"&&vr.isImportSpecifier(o)&&(vr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function nw(e){let t=new Set;return ZT(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function rw(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function ow(e,t){let r=(e==="default"?cc.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 iw(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return ut("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return ut("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return ut("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function ut(e,t){return{ok:!1,code:e,message:t}}function Tb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return lc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&sw.safeParse(i.path).success))return lc("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 lc("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 lc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=cw(t,e.materialization.entry.path),r=Pb({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:aw(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 aw(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function cw(e,t){let n=Ab.posix.relative(Ab.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function lc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as xw}from"@vcp-dev/contracts";import H1 from"node:fs";import G1 from"node:path";var lw=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Yi(e){let t=e.map(r=>bw(r.path)),n=uw(t);return n?t.filter(r=>fw(n,r)).map(r=>({routeId:pw(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function tf(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=yw(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function uw(e){return e.some(r=>r.startsWith("app/")&&!dw(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function dw(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function fw(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return lw.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function pw(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(gw).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function mw(e){return e.startsWith("(")&&e.endsWith(")")}function gw(e){return!e||e.startsWith("@")||e.startsWith("_")||mw(e)?null:hw(e)}function hw(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function yw(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function bw(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Zi=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Ut(e,t={}){throw new Zi("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function nf(e){return xw.safeParse(e).success||Ut("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function wb(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Ut("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Ut("invalid-template-key",{path:e})}return nf(t)!==e&&Ut("noncanonical-template-key",{path:e}),t}function Ew(e){let t=tf(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("(")||Sw(r)&&!Ob(r)))&&Ut("invalid-public-route",{routeId:e}),t}function Sw(e){return e.includes("[")||e.includes("]")}function Ob(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Lb(e){return e.some(Ob)}function Fb(e,t,n="app"){n!=="app"&&n!=="src/app"&&Ut("invalid-app-root");let r=Ew(e),o=nf(t),i=Lb(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))&&Ut("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Db(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Mb(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===".")&&Ut("invalid-file-path",{path:i}),n.has(i)&&Ut("duplicate-file-path",{path:i}),n.set(i,o)}return n}function dc(e){let t=Mb(e.files),n=Yi([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Zi("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(!Db(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Ut("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Lb(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=wb(u),g=d.length?`/${d.join("/")}`:"/";Fb(g,f,a).templateEntryFile!==i&&Ut("candidate-path-mismatch",{path:i,routeId:g});let m=r.get(g);(!m||!m.startsWith(`${a}/`))&&Ut("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:m,appRoot:a})}return o.sort((i,s)=>uc(i.routeId,s.routeId)||uc(i.templateId,s.templateId))}function fc(e){let t=Mb(e.files),n=dc({files:t}),r=Yi([...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)=>uc(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:uc(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function vw(e){let t=tf(e.selector.routeId),n=fc({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Ut("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||Ut("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function uc(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as Jw}from"@vcp-dev/contracts";import{parse as Dw}from"@babel/parser";import{parse as dX}from"@babel/parser";import{FormBlockIdSchema as pX,FormSpecV1Schema as mX}from"@vcp-dev/contracts";import{posix as oX}from"node:path";import Iw from"@babel/traverse";var rf=Iw,sX=typeof rf=="function"?rf:rf.default,aX=Symbol("unknown-member");var qi="components/site/generated/forms",hX=`${qi}/vcp-form-runtime.tsx`,pc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",yX=new RegExp(`^${qi}/form-(${pc})\\.spec\\.ts$`),bX=new RegExp(`^${qi}/form-(${pc})\\.tsx$`),xX=new RegExp(`^@/${qi}/form-(${pc})$`),EX=new RegExp(`(?:^|/)${qi}/form-(${pc})(?:\\.tsx?)?$`);var SX=Symbol("invalid-literal");import{createHash as kX}from"node:crypto";import{posix as RX}from"node:path";import{parse as NX}from"@babel/parser";import{FormSpecV1Schema as AX}from"@vcp-dev/contracts";var TX=Symbol("dynamic");import{parse as kw}from"@babel/parser";function mc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var _w=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Bb(e){let t=_w.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 Rw(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function jb(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Cw(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function of(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(of);if(t?.type==="ObjectExpression"){let n={};for(let r of mc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=jb(r.key);if(!o)throw new Error("unsupported object key");n[o]=of(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function sf(e,t){let n=[],r=Bb(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=kw(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 mc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of mc(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=Cw(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 mc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=jb(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=Rw(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=of(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 Nw}from"@babel/parser";var $b=["page","anchor","external","email","phone","group","file"],Pw=["link","cta"],Vb=["description","badge","iconKey"],af=["label","targetType","href","role","openInNewTab","nofollow","children",...Vb],Aw=new Set(af);function es(e){return Array.isArray(e)?e:[]}function Qi(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function Tw(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ub(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function cf(e){let t=[],n;try{n=Nw(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 es(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of es(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 es(r.elements).forEach((i,s)=>{let a=Kb(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Kb(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 es(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Tw(l.key);u&&(r[u]=l.value)}let o=Qi(r.label),i=Qi(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!$b.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${$b.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 Vb){if(r[l]===void 0)continue;let u=Qi(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))Aw.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 ${af.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=[];es(r.children.elements).forEach((u,d)=>{let f=Kb(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=Qi(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=Qi(r.role);if(c!==void 0&&(Pw.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Ub(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=Ub(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 ww}from"@babel/parser";function ts(e){return Array.isArray(e)?e:[]}function Jb(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function Ow(e){let t;try{t=ww(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of ts(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of ts(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=Jb(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 lf(e,t){let n=Xb(t);if(!n)return{status:"unsupported",source:e};let r=Ow(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(cf(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=ts(l.elements);for(let[d,f]of u.entries()){if(Fw(f,n)){let p=u[d+1],m=u[d-1],y=f.start,b=f.end;if(typeof y!="number"||typeof b!="number")continue;if(p&&typeof p.start=="number")s.push({start:y,end:p.start});else if(m&&typeof m.end=="number")s.push({start:m.end,end:b});else{let S=/^\s*,/.exec(e.slice(b));s.push({start:y,end:S?b+S[0].length:b})}continue}let g=Lw(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 Lw(e){if(e.type==="ObjectExpression")for(let t of ts(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Jb(t.value)}}function Xb(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function Fw(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of ts(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"&&Xb(n??"")===t}import{estimateNavLabelWidth as UX}from"@vcp-dev/contracts";import{parse as JX}from"@babel/parser";function Fn(e,t){let n;try{n=Dw(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=Wt(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 Wt(N.declarations)){let w=A.id,L=A.init;w?.type==="Identifier"&&typeof w.name=="string"&&L&&(Ir(L)?s.set(w.name,L):L.type==="Identifier"&&typeof L.name=="string"&&a.set(w.name,L.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let A=N.source?.value;if(typeof A!="string")continue;for(let w of Wt(N.specifiers)){let L=w.local;if(!(L?.type!=="Identifier"||typeof L.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(L.name,{source:A,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(L.name,{source:A,exportName:"*"});else if(w.type==="ImportSpecifier"){let B=w.imported,J=B?.type==="Identifier"&&typeof B.name=="string"?B.name:B?.type==="StringLiteral"&&typeof B.value=="string"?B.value:"";J&&i.set(L.name,{source:A,exportName:J})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let L=N.declaration;L&&Ir(L)?c.set("default",L):L?.type==="Identifier"&&typeof L.name=="string"&&c.set("default",L.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let A=N.declaration;if(A?.type==="FunctionDeclaration"){let L=A.id;L?.type==="Identifier"&&typeof L.name=="string"&&c.set(L.name,L.name)}else if(A?.type==="VariableDeclaration")for(let L of Wt(A.declarations)){let B=L.id;B?.type==="Identifier"&&typeof B.name=="string"&&c.set(B.name,B.name)}let w=N.source?.value;for(let L of Wt(N.specifiers)){let B=Wb(L.local),J=Wb(L.exported);if(!(!B||!J))if(typeof w=="string"){let $=`#re-export:${J}`;i.set($,{source:w,exportName:B}),c.set(J,$)}else c.set(J,B)}}let u=new Set,d=[],f=new Set,g=[],p=new Set,m=[],y=new Map,b=!1,S=[],x=new Map,E=new Map,k=(N,A="rendered")=>{let w=Hb(N,i);if(!w)return!1;let L=`${w.source}\0${w.exportName}`;if(A==="uncertain")return!f.has(L)&&!p.has(L)&&(p.add(L),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(L)&&(f.add(L),d.push({source:w.source,export_name:w.exportName}),p.delete(L))){let B=g.findIndex(J=>J.source===w.source&&J.export_name===w.exportName);B>=0&&g.splice(B,1)}return!0},v=(N,A="rendered",w=[])=>{let L=`${A}\0${df(w)}`,B=x.get(N)??new Set,J=E.get(N)??new Set;if(B.has(L)||J.has(A))return;B.add(L),x.set(N,B),J.add(A),E.set(N,J);let $=new Map(s),W=new Map,ee=[],Ge=(fe,nt=!1)=>{if(gc(fe)){if(!nt&&Ir(fe)){if(fe.type==="FunctionDeclaration"){let Me=fe.id;Me?.type==="Identifier"&&typeof Me.name=="string"&&$.set(Me.name,fe)}return}if(fe.type==="VariableDeclarator"){let Me=fe.id,ge=fe.init;Me?.type==="Identifier"&&typeof Me.name=="string"&&ge&&(Ir(ge)?$.set(Me.name,ge):W.set(Me.name,ge))}else if(fe.type==="ReturnStatement"){let Me=fe.argument;Me&&ee.push(Me)}if(fe.type==="CallExpression"){let Me=fe.callee;if(Me?.type==="Import"&&S.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:fe.loc?.start.line??1}),ns(Me)==="cms.forms.getConfig"){let ge=Wt(fe.arguments)[0];ge?.type==="StringLiteral"&&typeof ge.value=="string"&&ge.value.trim()?A==="rendered"?u.add(ge.value.trim()):S.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:fe.loc?.start.line??1}):S.push({code:"rendered-module.dynamic-form-code",message:"Rendered cms.forms.getConfig() requires a non-empty string literal.",file_path:t.filePath??"",line:fe.loc?.start.line??1})}}for(let[Me,ge]of Object.entries(fe))if(Me!=="loc")if(Array.isArray(ge))for(let $e of ge)Ge($e);else Ge(ge)}};Ge(N,!0);let tt=new Set,G=new Set,me=(fe,nt=A,Me=w)=>{if(!(!gc(fe)||Ir(fe))){if(fe.type==="Identifier"&&typeof fe.name=="string"){let ge=W.get(fe.name),$e=`${nt}\0${fe.name}\0${df(Me)}`;ge&&!tt.has($e)&&!G.has(fe.name)?(tt.add($e),G.add(fe.name),me(ge,nt,Me),G.delete(fe.name)):k(fe.name,nt);return}if(fe.type==="CallExpression"){let ge=fe.callee,$e=Wt(fe.arguments),Ct=ns(ge),hn=ge?.type==="Identifier"&&typeof ge.name=="string"?i.get(ge.name):void 0;if(nt==="rendered"&&(Ct==="createElement"||Ct.endsWith(".createElement")||hn?.source==="react"&&hn.exportName==="createElement")&&$e[0]?.type==="StringLiteral"&&$e[0].value==="form"&&(b=!0),ge?.type==="Identifier"&&typeof ge.name=="string"){let Nt=$.get(ge.name);if(Nt){v(Nt,nt,Me);return}}if(ge&&Ir(ge)){v(ge,nt,Me);return}if(jw(ge)){for(let Nt of $e)if(Ir(Nt))v(Nt,nt,Me);else if(Nt.type==="Identifier"&&typeof Nt.name=="string"){let js=$.get(Nt.name);js&&v(js,nt,Me)}return}for(let Nt of $e)$w(Nt)&&S.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Nt.loc?.start.line??1});return}if(fe.type==="JSXElement"){let ge=fe.openingElement,$e=ge?zb(Me,Mw(ge)):Me;me(ge,nt,$e);for(let Ct of Wt(fe.children))me(Ct,nt,$e);return}if(fe.type==="JSXOpeningElement"){let ge=hc(fe.name);nt==="rendered"&&ge==="form"&&(b=!0);let $e=ge?Hb(ge,i):void 0;if(nt==="rendered"&&$e&&typeof fe.start=="number"){let Ct=`${$e.source}\0${$e.exportName}\0${fe.start}`,hn=y.get(Ct);if(!hn){let Nt=Uw(fe).get("formBlockId");hn={source:$e.source,export_name:$e.exportName,start_offset:fe.start,...typeof Nt=="string"?{static_form_block_id:Nt}:{}},y.set(Ct,hn),m.push(hn)}Me.length>0&&(hn.static_render_blockers=zb(hn.static_render_blockers??[],Me))}if(ge&&!k(ge,nt)){let Ct=$.get(ge);Ct?v(Ct,nt,Me):W.has(ge)?me(W.get(ge),nt,Me):Bw(ge)||/^[A-Z]/.test(ge)&&S.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${ge} from a static import.`,file_path:t.filePath??"",line:fe.loc?.start.line??1})}for(let Ct of Wt(fe.attributes))me(Ct,"uncertain",Me);return}if(fe.type==="JSXAttribute"){let ge=fe.value,$e=ge?.type==="JSXExpressionContainer"?ge.expression:ge;$e&&Ir($e)?v($e,"uncertain",Me):me($e,"uncertain",Me);return}for(let[ge,$e]of Object.entries(fe))if(!(ge==="loc"||ge==="closingElement"))if(Array.isArray($e))for(let Ct of $e)me(Ct,nt,Me);else me($e,nt,Me)}},qe=N.body;qe&&qe.type!=="BlockStatement"&&ee.push(qe);for(let fe of ee)me(fe);J.delete(A)},I=c.get(t.exportName);if(typeof I=="string"){let N=I,A=new Set;for(;a.has(N)&&!A.has(N);)A.add(N),N=a.get(N);if(!k(N)){let w=s.get(N);w?v(w):S.push(Gb(t))}}else I?v(I):S.push(Gb(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:m,renders_native_form:b,diagnostics:S}}function df(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function zb(e,t){return[...new Map([...e,...t].map(r=>[df([r]),r])).values()]}function Mw(e){let t=new Map;for(let a of Wt(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Yb(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=hc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:Kw(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=uf(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 Wt(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,uf(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=uf(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 uf(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"&&Wt(e.expressions).length===0)return Wt(e.quasis)[0]?.value?.cooked}}function Hb(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 Bw(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function Ir(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function jw(e){let t=ns(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 $w(e){let t=!1;return ff(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&ns(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Wb(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Gb(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function ns(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=ns(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function Uw(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=Yb(o.name);i&&t.set(i,Vw(o.value))}return t}function Vw(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 Yb(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function Kw(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function ff(e,t){if(gc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)ff(o,t);continue}ff(r,t)}}}function gc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function hc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=hc(t.object),r=hc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function Wt(e){return Array.isArray(e)?e.filter(t=>gc(t)):[]}var Xw="components/site/generated/",rs=[".tsx",".ts",".jsx",".js"];function Zb(e){if(e.expectedUrlPath===Jw)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Yi(Object.keys(e.files).map(m=>({path:m}))).map(m=>m.entryFile)),n=Object.entries(e.files).filter(([m,y])=>{let b=m.replace(/\\/g,"/");if(!t.has(b))return!1;let S=sf(y,b);return S.found&&S.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 m=dc({files:new Map(Object.entries(e.files))});for(let y of m)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(m){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:m instanceof Error?m.message:"Invalid page template source."}}let i=zw(e.files);if(!i.ok)return i.error;let s=i.graph,a=Yw(o,s),c=Zw(o,a,s),l=[...a].filter(m=>!c.has(m)).sort((m,y)=>m.localeCompare(y)),u=[...o,...[...c].sort((m,y)=>m.localeCompare(y))],d=new Set(u),f=u.map(m=>({operation:"delete",file:m})),g=[],p=[];for(let[m,y]of Object.entries(e.files))if(!d.has(m)){if(y.includes("NAV_ITEMS")){let b=lf(y,e.expectedUrlPath);b.status==="removed"?(f.push({operation:"upsert",file:m,content:b.source}),g.push(m)):b.status==="unsupported"&&p.push(`unsupported_navigation:${m}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&p.push(`preserved_link:${m}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:p}}function zw(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")||!Hw(r))continue;let s=De(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(Ww(c))continue;let l=Nn(r,c),u=Gw(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 Hw(e){let t=e.toLowerCase();return rs.some(n=>t.endsWith(n))}function Ww(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!rs.some(n=>e.endsWith(n)))}function Gw(e,t){let n=e.replace(/\\/g,"/");return(rs.some(o=>n.endsWith(o))?[n]:[...rs.map(o=>`${n}${o}`),...rs.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function Yw(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(Xw)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function Zw(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 qx from"@babel/parser";import*as Fe from"@babel/types";import*as Lc from"node:path";import*as Ve from"@babel/types";function qb(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 Dn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return so(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ve.isObjectPattern(n)||Ve.isArrayPattern(n))return so(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(Qw(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function so(e,t,n=!1){return Ve.isIdentifier(e)?e.name===t&&n:Ve.isObjectPattern(e)?e.properties.some(r=>Ve.isObjectProperty(r)?so(r.value,t,n):so(r.argument,t,n)):Ve.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ve.isRestElement(r)?r.argument:r;return so(o,t,n)}):Ve.isAssignmentPattern(e)?so(e.left,t,!0):Ve.isRestElement(e)?so(e.argument,t,n):!1}function Uo(e,t){if(e.path.isObjectPattern()){if(t){let r=vn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Dn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Dn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Qb(r),i=!1,s=o?o.initBinding&&pf(o.initBinding)?(i=Dn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=Uo(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=vn(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||Dn(e)}}}}let n=nO(e);if(n){let r=qw(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||Dn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=eO(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Dn(e)}}let i=os(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Dn(e)}:null}if(pf(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Dn(e)}}return null}function qw(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=Qb(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=pf(i)?(a=Dn(i),[...s]):(()=>{let u=Uo(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=vn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Dn(t)}:null}function Qb(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=rO(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function pf(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function Qw(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function eO(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=vn(i.node,t);if(a)return a}return null}function ex(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=yc(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=os(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=tO(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=os(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 yc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=os(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&vn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=yc(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=yc(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=yc(r,t);if(o)return o}}return null}function vn(e,t,n=[]){if(Ve.isIdentifier(e))return e.name===t?n:null;if(Ve.isObjectPattern(e)){for(let r of e.properties)if(Ve.isObjectProperty(r)){let o=os(r);if(!o)continue;let i=vn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ve.isRestElement(r)){let o=vn(r.argument,t,n);if(o)return o}}if(Ve.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ve.isRestElement(o)?o.argument:o,s=vn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ve.isAssignmentPattern(e)?vn(e.left,t,n):null}function tO(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function nO(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 os(e){return e.computed?null:Ve.isIdentifier(e.key)?e.key.name:Ve.isStringLiteral(e.key)?e.key.value:null}function rO(e){let t=[],n=e;for(;Ve.isMemberExpression(n);){if(n.computed)if(Ve.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ve.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ve.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ve.isIdentifier(n)?{base:n.name,path:t}:null}import*as sx from"@babel/parser";import hf from"@babel/traverse";import*as Vo from"@babel/types";import*as Re from"@babel/types";var tx=new WeakMap;function Ec(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?bc(n,t):null}if(e.isMemberExpression()){let n=lO(e.node),r=oO(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?bc(o,[...r,...t]):null}return e.isAwaitExpression()||gf(e.node)?kr(dO(e.node),t,"awaited or fetched expression"):null}function oO(e){let t=[],n=e;for(;Re.isMemberExpression(n);){if(n.computed)if(Re.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Re.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Re.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Re.isIdentifier(n)?t:null}function bc(e,t=[],n){let r=iO(e,t);if(r)return r;let o=sO(e,t,n);if(o)return o;let i=aO(e,t,n);return i||null}function ss(e){return e?.kind==="api-source"}function iO(e,t){if(e.path.isVariableDeclarator()&&Re.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&mf(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return kr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Re.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Re.isObjectProperty(c)&&ox(c)==="data"&&is(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&mf(a.node))return kr(e.identifier.name,t,"query hook data binding")}let n=cO(e);if(!n||ox(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()||!mf(i.node)?null:kr(e.identifier.name,t,"query hook data binding")}function sO(e,t,n){if(e.path.isVariableDeclarator()&&Re.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!rx(c.node))return null;let[l,u]=e.path.node.id.elements;return!Re.isIdentifier(l)||l.name!==e.identifier.name||!Re.isIdentifier(u)?null:nx(e,u.name,n)?kr(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()||!rx(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Re.isIdentifier(a)&&nx(e,a.name,n)?kr(e.identifier.name,t,"state setter is updated by API data"):null}function aO(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()?kr(e.identifier.name,t,"awaited binding result"):gf(o.node,n)?kr(e.identifier.name,t,"fetch-backed binding result"):null:null}function cO(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 is(e,t){return Re.isIdentifier(e)?e.name===t:Re.isAssignmentPattern(e)?is(e.left,t):Re.isObjectPattern(e)?e.properties.some(n=>Re.isObjectProperty(n)?is(n.value,t):is(n.argument,t)):Re.isArrayPattern(e)?e.elements.some(n=>!!n&&is(Re.isRestElement(n)?n.argument:n,t)):!1}function nx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=tx.get(n);c||(c=new WeakMap,tx.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){gf(c.node)&&(r=!0),(uO(c.node.callee,t)||c.node.arguments.some(l=>Re.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function mf(e){let t=Sc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function rx(e){return Sc(e.callee)==="useState"}function gf(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=xc(e,o=>Re.isCallExpression(o)&&Sc(o.callee)==="fetch");return t?.set(e,r),r}function lO(e){let t=e;for(;Re.isMemberExpression(t);)t=t.object;return Re.isIdentifier(t)?t.name:null}function ox(e){return e.computed?null:Re.isIdentifier(e.key)?e.key.name:Re.isStringLiteral(e.key)?e.key.value:null}function Sc(e){return Re.isIdentifier(e)?e.name:Re.isMemberExpression(e)&&Re.isIdentifier(e.property)?e.property.name:null}function uO(e,t){return xc(e,n=>Re.isIdentifier(n)&&n.name===t)}function xc(e,t){if(t(e))return!0;let n=Re.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(Re.isNode(i)&&xc(i,t))return!0;continue}if(Re.isNode(o)&&xc(o,t))return!0}return!1}function dO(e){return Re.isIdentifier(e)?e.name:Re.isCallExpression(e)?Sc(e.callee)??"api":Re.isAwaitExpression(e)?"awaited-api":"api"}function kr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:fO(e,t),reason:n}}function fO(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var ax=typeof hf=="function"?hf:hf.default;function cx(e,t){let n=ux(e);if(!n)return{allowed:!0};let r=!1;return ax(n,{CallExpression(o){if(!dx(o.node,t.sourceRange)||!pO(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||ss(Ec(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function lx(e,t){let n=ux(e);if(!n)return{allowed:!0};let r=!1;return ax(n,{JSXExpressionContainer(o){dx(o.node,t.sourceRange)&&(Vo.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 ux(e){try{return sx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function pO(e){let t=e.callee;return Vo.isMemberExpression(t)&&Vo.isIdentifier(t.property)&&t.property.name==="map"}function dx(e,t){let n=e.loc;return n?ix({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&ix({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function ix(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 ne from"@babel/types";import*as fx from"@babel/parser";import yf from"@babel/traverse";import*as rt from"@babel/types";import*as Ko from"node:path";var In=typeof yf=="function"?yf:yf.default;function Et(e){try{return fx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function bf(e){return e.computed?rt.isStringLiteral(e.key)||rt.isNumericLiteral(e.key)?String(e.key.value):null:mO(e.key)}function mO(e){return rt.isIdentifier(e)?e.name:rt.isStringLiteral(e)||rt.isNumericLiteral(e)?String(e.value):null}function ao(e){return rt.isParenthesizedExpression(e)||rt.isTSAsExpression(e)||rt.isTSSatisfiesExpression(e)||rt.isTSNonNullExpression(e)||rt.isTSTypeAssertion(e)?ao(e.expression):rt.isExpression(e)?e:null}function xf(e){if(rt.isIdentifier(e))return[e.name];if((rt.isMemberExpression(e)||rt.isOptionalMemberExpression(e))&&!e.computed&&rt.isIdentifier(e.property)){let t=ao(e.object),n=t?xf(t):null;return n?[...n,e.property.name]:null}return null}function co(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Ko.normalize(Ko.join(Ko.dirname(e),t)).replace(/\\/g,"/"):t}function Gt(e,t){return vc(e)===vc(t)}function vc(e){let t=Jo(e);return t.endsWith("/index")?t.slice(0,-6):t}function Jo(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function gx(e,t,n){let r=xx(e,t);if(Ex(e,r),Sx(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 In(e,{JSXElement(s){_x(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Ic(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 hx(e,t){let n=new Map,r=i=>{let s=Xo(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 gO(i,n))o=r(s)||o}return[...n.values()]}function gO(e,t){let n=[],r=hO(e,t);for(let o of e.ast.program.body){if(ne.isExportDefaultDeclaration(o)&&ne.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=as(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(ne.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=co(e.file,o.source.value);for(let s of o.specifiers){if(ne.isExportNamespaceSpecifier(s)){let l=_r(s.exported);for(let u of t.values())Gt(u.file,i)&&n.push({file:e.file,namespace:Ef(l,u.namespace),exportName:u.exportName});continue}if(!ne.isExportSpecifier(s))continue;let a=_r(s.local),c=[...t.values()].filter(l=>Gt(l.file,i)&&lo(l.namespace,a));if(c.length>0){let l=_r(s.exported);for(let u of c){let d=as(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Xo({file:i,exportName:a}))&&n.push({file:e.file,exportName:_r(s.exported)})}continue}if(ne.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!ne.isExportSpecifier(i))continue;let s=_r(i.local),a=r.get(s)??[];if(a.length>0){let c=_r(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=as(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(ne.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=co(e.file,o.source.value),s=o.exported;if(s){let a=_r(s);for(let c of t.values())Gt(c.file,i)&&n.push({file:e.file,namespace:Ef(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Gt(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Ef(e,t){return t?`${e}.${t}`:e}function lo(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function as(e,t,n){return!lo(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function hO(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(!ne.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=co(e.file,i.source.value);for(let a of i.specifiers){if(ne.isImportDefaultSpecifier(a)){let c=t.get(Xo({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Gt(u.file,s)&&lo(u.namespace,"default"));for(let u of l){let d=as(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(ne.isImportSpecifier(a)){let c=_r(a.imported),l=[...t.values()].filter(d=>Gt(d.file,s)&&lo(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Xo({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(ne.isImportNamespaceSpecifier(a))for(let c of t.values())Gt(c.file,s)&&r(a.local.name,{...c,namespace:Ef(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(ne.isVariableDeclaration(i))for(let s of i.declarations){if(!ne.isIdentifier(s.id)||!s.init)continue;let a=ao(s.init);if(!a||!ne.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(Xo));for(let d of c){let f=as(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}:d,p=Xo(g);u.has(p)||(r(s.id.name,g),u.add(p),o=!0)}}}return n}function Xo(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${vc(e.file)}#${t}`}function _r(e){return ne.isIdentifier(e)?e.name:e.value}function yx(e,t){for(let n of e.program.body){if(ne.isExportDefaultDeclaration(n)){let o=n.declaration;if((ne.isFunctionDeclaration(o)||ne.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(ne.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!ne.isExportNamedDeclaration(n))continue;let r=n.declaration;if((ne.isFunctionDeclaration(r)||ne.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(ne.isVariableDeclaration(r)){for(let o of r.declarations)if(ne.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!ne.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:ne.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function vf(e){let t=yO(e),n=[],r=Sx(e.ast,t);return In(e.ast,{JSXElement(o){Gt(e.file,e.sourceFile)&&Ic(o)===e.sourceComponent||_x(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function bx(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function xx(e,t){let n=bx();return In(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function yO(e){let t=bx();return Gt(e.file,e.sourceFile)&&bO(t,xx(e.ast,e.sourceComponent)),In(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=co(e.file,o),s=e.componentIdentities.filter(a=>Gt(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(ne.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),ne.isImportDefaultSpecifier(a)){let l=s.filter(u=>lo(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=mx(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(ne.isImportSpecifier(a)){let l=ne.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>lo(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=mx(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(ne.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)}}}}}),Ex(e.ast,t),t}function bO(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 Ex(e,t){In(e,{VariableDeclarator(n){if(!n.node.init)return;let r=ao(n.node.init);if(r){if(ne.isIdentifier(n.node.id)){let o=uo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Sf(t,i,o);return}if(ne.isObjectPattern(n.node.id)){let o=uo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&kx(n.node.id,o.namespaceMembers,t,n)}}}})}function Sx(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return In(e,{ReferencedIdentifier(r){if(n){r.stop();return}xO(r)||!r.isIdentifier()||!vx(r,t)||EO(r,t)||SO(r)||(n=!0,r.stop())}}),n}function xO(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 vx(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)&&uo(r.node,t,r)?r:null}function EO(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!px(e,r))return!1;let o=vx(e,t);if(!o)return!1;if(ao(r.node)===o.node)return!!uo(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&px(e,a)&&!!uo(a.node,t,a)}function SO(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function px(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function uo(e,t,n){let r=ao(e);if(!r)return null;if(ne.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(ne.isObjectExpression(r))return vO(r,t,n);let o=xf(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?Ix(s,o.slice(1).join(".")):null}function vO(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!ne.isObjectProperty(i))continue;let s=bf(i);if(!s||!ne.isExpression(i.value)){ne.isExpression(i.value)&&(o||=uo(i.value,t,n)!==null);continue}let a=uo(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 Ix(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 Sf(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 kx(e,t,n,r){for(let o of e.properties){if(ne.isRestElement(o)){if(ne.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Sf(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!ne.isObjectProperty(o))continue;let i=bf(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=Ix(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=ne.isAssignmentPattern(o.value)?o.value.left:o.value;if(ne.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Sf(n,c,s);continue}if(ne.isObjectPattern(a)&&s.namespaceMembers.size>0){kx(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function mx(e,t){if(!lo(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 _x(e,t){let n=e.node.openingElement.name;if(ne.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=Rx(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 Rx(e){if(ne.isJSXIdentifier(e))return[e.name];if(ne.isJSXMemberExpression(e)){let t=Rx(e.object);return t?[...t,e.property.name]:null}return null}function Ic(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()&&ne.isIdentifier(n.node.id))return n.node.id.name}return null}function Cx(e,t){let n=Et(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=vf({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 Ue(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 je(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Mn(e,t){let n=je(e);return!!(n&&Yt(t,n))}function Yt(e,t){return t.start>=e.start&&t.end<=e.end}function mn(e,t){let n=Ie(e,Ue(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:kc(e,t)}function zo(e,t){let n=je(t);return n?e.slice(n.start,n.end):""}function Nx(e,t){return e.start===t.start&&e.end===t.end}function kc(e,t){let n=null;return In(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 _c(e,t){return If(e,t).length>0}function Rc(e,t){let n=je(e.node),r=je(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()&&!IO(o,n,r)))return!0;o=o.parentPath}return!1}function IO(e,t,n){let r=je(e.node.consequent);if(r&&Yt(r,t)&&!Yt(r,n))return!1;let o=e.node.alternate?je(e.node.alternate):null;return!(o&&Yt(o,t)&&!Yt(o,n))}function If(e,t){let n=je(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=je(o.node.consequent),a=je(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()&&kf(o.node.operator)){let s=je(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 kf(e){return e==="&&"||e==="||"||e==="??"}function Px(e,t){let n=je(e.consequent);if(n&&Yt(n,t))return n;let r=je(e.alternate);return r&&Yt(r,t)?r:null}function Ax(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=>Jo(a.file)));if(!t.has(Jo(e.sourceFile))||!t.has(Jo(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(Jo(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=yx(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=Et(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=hx(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=vf({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!Gt(s.file,e.targetFile)||Ic(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 PO}from"@vcp-dev/contracts";function Cc(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 cs();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return cs();let u=kO(a,l,o?.instanceCount);if(!u)return cs();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"?cs():{ok:!0,target:{kind:"jsx-attribute"}}}function cs(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function kO(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 Bn from"@babel/types";import{SiteEditSetPropsParamsSchema as _O}from"@vcp-dev/contracts";function Tx(e){let t=e.changes??(e.change?[e.change]:[]);if(!_O.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return ls("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return ls("target-mismatch","A repeat property plan must contain exactly one change for its target property");let r=t[0];if(r.operation==="remove"&&e.target.propertyState==="missing")return{ok:!0,steps:[]};let o=We(e.source,"value");if(!o.ok)return ls("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=Ie(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return ls("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?RO(r):CO(c.match.path.node,r.name);if(!l)return ls("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 RO(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function CO(e,t){let n=e.properties.filter(i=>Bn.isObjectProperty(i)&&NO(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Bn.isExpression(r.value))return null;let o=On(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function NO(e){return Bn.isIdentifier(e)?e.name:Bn.isStringLiteral(e)?e.value:Bn.isNumericLiteral(e)?String(e.value):null}function ls(e,t){return{ok:!1,errorCode:e,reason:t}}function wx(e){if(e.change.name!=="className"&&e.change.name!=="class")return us("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return us("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return us("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return us("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 us("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 us(e,t){return{ok:!1,errorCode:e,reason:t}}async function Lx(e){let t=PO.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 AO(e,r);if(o){if(!o.ok)return Rr("owner-plan-failed",o.reason);Ox(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(OO(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=Cc({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"){_f(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=Tx({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return Rr("repeat-target-failed",l.reason);Ox(n,l.steps);continue}_f(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:TO(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),wO(n)?Rr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function AO(e,t){return t.name!=="className"&&t.name!=="class"?null:wx({node:e.node,change:t,classNameSource:e.classNameSource})}function TO(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 wO(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 Ox(e,t){for(let n of t)_f(e,{...n,order:e.length})}function _f(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 OO(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Rf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Rf(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)=>Rf(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=>Rf(n[i],r[i]))}return!1}function Rr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Wo from"@babel/types";import*as ce from"@babel/types";function Cf(e,t,n){let r=mn(t,n);return r?jn(e,r):null}function jn(e,t){let n=t.findParent(m=>m.isArrowFunctionExpression()||m.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(m=>m===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(!ce.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=zo(e,u.node),f=r.node.params.map(m=>zo(e,m)),g=je(i.node),p=je(r.node);return!d||f.some(m=>m.length===0)||!g||!p?null:{callStart:g.start,callEnd:g.end,callbackStart:p.start,callbackEnd:p.end,collectionExpression:d,callbackParams:f,mapOperator:ce.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:Nc(u.node),callbackPath:r,collectionPath:u}}function ds(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function LO(e,t){let n=je(e.node);return n?FO(t).some(r=>{let o=je(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function FO(e){let t=e.callbackPath.node.body;return ce.isBlockStatement(t)?Cr(t.body):Nr(t)}function Cr(e){let t=[];for(let n of e){if(ce.isReturnStatement(n)){n.argument&&t.push(...Nr(n.argument));continue}if(ce.isBlockStatement(n)){t.push(...Cr(n.body));continue}if(ce.isIfStatement(n)){let r=ce.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...Cr(r)),n.alternate){let o=ce.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...Cr(o))}continue}if(ce.isSwitchStatement(n)){for(let r of n.cases)t.push(...Cr(r.consequent));continue}ce.isTryStatement(n)&&(t.push(...Cr(n.block.body)),n.handler&&t.push(...Cr(n.handler.body.body)),n.finalizer&&t.push(...Cr(n.finalizer.body)))}return t}function Nr(e){return ce.isJSXElement(e)?DO(e)?Fx(e.children):[e]:ce.isJSXFragment(e)?Fx(e.children):ce.isParenthesizedExpression(e)||ce.isTSAsExpression(e)||ce.isTSSatisfiesExpression(e)||ce.isTSNonNullExpression(e)||ce.isTSTypeAssertion(e)?Nr(e.expression):ce.isConditionalExpression(e)?[...Nr(e.consequent),...Nr(e.alternate)]:ce.isLogicalExpression(e)&&kf(e.operator)?Nr(e.right):[]}function Fx(e){return e.flatMap(t=>ce.isJSXElement(t)||ce.isJSXFragment(t)?Nr(t):ce.isJSXExpressionContainer(t)&&(ce.isJSXElement(t.expression)||ce.isJSXFragment(t.expression)||ce.isConditionalExpression(t.expression)||ce.isLogicalExpression(t.expression))?Nr(t.expression):[])}function DO(e){let t=e.openingElement.name;return ce.isJSXIdentifier(t)?t.name==="Fragment":ce.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function Dx(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function Nc(e){return!(ce.isIdentifier(e)||ce.isThisExpression(e)||ce.isMemberExpression(e)||ce.isOptionalMemberExpression(e)||ce.isCallExpression(e)||ce.isOptionalCallExpression(e))}function Mx(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(ce.isMemberExpression(n)||ce.isOptionalMemberExpression(n))&&ce.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function Ho(e,t){let n=Et(e);if(!n)return t.isRepeatItemRoot===!0;let r=Ie(n,Ue(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:kc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=jn(e,o);return i?LO(o,i):t.isRepeatItemRoot===!0}function Bx(e,t){let n=Et(e);if(!n)return!1;let r=Ie(n,Ue(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:kc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(ce.isMemberExpression(s)||ce.isOptionalMemberExpression(s))&&ce.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Xe from"@babel/types";function Nf(e){if(Xe.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Xe.isJSXMemberExpression(e)){let t=e;for(;Xe.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function MO(e,t){let n=je(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Mn(a.path.node,n)||Pr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Nf(i.node.name);s&&o(s,i)}}),[...r].sort()}function Pf(e,t,n){let r=Et(e);if(!r)return{ok:!0};let o=Ie(r,Ue(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Ie(r,Ue(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=ki(o.match.path,i.match.path);if(_c(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=MO(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function $x(e){let t=e;for(;Xe.isTSQualifiedName(t);)t=t.left;return Xe.isIdentifier(t)?t.name:null}function fs(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Pc(e){let t=[],n=r=>{if(r){if(Xe.isIdentifier(r)){t.push(r.name);return}if(Xe.isObjectPattern(r)){for(let o of r.properties){if(Xe.isRestElement(o)){n(o.argument);continue}Xe.isObjectProperty(o)&&n(o.value)}return}if(Xe.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Xe.isAssignmentPattern(r)){n(r.left);return}if(Xe.isRestElement(r)){n(r.argument);return}Xe.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Af(e,t){let n=je(e.node),r=je(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=jx(e),i=jx(t);if(!o||!i||!Nx(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=Px(s.node,n);if(a&&!Yt(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=je(s.node.right);if(a&&Yt(a,n)&&!Yt(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())&&Mx(s)){let a=je(s.node.body)??je(s.node);if(a&&!Yt(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 jx(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?je(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Xe.isJSXElement(t.node.body)||Xe.isJSXFragment(t.node.body)||Xe.isConditionalExpression(t.node.body)||Xe.isLogicalExpression(t.node.body)))return je(t.node.body);t=t.parentPath}return null}function Pr(e,t,n){return n.scope.getBinding(t)===e}function Tf(e,t,n,r={}){if(!r.preserveConditionalBoundary&&_c(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=je(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Pc(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||Mn(u.path.node,o)||i.has(u.path.node)||Pr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Nf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function wf(e,t,n){let r=je(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Pc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return fs(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Mn(a.path.node,r)||o.has(a.path.node)||Pr(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function Ux(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>Pc(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)||Pr(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(Wo.isIdentifier(l))o(l.name,c);else{let u=$x(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Of(e,t){let n=je(e.node),r=new Set;return fs(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Mn(i.path.node,n)||Pr(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 Vx(e){let t=[];for(let n of e.callbackPath.node.params){if(Wo.isIdentifier(n)){t.push(n.name);continue}if(Wo.isRestElement(n)&&Wo.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 Kx(e,t){return{...e,callbackParams:t}}function Lf(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function ps(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 Jx(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 fo(e){return{file:e.file,component:e.component}}function BO(e){return e.target.kind==="node"?e.target.key:null}function jO(e){return"kind"in e&&e.kind==="page-composition"}function wc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Ac(e){return!jO(e)&&!wc(e)}function jf(e,t){let n=Lc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Lc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Ff(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Tn(n,Ue(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Uf(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 $O(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function UO(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 Df(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function VO(e){let t=gx(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Af(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=KO({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=Qx(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?Nc(o):!0}}}function KO(e){let t=je(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||Mn(a.path.node,t))return;let c=zO(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=WO(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=JO(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=Of(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}Pr(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:GO(e.source,t,[...n.values()])}}function JO(e,t){if(t.length===0)return e;let n=Qx(e);if(!n)return null;let r=Nc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=XO(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function XO(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function zO(e,t,n){let r=HO(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=Uo(t,o);if(!i)return null;let s=r?.range??je(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function HO(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Mn(n.node,t)||n.node.computed||!Fe.isIdentifier(n.node.property))return null;let r=je(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function WO(e,t,n){let r=e.get("openingElement").get("attributes");if(r.some(c=>c.isJSXSpreadAttribute()))return{ok:!1,reason:"Cannot move prop-backed repeat child through spread props; use an explicit prop mapping"};let o=r.find(c=>c.isJSXAttribute()&&Fe.isJSXIdentifier(c.node.name)&&c.node.name.name===t);if(!o?.isJSXAttribute())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not passed explicitly`};let i=o.get("value");if(!i.isJSXExpressionContainer())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not an expression`};let s=i.get("expression");if(!s.isExpression())return{ok:!1,reason:`Cannot move prop-backed repeat child because prop '${t}' is not a usable expression`};let a=zo(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 GO(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 Qx(e){try{let n=qx.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Fe.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Fe.isExpression(r)?r:null}catch{return null}}function YO(e){let t=je(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||Mn(s.path.node,t))return;let a=Xx(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=Xx(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!ZO(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 fs(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 ZO(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 Xx(e,t,n){let r=qO(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=co(t,i),a=i.startsWith(".")?jf(n,s):i;if(r.isImportDefaultSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"default",local:c}}}if(r.isImportNamespaceSpecifier()){let c=r.node.local.name;return{localName:c,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"namespace",local:c}}}if(r.isImportSpecifier()){let c=Fe.isIdentifier(r.node.imported)?r.node.imported.name:r.node.imported.value,l=r.node.local.name;return{localName:l,moduleFile:s,moduleSpecifier:a,importSpec:{kind:"named",imported:c,local:l===c?void 0:l}}}return null}function qO(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function zx(e,t,n,r){let o=If(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=zo(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=QO(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${tL(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function QO(e,t){return eL(e.node)?t:`(${t})`}function eL(e){return Fe.isIdentifier(e)||Fe.isThisExpression(e)||Fe.isSuper(e)||Fe.isMemberExpression(e)||Fe.isOptionalMemberExpression(e)||Fe.isCallExpression(e)||Fe.isOptionalCallExpression(e)||Fe.isBooleanLiteral(e)||Fe.isNumericLiteral(e)||Fe.isStringLiteral(e)||Fe.isNullLiteral(e)||Fe.isUnaryExpression(e)}function tL(e){return e.trim().startsWith("<")?e:`(${e})`}var nL={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 Tc(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=nL[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 rL(e,t){for(let n of e.program.body){if(!Fe.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Fe.isImportDefaultSpecifier(o));if(r&&Fe.isImportDefaultSpecifier(r))return r.local.name}return null}function oL(e,t,n){for(let r of e.program.body){if(!Fe.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Fe.isImportSpecifier(i)&&(Fe.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Fe.isImportSpecifier(o))return o.local.name}return null}function Hx(e){let t=new Set;return In(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function Wx(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function iL(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Uf(e),o=Et(t);if(n.exportName!=="default"){let a=o?oL(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?Wx(r,Hx(o)):r;return{localName:c,importStep:Mf(e,c)}}if(!o)return{localName:r,importStep:Mf(e,r)};let i=rL(o,n.source);if(i)return{localName:i};let s=Wx(r,Hx(o));return{localName:s,importStep:Mf(e,s)}}function sL(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Uf(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 aL(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?cL(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function cL(e){return Object.fromEntries(Object.entries(e).filter(t=>$f(t[1])))}function $f(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every($f):typeof e=="object"?Object.values(e).every($f):!1}function Mf(e,t=Uf(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 Gx(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 lL(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Go(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Vf(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function ms(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:Vf(e,t.slice(0,n)),index:r.index}}return null}function Bf(e,t){return e.locator?e.collectionPathMap?.[t]?Vf(e.locator,e.collectionPathMap[t]):ms(e.locator)?dL(e.locator,fL(t,e.collectionIndexMap)):null:null}function uL(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:eE(o,t)}function eE(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=eE(r,t);return o===void 0?void 0:{[n.name]:o}}function dL(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},Vf(e,i)}return null}function fL(e,t){return t?.[e]??e}function Yx(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 pL(e,t){return mL(e.root,t.root)&&hL(e.path??[],t.path??[])}function mL(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&&gL(e.sourceRange,t.sourceRange)}}function gL(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function hL(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 Oc=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:Go(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:Go(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:Go(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:Go(t.kind,t.params.kind)};let r=t;if(wc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Ac(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=Gx(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:Go(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:Go(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=BO(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):Zx(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 Zx(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:Ue(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?Lx({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=Bf(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:Ue(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=Bf(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:Ue(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=Et(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Ie(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!$O(a.match.path))return{ok:!0,value:r};let c=UO(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=Bf(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=Et(this.graph.getFileContent(t));if(!o)return!1;let i=Ie(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=ms(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=ps(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:Ue(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||Cx(n,t)>1)return null;let r=jf(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(!Ac(n.params.position))return wc(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=ps(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=cx(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=Tc(r,n.params.node);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let m=[],y=0,b=n.params.node.kind==="component-call"?iL(n.params.node,this.graph.getFileContent(r.file)):void 0,S=b?.importStep;return S&&m.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:S.moduleSpecifier,imports:S.imports}),m.push({order:y++,file:r.file,type:"insert-child",parentLocator:Ue(r),node:{jsx:sL(n.params.node,b?.localName)},placement:n.params.position.relation,anchorLocator:i?Ue(i):void 0}),this.buildPlan(t,n,m,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Ac(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:aL(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(!Ac(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=ms(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=uL(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"?Yx(0,a.collectionIndexMap):Yx(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=ps(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 Ho(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:")||Bx(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&&Ho(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Et(c);if(!l)return null;let u=mn(l,r),d=mn(l,o);if(!u||!d)return null;let f=jn(c,u),g=jn(c,d);if(!ds(f,g))return null;if(a&&(s==="before"||s==="after")){let m=mn(l,a),y=m?jn(c,m):null;if(!ds(f,y))return null}if(Rc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let p=Pf(c,r,o);return p.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ue(r),targetParentLocator:Ue(o),placement:s,anchorLocator:a?Ue(a):void 0,selectionContext:fo(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&&Ho(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=Et(c);if(!l)return null;let u=mn(l,r),d=mn(l,o);if(!u||!d)return null;let f=jn(c,u);if(!f)return null;let g=jn(c,d);if(ds(f,g))return null;if(g&&!Dx(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 x=Cf(c,l,a);if(g&&!ds(g,x)||!g&&x)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 x=Tc(o,{kind:"native-tag",tag:r.tag});if(x)return{ok:!1,errorCode:"unsupported-operation",reason:x}}let p=Ff(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(Rc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let m=zx(c,u,d,p);for(let x of m.conditionPaths){let E=wf(x,d,f);if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${E.bindingNames.join(", ")}`}}let y=Tf(u,d,f,{preserveConditionalBoundary:m.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 b=Ux(f,d);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its callback parameters depend on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let S=f;if(r.component!==o.component){let x=VO({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason};S=x.context}else{let x=Of(f.collectionPath,d);if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason??`Cannot move repeat-backed child because the repeat collection is not visible at the target: ${x.bindingNames.join(", ")}`}}return this.buildPlan(t,n,[{order:0,file:r.file,type:"move-repeat-template-child",locator:Ue(r),targetParentLocator:Ue(o),placement:s,anchorLocator:a?Ue(a):void 0,repeatExpression:Lf(S,m.sourceJsx),selectionContext:fo(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&Ho(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=Et(c),d=Et(l);if(!u||!d)return null;let f=Ax({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=mn(u,r),p=mn(d,o);if(!g||!p)return null;let m=Af(f.callSitePath,p);if(!m.ok)return{ok:!1,errorCode:"unsupported-operation",reason:m.reason};let y=jn(c,g);if(!y)return null;if(jn(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")&&Cf(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=Tc(o,{kind:"native-tag",tag:r.tag});if(A)return{ok:!1,errorCode:"unsupported-operation",reason:A}}let S=Ff(this.graph,r);if(!S)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(Rc(g,p))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let x=zx(c,g,p,S);for(let A of x.conditionPaths){let w=wf(A,p,y);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${w.bindingNames.join(", ")}`}}let E=Tf(g,p,y,{preserveConditionalBoundary:x.conditionPaths.length>0});if(!E.ok)return{ok:!1,errorCode:"unsupported-operation",reason:E.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${E.bindingNames.join(", ")}`};let k=YO({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:p});if(!k.ok)return{ok:!1,errorCode:"unsupported-operation",reason:k.reason};let v=Vx(y);if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let I=Kx(y,v.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:Ue(r),removeWhitespace:!0}];for(let A of k.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:Ue(o),expression:Lf(I,x.sourceJsx),placement:s,anchorLocator:a?Ue(a):void 0,selectionContext:fo(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(wc(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 x=n.params.target,E=this.graph.getNode(x.anchorKey);if(!E||r.file!==E.file||r.component!==E.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let k=this.graph.getFileVersion(r.file);if(n.documentVersion!==k)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${k})`};let v=this.graph.getFileContent(r.file),I=Et(v),N=I?mn(I,r):null,A=I?mn(I,E):null,w=N?.parentPath,L=A?.parentPath;if(!N||!A||!w||!L||w.node!==L.node||!w.isJSXFragment()&&!(w.isJSXElement()&&Ze(w)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let B=w.node.loc;return B?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:Ue(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:B.start.line,startColumn:B.start.column,endLine:B.end.line,endColumn:B.end.column}},placement:x.relation,anchorLocator:Ue(E),selectionContext:fo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=Gx(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(lL(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 x=n.params.target.relation,E=i.anchorNode&&(x==="before"||x==="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:x,anchorSourceId:E?.kind==="external-entry"?E.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=ps(r,c,f);if(g&&!Df(g)&&!Jx(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 x=c,E=await this.graph.getTextWriteTarget(d.key,0);if(x?.kind==="value-binding"&&E?.kind==="value-binding"&&x.locator&&E.locator){let k=ms(x.locator),v=ms(E.locator);if(k&&v&&x.file===E.file&&pL(k.locator,v.locator)){let I=k.index,N=v.index,A=u==="before"?N-(I<N?1:0):N+(I<N?0:1);return this.buildPlan(t,n,[{order:0,file:x.file,type:"move-array-item",locator:k.locator,fromIndex:I,toIndex:A}],o)}}}if(r.isRepeatItemRoot&&Ho(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),m=Df(g)?g:p;if(m&&Df(m)){let x=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(x)return x;let E=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(E)return E;let k=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return k||{ok:!1,errorCode:"unsupported-operation",reason:m}}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 x=Tc(s,{kind:"native-tag",tag:r.tag});if(x)return{ok:!1,errorCode:"unsupported-operation",reason:x}}if(l)return this.planCrossFileMove(t,n,r,s,o,u,d);let b=Pf(this.graph.getFileContent(r.file),r,s);if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason??`Cannot move node because it depends on bindings outside the target scope: ${b.bindingNames.join(", ")}`};let S=[{order:0,file:r.file,type:"move-node",locator:Ue(r),targetParentLocator:Ue(s),placement:u,anchorLocator:d?Ue(d):void 0,selectionContext:fo(s)}];return this.buildPlan(t,n,S,o)}planCrossFileMove(t,n,r,o,i,s,a){let c=[],l=0,u=this.graph.getFileContent(r.file),d=Ff(this.graph,r)??`<${r.component} />`,f=lx(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:Ue(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let p=r.tag??r.component,y={moduleSpecifier:jf(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:Ue(o),node:{jsx:d},placement:s,anchorLocator:a?Ue(a):void 0,selectionContext:fo(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:Ue(o),node:{jsx:d},placement:s,anchorLocator:a?Ue(a):void 0,selectionContext:fo(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:_e(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 Zx(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 Gf from"@babel/generator";import{parse as AL,parseExpression as TL}from"@babel/parser";import*as R from"@babel/types";import*as $n from"@babel/types";import Kf from"@babel/generator";import*as Ke from"@babel/types";var yL=typeof Kf=="function"?Kf:Kf.default,bL=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,xL=/^((?:https?:)?\/\/)[^/@\s]+@/i,EL=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function nE(e,t){let n=Zt(e.callee);if(!n)return null;if(n==="fetch")return Jf(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(tE(r))return Jf(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(tE(r))return Jf(e.arguments[0],r,t,["ky client contract"])}return null}function Jf(e,t,n,r){if(!e||Ke.isSpreadElement(e)||Ke.isJSXNamespacedName(e))return kL(t,n,r,"missing url argument");let o=gs(e);return{sourceKind:IL(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 gs(e){if(Ke.isStringLiteral(e))return po(e.value);if(Ke.isTemplateLiteral(e))return po(SL(e));if(Ke.isBinaryExpression(e)&&e.operator==="+"){let t=gs(e.left),n=gs(e.right);return!t&&!n?void 0:po(`${t??Xf(e.left)}${n??Xf(e.right)}`)}if(Ke.isMemberExpression(e)){let t=rE(e);if(t)return`env:${t}`}if(!(Ke.isCallExpression(e)&&Zt(e.callee)==="new URL")){if(Ke.isNewExpression(e)&&Ke.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ke.isSpreadElement(t)?gs(t):void 0,o=n&&!Ke.isSpreadElement(n)?gs(n):void 0;return o&&r?po(`${o} + ${r}`):r??o}if(Ke.isIdentifier(e))return`:${e.name}`}}function SL(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+=Xf(r))}return t}function Xf(e){if(Ke.isIdentifier(e))return`:${e.name}`;if(Ke.isMemberExpression(e)){let t=rE(e);if(t)return`env:${t}`}return`:${vL(e)}`}function vL(e){return yL(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function po(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(xL,"$1<redacted>@").replace(EL,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?bL.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function IL(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 kL(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function tE(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function rE(e){return!Ke.isMemberExpression(e.object)||!Ke.isIdentifier(e.object.object,{name:"process"})||!_L(e.object.property,"env")?null:Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null}function _L(e,t){return Ke.isIdentifier(e)&&e.name===t}function Zt(e){if(Ke.isIdentifier(e))return e.name;if(Ke.isMemberExpression(e)){let t=Zt(e.object),n=Ke.isIdentifier(e.property)?e.property.name:Ke.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var RL=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),CL=new Set(["getConfig","submit"]);function Fc(e,t){let n=oE(Zt(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!RL.has(i))return null;let s=zf(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(!CL.has(i))return null;let s=zf(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=zf(e,0)??NL(e,0,"path")??"/cms/:path",s=PL(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 oE(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function iE(e,t){let n=Zt(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 Dc(e,t){let n=Zt(e.callee),r=t?oE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function zf(e,t){let n=e.arguments[t];return $n.isStringLiteral(n)?n.value:null}function NL(e,t,n){let r=e.arguments[t];if(!$n.isObjectExpression(r))return null;for(let o of r.properties)if($n.isObjectProperty(o)&&!o.computed&&($n.isIdentifier(o.key)&&o.key.name===n||$n.isStringLiteral(o.key)&&o.key.value===n)&&$n.isStringLiteral(o.value))return o.value.value;return null}function PL(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}import*as mt from"@babel/types";var Hf=new WeakMap;function Ar(e,t){let n=Hf.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;mt.isMemberExpression(u)||mt.isOptionalMemberExpression(u);)u=u.object;return mt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,mt.traverseFast(e,l=>{if(!mt.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(mt.getBindingIdentifiers(l.id)))r.has(d)||(r.add(d),i=!0)});let s=l=>{let u=o(l);return u?r.has(u):Object.keys(mt.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;mt.traverseFast(e,l=>{(mt.isAssignmentExpression(l)&&s(l.left)||mt.isUpdateExpression(l)&&s(l.argument)||mt.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Hf.get(e)??new Map;return c.set(t,a),Hf.set(e,c),a}function sE(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,m=p.get(c)??new Map;return m.set(l,f),p.set(c,m),g.set(a,p),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as Tt from"@babel/types";import{posix as Wf}from"node:path";function Yo(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Tt.isBooleanLiteral(e))return e.value;if(Tt.isUnaryExpression(e,{operator:"!"})){let l=Yo(e.argument,t,r);return l===void 0?void 0:!l}if(Tt.isLogicalExpression(e)){let l=Yo(e.left,t,r),u=Yo(e.right,t,r);if(e.operator==="&&")return l===!1||u===!1?!1:l===!0?u:void 0;if(e.operator==="||")return l===!0||u===!0?!0:l===!1?u:void 0}if(!Tt.isCallExpression(e)||!Tt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Wf.normalize(Wf.join(Wf.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=Tt.isExpression(s.body)?s.body:s.body.body.length===1&&Tt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Tt.isExpression(a))return;let c=s.params.flatMap(l=>Tt.isIdentifier(l)?[l.name]:[]);return Yo(a,{file:t.file,imports:new Map([...t.imports].filter(([l])=>!c.includes(l))),functions:new Map([...t.functions].filter(([l])=>!c.includes(l)))},r.add(s))}var GH=typeof Gf=="function"?Gf:Gf.default,hE=new WeakMap;function yE(e){let t=new Map;return hE.set(t,new Map([...e].map(n=>[n.file,n]))),t}var wL={maxFunctionDepth:8,maxImportDepth:6},OL=new Set(["src","href","alt","poster","content","title","aria-label"]),aE=new WeakMap;function LL(e,t,n){let r=aE.get(t.fileCache);r||(r=new WeakMap,aE.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 bE(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&lE(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=tp(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...wL,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:OE(n,e.element.componentName),scopeFunction:np(n,e.element.componentName)};await xE(e.element.componentName,e.graph,r);let o=[];o.push(...await BL(e.element,e.graph,r),...await jL(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await $L(s,e.element,e.graph,r);a&&o.push(Jc(a,"text","children"))}for(let s of e.element.attributes??[]){let a=lE(s,e.element);if(!a)continue;let c=await vE(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&go(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(zc(e.element.sourceRange))?.openingElement.attributes.find(d=>R.isJSXAttribute(d)&&R.isJSXIdentifier(d.name,{name:s.name}));R.isJSXExpressionContainer(u?.value)&&R.isExpression(u.value.expression)&&!kE(u.value.expression,e.element,e.graph)&&(c=await et(u.value.expression,r))}c&&o.push(Jc(c,a,s.name))}let i=qL(o).sort(TE);return{hasDynamicData:i.length>0,bindings:i}}async function xE(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 LL(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 FL(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 SE(l.sourceFile,n);if(!d)continue;let f=Lr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=OE(d,l.componentName),f.scopeFunction=np(d,l.componentName),f.lexicalContext=void 0,await xE(l.componentName,t,f);let g=await DL(l,t,f);for(let[p,m]of g){if(!m)continue;let y=a.get(p)??[];y.push(m),a.set(p,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=ep(u);d.length===1&&c.set(l,d[0])}ML(o,c,n)}var cE=new WeakMap;function FL(e,t,n,r){let o=cE.get(r.fileCache);return o||(o=sE(),cE.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>EE(e,t,n,r))}async function EE(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 SE(e,r))?.imports.get(t);if(!s||!Qe(s.source))return!1;let a=await op(e,s.source,r.exists);return a?a===n?!0:EE(a,s.importedName,n,r,o):!1}async function DL(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(zc(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!R.isJSXAttribute(s)||!R.isJSXIdentifier(s.name)||!R.isJSXExpressionContainer(s.value)||!R.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=e.attributes?.find(d=>d.name===s)?.source??null,u=(c?go(c.base,e,t):null)?await Hc(c,e,t,n):kE(a,e,t)?null:await et(a,n);u&&i.set(s,u)}return i}function zc(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function SE(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 tp(e,r,t.fileCache)}function ML(e,t,n){if(R.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Kc(Object.fromEntries(t),n.file));return}if(R.isObjectPattern(e))for(let r of e.properties){if(!R.isObjectProperty(r)||r.computed||!R.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=R.isAssignmentPattern(r.value)?r.value.left:r.value;R.isIdentifier(i)&&n.paramSources.set(i.name,kt(o))}}function lE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":OL.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function BL(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 Wc(i.collectionSource,n);s&&r.push(Jc(Tr(s),"repeat-region",i.collectionExpression))}return r}async function jL(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 Wc(i.conditionSource,n);s&&r.push(Jc(Tr(s),"conditional-region",i.conditionExpression))}return r}async function $L(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(zc(t.sourceRange))?.children.find(s=>R.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return R.isJSXExpressionContainer(i)&&R.isCallExpression(i.expression)&&Dc(i.expression)?IE(i.expression,t,n,r):null}return vE(e.source,t,n,r)}async function vE(e,t,n,r){return e&&go(e.base,t,n)?Hc(e,t,n,r):Wc(e,r)}async function Hc(e,t,n,r,o){if(!e)return null;let i=go(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?go(s.base,t,n,i.region):null)?await Hc(s,t,n,r,i.region):s?await Wc(s,r):await UL(i.candidate.collectionExpression,t,n,r,i.region);return c?hs(c,e.path,!0):null}async function UL(e,t,n,r,o){let i;try{i=TL(e,{plugins:["typescript","jsx"]})}catch{return null}return IE(i,t,n,r,o)}async function IE(e,t,n,r,o){let i=Lr(r.analysis,r),s=new Set;R.traverseFast(e,a=>{R.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=go(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Hc({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return et(e,i)}function go(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!uE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||uE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function uE(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function kE(e,t,n){let r=!1;return R.traverseFast(e,o=>{!r&&R.isIdentifier(o)&&go(o.name,t,n)&&(r=!0)}),r}async function Wc(e,t){if(!e)return null;let n=await qf(e.base,t);return n?hs(n,e.path,!1):null}async function qf(e,t){let n=t.paramSources.get(e);if(n)return kt(n);if(t.variableCache.has(e))return QL(t.variableCache.get(e)??null);let r=Or(e,t);if(r&&r!==t)return qf(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await KL(e,t);if(o)return t.variableCache.set(e,kt(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=R.isArrayExpression(s)&&s.elements.length===0?await VL(e,t):await et(s,t);return t.variableCache.set(e,c?kt(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await rp(a,t);if(c){let l=Lr(c,t,{importDepth:t.importDepth+1}),u=LE(a,c);if(u){let g=(await mo(u,[],l)).returnSource;return t.variableCache.set(e,g?kt(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await et(d,l);return t.variableCache.set(e,f?kt(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Or(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>wr(n).includes(e))?t:t.lexicalContext?Or(e,t.lexicalContext):void 0}function Mc(e,t,n=new Set){if(R.isIdentifier(e)){let s=Or(e.name,t);if(s&&s!==t)return Mc(e,s,n)}if(n.has(e))return null;if(n.add(e),R.isStringLiteral(e))return e.value;if(!R.isIdentifier(e))return null;let r=Or(e.name,t),o=t.paramArguments.get(e.name);if(o)return Mc(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?Mc(i,t,n):null}function Un(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(R.isStringLiteral(e))return e.value;if(R.isNumericLiteral(e))return String(e.value);if(R.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=Or(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?Un(s.expression,s.context,r):a?Un(a,i,r):null)??`:${e.name}`}if(R.isBinaryExpression(e,{operator:"+"})){let o=Un(e.left,t,r),i=Un(e.right,t,r);return o!==null&&i!==null?o+i:null}if(R.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!R.isExpression(s))return null;o+=(Un(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(R.isCallExpression(e)&&R.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&R.isExpression(e.arguments[0])){let o=Un(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return R.isTSAsExpression(e)||R.isTSNonNullExpression(e)||R.isParenthesizedExpression(e)?Un(e.expression,t,r):null}async function VL(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return R.traverseFast(u,f=>{R.isIdentifier(f,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;R.isMemberExpression(d);)d=d.object;return R.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(R.isFunction(u)){s(u)&&(o=!0);return}if(R.isVariableDeclarator(u)&&(wr(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(R.isAssignmentExpression(u)||R.isUpdateExpression(u))&&a(R.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(R.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(R.isCallExpression(u)){if(R.isMemberExpression(u.callee)&&R.isIdentifier(u.callee.object,{name:e})){if(!R.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let f of u.arguments){let g=R.isSpreadElement(f)?f.argument:f,p=R.isExpression(g)?await et(g,d):null;p?r.push(Zf(p)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(R.isForOfStatement(u)){let f=await et(u.right,d),g=Lr(d.analysis,d),p=R.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&p&&Uc(p,Zf(f),g),await c(u.body,g);return}for(let f of R.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let p of Array.isArray(g)?g:[g])R.isNode(p)&&await c(p,d)}}};await c(n.body,t);let l=ep(r);return!o&&i===1&&l.length===1?Tr(l[0]):null}async function KL(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(R.isIdentifier(e))return qf(e.name,t);if(R.isMemberExpression(e)||R.isOptionalMemberExpression(e)){let n=R.isMemberExpression(e)?iE(e,{file:t.file}):null;if(n)return PE(n);let r=await JL(e,t);if(!r)return null;let o=ZL(e);return hs(r,o,!1)}if(R.isAwaitExpression(e))return R.isExpression(e.argument)?et(e.argument,t):null;if((R.isCallExpression(e)||R.isOptionalCallExpression(e))&&(R.isMemberExpression(e.callee)||R.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&R.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&R.isExpression(e.callee.object))return qo(await et(e.callee.object,t));if(R.isCallExpression(e))return RE(e,t);if(R.isObjectExpression(e)){let n=await NE(e,t);return Object.keys(n).length>0?Kc(n,t.file):null}if(R.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!R.isExpression(o))continue;let i=await et(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?Kc(n,t.file):null}if(R.isConditionalExpression(e)){let n=await et(e.consequent,t),r=await et(e.alternate,t);return qo(pE(n,r))}if(R.isLogicalExpression(e)){let n=await et(e.left,t),r=await et(e.right,t);return qo(pE(n,r))}return R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e)||R.isTypeCastExpression(e)||R.isParenthesizedExpression(e)?et(e.expression,t):null}async function JL(e,t){let n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);)n=n.object;return R.isExpression(n)?et(n,t):null}async function _E(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=Or(e,t);if(r){if(r.scopeFunction&&Ar(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&R.isIdentifier(s.expression)?_E(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||Ar(t.analysis.ast,e))return null;let i=await op(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function RE(e,t){let n=e.arguments[0],r=R.isExpression(n)?Mc(n,t):null,i=Zt(e.callee)?.split(".")[0],s=i?await _E(i,t):null,a=r!==null&&!R.isStringLiteral(n)?{...e,arguments:[R.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&R.isObjectExpression(n)){let b=CE(n,"path"),S=b&&Un(b,t);S?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(x=>R.isObjectProperty(x)&&ei(x)==="path"?{...x,value:R.stringLiteral(po(S))}:x)},...e.arguments.slice(1)]})}let c=Fc(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(c){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&c.endpointPattern==="/content/by-url"&&R.isObjectExpression(n)){let b=dE(n,"query"),S=R.isObjectExpression(b)?dE(b,"path"):null,E=(S&&Un(S,t))?.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1];E&&(c.collection=E,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(R.isMemberExpression(e.callee)){let b=await nr(e.callee,t);if(b&&!Bc(b.node))return null;if(b&&Bc(b.node)){let S=await Yf(e,t,{node:b.node,context:b.context});return S&&{...S,...S.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&R.isExpression(n)){let b=Un(n,t);b?.startsWith("/")&&(c.endpointPattern=po(b))}return PE(c)}if(Zt(e.callee)==="Promise.all"&&R.isArrayExpression(n))return et(n,t);if(Dc(e)){if(!Dc(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!R.isExpression(e.callee))return null;let b=await nr(e.callee,t);if(b)return Bc(b.node)?Yf(e,t,{node:b.node,context:b.context}):null;let S=e.arguments[0];if(S&&R.isExpression(S))return qo(await et(S,t))}let l=await XL(e,t);if(l)return l;let u=nE(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await HL(e,t);if(d)return d;let f=await WL(e,t);if(f)return f;let g=await GL(e,t);if(g)return g;let p=await Yf(e,t);if(p)return p;let m=[];for(let b of e.arguments)if(R.isExpression(b)){let S=await et(b,t);S&&m.push(S)}let y=ep(m);return y.length===1?qo(y[0]):null}async function XL(e,t){let n=Zt(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=zL(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(R.isIdentifier(s)){let a=await Qo(s.name,t);if(a)return(await mo(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!R.isObjectExpression(r))return jc(t.file,`${n} without static options`);let o=CE(r,"queryFn");if(!o)return jc(t.file,`${n} without queryFn`);if(R.isIdentifier(o)){let i=await Qo(o.name,t);return i?(await mo(i.node,[],i.context)).returnSource:jc(t.file,`${n} queryFn unresolved`)}return R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)?(await mo(o,[],t)).returnSource:R.isCallExpression(o)?RE(o,t):null}function CE(e,t){for(let n of e.properties){if(!R.isObjectProperty(n)||!R.isExpression(n.value))continue;if(ei(n)===t)return n.value}return null}function dE(e,t){let n=new Set;for(let i of e.properties){if(!R.isObjectProperty(i)||i.computed)return null;let s=ei(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>R.isObjectProperty(i)&&ei(i)===t);if(r.length!==1)return null;let o=r[0];return R.isObjectProperty(o)&&R.isExpression(o.value)?o.value:null}function zL(e,t,n){return R.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 HL(e,t){if(!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted","reverse","toReversed"].includes(n))return null;let r=R.isExpression(e.callee.object)?await et(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Tr(r);let o=e.arguments[0];if(R.isIdentifier(o)){let i=await Qo(o.name,t);if(!i)return Tr(r);let s=await mo(i.node,[r],i.context);return{...Tr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(R.isArrowFunctionExpression(o)||R.isFunctionExpression(o)){let i=await mo(o,[r],t);return{...Tr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Tr(r)}async function WL(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"json"})||!R.isExpression(e.callee.object)?null:et(e.callee.object,t)}async function GL(e,t){return!R.isMemberExpression(e.callee)||!R.isIdentifier(e.callee.property,{name:"then"})||!R.isExpression(e.callee.object)?null:qo(await et(e.callee.object,t))}async function Yf(e,t,n){let r=n;if(!r&&R.isIdentifier(e.callee))r=await Qo(e.callee.name,t)??void 0;else if(!r&&R.isMemberExpression(e.callee)){let s=await nr(e.callee,t);s&&Bc(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!R.isExpression(s)){o.push(jc(t.file,`unsupported argument for ${Zt(e.callee)??"call"}`));continue}let a=await et(s,t);o.push(a)}return(await mo(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Bc(e){return R.isFunctionDeclaration(e)||Xc(e)||R.isObjectMethod(e)&&e.kind==="method"}async function nr(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(R.isTSAsExpression(e)||R.isTSSatisfiesExpression(e)||R.isTSNonNullExpression(e))return nr(e.expression,t,o);if(R.isIdentifier(e)){let i=Or(e.name,t),s=i??t;if(Ar(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return nr(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return nr(c,s,o);if(i)return null;let l=s.analysis.functions.get(e.name);if(l)return{node:l,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await rp(u,s);return d?nr(R.identifier(u.importedName),Lr(d,s,{importDepth:s.importDepth+1}),o):null}if(R.isMemberExpression(e)&&R.isExpression(e.object)){let i=e.computed?R.isStringLiteral(e.property)?e.property.value:null:R.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await nr(e.object,t,o);if(!s)return null;if(!R.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>R.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(R.isObjectMethod(l)||R.isObjectProperty(l))&&(R.isIdentifier(l.key)?l.key.name:R.isStringLiteral(l.key)?l.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let c=a[0];return R.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:R.isObjectProperty(c)&&R.isExpression(c.value)?nr(c.value,s.context,o):null}return{node:e,context:t}}async function Qo(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Xc(r.expression))return{node:r.expression,context:r.context};if(R.isIdentifier(r.expression))return Qo(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await rp(i,t);if(!s)return null;let a=Lr(s,t,{importDepth:t.importDepth+1}),c=LE(i,s);return c?{node:c,context:a}:Qo(i.importedName,a)}async function mo(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=Lr(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,f)=>{for(let y of wr(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=R.isAssignmentPattern(d)?d.left:d,p=r?.arguments[f];R.isIdentifier(g)&&R.isExpression(p)&&r&&o.paramArguments.set(g.name,{expression:p,context:r.context});let m=t[f];m&&Uc(d,Zf(m),o)});let a=YL(e,o),c=null,l,u=!1;for(let d of a){let f=Lr(n.analysis,o);if(R.isObjectExpression(d)){l={...l??{},...await NE(d,f)},c=c??Kc(l,n.file);continue}let g=await et(d,f);if(g){if(!c){c=g;continue}let p=Qf(c,g);if(!p){u=!0,c=null;continue}c=p}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function Uc(e,t,n){if(R.isIdentifier(e)){n.paramSources.set(e.name,kt(t));return}if(R.isAssignmentPattern(e)){Uc(e.left,t,n);return}if(R.isObjectPattern(e))for(let r of e.properties){if(!R.isObjectProperty(r)||r.computed||!R.isIdentifier(r.key))continue;let o=hs(t,[{kind:"property",name:r.key.name}],!0),i=R.isAssignmentPattern(r.value)?r.value.left:r.value;o&&Uc(i,o,n)}}function YL(e,t){if(R.isArrowFunctionExpression(e)&&R.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!R.isBlockStatement(r))return n;let o=i=>{if(R.isFunction(i)&&i!==e)return;if(R.isReturnStatement(i)){i.argument&&R.isExpression(i.argument)&&n.push(i.argument);return}if(R.isIfStatement(i)){let a=Yo(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!Or(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=R.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)R.isNode(l)&&o(l);else R.isNode(c)&&o(c)}};return o(r),n}async function NE(e,t){let n={};for(let r of e.properties){if(!R.isObjectProperty(r))continue;let o=ei(r);if(!o||!R.isExpression(r.value))continue;let i=await et(r.value,t);i&&(n[o]=i)}return n}function ei(e){return R.isIdentifier(e.key)&&!e.computed?e.key.name:R.isStringLiteral(e.key)?e.key.value:null}function ZL(e){let t=[],n=e;for(;R.isMemberExpression(n)||R.isOptionalMemberExpression(n);){let r=n.property;n.computed?R.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):R.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):R.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return R.isIdentifier(n),t}function hs(e,t,n){if(t.length===0)return kt(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?hs(s,t.slice(1),n):null}let i=kt(e);if(i.sourceType==="cms-field"){let s=t.filter(c=>c.kind==="property").map(c=>c.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Zo(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Zo(i.valuePath,"data")),i.fieldPath=Zo(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Zo(i.fieldPath,s.join(".")),i):(i.valuePath=Zo(i.valuePath,fE(t)),i)}return i.valuePath=Zo(i.valuePath,fE(t)),i}function fE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Zo(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function PE(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 Tr(e){let t=kt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Zf(e){let t=kt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function qo(e){return e?{...kt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function pE(e,t){return e?t?Qf(e,t):kt(e):t?kt(t):null}function Qf(e,t){if(Vc(e)!==Vc(t))return null;let n=wE(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function ep(e){let t=new Map;for(let n of e){let r=Vc(n),o=t.get(r);t.set(r,o?Qf(o,n):kt(n))}return[...t.values()]}function Vc(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Vc(r)])):void 0;return JSON.stringify({sourceKind:e.sourceKind,sourceType:e.sourceType,endpointPattern:e.endpointPattern,operation:e.operation,collection:e.collection,fieldPath:e.fieldPath,valuePath:e.valuePath,cmsFieldRoot:e.cmsFieldRoot,fieldMap:t})}function Kc(e,t){let n=Object.values(e)[0];return{sourceKind:n?.sourceKind??"unknown-api",sourceType:n?.sourceType??"api-field",endpointPattern:n?.endpointPattern,operation:n?.operation,collection:n?.collection,confidence:n?.confidence??"partial",readonly:!0,evidence:n?.evidence??[{file:t,reason:"object return map"}],fieldMap:e}}function jc(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Jc(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 AE(e){let t=[...e].sort(TE),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 qL(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 TE(e,t){return mE(e.targetKind)-mE(t.targetKind)||wE(e.confidence,t.confidence)||gE(e.sourceKind)-gE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function mE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function gE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function wE(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function tp(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=hE.get(n)?.get(e),i=o?.source===t?o.ast:AL(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,functionParents:new WeakMap},a=[],c=[];R.traverse(i,{enter(d){switch(R.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let f=d.loc;if(!f)return;let g=zc({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)R.isImportSpecifier(g)&&R.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,importedName:R.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):R.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&&(R.isFunctionDeclaration(f)||R.isFunctionExpression(f)||R.isArrowFunctionExpression(f)||R.isObjectMethod(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[m,y]of $c(d.id,R.isExpression(d.init)?d.init:null))p.set(m,y);if(R.isArrayPattern(d.id)&&R.isCallExpression(d.init)&&Zt(d.init.callee)==="useState"){let[m,y]=d.id.elements;R.isIdentifier(m)&&R.isIdentifier(y)&&s.stateSetters.set(m.name,y.name)}R.isIdentifier(d.id)&&Xc(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(!R.isExportSpecifier(p))continue;let m=R.isIdentifier(p.exported)?p.exported.name:p.exported.value,y=p.local.name;s.imports.set(m,{source:g,importedName:y,localName:m,isDefault:y==="default"})}if(R.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),R.isVariableDeclaration(f))for(let p of f.declarations)R.isIdentifier(p.id)&&Xc(p.init)&&s.functions.set(p.id.name,p.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((R.isFunctionDeclaration(f)||R.isFunctionExpression(f)||R.isArrowFunctionExpression(f))&&s.functions.set("default",f),R.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){R.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=R.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&R.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let p of d.arguments)R.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 $c(e,t){return R.isIdentifier(e)?[[e.name,t]]:R.isAssignmentPattern(e)?$c(e.left,t):R.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!R.isRestElement(n)?$c(n,t?R.memberExpression(t,R.numericLiteral(r),!0):null):[]):R.isObjectPattern(e)?e.properties.flatMap(n=>{if(!R.isObjectProperty(n)||n.computed)return[];let r=ei(n);return r?$c(n.value,t?R.memberExpression(t,R.stringLiteral(r),!0):null):[]}):[]}function wr(e){return!e||R.isVoidPattern(e)?[]:R.isIdentifier(e)?[e.name]:R.isObjectPattern(e)?e.properties.flatMap(t=>R.isObjectProperty(t)?wr(t.value):wr(t.argument)):R.isArrayPattern(e)?e.elements.flatMap(t=>t?wr(R.isRestElement(t)?t.argument:t):[]):R.isAssignmentPattern(e)?wr(e.left):R.isRestElement(e)?wr(e.argument):[]}function Xc(e){return R.isFunctionExpression(e)||R.isArrowFunctionExpression(e)}function OE(e,t){let n=np(e,t);return n?e.functionVariables.get(n):void 0}function np(e,t){return e.functions.get(t)??e.functions.get("default")}async function rp(e,t){let n=await op(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return tp(n,r,t.fileCache)}function LE(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function op(e,t,n){return Qe(t)?Xr(e,t,n):null}function Lr(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function QL(e){return e?kt(e):null}function kt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,kt(n)]))}:{}}}import*as sp from"@babel/parser";import ip from"@babel/traverse";import*as le from"@babel/types";import{classifySiteEditPropertyName as eF}from"@vcp-dev/contracts";var ap=typeof ip=="function"?ip:ip.default;function cp(e){let t=eF(e.propertyName);if(t.owner!=="generic")return qt("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return qt("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return qt("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return qt("missing-instance-index","A repeat property target requires an instance index");let r;try{r=sp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return qt("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=tF(r,e.element.sourceRange);if(!o)return qt("repeat-not-found","The selected element is not inside a supported map repeat");if(!le.isIdentifier(o.callback.params[0]))return qt("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=nF(r,o.collection,e.file,e.sources);if(!i)return qt("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,b]of s.elements.entries()){if(!b||!le.isObjectExpression(b)||!$E(b))return qt("unsafe-collection","Repeat materialization requires an array of local static objects without spreads");let S=[{kind:"index",index:y}];l.push(S),u.push({kind:"value",root:a.root,path:S})}let d=u.length;if(n.instanceCount!==void 0&&n.instanceCount!==d)return qt("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return qt("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!le.isObjectExpression(g))return qt("unsafe-collection","Selected repeat item is not an object");let p=cF(e.element,e.propertyName),m=sF(g,e.propertyName);return m?{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,b)=>b),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:m,selectedResolution:aF(g,e.propertyName),...p?{property:p}:{},selectionRef:n}:qt("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function tF(e,t){let n=[];return ap(e,{CallExpression(r){let o=FE(r.node);o&&ME(o.callback,t)&&n.push({...o,span:DE(r.node)})},OptionalCallExpression(r){let o=FE(r.node);o&&ME(o.callback,t)&&n.push({...o,span:DE(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function FE(e){let t=e.callee;if(!le.isMemberExpression(t)&&!le.isOptionalMemberExpression(t)||t.computed||!le.isIdentifier(t.property)||t.property.name!=="map"||!le.isExpression(t.object))return null;let n=e.arguments[0];return!n||!le.isExpression(n)||!le.isArrowFunctionExpression(n)&&!le.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function nF(e,t,n,r){let o=ys(t);if(o&&le.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:VE(o)}},sourceFile:n};if(!le.isIdentifier(t))return null;let i=[];if(ap(e,{VariableDeclarator(s){le.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=ys(i[0].init);return!s||!le.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return rF(e,t.name,n,r)}function rF(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!le.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!le.isStringLiteral(o.source)||!le.isImportSpecifier(i))continue;let s=iF(n,o.source.value,r);if(!s)return null;let a=le.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=sp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=oF(l,a),d=u?ys(u):null;return!d||!le.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function oF(e,t){let n=null;return ap(e,{VariableDeclarator(r){n||!le.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!le.isExpression(r.node.init)||(n=r.node.init)}}),n}function iF(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 ys(e){return le.isParenthesizedExpression(e)?ys(e.expression):le.isTSAsExpression(e)?jE(e.typeAnnotation)?ys(e.expression):null:le.isTSSatisfiesExpression(e)?null:e}function jE(e){return le.isTSTypeReference(e)&&le.isIdentifier(e.typeName)&&e.typeName.name==="const"}function $E(e){return e.properties.every(t=>!le.isObjectProperty(t)||t.computed||!le.isExpression(t.value)?!1:Gc(t.value))}function Gc(e){if(le.isTSAsExpression(e)&&jE(e.typeAnnotation))return Gc(e.expression);if(le.isTSSatisfiesExpression(e))return!1;if(le.isArrayExpression(e))return e.elements.every(n=>!n||le.isSpreadElement(n)||!le.isExpression(n)?!1:Gc(n));if(le.isObjectExpression(e))return $E(e);let t=On(e);return t.status==="resolved"||t.status==="undefined"}function sF(e,t){let n=e.properties.filter(o=>le.isObjectProperty(o)&&UE(o.key)===t);if(n.length>1)return null;let r=n[0];return r?le.isExpression(r.value)?Gc(r.value)?"static":le.isIdentifier(r.value)||le.isMemberExpression(r.value)?"binding":null:null:"missing"}function aF(e,t){let n=e.properties.filter(o=>le.isObjectProperty(o)&&UE(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!le.isExpression(r.value)?{status:"undefined"}:On(r.value)}function cF(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function UE(e){return le.isIdentifier(e)?e.name:le.isStringLiteral(e)?e.value:le.isNumericLiteral(e)?String(e.value):null}function VE(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 DE(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function ME(e,t){let n=VE(e);return BE(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&BE(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function BE(e,t,n,r){return e===n?t-r:e-n}function qt(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as zF}from"@vcp-dev/contracts";import*as pe from"@babel/types";import vs from"node:path";import*as Z from"@babel/types";import*as WE from"@babel/parser";import lp from"@babel/traverse";import*as xe from"@babel/types";function Zc(e,t){let n=[],r=e;for(;xe.isMemberExpression(r);){if(r.computed)if(xe.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(xe.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!xe.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!xe.isIdentifier(r)||r.name!==t?null:n}function KE(e){if(xe.isIdentifier(e))return{base:e.name,path:[]};if(!xe.isMemberExpression(e))return null;let t=[],n=e;for(;xe.isMemberExpression(n);){if(n.computed)if(xe.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(xe.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!xe.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return xe.isIdentifier(n)?{base:n.name,path:t}:null}function wt(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 Yc(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 Yc(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||xe.isSpreadElement(n))return Vn;let r=Yc(n);if(r===Vn)return Vn;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!xe.isObjectProperty(n)||n.computed||n.shorthand||!xe.isExpression(n.value))return Vn;let r=xe.isIdentifier(n.key)?n.key.name:xe.isStringLiteral(n.key)?n.key.value:null;if(!r)return Vn;let o=Yc(n.value);if(o===Vn)return Vn;t[r]=o}return t}default:return Vn}}function JE(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=Yc(i);if(f!==Vn)return f;if(!xe.isTemplateLiteral(i)){if(xe.isTSAsExpression(i)||xe.isTSSatisfiesExpression(i)||xe.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(xe.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(xe.isArrayExpression(i)){let g=[];for(let p of i.elements){if(!p||xe.isSpreadElement(p))return;let m=await r(p,s,a,c,l,u,d);if(m===void 0)return;g.push(m)}return g}if(xe.isObjectExpression(i)){let g={};for(let p of i.properties){if(!xe.isObjectProperty(p)||p.computed)return;let m=null;if(xe.isIdentifier(p.key)?m=p.key.name:xe.isStringLiteral(p.key)&&(m=p.key.value),!m)return;if(p.shorthand){if(!xe.isIdentifier(p.value))return;let b=await r(p.value,s,a,c,l,u,d);if(b===void 0)return;g[m]=b;continue}if(!xe.isExpression(p.value))return;let y=await r(p.value,s,a,c,l,u,d);y!==void 0&&(g[m]=y)}return g}if(xe.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 m=await t({currentFile:a,binding:p,readFile:c,exists:l,fileCache:u,visited:d});return!m||m.kind!=="static"?void 0:wt(m.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!xe.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(xe.isIdentifier(i))return{base:i.name,path:[]};if(!xe.isMemberExpression(i))return null;let f=[],g=i;for(;xe.isMemberExpression(g);){if(g.computed){let p=g.property;if(xe.isNumericLiteral(p))f.unshift({kind:"index",index:p.value});else if(xe.isStringLiteral(p))f.unshift({kind:"property",name:p.value});else{let m=xe.isExpression(p)?await n(p,s,a,c,l,u,d):void 0;if(typeof m=="string")f.unshift({kind:"property",name:m});else if(Number.isInteger(m))f.unshift({kind:"index",index:m});else return null}}else{if(!xe.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return xe.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var GE=typeof lp=="function"?lp:lp.default,XE=new WeakMap;function YE(e){try{return WE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function qc(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=YE(n);return e.set(t,{source:n,ast:o}),o}function Qc(e,t){return up(bs(e).expressionRanges,t,!1)}function ZE(e,t){return bs(e).exactExpressions.get(qE(t))??null}function el(e,t){return up(bs(e).jsxRanges,t,!0)}function bs(e){let t=XE.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return GE(e,{Expression(r){let o=r;n.expressions.push(o);let i=zE(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=qE(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=zE(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(HE),n.jsxRanges.sort(HE),XE.set(e,n),n}function zE(e,t){let n=xs(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function qE(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function HE(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function up(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 xs(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 ti(e,t){if(t)return dp(e,t);let n=KE(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function dp(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Es(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of bs(e).expressions){if(dp(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function QE(e,t,n,r){return up(bs(e).expressionRanges,r,!0,o=>dp(o.node,t)===n)}function ni(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ss(e){let t=null;if(GE(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function kn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=YE(o),s={source:o,ast:i};return n.set(e,s),s}function lF(e){return Z.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:Z.isMemberExpression(e.callee)&&Z.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function uF(e){if(!Z.isNewExpression(e)||!Z.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!Z.isIdentifier(e.arguments[0])||!Z.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!Z.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!Z.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(Z.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(Z.isIfStatement(i)&&Z.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=Z.isIfStatement(i)?i.test:null,c=a&&Z.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=Z.isIfStatement(i)?Z.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=Z.isReturnStatement(s)?s.argument:null;return!a||!Z.isLogicalExpression(a,{operator:"&&"})||!Z.isBinaryExpression(a.left,{operator:"==="})||!Z.isUnaryExpression(a.left.left,{operator:"typeof"})||!Z.isIdentifier(a.left.left.argument,{name:r.name})||!Z.isStringLiteral(a.left.right,{value:"string"})||!Z.isUnaryExpression(c,{operator:"!"})||!Z.isBinaryExpression(c.argument,{operator:"in"})||!Z.isIdentifier(c.argument.left,{name:r.name})||!Z.isIdentifier(c.argument.right,{name:n.name})||!Z.isReturnStatement(l)||!Z.isIfStatement(i)||i.alternate||!Z.isCallExpression(u)||!Z.isMemberExpression(u.callee)||!Z.isIdentifier(u.callee.object,{name:"Reflect"})||!Z.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!Z.isIdentifier(u.arguments[0],{name:n.name})||!Z.isIdentifier(u.arguments[1],{name:r.name})||!Z.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function dF(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()||!Z.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 eS(e,t){let n=dF(e.path);if(!n)return null;let r=Uo(e,t);return r?{...n,...r}:null}function tS(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function fp(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 pp(e,t){for(let n of e.program.body){if(t==="default"&&Z.isExportDefaultDeclaration(n))return Z.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(Z.isExportNamedDeclaration(n)){if(n.declaration){if(Z.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(Z.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((Z.isFunctionDeclaration(n.declaration)||Z.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((Z.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&Z.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 nS(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(m){let{currentFile:y,binding:b,readFile:S,exists:x,fileCache:E,visited:k}=m,v=`${y}::${b.kind}::${b.identifier.name}`;if(k.has(v))return null;k.add(v);try{let I=await a({currentFile:y,binding:b,readFile:S,exists:x,fileCache:E,visited:k});if(I)return I;if(b.path.isImportSpecifier()||b.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:b,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,fileCache:E,visited:k});if(b.kind==="param")return null;if(b.path.isVariableDeclarator()){let N=b.path.node.init;if(!N||!Z.isExpression(N))return null;let A=uF(N);if(A&&!b.path.scope.getBinding("Proxy")&&!b.path.scope.getBinding("Reflect")){let B=b.path.scope.getBinding(A),J=B?await s({...m,binding:B}):null;if(J?.kind==="static"&&J.value!==null&&!Array.isArray(J.value)&&typeof J.value=="object")return J}let w=b.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let B=await t({currentFile:y,expressionPath:w,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(B)return B;if(w.isCallExpression()){let J=await n({currentFile:y,callPath:w,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});if(J)return J}}let L=await r(N,b.path.scope,y,S,x,E,k);return L===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:L,sourceKind:"binding"}}if(b.path.isIdentifier()&&b.path.parentPath?.isExportDefaultDeclaration()){let N=b.path.parentPath.node.declaration;if(!Z.isExpression(N))return null;let A=await r(N,b.path.scope,y,S,x,E,k);return A===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:A,sourceKind:"binding"}}return null}finally{k.delete(v)}}async function a(m){let{currentFile:y,binding:b,readFile:S,exists:x,fileCache:E,visited:k}=m;if(!b.path.isVariableDeclarator()||!b.path.get("id").isArrayPattern())return null;let v=b.path,I=v.node.init;if(!I||!Z.isCallExpression(I))return null;let N=lF(I);if(!N||!Z.isArrayPattern(v.node.id)||v.node.id.elements.findIndex(J=>Z.isIdentifier(J)&&J.name===b.identifier.name)!==0)return null;let w=N==="useReducer"?1:0,L=I.arguments[w];if(!L||!Z.isExpression(L))return null;let B=await r(L,v.scope,y,S,x,E,k);return B===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:b.identifier.name,hook:N},value:B,sourceKind:"binding"}}async function c(m){let y=m.expressionPath.scope.getBinding(m.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!m.graph)return null;let b=eS(y,m.sourceInfo);if(!b)return null;let S=[...m.graph.elements.values()].filter(E=>tS(E,m.currentFile,b.componentName,b.exportName));if(!S.length)return null;let x=[];for(let E of S){if(E.sourceFile!==S[0].sourceFile||E.componentName!==S[0].componentName||E.attributeSpreads?.length)return null;let k=await kn(E.sourceFile,m.readFile,m.fileCache),v=k.ast?el(k.ast,E.sourceRange):null;if(!v)return null;let I=v.parentPath;for(;I&&!I.isFunction();){if(I.isJSXElement()){let $=I.node.openingElement.name;if(!Z.isJSXIdentifier($)||!/^[a-z]/.test($.name))return null}else if(!I.isJSXFragment()&&!I.isReturnStatement()&&!I.isBlockStatement())return null;I=I.parentPath}if(!I)return null;let N=v.get("openingElement").get("attributes").filter($=>$.isJSXAttribute()&&Z.isJSXIdentifier($.node.name,{name:b.propName}));if(N.length!==1)return null;let A=N[0];if(!A?.isJSXAttribute())return null;let w=A.get("value"),L=w.isJSXExpressionContainer()?w.get("expression"):w;if(!L.isExpression())return null;let B=await r(L.node,L.scope,E.sourceFile,m.readFile,m.exists,m.fileCache,m.visited),J=B===void 0?void 0:wt(B,b.remainingPath);if(J===void 0)return null;x.push(J)}return x}async function l(m){let y=eS(m.binding,m.sourceInfo);if(!y||!m.graph)return null;let b=["component-prop",m.currentFile,m.binding.identifier.start??m.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(m.visited.has(b))return null;m.visited.add(b);try{return await u(m,y,m.graph)}finally{m.visited.delete(b)}}async function u(m,y,b){let S=[...b.elements.values()].filter(A=>tS(A,m.currentFile,y.componentName,y.exportName));if(S.length!==1)return null;let x=S[0],E=x.attributes?.find(A=>A.name===y.propName);if(E&&!E.source){let A=await d({caller:x,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,fileCache:m.fileCache});if(A)return fp(A,{componentName:y.componentName,propName:y.propName,file:x.sourceFile})}if(!E?.source){let A=await f({caller:x,propName:y.propName,remainingPath:y.remainingPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(A)return fp(A,{componentName:y.componentName,propName:y.propName,file:x.sourceFile});let w=ex(m.binding,y.componentName,y.propName);if(!w||w.propName!==y.propName)return null;let L=await r(w.expressionPath.node,w.expressionPath.scope,m.currentFile,m.readFile,m.exists,m.fileCache,m.visited);if(L===void 0)return null;let B=y.remainingPath;return B.length>0&&wt(L,B)===void 0?null:{kind:"value",file:m.currentFile,root:{kind:"binding",name:y.propName},path:B,sourceKind:"binding",semanticKind:"component-prop",displayExpression:w.displayPath,chainPrefix:[{kind:"component-prop",file:m.currentFile,displayName:w.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let k=await kn(x.sourceFile,m.readFile,m.fileCache);if(!k.ast)return null;let v=QE(k.ast,k.source,E.source.expression,E.sourceRange)??Es(k.ast,k.source,E.source.expression);if(!v)return null;let I={...E.source,expression:ni(E.source.expression,y.remainingPath),path:[...E.source.path,...y.remainingPath]},N=await o({currentFile:x.sourceFile,expressionPath:v,sourceInfo:I,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});return N?fp(N.kind==="external"?N:{...N,displayExpression:I.expression},{componentName:y.componentName,propName:y.propName,file:x.sourceFile}):null}async function d(m){let y=await kn(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let b=el(y.ast,m.caller.sourceRange);if(!b)return null;let S=b.get("openingElement").get("attributes").find(v=>v.isJSXAttribute()&&v.node.name.type==="JSXIdentifier"&&v.node.name.name===m.propName);if(!S?.isJSXAttribute())return null;let x=S.get("value"),E=x.isStringLiteral()?x:x.isJSXExpressionContainer()?x.get("expression"):null;if(!E?.isExpression())return null;let k=xs(E.node);return k?{kind:"value",file:m.caller.sourceFile,root:{kind:"expression",sourceRange:k},path:m.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:m.propName,editMode:"upstream",diagnostics:[]}:null}async function f(m){let y=await kn(m.caller.sourceFile,m.readFile,m.fileCache);if(!y.ast)return null;let b=el(y.ast,m.caller.sourceRange);if(!b)return null;let S=b.get("openingElement");for(let x of S.get("attributes")){if(!x.isJSXSpreadAttribute())continue;let E=x.get("argument");if(!E.isExpression())continue;let k=await i({expression:E.node,scope:E.scope,source:y.source,currentFile:m.caller.sourceFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!k)continue;let v=[{kind:"property",name:m.propName},...m.remainingPath],I={...k,expression:ni(k.expression,v),path:[...k.path,...v]},N=await o({currentFile:m.caller.sourceFile,expressionPath:E,sourceInfo:I,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:I.expression}}return null}async function g(m){let{currentFile:y,binding:b,readFile:S,exists:x,fileCache:E,visited:k}=m,v=b.path.parentPath;if(!v||!v.isImportDeclaration())return null;let I=v.node.source.value;if(typeof I!="string")return null;let N=await Xr(y,I,x);if(!N)return null;if(b.path.isImportDefaultSpecifier()){let $=await kn(N,S,E),W=$.ast?pp($.ast,"default"):null,ee=await p({file:N,exportName:"default",readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return!ee||ee.kind!=="static"?null:{kind:"static",file:W?.kind==="default-expression"?ee.file:N,root:W?.kind==="default-expression"?ee.root:{kind:"default-export"},value:ee.value,sourceKind:"imported-binding"}}if(!b.path.isImportSpecifier())return null;let A=b.path.node.imported,w=Z.isIdentifier(A)?A.name:A.value,L=await kn(N,S,E),B=L.ast?pp(L.ast,w):null,J=await p({file:N,exportName:w,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k});return J?J.kind==="external"?J:{kind:"static",file:B?.kind==="re-export"?J.file:N,root:B?.kind==="re-export"||J.root.kind==="binding"&&J.root.name!==B?.name?J.root:{kind:"named-export",name:w},value:J.value,sourceKind:"imported-binding"}:null}async function p(m){let{file:y,exportName:b,readFile:S,exists:x,fileCache:E,visited:k}=m,v=`export::${y}::${b}`;if(!k.has(v)){k.add(v);try{let I=await kn(y,S,E);if(!I.ast)return;let N=pp(I.ast,b);if(!N)return;if(N.kind==="default-expression"){let B=N.expression;if(!B||!Z.isIdentifier(B))return;let J=Ss(I.ast).getBinding(B.name);return J?await s({currentFile:y,binding:J,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let B=await Xr(y,N.source,x);return B?p({...m,file:B,exportName:N.name}):void 0}let A=N.name;if(!A)return;let w=Ss(I.ast).getBinding(A);return w?await s({currentFile:y,binding:w,readFile:S,exists:x,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:E,visited:k})??void 0:void 0}finally{k.delete(v)}}}return{resolveExportValue:p,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as ae from"@babel/types";function gp(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=vn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!fF(s,r)?null:{callPath:s,basePath:i}}function fF(e,t){let n=e.node.callee;return!ae.isMemberExpression(n)||!ae.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function sS(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Ec(r,t)}function rS(e,t){return e?ae.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function oS(e,t,n,r,o){let i=ae.isExpression(e.body)?e.body:e.body.body.find(a=>ae.isReturnStatement(a))?.argument;if(!i||!ae.isExpression(i))return;let s=mp(i,t,n,r,o);return typeof s=="number"?s:void 0}function mp(e,t,n,r,o){if(ae.isNumericLiteral(e)||ae.isStringLiteral(e)||ae.isBooleanLiteral(e))return e.value;if(ae.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(ae.isMemberExpression(e)){let i=Zc(e,t);if(i)return wt(r,i);let s=Zc(e,n);return s?wt(o,s):void 0}if(ae.isBinaryExpression(e)&&e.operator==="-"){let i=ae.isExpression(e.left)?mp(e.left,t,n,r,o):void 0,s=ae.isExpression(e.right)?mp(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function pF(e){if(ae.isExpression(e.body))return e.body;for(let t of e.body.body)if(ae.isReturnStatement(t)&&t.argument&&ae.isExpression(t.argument))return t.argument;return null}function mF(e,t,n){let r=ho(e,t,n);return typeof r=="boolean"?r:void 0}function ho(e,t,n){if(ae.isStringLiteral(e)||ae.isNumericLiteral(e)||ae.isBooleanLiteral(e))return e.value;if(ae.isNullLiteral(e))return null;if(ae.isIdentifier(e))return e.name===t?n:void 0;if(ae.isMemberExpression(e)){let r=Zc(e,t);return r?wt(n,r):void 0}if(ae.isUnaryExpression(e)&&e.operator==="!"){let r=ho(e.argument,t,n);return r===void 0?void 0:!r}if(ae.isLogicalExpression(e)){let r=ho(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&ho(e.right,t,n);if(e.operator==="||")return r||ho(e.right,t,n)}if(ae.isBinaryExpression(e)){let r=ae.isExpression(e.left)?ho(e.left,t,n):void 0,o=ae.isExpression(e.right)?ho(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 aS(e){let t=[],n=e;for(;ae.isMemberExpression(n)||ae.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(ae.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(ae.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(ae.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(ae.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return ae.isIdentifier(n)?{base:n.name,segments:t}:null}function cS(e){return e.some(t=>t.kind==="dynamic")}function iS(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function lS(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 gF(e,t){let n=[],r=[];for(let o of t){let i=wt(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 uS(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(p){let{currentFile:m,callPath:y,readFile:b,exists:S,fileCache:x,visited:E}=p,k=y.node.callee;if(!ae.isMemberExpression(k)||!ae.isIdentifier(k.property)||k.property.name!=="map")return null;let v=y.get("callee");if(!v.isMemberExpression())return null;let I=v.get("object");if(Array.isArray(I)||!I.isExpression())return null;let N=await a({currentFile:m,expressionPath:I,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:x,visited:E});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(p){let{currentFile:m,expressionPath:y,readFile:b,exists:S,fileCache:x,visited:E}=p;if(y.isIdentifier()){let k=y.scope.getBinding(y.node.name);if(!k)return null;let v=await t({currentFile:m,binding:k,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:x,visited:E});return v?.kind==="static"?v:null}if(y.isCallExpression())return l({currentFile:m,callPath:y,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:x,visited:E});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let k=y.get("expression");if(!Array.isArray(k)&&k.isExpression())return a({...p,expressionPath:k})}if(y.isArrayExpression()){let k=xs(y.node);if(!k)return null;let v=await n(y.node,y.scope,m,b,S,x,E);return Array.isArray(v)?{kind:"static",file:m,root:{kind:"expression",sourceRange:k},value:v,sourceKind:"binding"}:null}if(y.isMemberExpression()){let k=await r({expression:y.node,scope:y.scope,currentFile:m,readFile:b,exists:S,fileCache:x,visited:E});if(!k)return null;let v=await o({currentFile:m,expressionPath:y,sourceInfo:k,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:x,visited:E});if(!v||v.kind==="external")return null;let I=await c({currentFile:m,expressionPath:y,provenance:v,readFile:b,exists:S,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:x,visited:E});if(!I||I.kind!=="static")return null;if(v.collectionPathMap?.length){let A=gF(I.value,v.collectionPathMap);if(A)return{kind:"static",file:v.file,root:v.root,value:A.value,sourceKind:v.sourceKind,collectionPathMap:A.collectionPathMap}}let N=wt(I.value,v.path);return Array.isArray(N)?{kind:"static",file:v.file,root:v.root,value:N,sourceKind:v.sourceKind,pathPrefix:v.path,collectionIndexMap:v.collectionIndexMap,collectionPathMap:v.collectionPathMap}:null}return null}async function c(p){let{provenance:m}=p;if(m.root.kind==="binding"){let x=p.expressionPath.scope.getBinding(m.root.name);if(!x&&m.file!==p.currentFile){let E=await kn(m.file,p.readFile,p.fileCache);x=E.ast?Ss(E.ast).getBinding(m.root.name):void 0}return x?await t({currentFile:m.file,binding:x,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(m.root.kind!=="expression")return null;let y=await kn(m.file,p.readFile,p.fileCache);if(!y.ast)return null;let b=ZE(y.ast,m.root.sourceRange);if(!b)return null;let S=await n(b.node,b.scope,m.file,p.readFile,p.exists,p.fileCache,p.visited);return S===void 0?null:{kind:"static",file:m.file,root:m.root,value:S,sourceKind:m.sourceKind}}async function l(p){return await u(p)??await d(p)??await f(p)}async function u(p){let{callPath:m}=p,y=m.node.callee;if(!ae.isMemberExpression(y)||!ae.isIdentifier(y.property)||y.property.name!=="filter")return null;let b=m.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let x=await a({currentFile:p.currentFile,expressionPath:S,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(!x||!Array.isArray(x.value))return null;let[E]=m.node.arguments;if(!ae.isArrowFunctionExpression(E)&&!ae.isFunctionExpression(E))return null;let k=E.params[0];if(!ae.isIdentifier(k))return null;let v=pF(E);if(!v)return null;let I=[],N=[],A=[];for(let[w,L]of x.value.entries()){let B=mF(v,k.name,L);if(typeof B!="boolean")return null;if(B){I.push(L),N.push(x.collectionIndexMap?.[w]??w);let J=x.collectionPathMap?.[w];J&&A.push(J)}}return{...x,value:I,pathPrefix:x.pathPrefix,collectionIndexMap:N,...A.length>0?{collectionPathMap:A}:{}}}async function d(p){let{callPath:m}=p,y=m.node.callee;if(!ae.isMemberExpression(y)||!ae.isIdentifier(y.property)||y.property.name!=="slice")return null;let b=m.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let x=await a({currentFile:p.currentFile,expressionPath:S,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(!x||!Array.isArray(x.value))return null;let[E,k]=m.node.arguments,v=rS(E,0),I=rS(k,x.value.length);if(v===null||I===null)return null;let N=Math.max(0,v<0?x.value.length+v:v),A=Math.max(0,I<0?x.value.length+I:I),w=x.value.map((B,J)=>x.collectionIndexMap?.[J]??J).slice(N,A),L=x.collectionPathMap?.slice(N,A);return{...x,value:x.value.slice(N,A),pathPrefix:x.pathPrefix,collectionIndexMap:w,...L?{collectionPathMap:L}:{}}}async function f(p){let{callPath:m}=p,y=m.node.callee;if(!ae.isMemberExpression(y)||!ae.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let b=m.get("callee");if(!b.isMemberExpression())return null;let S=b.get("object");if(Array.isArray(S)||!S.isExpression())return null;let x=await a({currentFile:p.currentFile,expressionPath:S,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(!x||!Array.isArray(x.value))return null;let[E]=m.node.arguments;if(!ae.isArrowFunctionExpression(E)&&!ae.isFunctionExpression(E))return null;let[k,v]=E.params;if(!ae.isIdentifier(k)||!ae.isIdentifier(v))return null;let I=x.value.map((A,w)=>({value:A,sourceIndex:x.collectionIndexMap?.[w]??w,originalIndex:w})),N=[...I];for(let A of I)for(let w of I)if(oS(E,k.name,v.name,A.value,w.value)===void 0)return null;return N.sort((A,w)=>{let L=oS(E,k.name,v.name,A.value,w.value)??0;return L===0?A.originalIndex-w.originalIndex:L}),{...x,value:N.map(A=>A.value),pathPrefix:x.pathPrefix,collectionIndexMap:N.map(A=>A.sourceIndex),...x.collectionPathMap?{collectionPathMap:N.map(A=>x.collectionPathMap?.[A.originalIndex]).filter(A=>!!A)}:{}}}async function g(p){let m=null,y=!1,b,S=[];for(let E of p.segments){if(E.kind!=="dynamic")continue;let k=await r({expression:E.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(!k)return null;let v=gp(p.expressionPath,k.base),I;if(v){y=!0;let N=await s({currentFile:p.currentFile,callPath:v.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;I=N.value.map((A,w)=>{let L=wt(N.value,[{kind:"index",index:w},...v.basePath,...k.path]);return iS(L)}),b??=N.collectionIndexMap}else{let N=await i({...p,sourceInfo:k});if(!N)return null;I=N.map(iS)}if(I.some(N=>N===null)||m!==null&&m!==I.length)return null;m=I.length,S.push(I)}if(m===null||m===0)return null;let x=[];for(let E=0;E<m;E+=1){let k=[...p.rootPath],v=0;for(let I of p.segments){if(I.kind==="dynamic"){let N=S[v]?.[E];if(!N)return null;k.push(N),v+=1;continue}k.push({...I})}x.push(k)}return{sourceKind:y||m>1?"repeat-template":"binding",...b?{collectionIndexMap:b}:{},collectionPathMap:x}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:hF,evaluateStaticExpression:tl}=JE({resolveBindingTarget:e=>nl(e)}),{resolveRepeatCollectionTarget:yF,resolveCollectionCallTarget:bF,resolveDynamicMemberPathMap:xF}=uS({resolveBindingTarget:e=>nl(e),evaluateStaticExpression:tl,buildExpressionSourceInfo:Kn,resolveSourceInfoProvenance:gn,resolveComponentPropValues:e=>vF(e)}),{resolveExportValue:EF,resolveComponentPropBinding:SF,resolveComponentPropValues:vF,resolveBindingTarget:nl}=nS({resolveExternalExpression:vp,resolveCollectionCallTarget:bF,evaluateStaticExpression:tl,resolveSourceInfoProvenance:gn,buildExpressionSourceInfo:Kn});function xS(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var dS=new WeakMap;function IF(e){let t=dS.get(e);return t||(t=new WeakMap,dS.set(e,t)),t}function fS(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 ES(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=qc(s,t,n);if(!a)return null;let c=Qc(a,r.sourceRange);if(!c)return null;let l=await Kn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Rp({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?bp(f,ti(c.node,n)):null}let u=new Set,d=await XF({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?bp(d,l.expression):null}async function ri(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=qc(i,t,n);if(!s)return null;let a=e.sourceRange?Qc(s,e.sourceRange):e.expression!==void 0?Es(s,n,e.expression):null;if(!a)return null;let c=rl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await Kn({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await gn({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 NS({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 bp(d,e.expression??ti(c.node,n))}async function Sp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=qc(i,t,n);if(!s)return Qt("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?kF({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}):_F({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function Kn(e){if(pe.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!pe.isMemberExpression(e.expression))return null;let t=await hF(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:ti(e.expression,e.source),base:t.base,path:t.path}:null}function bp(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 kF(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Qc(r,o.sourceRange),u=l?await Kn({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 pS(t,o.value);let f=await Rp({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"?bS(t,f):Ep(t,ti(l.node,n),f):RF({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return Qt("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await gn({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=xp(l.node);if(f)return Qt(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let p=xp(g.path.node.init);if(p)return Qt(p.code,p.message)}return g?.path.isVariableDeclarator()&&pe.isCallExpression(g.path.node.init)?CF("unsupported-expression",_S(g.path.node.init,e.functionCallContracts)):Qt("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?bS(t,d):Ep(t,u.expression,d)}async function _F(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return Qt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Es(r,n,o.conditionExpression);if(!l)return Qt("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await gn({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 Qt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return Qt("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Ep(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 pS(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 RF(e){let t=await vS(e);if(t.length===0)return Qt("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(NF(e.expression))return SS(t);if(kS(e.expression))return Qt("unsupported-expression","i18n helpers require a static message id string");if(pe.isMemberExpression(e.expression)&&e.expression.computed&&!pe.isNumericLiteral(e.expression.property)&&!pe.isStringLiteral(e.expression.property))return Qt("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return Qt(n.code,n.message)}function Qt(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function CF(e,t){return SS([{code:e,message:t}])}function SS(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function NF(e){return pe.isCallExpression(e)||pe.isConditionalExpression(e)||pe.isLogicalExpression(e)||pe.isBinaryExpression(e)}function Is(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 vS(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=xp(t);if(l)return[l];if(pe.isCallExpression(t))return[{code:"unsupported-expression",message:_S(t,c)}];if(pe.isMemberExpression(t)&&t.computed){let u=t.property;if(!pe.isNumericLiteral(u)&&!pe.isStringLiteral(u)){if(!pe.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await tl(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 pe.isBinaryExpression(t)?Is([...await hp(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):pe.isLogicalExpression(t)?Is([...await hp(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"}]):pe.isConditionalExpression(t)?Is([...await hp(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 xp(e){return kS(e)?mS("i18n helpers require a static message id string"):OF(e)?mS("CMS helpers require static entry id and field path string arguments"):null}async function hp(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await vS({...t,expression:o}));return r}function PF(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:[AF(e.sourceType)]}}async function vp(e){for(let n of MF){if(!gS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return yS(hS(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(!gS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return yS(hS(r),e.externalAdapters)}return null}function AF(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function TF(e){return{code:"external-source-readonly",message:e}}function mS(e){return{code:"unsupported-expression",message:e}}function Ip(e){return!e||!pe.isCallExpression(e)?null:pe.isIdentifier(e.callee)?e.callee.name:pe.isMemberExpression(e.callee)&&!e.callee.computed&&pe.isIdentifier(e.callee.object)&&pe.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function gS(e,t){if(!t||t.length===0)return!0;let n=Ip(e.node);return n?t.includes(n):!1}function hS(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:Is(e.diagnostics??[])}:{match:e,diagnostics:[]}}function yS(e,t){let n=PF(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:Is([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function wF(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!pe.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!pe.isStringLiteral(n)||!pe.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 OF(e){return!!e&&pe.isCallExpression(e)&&pe.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!pe.isStringLiteral(e.arguments[0])||!pe.isStringLiteral(e.arguments[1]))}function IS(e){if(!(!e||!pe.isCallExpression(e))){if(pe.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&pe.isStringLiteral(t)?t.value:null}if(pe.isMemberExpression(e.callee)&&!e.callee.computed&&pe.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&pe.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!pe.isObjectExpression(t))return null;for(let n of t.properties)if(pe.isObjectProperty(n)&&!n.computed&&(pe.isIdentifier(n.key)&&n.key.name==="id"||pe.isStringLiteral(n.key)&&n.key.value==="id")&&pe.isStringLiteral(n.value))return n.value.value;return null}}}function kS(e){return IS(e)===null}async function LF(e,t,n){let r=new Set,o=vs.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=vs.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"]:[vs.posix.join(i,"locales"),vs.posix.join(i,"messages")];for(let a of s){let c=vs.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function FF(e){let t=IS(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await LF(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function DF(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!pe.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!pe.isExpression(n))return null;let o=await tl(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:[TF("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var MF=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>wF(e)},{helperNames:["apiField"],resolve:e=>DF(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>FF({currentFile:e,expressionPath:t,exists:n})}];function kp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function bS(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 Ep(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=JF(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 BF=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function _p(e,t){let n=[...BF,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function _S(e,t){let n=e.callee;return pe.isIdentifier(n)&&_p(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 Rp(e){let t=await vp(e);if(t)return t;let n=await RS({...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 Kn({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 gn({...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 VF(e)}async function RS(e){let t=await _n({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=rl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:kp(t.provenance)}async function _n(e){let t=rl(e.expressionPath),n=UF(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 Kn({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 gn({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 Kn({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 gn({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 _n({...e,expressionPath:r,allowComposed:!0}),a=await _n({...e,expressionPath:o,allowComposed:!1}),c=await _n({...e,expressionPath:i,allowComposed:!1});return yp(s,a,c)}if(t.isCallExpression())return jF({...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 _n({...e,expressionPath:r,allowComposed:!0}),s=await _n({...e,expressionPath:o,allowComposed:!0});return yp(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 _n({...e,expressionPath:r,allowComposed:!0}),s=await _n({...e,expressionPath:o,allowComposed:!0});return yp(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:_n({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function rl(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();){let n=t.get("expression");if(Array.isArray(n)||!n.isExpression())return t;t=n}return t}async function jF(e){let t=Ip(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:_n({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(pe.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:_n({...e,expressionPath:o,allowComposed:!1})}}return null}function yp(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!$F(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function $F(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 UF(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function VF(e){if(!e.expressionPath.isCallExpression())return null;let t=Ip(e.expressionPath.node);if(!t)return null;let n=_p(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 CS({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?kp(i):null}async function CS(e){let t=await vp({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 Kn({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 gn({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 Rp({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 KF(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!pe.isCallExpression(t))return null;let n=t.callee;if(!pe.isIdentifier(n))return null;let r=_p(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 CS({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?kp(a):null}function JF(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=ni(t,e.path);return{sourceId:o,displayPath:o}}async function XF(e){let t=e.segment.source;return t?gn({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 gn(e){let t=e.sourceInfo,n=gp(e.expressionPath,t.base);if(n){let l=await yF({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 m=sS(n.callPath,[...n.basePath,...t.path]);return ss(m)?fS(e.currentFile,m.sourceId,m.displayPath):null}let u=lS(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 wt(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 Xr(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await EF({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 wt(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=qb(r);if(o){let l=o.expressionPath,u=await Kn({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 gn({...e,expressionPath:l,sourceInfo:{...u,expression:ni(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 NS({...e,expressionPath:rl(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await RS({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 SF({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 KF({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=bc(r,t.path,IF(e.fileCache));if(ss(s))return fS(e.currentFile,s.sourceId,s.displayPath);let a=await nl({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:wt(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 NS(e){let t=aS(e.expressionPath.node);if(!t||!cS(t.segments))return null;let n=await gn({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 xF({...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 nl({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>wt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:ti(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function PS(e){let t=zF(e.propertyName);if(t.owner==="blocked")return Fr(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Fr(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 Fr("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 WF(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 Fr("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}:Fr("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?Fr("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):HF(e,s.attribute)}async function HF(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await ri({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}}:Fr("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 ri({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"?Fr("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 WF(e,t){let n=t.source?.expression;if(!n)return;let r=await ri({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:GF(r,e.propertyName)}}function GF(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 Fr(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function AS(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(yo(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=>QF(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>YF({...r,graph:e},n)}function YF(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=qF(n,r,o,t),a=s?.tag??(yo(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=tD(s),u=nD(n,r,o,i,s),d=ZF(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:eD(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:rD(d),alternativeStrategies:oD(d)}}function ZF(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Cp(e,n)?"instance":!yo(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function qF(e,t,n,r){if(yo(t.tag))return t;let o=Cp(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function QF(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function eD(e,t){return yo(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function tD(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 nD(e,t,n,r,o){let i=new Set,s=Cp(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&&yo(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Cp(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(yo(r.tag))return r;n=r.parentKey}return null}function yo(e){return/^[A-Z]/.test(e)}function rD(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function oD(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function OS(e){let t=e.isRepeat??(e.graph?pD(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=fD(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>iD({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:mD(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 iD(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=sD(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:Cc({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=aD(t,n,l,e.isRepeat),d=c?uD(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?lD(n,o,e.element):"unsupported",p=o?"repeat-item":e.isRepeat?"repeat-template":"node",m=dD(t,n,r);if(f.length===0&&m.length===0){let y=s.find(({result:b})=>!b.ok)?.result;y&&!y.ok&&m.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:m}}function sD(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 aD(e,t,n,r){return n?TS(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:TS(cD(e))}function cD(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 TS(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function lD(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 uD(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:wS({...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:wS(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function dD(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 fD(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function pD(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 wS(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 mD(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 gD(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var hD=160;function LS(e,t,n,r={}){let o=No(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 FS(e,t,n,r,o,i,s,a,c,l,u){let d=No(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 m=$S(f.textSegments,s),y=US(e,t,f,p,m),b=m?ED(m):void 0,S=SD(i,m),x=f.textSegments.map(I=>({index:I.index,value:I.value,editable:VS(I,p,s?.get(I.index)??null),source:o.get(I.index)??null})),E=BS(f,t),k=f.childKeys.map(I=>{let N=t.elements.get(I);return N?{key:I,tag:N.tag,label:N.tag}:null}).filter(I=>I!==null),v=[];if(f.parentKey){let I=t.elements.get(f.parentKey);if(I)for(let N of I.childKeys){if(N===e)continue;let A=t.elements.get(N);A&&v.push({key:N,tag:A.tag,label:A.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:MS(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:S,provenanceChain:b,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:x,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:E,children:k,siblings:v}}function DS(e,t,n,r,o,i,s,a){let c=No(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=$S(l.textSegments,i),g=yD(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:MS(l),label:l.tag,capabilities:US(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 m=o.get(p.index);return{index:p.index,editable:VS(p,d,i?.get(p.index)??null),source:m?{kind:m.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:BS(l,t)}}function yD(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 MS(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:bD(e.sourceRange),structuralPath:e.identity.structuralPath,...xD(e.textSegments)}}function BS(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 bD(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function xD(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,hD)}:{}}function jS(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 $S(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function US(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&&KS(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 VS(e,t,n){return!e.editable||!t.canUpdateText?!1:n?KS(n.editMode):!0}function KS(e){return e==="direct"||e==="proxy"||e==="upstream"}function ED(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 SD(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}:gD(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 Np=["set-class-name-source","apply-style-draft"];function JS(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Np,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:Np,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Np}}import XS from"node:path";function Ap(){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 HS(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=_D(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 ol(e){let t=()=>vD(e);return e.mutex?e.mutex.runExclusive(t):t()}async function vD(e){let t=await HS(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=ID(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 Pp({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 Pp({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 Pp({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 zS("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return zS("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 ID(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 Pp(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:kD(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 zS(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function kD(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 _D(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)||XS.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=XS.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 RD=50,CD=8*1024*1024;function ZS(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??RD),s=Math.max(0,t.maxUndoBytes??CD);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(I){let N=[...I.steps].sort(($,W)=>$.order-W.order),A=N.filter($=>$.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 w=new Set(A.map($=>$.file)),L=await S(w),B=new Map(L.map($=>[$.file,$.exists===!1?"":$.content])),J;for(let $ of A){let W=YS($,B.get($.file)??"");if(!W.ok)return{ok:!1,errorCode:W.errorCode,reason:W.reason};B.set($.file,W.source),J=W.selectionRef??J}return{ok:!0,filePlan:{operationId:I.operationId,kind:"source-edit",target:I.target,documentVersion:I.documentVersion,conflictPolicy:"compare-and-swap",edits:[...B].map(([$,W])=>({operation:"upsert",file:$,content:W,baseContentHash:L.find(ee=>ee.file===$)?.sha256??null}))},...J?{selectionRef:J}:{}}}async function c(I){let N=[...I.steps].sort((ee,Ge)=>ee.order-Ge.order),A=N.filter(ee=>ee.type!=="invoke-external-adapter"),w=N.filter(ee=>ee.type==="invoke-external-adapter"),L=new Set(A.map(ee=>ee.file));if(A.length>0&&w.length>0)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(A.length===0)return y(I,w);let B=await S(L),J=new Map;for(let ee of B)J.set(ee.file,ee.exists===!1?"":ee.content);let $;for(let ee of A){let Ge=J.get(ee.file)??"",tt=YS(ee,Ge);if(!tt.ok)return{ok:!1,operationId:I.operationId,errorCode:tt.errorCode,reason:tt.reason,rolledBack:!1};J.set(ee.file,tt.source),tt.selectionRef&&($=tt.selectionRef)}let W=await E([...J].map(([ee,Ge])=>({file:ee,content:Ge,exists:!0,version:0,sha256:_e(Ge)})),B);return W.ok===!1?{ok:!1,operationId:I.operationId,errorCode:W.rolledBack?"writeback-failed":"rollback-failed",reason:W.reason,rolledBack:W.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:B,postSnapshots:W.snapshots,plan:I}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...W.snapshots.map(ee=>ee.version)),affectedFiles:[...L],...$?{selectionRef:$}:{}})}async function l(I){let N=new Set(I.edits.map(W=>W.file)),A=await S(N),w=b(I,A);if(w)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let L=new Map(A.map(W=>[W.file,W])),B=I.edits.find(W=>W.operation==="create-only"&&L.get(W.file)?.exists!==!1);if(B)return{ok:!1,operationId:I.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${B.file}`,affectedFiles:[B.file],rolledBack:!1};let J=I.edits.map(W=>W.operation==="delete"?{file:W.file,content:"",exists:!1,version:0}:{file:W.file,content:W.content,exists:!0,version:0,sha256:_e(W.content)}),$=await E(J,A,new Set(I.edits.filter(W=>W.operation==="create-only").map(W=>W.file)));return $.ok===!1?{ok:!1,operationId:I.operationId,errorCode:$.rolledBack?"writeback-failed":"rollback-failed",reason:$.reason,rolledBack:$.rolledBack}:(n.push({operationId:I.operationId,preSnapshots:A,postSnapshots:$.snapshots,plan:{operationId:I.operationId,kind:I.kind,target:I.target,documentVersion:I.documentVersion,steps:[],preSnapshots:A}}),f(),r.length=0,{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:Math.max(...$.snapshots.map(W=>W.version)),affectedFiles:[...N]})}async function u(){let I=n.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await E(I.preSnapshots,I.postSnapshots);return N.ok===!1?{ok:!1,operationId:I.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(I),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:I.preSnapshots.map(A=>A.file)})}async function d(){let I=r.at(-1);if(!I)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await E(I.postSnapshots,I.preSnapshots);return N.ok===!1?{ok:!1,operationId:I.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(I),f(),{ok:!0,operationId:I.operationId,kind:I.plan.kind,target:I.plan.target,resultVersion:Math.max(...N.snapshots.map(A=>A.version)),affectedFiles:I.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((I,N)=>I+p(N),0)}function p(I){return m(I.preSnapshots)+m(I.postSnapshots)}function m(I){return I.reduce((N,A)=>N+A.file.length+A.content.length,0)}async function y(I,N){let A=[];for(let w of N){let L=w.capability??"write-text",B=o.find($=>$.sourceType===w.sourceType&&(w.adapterId===void 0||$.adapterId===w.adapterId)&&($.capabilities===void 0||$.capabilities.includes(L)));if(!B)return{ok:!1,operationId:I.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${w.sourceType}`,rolledBack:!1};let J=await B.execute(w);if(!J.ok)return{ok:!1,operationId:I.operationId,errorCode:"writeback-failed",reason:J.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};A.push(w.file)}return{ok:!0,operationId:I.operationId,kind:I.kind,target:I.target,resultVersion:0,affectedFiles:A}}function b(I,N){if(I.conflictPolicy!=="compare-and-swap")return null;let A=new Map(N.map(w=>[w.file,w]));for(let w of I.edits){if(w.operation==="create-only")continue;if(w.baseContentHash===void 0)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};let L=A.get(w.file),B=w.baseContentHash;if(B===null){if(L?.exists!==!1)return{file:w.file,reason:`Source file ${w.file} was created or changed before save.`};continue}if(!B)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};if(L?.exists===!1||L?.sha256!==B)return{file:w.file,reason:`Source file ${w.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function S(I){let N=[];for(let A of I)N.push(await x(A));return N}async function x(I){if(!await e.exists(I))return{file:I,content:"",version:0,exists:!1};let A=Math.max(1,e.getVersion(I)),w=await e.readFile(I);return{file:I,content:w,version:A,exists:!0,sha256:_e(w)}}async function E(I,N,A=new Set){let w=[];try{for(let L of I){if(A.has(L.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(L.file,L.content)}else await k(L);let B=e.bumpVersion(L.file);w.push(L.file),L.version=B}}catch(L){let B=await v(N.filter($=>w.includes($.file)));if(B.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${B.failedFiles.join(", ")}: ${GS(L)}`,rolledBack:!1,instanceConflict:WS(L)};let J=WS(L);return{ok:!1,reason:`${J?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${GS(L)}`,rolledBack:!0,instanceConflict:J}}return{ok:!0,snapshots:I.map(ND)}}async function k(I){if(I.exists===!1){await e.deleteFile(I.file);return}await e.writeFile(I.file,I.content)}async function v(I){let N=[];for(let A of I)try{await k(A),e.bumpVersion(A.file)}catch{N.push(A.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function WS(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function ND(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:_e(e.content)}:{}}}function GS(e){return e instanceof Error?e.message:String(e)}function YS(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 _t(ln({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return _t(Co({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return _t(Qr({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return _t(cn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return _t(ca({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return _t(Ri({source:t,locator:e.locator,next:e.value}));case"update-array-item":return _t(Ri({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return _t(ma({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return _t(la({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return _t(ga({source:t,locator:e.locator,index:e.index}));case"move-array-item":return _t(ha({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return _t(to({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return _t(ua({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 PD(e,t);case"set-property-changes":return _t(da({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return _t(fa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return _t(pa({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return _t(ba({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function PD(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!lh(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!==_e(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:ch({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function _t(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 il,SiteEditCompositionContextSchema as AD,SiteEditCompositionSelectorSchema as TD}from"@vcp-dev/contracts";var Ot=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function qS(e,t){throw new Ot("INVALID_COMPOSITION",e,{value:t})}function sl(e){let t=AD.safeParse(e);return t.success?t.data:qS("Invalid SiteEditCompositionContext.",e)}function QS(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=sl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ot("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=il(u);if(n.has(d))throw new Ot("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new Ot("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 Ot("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=sl(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Ot("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=il(u);if(!n.has(d))throw new Ot("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Ot("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=TD.safeParse(l);if(!u.success)return qS("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 Ot("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Ot("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=sl(l),d=il(u),f=n.get(d);if(!f)throw new Ot("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=sl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Ot("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=il(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new Ot("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(m=>m.entryFile===l.entryFile);if(g)throw new Ot("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 Tp(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 ev(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 wD,stripSiteEditRepeatInstanceKeys as tv}from"@vcp-dev/contracts";function nv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=tv(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 OD(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 al(e){return e?.map(t=>({...t}))}function wp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=al(e.collectionPathMap?.[t])??al(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:al(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>al(o)??[])}}function rv(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)=>wD(g,p),c=(g,p,m)=>{let y=o.get(g);if(!y)return a(g,m);let b=a(g,m),S={...y,key:b,parentKey:p,childKeys:[]};return i.push(S),S.childKeys=y.childKeys.flatMap(x=>l(x,m,b)),b},l=(g,p,m)=>{if(!r.has(g))return[c(g,m,p)];let y=d(g,p),b=[];for(let S=0;S<y;S+=1)b.push(c(g,m,[...p,S]));return b},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 m=0;m<p;m+=1)c(g,null,[m])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,p){let m=new Set;for(let y of f(g)){let b=n.get(y);if(b){for(let S of[...b.textTargets.values(),...b.elementPropertyTargets.values()])if(!(S?.kind!=="value-binding"||S.sourceKind!=="repeat-template"))for(let x of LD(S))x.length<=p.length||FD(x,p)&&m.add(x[p.length])}}return m.size>0?m.size:OD(n.get(g))}function f(g){let p=s.get(g);if(p)return p;let m=[g],y=o.get(g);for(let b of y?.childKeys??[])m.push(...f(b));return s.set(g,m),m}}function ov(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function iv(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((tv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function LD(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 FD(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 sv(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 av(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 cv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function DD(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ks=class extends Error{constructor(t){let n=t.map(cv);super(DD(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function lv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ks?{routeId:e,message:n,diagnostics:t.diagnostics.map(cv)}:{routeId:e,message:n}}function Op(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Lp(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function _s(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function uv(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function cl(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 dv(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 JD=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,XD=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],fv=32,ul=256;function zD(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var pv={maxEntries:50,maxBytes:8*1024*1024};function HD(){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 Sa(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 mv(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 WD(){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>pv.maxEntries||GD(e)>pv.maxBytes;)e.shift()}}function GD(e){return e.reduce((t,n)=>t+YD(n),0)}function YD(e){return gv(e.preSnapshots)+gv(e.postSnapshots)+ZD(e.provenance)}function ZD(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function gv(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function hv(e,t){return{key:BD(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 dl=class extends Error{constructor(t){super(t.reason),this.result=t}},bo=class extends Error{constructor(t){super(Op(t)),this.failedRoutes=t}};function yv(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=Vt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(Vt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function qD(e,t,n){if(!n)return;let r=Vt(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 QD=/\.(?:[cm]?[jt]sx?)$/i,eM=/\.json$/i,tM=/\.(?:css|scss|sass)$/i,nM=/\.mdx$/i,rM=/\.ya?ml$/i;function oM(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 iM(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function sM(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=Iv(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(aM(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 aM(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Iv(e){return Array.isArray(e)?{files:e}:e}function cM(e){if(!$D(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!==VD||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=jD(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(QD.test(e.path)){let t=Pn({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(eM.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Ft(t)}`,details:{path:e.path}}}if(tM.test(e.path)){let t=bv({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(nM.test(e.path)){let t=bv({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(rM.test(e.path))try{KD(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Ft(t)}`,details:{path:e.path}}}return{ok:!0}}function bv({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
- `,d);if(p===-1){l=!0;break}d=p,l=!0;continue}if(c){l=f===`
9
- `||f==="\r";continue}if(s){f==="*"&&g==="/"&&(s=!1,d+=1),l=f===`
10
- `||f==="\r";continue}if(a){f===`
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
- `||f==="\r"))return oi(t,`Unterminated string literal in ${t}.`);l=f===`
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===")"?"(":"[",m=r.pop();if(!m||m.char!==p)return oi(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
14
- `||f==="\r"}if(s)return oi(t,`Unterminated block comment in ${t}.`);if(o)return oi(t,`Unterminated string literal in ${t}.`);if(c)return oi(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?oi(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function oi(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function fl(e){let t="idle",n=e.fileSystem??HD(),r=uh(),o=QS({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Qh(e.historyStore):WD()),u=ZS(n,{externalAdapters:e.externalAdapters}),d=new Map,f=Eh(ul),g=new Set,p=0,m=e.historyStore?.recoveryRequired??!1,y=Ap(),b=k();function S(h){return(ll.isAbsolute(h)?ll.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function x(h,C){let _=ll.posix.dirname(h),T=C.replace(/\.(?:tsx?|jsx?)$/i,""),F=ll.posix.relative(_,T);return F.startsWith(".")?F:`./${F}`}function E(h,C){return h.startLine===C.startLine&&h.startColumn===C.startColumn&&h.endLine===C.endLine&&h.endColumn===C.endColumn}async function k(){let h=e.historyStore;if(h)try{let C=await h.readTransactionJournal();if(!C)return;let _=await h.readIndex(),T=await Promise.all(C.files.map(async D=>await n.exists(D.path)?_e(await n.readFile(D.path)):null));if(dv({journal:C,index:_,observedFileDigests:T})!=="ambiguous"){await h.clearTransactionJournal(C.transactionId);let D=await h.readStatus();D.recoveryRequired||(await h.cleanupTmp(),D=await h.readStatus()),m=D.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${C.transactionId} at phase ${C.phase}`),m=!0}catch(C){m=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${Ft(C)}`).catch(()=>{})}}function v(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let C=hv(h.context,h.entryFile);i.set(h.key,C),I(C,C.dependencyFiles)}function I(h,C){let _=new Set(C);N(h),h.dependencyFiles=_;for(let T of h.dependencyFiles){let F=s.get(T);F||(F=new Set,s.set(T,F)),F.add(h.key)}}function N(h){for(let C of h.dependencyFiles){let _=s.get(C);_&&(_.delete(h.key),_.size===0&&s.delete(C))}h.dependencyFiles.clear()}function A(h){let C=new Set;for(let _ of h)for(let T of s.get(_)??[])C.add(T);return C}function w(h){for(let C of h)if(!s.has(C))return!1;return!0}async function L(h,C,_,T,F,D){let K=new Map,X=AS(h),Q=xS(F.values()),H=yE(F.values()),z=typeof D.exists=="function"?re=>D.exists(re):async()=>!1;for(let[re,ue]of h.elements){let ke=C.nodes.get(re);if(!ke)continue;let se=_.get(ue.sourceFile)??T.get(ue.sourceFile),we=new Map,ve=new Map,j=new Map,q=[];for(let Ye of ue.textSegments){if(!se){we.set(Ye.index,null);continue}let mi=await ES({file:ue.sourceFile,source:se,segment:Ye,readFile:Kt=>D.readFile(Kt),exists:z,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Kt,adapterId:Jr,capabilities:Hl})=>({sourceType:Kt,adapterId:Jr,capabilities:Hl})),functionCallContracts:e.functionCallContracts,fileCache:Q}),Lt=await Sp({file:ue.sourceFile,source:se,target:{kind:"text-segment",segment:Ye},readFile:Kt=>D.readFile(Kt),exists:z,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Kt,adapterId:Jr,capabilities:Hl})=>({sourceType:Kt,adapterId:Jr,capabilities:Hl})),functionCallContracts:e.functionCallContracts,fileCache:Q}),on=oM(mi);we.set(Ye.index,on),ve.set(Ye.index,mi),j.set(Ye.index,Lt),q.push({editable:Ye.editable,source:on})}let ye=new Map,Ne=new Map;if(se)for(let Ye of ue.attributes??[]){let mi=await ri({file:ue.sourceFile,source:se,sourceRange:Ye.sourceRange,expression:Ye.source?.expression??Ye.value,sourceInfo:Ye.source,readFile:on=>D.readFile(on),exists:z,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:on,adapterId:Kt,capabilities:Jr})=>({sourceType:on,adapterId:Kt,capabilities:Jr})),functionCallContracts:e.functionCallContracts,fileCache:Q}),Lt=await PS({element:ue,file:ue.sourceFile,source:se,propertyName:Ye.name,readFile:on=>D.readFile(on),exists:z,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:on,adapterId:Kt,capabilities:Jr})=>({sourceType:on,adapterId:Kt,capabilities:Jr})),functionCallContracts:e.functionCallContracts,fileCache:Q});Ne.set(Ye.name,Lt),ye.set(Ye.name,mi)}let Oe=jS(iM(ke.writeTarget),q),ot=X({key:re,element:ue,provenances:j}),sr=JS(ue),Cn=se?await bE({element:ue,graph:h,file:ue.sourceFile,source:se,readFile:Ye=>D.readFile(Ye),exists:z,fileCache:H}):void 0,Kr=h.regions.find(Ye=>Ye.kind==="conditional-region"&&Ye.childKeys.includes(re)),vt,rn=Kr?.sourceCandidates?.[0];if(se&&Kr&&rn?.kind==="conditional-branch"){let Ye=await Sp({file:ue.sourceFile,source:se,target:{kind:"conditional-branch",candidate:rn},readFile:Lt=>D.readFile(Lt),exists:z,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Lt,adapterId:on,capabilities:Kt})=>({sourceType:Lt,adapterId:on,capabilities:Kt})),functionCallContracts:e.functionCallContracts,fileCache:Q});vt={currentBranch:Kr.childKeys.indexOf(re)<=0?"then":"else",availableBranches:Kr.childKeys.length>1?["then","else"]:["then"],conditionExpression:rn.conditionExpression,provenance:{finalSource:Ye.finalSource?{kind:Ye.finalSource.kind,file:Ye.finalSource.file,displayPath:Ye.finalSource.displayPath}:null,chain:Ye.chain.map(Lt=>({kind:Lt.kind,file:Lt.file,displayName:Lt.displayName,canEditHere:Lt.canEditHere})),confidence:Ye.confidence,editMode:Ye.editMode,diagnostics:Ye.diagnostics.map(Lt=>({code:Lt.code,message:Lt.message}))}}}K.set(re,{textSources:we,textTargets:ve,elementPropertyTargets:ye,propertyProvenances:Ne,isRepeat:kM(re,h),provenances:j,writeTarget:Oe,componentSemantic:ot,styleSource:sr,conditional:vt,dynamicData:Cn})}return K}function B(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function J(h,C){let _=o.initialVersions.get(h.key)??0;for(let T of C.values())_=Math.max(_,T);return Math.max(_,h.graph?.version??0)}function $(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function W(h){try{return $(o.resolveSelector(h.composition).key)}catch{return 0}}async function ee(h,C,_=n,T={}){let F=await Ta(h,C,D=>_.readFile(D),D=>_.exists(D),{additionalEntries:await tt(h,_),...T});if(F.diagnostics.length>0)throw new ks(F.diagnostics);return T.validationOnly||f.remember(F.parsedModules.values()),F}async function Ge(h,C,_={}){let T=i.get(h);if(!T)return null;let F=_.sourceCache??Lp(d,[]),D=_.fileSystem??Tp(n),{graph:K,allSources:X,parsedModules:Q,entryModule:H}=await ee(T.entryFile,C,D,{version:T.graph?.version??1}),z=new Map;for(let vt of X.keys())z.set(vt,B(vt));let re=Math.max(J(T,z),_.minimumVersion??0);_.changed&&re<=(T.graph?.version??0)&&(re=(T.graph?.version??0)+1),K.version=re;for(let[vt,rn]of X)cl(F,vt,rn,ul);let ue=await G(T.composition,T.entryFile,X,F,D);K.routeId=T.routeId,K.composition=T.composition;let ke=sc(K),se=xa(ke,K),we=await L(K,ke,X,F,Q,D);nt(se,we);let ve=fe(K,se,we),j=qe(we),q=rv(LS(K,ke,se,{canUpdateTextByKey:ve,dynamicDataSummaryByKey:j}),K,we),ye=xn({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:re,source:C,ast:H?.ast}),Ne=tb(ye),Oe=null,ot=[];if(ye.ok){uM(q,K,ye.projection,Q);let vt=ic({composition:T.composition,entryFile:T.entryFile,graph:K,parsedModules:Q,projection:ye.projection});if(vt.diagnostics.length===0){let rn=Gi({composition:T.composition,entryFile:T.entryFile,graph:K,parsedModules:Q,projection:ye.projection,documentVersion:re,roots:vt.roots});rn.diagnostics.length===0&&(Oe=rn,ot=rn.descriptors)}}let sr={...q,composition:T.composition,pageBlocks:ot,...ue?{styleContext:ue}:{},pageComposition:Ne},Cn=new Set([T.entryFile,...X.keys()]);if(ue){Cn.add(ue.entryCss.path);for(let vt of ue.stylesheets)Cn.add(vt.path)}let Kr={...T,dependencyFiles:Cn,graph:K,topology:ke,capabilities:se,document:sr,pageBlockIndex:Oe,pageComposition:Ne,pageCompositionProjection:ye.projection,pagePlacementByKey:ye.ok?ye.projection.placementByKey:null,pagePlacementUnitByKey:ye.ok?ye.projection.placementUnitByKey:null,pageUnitByKey:ye.ok?ye.projection.unitByKey:null,pagePlacementsByUnitKey:ye.ok?ye.projection.placementsByUnitKey:null,documentIndex:nv(sr),detailProjections:we,fileVersions:z,styleContext:ue};if(_.publish===!1)return Kr;for(let vt of Cn){let rn=X.get(vt)??F.get(vt);rn!==void 0&&(cl(d,vt,rn,ul),g.delete(vt))}return I(T,Cn),Object.assign(T,Kr),T}async function tt(h,C=n){let _=[];for(let T of bM(h))typeof C.exists=="function"&&await C.exists(T)&&_.push({file:T,source:await C.readFile(T)});return _}async function G(h,C,_,T,F){let D=[];for(let[z,re]of _){if(Fp(z)){D.push(z);continue}for(let ue of EM(re)){let ke=vv(z,ue);ke&&D.push(ke)}}if(!D.length){for(let z of xM(C))if(await F.exists(z)){D.push(z);break}}let K=new Map,X=IM(D).slice(0,fv);for(;X.length>0&&K.size<fv;){let z=X.shift();if(K.has(z)||!Fp(z))continue;let re=await me(z,T,F);if(re!==null){K.set(z,{path:z,content:re});for(let ue of SM(re)){let ke=vv(z,ue);ke&&!K.has(ke)&&!X.includes(ke)&&X.push(ke)}}}let Q=[...K.values()].map(z=>({...z,hash:_e(z.content)})),H=Q[0];return H?{composition:h,revision:_e(JSON.stringify(Q.map(({path:z,hash:re})=>({path:z,hash:re})))),entryCss:H,stylesheets:Q.slice(1)}:null}async function me(h,C,_){let T=C.get(h);if(T!==void 0)return T;if(!await _.exists(h))return null;let F=await _.readFile(h);return cl(C,h,F,ul),F}function qe(h){let C=new Map;for(let[_,T]of h)T.dynamicData?.bindings.length&&C.set(_,AE(T.dynamicData.bindings));return C}function fe(h,C,_){let T=new Map;for(let[F,D]of h.elements){if(!C.get(F)?.canUpdateText){T.set(F,!1);continue}let X=_.get(F),Q=D.textSegments.some(H=>{if(!H.editable)return!1;let z=X?.provenances.get(H.index)??null;return!z||Me(z)});T.set(F,Q)}return T}function nt(h,C){for(let[_,T]of C){let F=h.get(_);F?.canUpdateText&&T.dynamicData?.bindings.some(D=>D.readonly&&(D.targetKind==="text"||D.targetKind==="richtext"))&&h.set(_,{...F,canUpdateText:!1})}}function Me(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function ge(h,C={}){let _=[...new Set(h)],T=C.affectedCompositionKeys!==void 0,F=T?new Set(C.affectedCompositionKeys):A(_);if(!T&&(F.size===0||!w(_)))for(let H of i.values())Dm(H,_)&&F.add(H.key);let D=!T&&F.size===0&&_.some(Sv),K=C.publish===!1?Lp(d,_):void 0,X={rebuiltRoutes:[],failedRoutes:[],...C.publish===!1?{candidateRouteStates:[],candidateSourceCache:K}:{}},Q=Tp(n);for(let H of i.values())if(!(C.excludedCompositionKeys?.has(H.key)||!(F.has(H.key)||D)))try{let re=!!H.graph,ue=await Q.readFile(H.entryFile),ke=await Ge(H.key,ue,{...C,fileSystem:Q,...K?{sourceCache:K}:{}});ke?.graph&&(X.rebuiltRoutes.push({documentChanged:re,composition:H.composition,routeId:H.routeId,version:ke.graph.version}),X.candidateRouteStates?.push({composition:H.composition,key:H.key,routeId:H.routeId,state:ke}))}catch(re){X.failedRoutes.push({...lv(H.routeId,re),composition:H.composition})}return X}function $e(h){let C=[...new Set(h)],_=A(C);if(_.size>0&&w(C))return[..._];for(let T of i.values())Dm(T,C)&&_.add(T.key);return[..._]}function Ct(h){let C=new Set($e(h));return o.entries.filter(_=>C.has(_.key)).map(_=>_.context)}function hn(h){return[...new Set($e(h))].sort((_,T)=>_<T?-1:_>T?1:0).map(_=>o.getByKey(_)?.context).filter(_=>_!==void 0)}function Nt(h,C){let _=new Set($e(C)),T=h.provenance?.affectedCompositions??[];if(T.length===0)return _;if([...new Set(T.map(D=>o.resolveContext(D).key))].some(D=>!_.has(D)))throw new Error("History provenance does not match the affected composition index.");return _}function js(h,C){let _=h.composition??h.provenance?.initiatingComposition;if(_){let D=o.resolveContext(_);return{context:D.context,key:D.key}}let T=[...new Set($e(C))];if(T.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${T.length}).`);let F=o.getByKey(T[0]);if(!F)throw new Error("Legacy history entry references an unknown affected composition.");return{context:F.context,key:F.key}}function $l(h,C){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:_,version:T}of C.rebuiltRoutes)r.emit({type:"document-changed",composition:_,version:T});for(let{composition:_,message:T}of C.failedRoutes)r.emit({type:"graph-error",composition:_,message:T})}function Dm(h,C){return C.some(_=>h.dependencyFiles.has(_)||h.entryFile===_||h.graph?.fileIndex.has(_))}function Mm(h){for(let C of h)a.add(C);c||v()||(c=(async()=>{t="building";let C=!1;try{for(;a.size>0;){if(v())return;await ak(),await y.runExclusive(async()=>{if(p>0||v())return;let _=[...a];a.clear();let T=await Bm(_);if(T.length===0)return;let F=$e(T);for(let X of F){let Q=i.get(X)?.composition;Q&&r.emit({type:"graph-invalidated",composition:Q})}let{rebuiltRoutes:D,failedRoutes:K}=await ge(T,{changed:!0});for(let{documentChanged:X,composition:Q,version:H}of D)r.emit({type:"graph-ready",composition:Q,version:H}),X&&r.emit({type:"document-changed",composition:Q,version:H});for(let{composition:X,message:Q}of K)C=!0,r.emit({type:"graph-error",composition:X,message:Q})})}}finally{c=null,t!=="disposed"&&(t=!C&&[...i.values()].some(_=>_.graph)?"ready":"idle"),a.size>0&&Mm([])}})())}async function ak(){for(;p>0;)await new Promise(h=>setTimeout(h,0))}async function Bm(h){let C=[];for(let _ of new Set(h)){let T=d.get(_);if(T===void 0){if(g.has(_)&&!await n.exists(_))continue;g.delete(_),C.push(_);continue}try{await n.readFile(_)!==T&&(g.delete(_),C.push(_))}catch(F){if(!lM(F))try{if(await n.exists(_))continue}catch{continue}g.add(_),C.push(_)}}return C}function jm(h){uv(d,h);for(let C of h)C.exists===!1?g.add(C.file):g.delete(C.file)}function $m(h){g.clear();for(let C of h)g.add(C)}async function Um(h){let C=await Bm(h);if(C.length===0)return;let _=$e(C);for(let D of _){let K=i.get(D)?.composition;K&&r.emit({type:"graph-invalidated",composition:K})}let{rebuiltRoutes:T,failedRoutes:F}=await ge(C,{changed:!0});for(let{documentChanged:D,composition:K,version:X}of T)r.emit({type:"graph-ready",composition:K,version:X}),D&&r.emit({type:"document-changed",composition:K,version:X});for(let{composition:D,message:K}of F)r.emit({type:"graph-error",composition:D,message:K})}async function ck(h,C){let _=Io(h,C);if(!_?.graph)return;let T=Vt(h)??h,F=_.graph.elements.get(T);F&&await Um([F.sourceFile])}async function Vm(h){let C=new Set;if(h.target.kind==="node"){let _=Io(h.target.key,h.composition),T=Vt(h.target.key)??h.target.key,F=_?.graph?.elements.get(T);F&&C.add(F.sourceFile)}else if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&C.add(_.entryFile)}else if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&C.add(_.entryFile)}else if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key),T=_?.pageBlockIndex?.bindings.get(h.target.blockKey);if(T&&(C.add(T.ownerFile),C.add(T.descriptor.source.file)),_?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let F=_.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);F&&(C.add(F.ownerFile),C.add(F.descriptor.source.file))}}else if(h.target.kind==="source-file")C.add(h.target.path);else if(h.target.kind==="source-batch")for(let _ of h.target.paths)C.add(_);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let _=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let T of _){let F=Io(T,h.composition),D=Vt(T)??T,K=F?.graph?.elements.get(D);K&&C.add(K.sourceFile)}}await Um(C)}async function lk(h){if(h.params.kind!=="source-edit")return Kl(h,"invalid-params","source-edit requires source-edit params");for(let C of h.params.edits){let _=cM(C);if(!_.ok)return Kl(h,_.errorCode,_.message,_.details)}p+=1;try{let C=await bk(h.params.edits);if(!C.ok)return Kl(h,C.errorCode,C.message,C.details);await Vm(h);let _={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(T=>T.operation==="delete"?{operation:"delete",file:T.path,baseContentHash:T.baseContentHash??null}:{operation:"upsert",file:T.path,baseContentHash:T.baseContentHash??null,content:T.content})};return await ir({request:h,filePlan:_})}catch(C){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:U.INTERNAL_ERROR,message:Ft(C)}}}finally{p-=1}}async function uk(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return Y(h,U.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");p+=1;try{let C=await hi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(T=>T.materialization.files.map(F=>({path:F.pathTemplate,content:F.content}))),...h.params.artifact.pages.flatMap(T=>T.materialization.files.map(F=>({path:F.pathTemplate,content:F.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!C.ok)return Y(h,U.MATERIALIZATION_REJECTED,C.message);let _=await cd({artifact:h.params.artifact,exists:T=>n.exists(T)});return _.ok?await ir({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:_.files},output:{kind:"insert-page-resource",package_instance_id:_.packageInstanceId,pages:_.pages},historyPolicy:"none"}):Y(h,_.code==="MATERIALIZATION_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,_.message,_.path?{path:_.path}:void 0)}catch(C){return Y(h,U.INTERNAL_ERROR,Ft(C))}finally{p-=1}}async function dk(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return Y(h,U.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return Y(h,U.PLAN_FAILED,"Complete project file listing is required for page deletion.");p+=1;try{let C=Iv(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(C.truncated)return Y(h,U.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:C.truncated.reasons});let _=C.files.filter(({path:K})=>/\.(?:tsx?|jsx?)$/.test(K)),T=Object.fromEntries(await Promise.all(_.map(async({path:K})=>[K,await n.readFile(K)]))),F=Zb({expectedUrlPath:h.params.expectedUrlPath,files:T});if(!F.ok)return Y(h,F.code==="HOME_PAGE_LOCKED"?U.HOME_PAGE_LOCKED:F.code==="ROUTE_NOT_FOUND"?U.ROUTE_NOT_FOUND:U.PLAN_FAILED,F.message);let D=await Promise.all(F.edits.map(async K=>({...K,baseContentHash:_e(await n.readFile(K.file))})));return ir({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:D},output:{kind:"delete-page-source",deleted_files:F.deletedFiles,updated_files:F.updatedFiles,preserved_shared_files:F.preservedSharedFiles,warnings:F.warnings},historyPolicy:"none"})}catch(C){return Y(h,U.INTERNAL_ERROR,Ft(C))}finally{p-=1}}async function fk(h,C){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(h.params.kind!=="insert-child"&&h.params.kind!=="replace-node"||h.kind!==h.params.kind)return Y(h,U.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(h.params.kind==="insert-child"){if(!("kind"in h.params.position)||h.params.position.kind!=="page-composition")return Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let _=C.document,T=C.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let F=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!F)return Y(h,U.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let D=h.params.kind==="insert-child"?h.params.position:null,K=await hi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:F.files.map(H=>({path:H.pathTemplate,content:H.content})),exists:H=>n.exists(H),readFile:H=>n.readFile(H)});if(!K.ok)return Y(h,U.MATERIALIZATION_REJECTED,K.message);let X=await mv(n,Object.keys(F.projectDependencies??{})),Q=await gd({manifest:F,generatedRoot:"components/site/generated",controlledFiles:F.files.map(H=>({pathTemplate:H.pathTemplate})),exists:H=>n.exists(H),availableHostDependencies:X,hostCapabilities:rd(),commit:async H=>{let z=await n.readFile(C.entryFile),re=C.document,ue=C.pageCompositionProjection;if(!re||re.pageComposition?.status!=="supported"||re.version!==h.documentVersion||!ue||ue.status!=="supported"||ue.documentVersion!==re.version)return{ok:!0,data:Y(h,U.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let ke=H.entry.path,se=_k(H.instanceName),we,ve=[];if(h.params.kind==="insert-child"){if(!D||!("kind"in D)||D.kind!=="page-composition")return{ok:!0,data:Y(h,U.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ne=Vi({routeId:C.routeId,entryFile:C.entryFile,currentDocumentVersion:re.version,expectedDocumentVersion:h.documentVersion,source:z,projection:ue,placementKey:D.placementKey,component:{source:ke,exportName:H.entry.export.kind==="default"?"default":H.entry.export.name,localName:se}});if(!Ne.ok)return{ok:!0,data:Y(h,zl(Ne.error.code),Ne.error.message,{diagnostics:Ne.error.diagnostics})};let Oe=Ne.plan.rewriteStep,ot;switch(Oe.kind){case"insert-root-expression":ot=Ki({source:z,locator:Oe.locator,expectedSourceHash:Oe.sourceHash,action:{kind:"insert",jsx:Oe.node.jsx,placement:Oe.placement,replaceOriginal:Oe.replaceOriginal}});break;case"insert-child":ot=cn({source:z,locator:Oe.parentLocator,node:Oe.node,placement:Oe.placement,...Oe.anchorLocator?{anchorLocator:Oe.anchorLocator}:{}});break;default:ot={ok:!1,source:z,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Oe)}`}}}if(!ot.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,ot.diagnostic.message)};we=ot.source}else{let Ne=Ld({routeId:C.routeId,composition:C.composition,entryFile:C.entryFile,currentDocumentVersion:re.version,expectedDocumentVersion:h.documentVersion,source:z,projection:ue,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Ne.ok)return{ok:!0,data:Y(h,zl(Ne.error.code),Ne.error.message,{diagnostics:Ne.error.diagnostics})};let Oe=Ne.plan.rewriteStep,ot;switch(Oe.kind){case"replace-root-expression":ot=Ki({source:z,locator:Oe.locator,expectedSourceHash:Oe.sourceHash,action:{kind:"replace",jsx:`<${se} />`}});break;case"replace-node":ot=_o({source:z,locator:Oe.locator,node:{jsx:`<${se} />`}});break;default:ot={ok:!1,source:z,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Oe.kind}`}}}if(!ot.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,ot.diagnostic.message)};let sr=await Vl({routeState:C,placementUnitKey:h.target.placementUnitKey,source:z,mutatedSource:ot.source});we=sr.source,ve=await Promise.all(sr.files.map(async Cn=>({operation:"delete",file:Cn,baseContentHash:_e(await n.readFile(Cn))})))}let j=ln({source:we,moduleSpecifier:x(C.entryFile,ke),imports:H.entry.export.kind==="default"?[{kind:"default",local:se}]:[{kind:"named",imported:H.entry.export.name,local:se}]});if(!j.ok)return{ok:!0,data:Y(h,U.AST_PARSE_ERROR,j.diagnostic.message)};let q=H.files.map(Ne=>({operation:"create-only",file:Ne.path,content:Ne.content})),ye=[{operation:"upsert",file:C.entryFile,content:j.source,baseContentHash:_e(z)},...q,...ve];p+=1;try{let Ne=await ir({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:C.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:ye}});return!Ne.ok&&Ne.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ne.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ne}}finally{p-=1}}});return Q.ok?Q.data:Y(h,Q.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,Q.error.message,{materializationCode:Q.error.code})}async function pk(h,C){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(h.params.kind!==h.kind||h.kind==="replace-node"&&h.params.kind!=="replace-node"||h.kind==="insert-child"&&h.params.kind!=="insert-child")return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let _=C.document,T=C.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let F=$o(T,h.target,h.documentVersion,h.selectionRef);if(!F.ok)return Y(h,$s(F.code),F.message);let D=F.binding;if(!(h.kind==="insert-child"?D.descriptor.capabilities.insert:D.descriptor.capabilities.replace)){let se=D.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,se)}let X=(h.kind==="insert-child",h.params);if(X.kind!==h.kind)return Y(h,U.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let Q=X.node;if(Q.kind!=="component-call"||!Q.materialization)return Y(h,U.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let H;if(X.kind==="insert-child"){let se=X.position;if(!("kind"in se&&se.kind==="block-boundary"))return Y(h,U.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(se.documentVersion!==h.documentVersion)return Y(h,U.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let we=ac(T,se);if(!we.ok)return Y(h,$s(we.code),we.message);H=we.boundary}let z=Q.materialization,re=await hi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:z.files.map(se=>({path:se.pathTemplate,content:se.content})),exists:se=>n.exists(se),readFile:se=>n.readFile(se)});if(!re.ok)return Y(h,U.MATERIALIZATION_REJECTED,re.message);let ue=await mv(n,Object.keys(z.projectDependencies??{})),ke=await gd({manifest:z,generatedRoot:"components/site/generated",controlledFiles:z.files.map(se=>({pathTemplate:se.pathTemplate})),exists:se=>n.exists(se),availableHostDependencies:ue,hostCapabilities:rd(),commit:async se=>{let we=C.document,ve=C.pageBlockIndex;if(!we||!ve||we.version!==h.documentVersion||ve.documentVersion!==we.version||!ve.bindings.has(D.blockKey))return{ok:!0,data:Y(h,U.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let j=ve.bindings.get(D.blockKey);if(!j||j.ownerFile!==D.ownerFile||j.ownerSourceHash!==D.ownerSourceHash||j.sourceHash!==D.sourceHash)return{ok:!0,data:Y(h,U.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let q=new Set([D.ownerFile,D.descriptor.source.file,...H?[H.ownerFile,H.anchorLocator.file,...H.parentLocator?[H.parentLocator.file]:[]]:[]]),ye=new Map;try{for(let Oe of q)ye.set(Oe,await n.readFile(Oe))}catch{return{ok:!0,data:Y(h,U.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ne=Tb({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:D,...H?{boundary:H}:{},operation:X.kind,materialization:se,files:ye});if(!Ne.ok){let Oe=yk(Ne.code);return{ok:!0,data:Y(h,Oe,Ne.message,{materializationCode:Ne.code})}}p+=1;try{let Oe=await ir({request:h,filePlan:Ne.plan});return!Oe.ok&&Oe.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Oe.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Oe}}finally{p-=1}}});return ke.ok?ke.data:Y(h,ke.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?U.MATERIALIZATION_CONFLICT:U.MATERIALIZATION_REJECTED,ke.error.message,{materializationCode:ke.error.code})}async function mk(h,C){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let _=C.document,T=C.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!T||T.status!=="supported")return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let F=await n.readFile(C.entryFile),D=Ld({routeId:C.routeId,composition:C.composition,entryFile:C.entryFile,currentDocumentVersion:_.version,expectedDocumentVersion:h.documentVersion,source:F,projection:T,placementUnitKey:h.target.placementUnitKey,operation:h.kind,targetPlacement:h.kind==="move-node"&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="page-composition"?h.params.target:void 0});if(!D.ok)return Y(h,zl(D.error.code),D.error.message,{diagnostics:D.error.diagnostics});let K=D.plan.rewriteStep,X;switch(K.kind){case"move-node":X=to({source:F,locator:K.locator,targetParentLocator:K.targetParentLocator,placement:K.placement,...K.anchorLocator?{anchorLocator:K.anchorLocator}:{}});break;case"remove-node":X=Qr({source:F,locator:K.locator});break;case"remove-root-expression":X=Ki({source:F,locator:K.locator,expectedSourceHash:K.sourceHash,action:{kind:"remove"}});break;default:X={ok:!1,source:F,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${K.kind}`}}}if(!X.ok)return Y(h,U.AST_PARSE_ERROR,X.diagnostic.message);let Q=X.source,H=[];if(h.kind==="remove-node"){let re=await Vl({routeState:C,placementUnitKey:h.target.placementUnitKey,source:F,mutatedSource:Q});Q=re.source,H=await Promise.all(re.files.map(async ue=>({operation:"delete",file:ue,baseContentHash:_e(await n.readFile(ue))})))}let z=[{operation:"upsert",file:C.entryFile,content:Q,baseContentHash:_e(F)},...H];p+=1;try{return await ir({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:C.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:z}})}finally{p-=1}}async function gk(h,C){if(h.kind!=="move-node"&&h.kind!=="remove-node")return Y(h,U.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let _=C.document,T=C.pageBlockIndex;if(!_||!T||T.diagnostics.length>0)return Y(h,U.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||T.documentVersion!==_.version)return Y(h,U.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let F=$o(T,h.target,h.documentVersion,h.selectionRef);if(!F.ok)return Y(h,$s(F.code),F.message);let D=F.binding;if(D.documentVersion!==_.version)return Y(h,U.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?D.descriptor.capabilities.move:D.descriptor.capabilities.remove)){let ve=D.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return Y(h,U.UNSUPPORTED_OPERATION,ve)}if(h.kind==="remove-node"){let ve=[...i.values()].filter(j=>j.dependencyFiles.has(D.ownerFile));if(ve.includes(C)||ve.push(C),ve.some(j=>!j.pageBlockIndex||j.pageBlockIndex.descriptors.length<=1))return Y(h,U.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let X=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return Y(h,U.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===D.blockKey)return Y(h,U.INVALID_TARGET,"A page block cannot be moved relative to itself.");let ve=ac(T,h.params.target);if(!ve.ok)return Y(h,$s(ve.code),ve.message);let j=T.bindings.get(h.params.target.anchorBlockKey);if(!j||!D.descriptor.siblingBlockKeys.includes(j.blockKey)||!j.descriptor.siblingBlockKeys.includes(D.blockKey)||j.ownerFile!==D.ownerFile||j.root.ownerNode.kind!==D.root.ownerNode.kind||j.root.ownerNode.key!==D.root.ownerNode.key||j.root.parentStructuralPath!==D.root.parentStructuralPath)return Y(h,U.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(X=ve.boundary,X.ownerFile!==D.ownerFile||X.sourceHash!==D.ownerSourceHash||!X.parentLocator)return Y(h,U.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let Q=D.ownerFile,H=await n.readFile(Q);if(_e(H)!==D.ownerSourceHash)return Y(h,U.VERSION_STALE,"The page-block owner source changed after resolution.");let z=D.descriptor.source.file===Q?H:await n.readFile(D.descriptor.source.file);if(_e(z)!==D.descriptor.source.contentHash)return Y(h,U.VERSION_STALE,"The selected page-block source changed after resolution.");let re=hk(D),ue=h.kind==="remove-node"?Qr({source:H,locator:re}):to({source:H,locator:re,targetParentLocator:Ul(X.parentLocator),anchorLocator:Ul(X.anchorLocator),placement:X.placement});if(!ue.ok)return Y(h,U.AST_PARSE_ERROR,ue.diagnostic.message);let ke=ue.source,se=[];if(h.kind==="remove-node"&&D.root.ownerNode.kind==="route-member"&&D.root.callChain.length>0&&D.descriptor.placementUnitKey){let ve=await Vl({routeState:C,placementUnitKey:D.descriptor.placementUnitKey,source:H,mutatedSource:ke});ke=ve.source,se=ve.files}let we=[{operation:"upsert",file:Q,content:ke,baseContentHash:D.ownerSourceHash},...await Promise.all(se.map(async ve=>({operation:"delete",file:ve,baseContentHash:_e(await n.readFile(ve))})))];p+=1;try{return await ir({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:we}})}finally{p-=1}}function hk(h){return Ul(h.ownerLocator)}function Ul(h){return{kind:"jsx-node",strategy:"source-range",sourceRange:h.sourceRange,...h.structuralPath&&h.componentName?{expectedIdentity:{file:h.file,component:h.componentName,structuralPath:h.structuralPath}}:{}}}function $s(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:U.INVALID_TARGET}function yk(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="INVALID_PARAMS"?U.INVALID_PARAMS:h==="INVALID_TARGET"?U.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?U.MATERIALIZATION_REJECTED:U.UNSUPPORTED_OPERATION}async function Vl(h){let C={source:h.mutatedSource,files:[]},_=h.routeState.graph,T=h.routeState.pageCompositionProjection;if(!_||!T||T.status!=="supported"||!n.listFiles)return C;let D=T.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!D)return C;let K=[..._.elements.values()].find(j=>j.sourceFile===h.routeState.entryFile&&j.importedFrom&&E(j.sourceRange,D));if(!K?.importedFrom||!K.exportName)return C;let X=S(K.importedFrom),Q="components/site/generated/";if(!X.startsWith(Q))return C;let H=X.slice(Q.length).split("/")[0];if(!H||!/-[0-9a-f]{8}$/i.test(H))return C;let z=`${Q}${H}`;if([..._.elements.values()].filter(j=>j.sourceFile===h.routeState.entryFile&&S(j.importedFrom??"")===X).length!==1)return C;let ue=await n.listFiles({maxFiles:5e3,maxDepth:32}),ke=Array.isArray(ue)?ue:ue.files;if(!Array.isArray(ue)&&ue.truncated)return C;let se=ke.map(({path:j})=>j).filter(j=>j===z||j.startsWith(`${z}/`));if(se.length===0||!se.includes(X))return C;for(let{path:j}of ke)if(!(j===h.routeState.entryFile||j===z||j.startsWith(`${z}/`)))try{if((await n.readFile(j)).includes(H))return C}catch{return C}let we=x(h.routeState.entryFile,X),ve=Co({source:h.mutatedSource,moduleSpecifier:we,imports:K.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:K.exportName}]});return ve.ok?ve.source.includes(H)?{source:ve.source,files:[]}:{source:ve.source,files:se.sort((j,q)=>j.localeCompare(q))}:C}async function bk(h){if(n.getFileInfo){for(let K of h)if(await n.exists(K.path)&&await n.getFileInfo(K.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${K.path}`,details:{path:K.path}}}for(let K of h){if(K.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(K.path))continue;let X=await n.exists(K.path)?await cu(n,K.path):null;if(X?.ok){let Q=MD(X.content,K.content);if(!Q.ok)return{ok:!1,errorCode:"invalid-params",message:Q.message,details:{path:K.path,code:Q.code}}}}let C=xk(h);if(C.length===0)return{ok:!0};let _=sM(n,h),T=new Map,F=(K,X)=>{let Q=T.get(K);if(Q?.source===X)return Q.result;let H=De(K,X);return T.set(K,{source:X,result:H}),H},D;try{D=await ev(C,async K=>{let X=i.get(K);return X?[...(await ee(X.entryFile,await _.readFile(X.entryFile),_,{validationOnly:!0,parseModule:F,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(K){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Ft(K)}`,details:{compositionKeys:C}}}for(let K of D)f.remember(K);return{ok:!0}}function xk(h){return h.map(_=>_.path).some(Sv)?[...i.keys()]:[]}function Kl(h,C,_,T){let F=Rs(C);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:F,message:_,...T?{details:T}:{}}}}async function Jl(h){let C=[];for(let _ of new Set(h))C.push(await Ek(_));return C}async function Ek(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,B(h)),exists:!1};let _=await n.readFile(h);return{file:h,content:_,version:Math.max(1,B(h)),exists:!0,sha256:_e(_)}}async function Km(h,C,_,T){if(!e.historyStore)return null;let F=new Map(C.map(X=>[X.file,X])),D=new Map(_.map(X=>[X.file,X])),K=[...new Set([...F.keys(),...D.keys()])].sort().map(X=>{let Q=F.get(X),H=D.get(X);return{path:X,preDigest:Q?.exists===!1||!Q?null:_e(Q.content),postDigest:H?.exists===!1||!H?null:_e(H.content)}});return{schemaVersion:2,transactionId:`${h}:${T.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:T,files:K}}async function Jm(h){return!h||!e.historyStore||await e.historyStore.writeTransactionJournal(h),h}async function vo(h){h&&e.historyStore&&await e.historyStore.clearTransactionJournal(h.transactionId)}async function Xl(h,C){let _=[];try{for(let T of h)await Xm(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),_.push(T.file)}catch(T){let F=await Sk(C.filter(D=>_.includes(D.file)));return F.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Ft(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${F.failedFiles.join(", ")}: ${Ft(T)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(vk)}}async function Xm(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function Sk(h){let C=[];for(let _ of h)try{await Xm(_),typeof n.bumpVersion=="function"&&n.bumpVersion(_.file)}catch{C.push(_.file)}return C.length===0?{ok:!0}:{ok:!1,failedFiles:C}}function vk(h){let C=h.exists!==!1;return{file:h.file,content:C?h.content:"",version:h.version,exists:C,...C?{sha256:_e(h.content)}:{}}}async function ir(h){return y.runExclusive(()=>Ik(h))}async function Ik(h){let C=h.filePlan.edits.map(j=>j.file),_=o.resolveSelector(h.request.composition),T=_.context,F=h.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:hn(C)},D=await Jl(C),K=new Map(D.filter(j=>j.exists!==!1).map(j=>[j.file,j.content])),X=Hm(),Q=new Map(d),H=new Set(g),z=new Set([...i.values()].filter(j=>h.filePlan.edits.some(q=>q.operation==="delete"&&q.file===j.entryFile)).map(j=>j.key)),re=h.filePlan.edits.map(j=>j.operation==="delete"?{file:j.file,content:"",version:0,exists:!1}:{file:j.file,content:j.content,version:0,exists:!0,sha256:_e(j.content)}),ue={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(j=>j.operation==="delete"?{kind:"delete",path:j.file}:{kind:j.operation==="create-only"?"create-only":"upsert",path:j.file,content:j.content})},ke=null,se=!1,we=await ol({overlay:K,exists:j=>n.exists(j),plan:ue,buildCandidate:async({plan:j})=>({plan:j}),prepareHistory:async()=>{let j=h.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(h.request.composition).context,operationId:h.request.id,kind:h.request.kind,target:h.request.target,preSnapshots:D,postSnapshots:re,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...F?{provenance:F}:{}}),q=j?.historyTransition?j.historyTransition:e.historyStore?zD(await e.historyStore.readIndex()):null;if(e.historyStore&&!q)throw new Error("Durable history did not provide an exact index transition.");return ke=await Km(h.request.id,D,re,q),ke=await Jm(ke),{history:j,historyTransition:q}},reverify:async()=>{},writeCandidate:async()=>{let j=await u.executeFilePlan(h.filePlan);if(!j.ok)throw new dl(j);return{postSnapshots:await Jl(j.affectedFiles),affectedFiles:j.affectedFiles,internalResultVersion:j.resultVersion}},validateCandidate:async({candidate:j,receipt:q})=>{let ye=await ge(q.affectedFiles,{changed:!0,minimumVersion:q.internalResultVersion,publish:!1,excludedCompositionKeys:z});if(ye.failedRoutes.length>0)throw new bo(ye.failedRoutes);let Ne=Gm(X,ye.candidateRouteStates??[]),Oe=Wm(Ne,_.key);return{...j,rebuild:ye,routeSnapshots:Ne,resultVersion:Oe,...yv(h.selectionRef,Ne.map(ot=>ot.state.document))?{selectionRef:yv(h.selectionRef,Ne.map(ot=>ot.state.document))}:{}}},publishCandidate:async({candidate:j,history:q,receipt:ye})=>{q?.history&&(await l.publishPrepared(q.history),se=!0);let Ne=j.resultVersion??ye.internalResultVersion;return{composition:T,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Ne,affectedFiles:ye.affectedFiles,fileChanges:ye.postSnapshots.map(Oe=>({path:Oe.file,operation:Oe.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...j.selectionRef?{selectionRef:j.selectionRef}:{}}},swapCandidate:({candidate:j,receipt:q})=>{j.routeSnapshots&&Us(j.routeSnapshots),j.rebuild?.candidateSourceCache&&_s(d,j.rebuild.candidateSourceCache),jm(q.postSnapshots)},finalizeCandidate:async()=>{await vo(ke);for(let j of z)i.delete(j)},emitCommitted:({candidate:j,published:q})=>{$l(q,j.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:j,receipt:q})=>{if(se)throw new Error("history was published before transaction finalization failed");if(q){let ye=await Xl(D,q.postSnapshots);if(!ye.ok)throw new Error(ye.reason)}Us(X),_s(d,Q),$m(H),j?.history&&await l.discardPrepared?.(j.history),await vo(ke)}});if(we.ok)return we.published;if(we.stage==="precheck"||we.stage==="build")try{await vo(ke)}catch(j){let q=await Ks(Ft(j));return Y(h.request,q,"Unable to clear an uncommitted transaction journal.")}if(we.recoveryRequired){let j=await Ks(we.reason);return Y(h.request,j===U.RECOVERY_PERSIST_FAILED?j:U.ROLLBACK_FAILED,we.reason)}let ve=we.error;return ve instanceof dl?{...Y(h.request,Rs(ve.result.errorCode),ve.result.reason),...ve.result.affectedFiles?{affectedFiles:ve.result.affectedFiles}:{}}:ve instanceof bo?Y(h.request,U.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Op(ve.failedRoutes)}`,{failedRoutes:ve.failedRoutes}):Y(h.request,Zm(we.stage),Ft(ve))}async function zm(h){return y.runExclusive(async()=>{let C=h==="undo"?await l.prepareUndo():await l.prepareRedo();return C?kk(h,C):{composition:o.entries[0].context,requestId:h,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:U.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function kk(h,C){let _=C.entry,T=h==="undo"?_.preSnapshots:_.postSnapshots,F=h==="undo"?_.postSnapshots:_.preSnapshots,D=T.map(q=>q.file),{context:K,key:X}=js(_,D),Q=await Jl(D),H=new Map(Q.filter(q=>q.exists!==!1).map(q=>[q.file,q.content])),z=$(X),re=Hm(),ue=new Map(d),ke=new Set(g),se=null,we=!1,ve,j=await ol({overlay:H,plan:{operationId:`${h}:${_.operationId}`,intents:T.map(q=>q.exists===!1?{kind:"delete",path:q.file}:{kind:"upsert",path:q.file,content:q.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(se=await Km(`${h}:${_.operationId}`,Q,T,C.historyTransition),se=await Jm(se),C),reverify:async()=>{},writeCandidate:async()=>{let q=await Xl(T,F);if(!q.ok)throw new Error(q.reason);return{snapshots:q.snapshots}},validateCandidate:async({candidate:q})=>{ve=Nt(_,D);let ye=await ge(D,{changed:!0,minimumVersion:z+1,publish:!1,affectedCompositionKeys:ve});if(ye.failedRoutes.length>0)throw new bo(ye.failedRoutes);let Ne=Gm(re,ye.candidateRouteStates??[]),Oe=Wm(Ne,X);return{...q,rebuild:ye,routeSnapshots:Ne,resultVersion:Oe}},publishCandidate:async({candidate:q,history:ye,receipt:Ne})=>{if(!ye)throw new Error("history cursor intent is missing");await l.publishPrepared(ye),we=!0;let Oe=q.resultVersion??z+1;return{composition:K,requestId:h,kind:_.kind,target:_.target,ok:!0,resultVersion:Oe,affectedFiles:D,fileChanges:Ne.snapshots.map(ot=>({path:ot.file,operation:ot.exists===!1?"delete":"upsert"})),..._.output?{output:_.output}:{}}},swapCandidate:({candidate:q,receipt:ye})=>{q.routeSnapshots&&Us(q.routeSnapshots),q.rebuild?.candidateSourceCache&&_s(d,q.rebuild.candidateSourceCache),jm(ye.snapshots)},finalizeCandidate:async()=>{await vo(se)},emitCommitted:({candidate:q,published:ye})=>$l(ye,q.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:q,receipt:ye})=>{if(we)throw new Error("history cursor was published before transaction finalization failed");if(ye){let Ne=await Xl(F,ye.snapshots);if(!Ne.ok)throw new Error(Ne.reason)}Us(re),_s(d,ue),$m(ke),q&&await l.discardPrepared?.(q),await vo(se)}});if(j.ok)return j.published;if(j.stage==="precheck"||j.stage==="build")try{await vo(se)}catch(q){let ye=await Ks(Ft(q));return{composition:K,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:z,error:{code:ye,message:"Unable to clear an uncommitted transaction journal."}}}if(j.recoveryRequired){let q=await Ks(j.reason);return{composition:K,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:z,affectedFiles:D,error:{code:q===U.RECOVERY_PERSIST_FAILED?q:U.ROLLBACK_FAILED,message:j.reason}}}return{composition:K,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:z,affectedFiles:D,error:{code:j.error instanceof bo?U.ROUTE_REBUILD_FAILED:Zm(j.stage),message:Ft(j.error),...j.error instanceof bo?{details:{failedRoutes:j.error.failedRoutes}}:{}}}}function Hm(){return[...i.values()].map(h=>({composition:h.composition,key:h.key,routeId:h.routeId,state:{...h,dependencyFiles:new Set(h.dependencyFiles),fileVersions:new Map(h.fileVersions)}}))}function Wm(h,C){return h.find(T=>T.key===C)?.state.graph?.version??o.initialVersions.get(C)??0}function Gm(h,C){let _=new Map(h.map(T=>[T.key,T]));for(let T of C)_.set(T.key,T);return[..._.values()]}function Us(h){for(let C of i.values())N(C);for(let C of h){let _={...C.state,dependencyFiles:new Set(C.state.dependencyFiles),fileVersions:new Map(C.state.fileVersions)};i.set(C.key,_),I(_,_.dependencyFiles)}}async function Vs(h){let C=i.get(h);if(!C)throw new Error(`Composition not found: ${h}`);if(C.graph)return;let _=await n.readFile(C.entryFile);await Ge(h,_)}function Io(h,C){let _=i.get(o.resolveSelector(C).key)??null;return!_||!Ym(_,h)?null:_}function Ym(h,C){if(h.documentIndex?.entriesByKey.has(C)||h.graph?.elements.has(C))return!0;let _=Vt(C);return _&&_!==C?h.graph?.elements.has(_)===!0:!1}function Y(h,C,_,T){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:C,message:_,...T?{details:T}:{}}}}function Zm(h){return h==="validate"?U.ROUTE_REBUILD_FAILED:h==="publish"?U.HISTORY_COMMIT_FAILED:U.WRITE_IO_ERROR}async function Ks(h){if(m=!0,!l.markRecoveryRequired)return U.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),U.RECOVERY_REQUIRED}catch{return U.RECOVERY_PERSIST_FAILED}}function _k(h){let _=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return _?`Prefab${_}`:"GeneratedPrefab"}function zl(h){return h==="VERSION_STALE"?U.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?U.CROSS_PAGE_MOVE_UNSUPPORTED:U.UNSUPPORTED_OPERATION}async function qm(h){if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Vs(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Vs(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Vs(_.key),_):Y(h,U.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return Y(h,U.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let C=i.get(o.resolveSelector(h.composition).key)??null;return C?(C.graph||await Vs(C.key),Ym(C,h.target.key)?C:Y(h,U.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):Y(h,U.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(h,C){let _=o.register({context:h,entryFile:C}),T=i.get(_.key);if(T?.entryFile===C)return;T&&N(T);let F=hv(_.context,C);i.set(_.key,F),I(F,F.dependencyFiles),r.emit({type:"graph-invalidated",composition:_.context})},unregisterComposition(h){let C=o.resolveSelector(h),_=i.get(C.key);_&&(N(_),i.delete(C.key),o.unregister(C.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:C.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let C=o.resolveSelector(h),_=i.get(C.key);if(!_)throw new Error(`Composition not registered: ${C.key}`);if(_.graph)t="ready";else{t="building";try{let T=await n.readFile(_.entryFile);await Ge(C.key,T),t="ready",r.emit({type:"graph-ready",composition:C.context,version:i.get(C.key)?.graph?.version??0})}catch(T){throw t="idle",r.emit({type:"graph-error",composition:C.context,message:Ft(T)}),T}}},getDocument(h){let C=o.resolveSelector(h),_=i.get(C.key);if(!_)throw new Error(`Composition not registered: ${C.key}`);if(!_.document)throw new Error(`Composition not built: ${C.key}`);return _.document},async getHistoryStatus(){await b;let h=await l.getStatus?.();return h?{...h,recoveryRequired:m}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:m}},getObjectEditContext(h,C,_){let T=Io(h,C),F=Vt(h)??h;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let D=T.detailProjections.get(F);if(D){let K=T.graph.elements.get(F);if(!K)throw new Error(`Key not found: ${h}`);let X=qD(h,F,_),Q=new Map;if(D.isRepeat&&X?.instanceIndex!==void 0)for(let re of K.attributes??[])Q.set(re.name,cp({file:K.sourceFile,source:d.get(K.sourceFile)??"",element:K,propertyName:re.name,selectionRef:X,graph:T.graph,sources:d}));let H=OS({element:K,graph:T.graph,source:d.get(K.sourceFile),documentVersion:T.graph.version,selectionRef:_,isRepeat:D.isRepeat,propertyProvenance:D.propertyProvenances,repeatTargets:Q}),z=DS(F,T.graph,T.topology,T.capabilities,D.textSources,D.provenances,D.dynamicData,H);return h===F?z:av(z,h,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,C){let _=Io(h,C),T=Vt(h)??h;if(_?.graph&&_.topology&&_.capabilities&&_.detailProjections){let F=_.detailProjections.get(T);if(F){let D=FS(T,_.graph,_.topology,_.capabilities,F.textSources,F.writeTarget,F.provenances,F.conditional,F.componentSemantic,F.styleSource,F.dynamicData);return h===T?D:sv(D,h,_.document??null,_.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,C){let _=Io(h,C),T=Vt(h)??h;if(!_?.graph)throw new Error(`Key not found: ${h}`);let F=_.graph.elements.get(T);if(!F)throw new Error(`Key not found: ${h}`);let D=d.get(F.sourceFile);if(D===void 0)throw new Error(`Source not loaded: ${F.sourceFile}`);return Cu({key:T,route:{composition:_.composition,routeId:_.routeId,graph:_.graph,source:D}})},refreshSourceForKey:ck,async execute(h){if(await b,m)return Y(h,U.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return lk(h);if(h.kind==="insert-page-resource")return uk(h);if(h.kind==="delete-page-source")return dk(h);let C=await qm(h);if("ok"in C)return C;await Vm(h);let _=await qm(h);if("ok"in _)return _;let T=_;if(h.target.kind==="page-unit"){let z=h;return h.kind==="insert-child"||h.kind==="replace-node"?fk(z,T):h.kind==="move-node"||h.kind==="remove-node"?mk(z,T):Y(h,U.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(h.target.kind==="page-block"){let z=h;return h.kind==="insert-child"||h.kind==="replace-node"?pk(z,T):h.kind==="move-node"||h.kind==="remove-node"?gk(z,T):Y(h,U.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let D=h.params,K=h.target.kind==="node"?h.target.key:null;if(D.kind==="move-node"&&"kind"in D.target&&D.target.kind==="source-sibling"){let z=D.target,re=K?T.document?.entries.find(q=>q.key===K):null,ue=T.document?.entries.find(q=>q.key===z.anchorKey),ke=re?.pageCompositionActionScope,se=ke?.kind==="source-siblings"?ke.siblingKeys:null,we=se?.indexOf(re?.key??"")??-1,ve=se?.indexOf(z.anchorKey)??-1,j=z.relation==="before"?we-1:we+1;if(!re||!ue||!se||we<0||ve!==j||ue.pageCompositionActionScope?.kind!=="source-siblings"||ue.pageCompositionActionScope.siblingKeys.length!==se.length||ue.pageCompositionActionScope.siblingKeys.some((q,ye)=>q!==se[ye])||!re.operationSummary.canMove)return Y(h,U.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!T.graph||!T.topology||!T.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:h.target.kind==="route"?U.ROUTE_NOT_FOUND:U.NODE_NOT_FOUND,message:h.target.kind==="route"?"Composition not ready for route target.":h.target.kind==="node"?`Target key not found: ${h.target.key}`:`${h.kind} source target execution is not implemented yet.`}};let X=hM(T,T.graph,T.capabilities,d,i),Q=await new Oc(X).plan(h);if(!Q.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:Rs(Q.errorCode),message:Q.reason}};let H=Q.plan;if(H.steps.length===0)return h.kind==="set-props"?{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:W(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:U.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};p+=1;try{if(H.steps.some(re=>re.type==="invoke-external-adapter")){let re=await u.execute(H);if(!re.ok)return Y(h,Rs(re.errorCode),re.reason);let ue={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(W(h),re.resultVersion),affectedFiles:re.affectedFiles,...re.selectionRef?{selectionRef:re.selectionRef}:{}};return $l(ue,{rebuiltRoutes:[],failedRoutes:[]}),ue}let z=await u.prepareRewritePlan(H);return z.ok?await ir({request:h,filePlan:z.filePlan,...z.selectionRef?{selectionRef:z.selectionRef}:{}}):Y(h,Rs(z.errorCode),z.reason)}catch(z){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:W(h),error:{code:U.INTERNAL_ERROR,message:Ft(z)}}}finally{p-=1}},async undo(h){if(await b,m)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};p+=1;try{return await zm("undo")}finally{p-=1}},async redo(h){if(await b,m)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:$(o.entries[0].key),error:{code:U.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};p+=1;try{return await zm("redo")}finally{p-=1}},notifyFileChanged(h){Mm([h])},getAffectedCompositions(h){return Ct(h)},subscribe(h){return r.subscribe(h)}}}function lM(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function uM(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let p=d.get(f)??new Set,m=p.size;return p.add(g),d.set(f,p),p.size!==m},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(m=>m.sourceRange!==null&&Cs(d.sourceRange,m.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=Vt(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&&Cs(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(b=>b.members.some(S=>S.sourceRange!==null&&(Cs(g.sourceRange,S.sourceRange)||gM(S.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 m=i.get(g.sourceFile);m?.size===1&&(d.pageCompositionUnitKey=m.values().next().value)}dM(e,t,n,r)}function dM(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&&Cs(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 m=s.get(p.owner)??s.get(p.ownerDefault)??0;if(!m)continue;let y=s.get(p.target)??0,b=Math.min(2,y+m);b!==y&&(s.set(p.target,b),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!==(Vt(f.key)??f.key))continue;let p=r.get(g.sourceFile);if(!p)continue;let m=Ie(p.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!m.ok||!m.match.path.isJSXElement())continue;let y=m.match.path,b=y.parentPath;if(!b||!b.isJSXFragment()&&!(b.isJSXElement()&&Ze(b))){u(g)===1&&xv(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!xv(b))continue;let S=d.get(b.node)??[];S.push({entry:f,element:g,parentPath:b}),d.set(b.node,S)}for(let f of d.values()){let g=f[0];if(!g)continue;let p=g.entry.pageCompositionUnitKey,m=[],y=!!(p&&u(g.element)===1);for(let S of g.parentPath.node.children){if(fM(S))continue;if(!pM(S)){y=!1;break}let x=[...t.elements.values()].find(k=>k.sourceFile===g.element.sourceFile&&k.componentName===g.element.componentName&&Cs(k.sourceRange,mM(S))),E=x?o.get(x.identity.key):null;if(!x||!E||E.parentKey||E.pageCompositionUnitKey!==p||u(x)!==1){y=!1;break}m.push(E)}if(!y||m.length!==f.length||f.some(({entry:S})=>!m.some(x=>x.key===S.key)))continue;if(m.length===1){m[0].pageCompositionActionScope={kind:"route-unit"};continue}if(m.length<2)continue;let b=m.map(S=>S.key);for(let S of m)S.pageCompositionActionScope={kind:"source-siblings",siblingKeys:b}}}function xv(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function fM(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function pM(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function mM(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 Cs(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function gM(e,t){return Ev(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ev(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ev(e,t,n,r){return e!==n?e-n:t-r}function hM(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(m=>{let y=Vt(m)??m,b=t.elements.get(y);return b?l(m,b):null}).filter(m=>m!==null);let p=t.elements.get(d.baseKey);return p?p.childKeys.map(m=>{let y=t.elements.get(m);return y?l(m,y):null}).filter(m=>m!==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:Cu({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 wp(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return wp(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 b=p.attributes?.find(S=>S.name===d);return b?b.source?{status:"blocked",owner:"generic",diagnostic:{code:"unsupported-property-source",message:`Property '${d}' has an unresolved value source`}}:{status:"direct",owner:"generic",attribute:b,target:{kind:"jsx-attribute",file:p.sourceFile,sourceRange:b.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 m=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return cp({file:p.sourceFile,source:r.get(p.sourceFile)??"",element:p,propertyName:d,selectionRef:m,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=UD(u);return d?{baseKey:d.baseKey,repeatIndex:iv(e.document??null,u,d.baseKey,e.documentIndex)??ov(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=Vt(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(m=>({...m}))}:null,resolvedValue:p.resolvedValue}))}}}var yM={"stale-version":U.VERSION_STALE,"capability-denied":U.CAPABILITY_REJECTED,"invalid-params":U.INVALID_PARAMS,"locator-miss":U.LOCATOR_FAILED,"route-not-found":U.ROUTE_NOT_FOUND,"unsupported-operation":U.UNSUPPORTED_OPERATION,"invalid-target":U.INVALID_TARGET,"ast-error":U.AST_PARSE_ERROR,"writeback-failed":U.WRITE_IO_ERROR,"rollback-failed":U.RECOVERY_REQUIRED,unknown:U.INTERNAL_ERROR};function Rs(e){return yM[e]}function Ft(e){return e instanceof Error&&e.message?e.message:String(e)}function Sv(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function bM(e){let t=xo(e);if(!JD.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=>XD.map(a=>`${s}/${a}`))}function xM(e){let n=xo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function EM(e){return kv(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function SM(e){return kv(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function kv(e,t){let n=[];for(let r of e.matchAll(t)){let o=_v(r[1]??"");o&&n.push(o)}return n}function vv(e,t){let n=_v(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?xo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?xo(`${vM(e)}/${n}`):n.startsWith("/")?xo(n.slice(1)):Fp(n)?xo(n):null}function _v(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Fp(e){return/\.css$/i.test(e)}function vM(e){let t=xo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function IM(e){return Array.from(new Set(e))}function xo(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 kM(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 pl=class{constructor(t){this.options=t,this.fileSystem=new yi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Ys(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 Zs(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ea(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return ta(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return na(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=RM.safeParse(t);if(!n.success)return{result:Gs(t,n.error.issues.map(i=>i.message))};let r=new yi(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:Yr(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=CM.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>NM(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 fl({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=qs(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 NM(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:_e(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:_e(e.before)},fullContent:e.after}}function PM(e){return new pl(e)}import{SiteEditOperationRequestSchema as wM}from"@vcp-dev/contracts";import Rn from"node:fs/promises";import Dt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as AM,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as TM}from"@vcp-dev/contracts";var ml=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=fl({...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 ea(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return ta(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return na(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 Rn.readFile(Dt.join(n,r),"utf8")},async readFileBytes(r){return Rn.readFile(Dt.join(n,r))},async getFileInfo(r){let o=Dt.join(n,...r.split("/"));try{let i=await Rn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await Sa(Dt.join(n,r),o)},async createExclusive(r,o){let i=Dt.join(n,r);await Rn.mkdir(Dt.dirname(i),{recursive:!0});let s=await Rn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Rn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Rn.rm(Dt.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=Dt.join(n,i),a=Dt.dirname(Dt.join(n,o));for(;a!==s&&a.startsWith(`${s}${Dt.sep}`);){try{await Rn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=Dt.dirname(a);continue}break}a=Dt.dirname(a)}},async exists(r){try{return await Rn.access(Dt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...TM,...AM],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=Dt.join(n,...d.split("/")),m;try{m=await Rn.lstat(p)}catch{return}if(m.isSymbolicLink())return;if(m.isFile()){let b=m.ino>0?`${String(m.dev)}:${String(m.ino)}`:null;if(b&&s.has(b))return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+m.size>r.maxTotalBytes){a.add("max-total-bytes");return}b&&s.add(b),f.push({path:d,sizeBytes:m.size}),c+=m.size;return}if(!m.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await Rn.readdir(p,{withFileTypes:!0});for(let b of y)b.isSymbolicLink()||await u(`${d}/${b.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 Dp(e){return new ml(e)}var gl=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Dp({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=qs(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:Ys(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:Zs(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=wM.safeParse(r);if(!o.success)return Gs(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:Yr(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:Yr(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:Yr(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 OM(e){return new gl(e)}import{GeneratedSiteCapabilitiesSchema as jM}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as LM}from"@vcp-dev/contracts";function ii(e){let t=DM(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)?rr(e.node,"platform-managed","controlled platform package"):t?MM(e.node.path,t)?rr(e.node,"host-public","declared Starter runtime dependency"):rr(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):rr(e.node,"unknown","trusted host capability contract is invalid"):Rv(e.node.path,n)?rr(e.node,"platform-managed","controlled platform path"):t?Nv(e.node.path,t.generated_sections_path)?rr(e.node,"private","site-generated section path"):Rv(e.node.path,t.public_paths)?rr(e.node,"host-public","declared Starter public path"):rr(e.node,"private","site-local file outside host public paths"):rr(e.node,"unknown","trusted host capability contract is invalid")}function FM(e){return e.nodes.map(t=>ii({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function rr(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function DM(e){let t=LM.safeParse(e);return t.success?t.data:null}function MM(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function Rv(e,t){return t.some(n=>Nv(e,n))}function Nv(e,t){let n=BM(t),r=Pv(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):Cv(r)===Cv(n)}function BM(e){return Pv(e.split("#",1)[0]??e)}function Pv(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function Cv(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function hl(e){let t=jM.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=ii({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=$M(n).sort(UM);return{complete:o.length===0,nodes:r.sort(VM),edges:[...e.closure.edges].sort(KM),errors:o}}function $M(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function UM(e,t){return en(e.path,t.path)||en(e.code,t.code)||en(e.specifier??"",t.specifier??"")||en(e.message,t.message)}function VM(e,t){return en(e.path,t.path)||en(e.kind,t.kind)||en(e.ownership,t.ownership)||en(e.status,t.status)}function KM(e,t){return en(e.from,t.from)||en(e.target??"",t.target??"")||en(e.specifier??"",t.specifier??"")||en(e.kind,t.kind)||en(e.resolution,t.resolution)}function en(e,t){return e<t?-1:e>t?1:0}import{createHash as Cm}from"node:crypto";import{BlockRenderRefSchema as s0,GeneratedSiteCapabilitiesSchema as a0,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as UI,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as c0,SiteEditPageBlockTargetSchema as l0}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as JM,SiteIdSchema as XM,SnapshotIdSchema as zM}from"@vcp-dev/contracts";async function Bp(e){if(!XM.safeParse(e.site_id).success||!zM.safeParse(e.base_snapshot_id).success||!JM.safeParse(e.target).success)return Jn("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!WM(e.composition,e.target.composition))return Jn("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(!Mp(u))return Jn("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:HM(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=fc({files:n})}catch{return Jn("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 Jn("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return Jn("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Ta(o.entryFile,i,async u=>{if(!Mp(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=>Mp(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return Jn("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=xn({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 Jn("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=ic({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return Jn("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Gi({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?{...Jn("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...$o(l,e.target,e.document_version,e.selection_ref),index:l}}function HM(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 Mp(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function WM(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function Jn(e,t){return{ok:!1,code:e,message:t}}import{createHash as cB}from"node:crypto";import Ns from"node:path";import Vp from"@babel/generator";import{parse as lB}from"@babel/parser";import uB from"@babel/traverse";import*as O from"@babel/types";import{SiteEditSourcePathSchema as dB}from"@vcp-dev/contracts";import*as Mt from"@babel/types";var Av=[".tsx",".ts",".jsx",".js"],GM=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 Mr(e){let t=qM(e.files),n=wv(e.max_depth??32,"max_depth"),r=wv(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(Fv).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 m of o)if(!(!m||l.has(m))){if(!si(m,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:m,message:"Portable source closure node budget was exhausted."});continue}l.add(m),d.push({path:m,depth:0})}for(;d.length>0;){let m=d.shift();if(u.has(m.path))continue;u.add(m.path);let y=t.get(m.path);if(y===void 0){let v=o.includes(m.path)?"SOURCE_ENTRY_UNRESOLVED":ai(m.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Dr(i,{path:m.path,kind:ai(m.path)?"asset":"source",depth:m.depth,status:"unresolved"}),a.push({code:v,path:m.path,message:`Portable source closure could not read ${m.path}.`});continue}let b=ai(m.path)?"asset":"source";if(b==="asset"){let v=QM(m.path,y);Dr(i,{path:m.path,kind:b,depth:m.depth,status:v?"parse-failed":"complete"}),v&&a.push(v);continue}let S=$p(y),x=De(m.path,S);if(!x.ok){Dr(i,{path:m.path,kind:b,depth:m.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:m.path,message:x.diagnostic.message});continue}let E=ZM(x.module.ast),k=!1;for(let v of E){let I=YM({from:m.path,depth:m.depth,reference:v,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(I.edge),I.next&&(I.next.depth>n?k=!0:!u.has(I.next.path)&&!l.has(I.next.path)&&(l.add(I.next.path),d.push(I.next))),I.depthExhausted&&(k=!0)}Dr(i,{path:m.path,kind:b,depth:m.depth,status:k?"depth-exhausted":"complete"}),k&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:m.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(iB),g=rB(s).sort(sB),p=oB(a).sort(aB);return{entry_files:o.sort(Xn),nodes:f,edges:g,errors:p,complete:p.length===0,budget:{max_depth:n,max_nodes:r}}}function YM(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(!Qe(t.specifier)){let o=tB(t.specifier);return si(o,e.discovered,e.maxNodes)?(Dr(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=Up(e.from,t.specifier);if(Dv(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}.`}),si(n,e.discovered,e.maxNodes)?Dr(e.nodes,{path:n,kind:ai(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=Lv(e.from,t.specifier,e.files);if(!r){let o=ai(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}.`}),si(n,e.discovered,e.maxNodes)?Dr(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=ai(r)?"asset":"source";return si(r,e.discovered,e.maxNodes)?Dr(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 si(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 ZM(e){let t=[];for(let n of e.program.body)Mt.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Mt.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Mt.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return jp(e.program,n=>{if(Mt.isCallExpression(n)&&Mt.isImport(n.callee)){let r=n.arguments[0];Mt.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Mt.isTSImportType(n)&&t.push({specifier:Mt.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),nB(t)}function jp(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)Ov(r)&&jp(r,t);else Ov(n)&&jp(n,t)}function Br(e,t,n){let r=Up(e,t);return!Qe(t)||Dv(e,t,r)?null:Lv(e,t,n)}function Lv(e,t,n){let r=Up(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(eB(o))return null;for(let i of Av){let s=`${o}${i}`;if(n.has(s))return s}for(let i of Av){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Up(e,t){let n=Nn(e,t);return Fv(n)}function Fv(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 qM(e){return e instanceof Map?e:new Map(Object.entries(e))}function $p(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function QM(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test($p(t)))return{code:"SOURCE_ASSET_INVALID",path:e,message:"Stylesheet dependencies or escaped/dynamic CSS are not statically closed."};if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse($p(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Dr(e,t){let n=e.get(t.path);(!n||Tv(t.status)>Tv(n.status))&&e.set(t.path,t)}function si(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function Tv(e){return e==="complete"?1:0}function ai(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&GM.has(n)}function eB(e){return/\.[a-z0-9]+$/iu.test(e)}function tB(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function nB(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 rB(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function oB(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function iB(e,t){return Xn(e.path,t.path)||Xn(e.kind,t.kind)}function sB(e,t){return Xn(e.from,t.from)||Xn(e.target??"",t.target??"")||Xn(e.specifier??"",t.specifier??"")||Xn(e.kind,t.kind)}function aB(e,t){return Xn(e.path,t.path)||Xn(e.code,t.code)||Xn(e.specifier??"",t.specifier??"")}function Xn(e,t){return e<t?-1:e>t?1:0}function wv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function Ov(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Dv(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("/")}var Kp=uB,Wp=typeof Kp=="function"?Kp:Kp.default,fB=typeof Vp=="function"?Vp:Vp.default,Mv=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),Vv=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),Kv=new Set(["Boolean","Number","String"]),pB=new Set(["assign","values","entries"]);function Gp(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!Hp(r))return Rt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!dB.safeParse(t.source_file).success)return Rt("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 Rt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Rt("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 Rt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=El(n,t.source_file);return i===null||!Uv(t,i)?Rt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):yl({entryFile:r,entryContent:i,files:n,selection:t})}let o=El(n,t.source_file);if(o===null||!Uv(t,o))return Rt("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 yl({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!Hp(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return Rt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=xr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Rt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",c=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
1
+ import*as eC from"@babel/parser";import*as Wt from"@babel/types";import*as Mr from"node:path";var Bu=[".tsx",".ts",".jsx",".js"],tC=Bu.map(e=>`/index${e}`),nC=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 eh(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&nC.has(n[1].toLowerCase())}function th(e){let t=[];for(let n of e.program.body)Wt.isImportDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),Wt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),Wt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value);return Wt.traverseFast(e.program,n=>{let r=Wt.isImportExpression(n)?n.source:Wt.isCallExpression(n)&&Wt.isImport(n.callee)?n.arguments[0]:null;Wt.isStringLiteral(r)&&mt(r.value)&&t.push(r.value)}),t}function mt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function Qn(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=Mr.dirname(e);return Mr.join(n,t).replace(/\\/g,"/")}async function rC(e,t){for(let n of nh(e))if(await t(n))return n;return null}function nh(e){return[...Bu.some(t=>e.endsWith(t))?[e]:[],...Bu.map(t=>`${e}${t}`),...tC.map(t=>`${e}${t}`)]}function Br(e,t,n){let r=Qn(e,t);if(!mt(t)||!rh(e,t,r))return null;for(let o of nh(r))if(n.has(o))return o;return null}async function Io(e,t,n){let r=await Ca(e,t,n);return r.ok?r.path:null}async function Ca(e,t,n){let r=Qn(e,t);try{if(!rh(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 rC(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 rh(e,t,n){if(!mt(t)||t.includes("\0")||t.includes("\\")||Mr.posix.isAbsolute(n))return!1;let r=Mr.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!Mr.posix.isAbsolute(e)}import{createHash as iC}from"node:crypto";import*as oh from"@babel/parser";function vo(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function fe(e,t,n,r,o){return{ok:!1,source:e,diagnostic:vo(t,n,r,o)}}function ju(e,t,n,r,o){return{ok:!1,source:e,diagnostic:vo(t,n,r,o)}}var oC={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function er(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:oh.parse(t,{sourceType:"module",plugins:oC[n]})}}catch(r){return{ok:!1,source:t,diagnostic:vo("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function $u(e,t){return er({source:e,profile:ih(t.kind)})}function Wi(e,t){return er({source:e,profile:ih(t)})}function ih(e){return"next-app-entry"}function ko(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 Fe=(e,t)=>{let n=er({source:t,profile:ko({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${iC("sha256").update(t).digest("hex")}`,ast:n.ast,imports:th(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function sC(e,t){return Fe(e,t)}function aC(e,t){return Qn(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as cC,parseComponentI18nResourcesJson as lC,resolveSiteTextDirection as uC,SiteLocaleSchema as dC}from"@vcp-dev/contracts";var fC=["i18next","react-i18next"],pC="components/ui/site-locale-provider.tsx",mC="components/ui/component-i18n-provider.tsx",sh="app/layout.tsx";async function Gi(e){let t=e.files.filter(p=>p.path.endsWith(cC));if(t.length===0)return{ok:!0};for(let p of["package.json",sh,pC,mC])if(!await e.exists(p))return jr(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return jr("Target snapshot package.json is invalid.")}let r=ah(n)&&ah(n.dependencies)?n.dependencies:{},o=fC.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return jr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(sh),s=Uu(i,"html","lang"),a=Uu(i,"html","dir"),c=Uu(i,"SiteLocaleProvider","locale"),l=dC.safeParse(s);if(!l.success||!a||!c||s!==c||a!==uC(l.data))return jr("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 jr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return jr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let p of t){let g=lC(p.content);if(!g.success)return jr(`Component i18n resource is invalid: ${p.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return jr(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Uu(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 ah(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jr(e){return{ok:!1,message:e}}import Ju from"@babel/generator";import*as ph from"@babel/parser";import Ku from"@babel/traverse";import*as lt from"@babel/types";import{computeSiteEditSourceIdentityKey as hC}from"@vcp-dev/contracts";var ch="data-vcp-ui-component",Ra="components/ui";function Er(e){if(!e)return!1;let t=Vu(e);return t===Ra||t.startsWith(`${Ra}/`)||t.includes(`/${Ra}/`)||t.endsWith(`/${Ra}`)}function _o(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?Er(e.slice(2)):e.startsWith("./")||e.startsWith("../")?Er(Vu(`${gC(t)}/${e}`)):Er(e):!1}function Vu(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 gC(e){let t=Vu(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as TV}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as OV,isSiteEditRuntimeTextTag as LV}from"@vcp-dev/contracts/site-edit-runtime-capability";var lh={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 yC=typeof Ju=="function"?Ju:Ju.default,xC=typeof Ku=="function"?Ku:Ku.default,bC=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),EC="suppressHydrationWarning",SC=new Set(["SiteEditBootstrap"]);function IC(e){let t=_C(e.file,e.projectRoot);if(!kC(e.source)||Er(t))return{code:e.source,elements:[]};let n=e.attributes??lh,r=ph.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=RC(r,t);return xC(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!NC(c)||mh(a,n.key))return;let l=TC(s)??"default",u=OC(s),d=hC(t,l,u),p=Na(c)??"unknown",g=CC(c)?"jsx":"component-call";if(g==="component-call"&&!wC(s.node.children)&&SC.has(p))return;let m=g==="component-call"&&PC(p,i);AC(a,n.key,d),m&&uh(a,ch),vC(s)&&uh(a,EC),o.push({key:d,tag:p,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:yC(r,{jsescOption:{minimal:!0}}).code,elements:o}}function vC(e){return!e.findParent(t=>t.isJSXElement())}function kC(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function _C(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 CC(e){return lt.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function Na(e){return lt.isJSXIdentifier(e)?e.name:lt.isJSXMemberExpression(e)?hh(e):null}function RC(e,t){let n=new Set;for(let r of e.program.body)if(!(!lt.isImportDeclaration(r)||!_o(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function PC(e,t){let n=e.split(".")[0]??e;return t.has(n)}function NC(e){let t=Na(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!bC.has(t)}function mh(e,t){return e.attributes.some(n=>lt.isJSXAttribute(n)&&lt.isJSXIdentifier(n.name,{name:t}))}function AC(e,t,n){gh(e,lt.jsxAttribute(lt.jsxIdentifier(t),lt.stringLiteral(n)))}function uh(e,t){mh(e,t)||gh(e,lt.jsxAttribute(lt.jsxIdentifier(t),null))}function gh(e,t){let n=e.attributes.findIndex(r=>lt.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function hh(e){return`${lt.isJSXIdentifier(e.object)?e.object.name:hh(e.object)}.${e.property.name}`}function TC(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&lt.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 wC(e){return e.some(t=>lt.isJSXElement(t)||lt.isJSXFragment(t))}var dh=new WeakMap,Pa=new WeakMap,Xu=new WeakMap;function OC(e){let t=dh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=LC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return dh.set(e.node,o),o}function LC(e){let t=Na(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${fh(e,t)}`:`${t}#${fh(e,t)}`}function fh(e,t){let n=yh(e)??e.getFunctionParent();if(!n)return 0;let r=Xu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Xu.get(n.node);o||(o=new Map,Xu.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()?Aa(n):FC(n);for(let c of a)if(Na(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 FC(e){let t=Pa.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!yh(r)&&n.push(r)}}),Pa.set(e.node,n),n}function yh(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 Aa(e){let t=Pa.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(...Aa(o));continue}o.isJSXExpressionContainer()&&n.push(...Co(o.get("expression")))}return Pa.set(e.node,n),n}function Co(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Aa(e);if(e.isParenthesizedExpression())return Co(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Co(e.get("right"));if(e.isConditionalExpression())return[...Co(e.get("consequent")),...Co(e.get("alternate"))];if(e.isCallExpression()&&MC(e.node)){let t=e.get("arguments")[0];return DC(t)}return[]}function DC(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Aa(t);if(t.isParenthesizedExpression())return Co(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?Co(r):[]}return[]}function MC(e){return lt.isMemberExpression(e.callee)&&lt.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as ej,SiteEditPatchPlanSchema as tj}from"@vcp-dev/contracts";function Ro(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 Ta(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 wa(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 Oa(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:BC(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 La(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:Ro(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 BC(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 dB,computeSiteEditCompositionKey as fB,getSiteEditSourceDeleteProtectionReason as pB,isSiteEditTextSourcePath as mB,parseSiteEditRepeatInstanceKey as gB,SITE_EDIT_SOURCE_DELETE_CAPABILITY as hB,stripSiteEditRepeatInstanceKeys as ln}from"@vcp-dev/contracts";import zl from"node:path";import{parse as yB}from"yaml";import Yu from"node:path";import{TextDecoder as $C}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as bh,SITE_EDIT_SOURCE_ALLOWED_DIRS as Eh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Sh,SiteEditCompositionContextSchema as UC,SiteEditSourceFileResponseSchema as zu,SiteEditSourceLocationSchema as VC,SiteEditSourcePathSchema as Fa,SiteEditSourceTreeResponseSchema as JC,isSiteEditTextSourcePath as KC}from"@vcp-dev/contracts";import{createHash as jC}from"node:crypto";var Yi=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 je(e){return`sha256:${jC("sha256").update(e).digest("hex")}`}var XC=[...Sh,...bh,...Eh];function Zu(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return UC.parse(e.composition)}var Hu=2e3,Wu=12,Gu=24*1024*1024,xh=512*1024,zC=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),HC={".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"},WC={".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"},GC=new $C("utf-8",{fatal:!0});async function Da(e,t={}){let n=Zu(t),{files:r,truncated:o}=await nR(e,t),i=iR(r.map(s=>s.metadata));return JC.parse({composition:n,nodes:i,defaultPath:sR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function Ma(e,t,n={}){let r=Zu(n),o=Fa.parse(t.path),i=await ZC(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Qu(o)){let a=kh(o),c=await QC(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return zu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await qu(e,o);return s.ok?zu.parse({composition:r,path:o,kind:"text",language:_h(o),sizeBytes:s.sizeBytes,contentHash:je(s.content),readonly:!1,content:s.content}):zu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function qu(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=YC(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 YC(e){if(e.includes(0))return null;try{return GC.decode(e)}catch{return null}}async function ZC(e,t,n){if(!eR(t,n))return null;let r=await qC(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function qC(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Ih(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(Qu(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function QC(e,t){if(!zC.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>xh)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>xh?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function eR(e,t){return Sh.some(n=>n===e)||bh.some(n=>n===e)||Eh.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Fa.safeParse(n);return r.success&&r.data===e})}function Ba(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return VC.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 Ih(e){return Array.isArray(e)?{files:e}:e}function tR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function nR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Ih(await e.listFiles({roots:rR(t),maxFiles:Hu+1,maxDepth:Wu,maxTotalBytes:Gu+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=Fa.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Wu){o.add("max-depth");continue}if(r.size>=Hu){o.add("max-files");break}if(i+a.sizeBytes>Gu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:oR(l,a.sizeBytes,Zu(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:tR([...o]),maxFiles:Hu,maxDepth:Wu,maxTotalBytes:Gu}}:{}}}function rR(e){let t=new Set(XC);for(let n of e.routeEntryFiles??[]){let r=Fa.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function oR(e,t,n){return Qu(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:kh(e),readonly:!0}:{composition:n,path:e,kind:"text",language:_h(e),sizeBytes:t,readonly:!1}}function iR(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 vh(t)}function vh(e){return e.map(t=>t.kind==="directory"?{...t,children:vh(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function sR(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 Qu(e){return!KC(e)}function kh(e){let t=Yu.posix.extname(e).toLowerCase();return!t&&Yu.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":HC[t]??"application/octet-stream"}function _h(e){let t=Yu.posix.extname(e).toLowerCase();return WC[t]??"plaintext"}import*as No from"@babel/types";import ed from"@babel/traverse";import*as tr from"@babel/types";function ft(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(tr.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(tr.isIdentifier(s)&&s.name==="Fragment"||tr.isStringLiteral(s)&&s.value==="Fragment")&&Ch(i.parentPath)}if(!tr.isJSXMemberExpression(t)||!tr.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!tr.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())&&Ch(r.parentPath)}function Ch(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var $r=typeof ed=="function"?ed:ed.default,ja=new WeakMap,$a=new WeakMap;function nr(e,t){let n=$u(e,t);if(!n.ok)return ju(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=De(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}}:ju(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function De(e,t){return t.kind==="jsx-node"?Ah(e,t):t.kind==="jsx-attribute"?fR(e,t):t.kind==="value"?pR(e,t):t.kind==="expression"?mR(e,t):t.kind==="directive"?gR(e,t):t.kind==="export"?hR(e,t):{ok:!1,diagnostic:vo("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Ah(e,t){return t.strategy==="source-range"?aR(e,t):cR(e,t)}function aR(e,t){let n=null;if($r(e,{JSXElement(o){if(!Po(o.node,t.sourceRange))return;let i=kt("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!Po(o.node,t.sourceRange))return;let i=kt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!Po(o.node,t.sourceRange))return;let i=kt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!Po(o.node,t.sourceRange))return;let i=kt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return Nt("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!PR(r.path,t.expectedIdentity)?Nt("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function cR(e,t){if(t.structuralPath===""){let r=uR(e,t.component);if(r){let o=dR(r);if(o)return o}}let n=null;return $r(e,{JSXElement(r){if(qi(r)!==t.component||nd(r)!==t.structuralPath)return;let i=kt("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(qi(r)!==t.component||nd(r)!==t.structuralPath)return;let i=kt("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=lR(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:Nt("jsx-node","locator-miss","JSX node not found for structural-path locator")}function lR(e,t,n){let r=null;return $r(e,{JSXElement(o){if(qi(o)!==t||!Po(o.node,n))return;let i=kt("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(qi(o)!==t||!Po(o.node,n))return;let i=kt("jsx-node",o);i&&(r=i,o.stop())}}),r}function uR(e,t){let n=null;return $r(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 dR(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 Nt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?Nt("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 Nt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function fR(e,t){let n=Ah(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>NR(c,t.name));if(!s||!s.isJSXAttribute())return Nt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=kt("jsx-attribute",s);return a?{ok:!0,match:a}:Nt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function pR(e,t){let n=yR(e,t);if(!n.ok)return n;let r=xR(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!Ir(r.match.path.node.loc,t.expectedRange)?Nt("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function mR(e,t){let n=null;return $r(e,{Identifier(r){if(!kR(r))return;let o=Ph(r);if(!o||!Nh(o,t))return;let i=kt("expression",r);i&&(t.expectedRange&&!Ir(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Ph(r);if(!o||!Nh(o,t))return;let i=kt("expression",r);i&&(t.expectedRange&&!Ir(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Nt("expression","locator-miss","Expression not found")}function gR(e,t){let n=null;return $r(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!Ir(i.node.loc,t.expectedRange))return;let s=kt("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:Nt("directive","locator-miss",`Directive '${t.value}' not found`)}function hR(e,t){let n=null;return $r(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=kt("export",c);if(!p||t.expectedRange&&!Ir(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=rd(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=kt("export",u);if(!d||t.expectedRange&&!Ir(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=rd(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!Ir(s.node.loc,t.expectedRange))return;let a=kt("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=kt("export",o);i&&(t.expectedRange&&!Ir(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:Nt("export","export-not-found",`Export '${RR(t)}' not found`)}function yR(e,t){let n=null;return $r(e,{Expression(r){if(n||t.root.kind!=="expression"||!Po(r.node,t.root.sourceRange))return;let o=kt("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 m=kt("value",g);if(!m)return;n=m,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 p=kt("value",d);p&&(n=p,r.stop())},ExportNamedDeclaration(r){if(n||t.root.kind!=="named-export")return;let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=rd(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=kt("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=kt("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:Nt("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 xR(e,t){let n=td(e);for(let o of t){if(n=td(n),o.kind==="property"){if(!n.isObjectExpression())return Nt("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return Nt("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>AR(l,o.name));if(!c||!c.isObjectProperty())return Nt("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return Nt("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return Nt("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return Nt("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=td(n);let r=kt("value",n);return r?{ok:!0,match:r}:Nt("value","locator-miss","Resolved value has no source range")}function td(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function kt(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 Po(e,t){return Ir(e.loc,t)}function Ir(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 nd(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!ft(n)){let o=wh(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${Rh(n,o)}`):t.unshift(`${o}#${Rh(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||IR(n.parentPath)&&!vR(n.parentPath))break;n=n.parentPath}return t.join("/")}function Rh(e,t){let n=Th(e)??e.getFunctionParent();if(!n)return 0;let r=ja.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=ja.get(n.node)?.get(t);if(!i){let a=ja.get(n.node);a||(a=new Map,ja.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Zi(n):bR(n);for(let a of s)if(wh(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function bR(e){let t=$a.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Th(r)&&n.push(r)}}),$a.set(e.node,n),n}function Th(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ft(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Zi(e){let t=$a.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(ft(o)){n.push(...Zi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Zi(o));continue}o.isJSXExpressionContainer()&&n.push(...Sr(o.get("expression")))}return $a.set(e.node,n),n}function Sr(e){if(e.isJSXElement())return ft(e)?Zi(e):[e];if(e.isJSXFragment())return Zi(e);if(e.isParenthesizedExpression())return Sr(e.get("expression"));if(e.isLogicalExpression()&&ER(e.node.operator))return Sr(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(...Sr(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...Sr(a));break}}return i}else if(o.node&&o.isExpression())return Sr(o)}}}}return e.isConditionalExpression()?[...Sr(e.get("consequent")),...Sr(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Sr(t)):[]}function ER(e){return e==="&&"||e==="||"||e==="??"}function wh(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?SR(e.name):null}function SR(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 qi(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 IR(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function vR(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 kR(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Ph(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 Nh(e,t){return e.base===t.base&&_R(e.path,t.path??[])}function _R(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 CR(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function RR(e){return e.exportKind==="named"?e.name:e.exportKind}function Nt(e,t,n,r){return{ok:!1,diagnostic:vo(t,n,e,r)}}function PR(e,t){return qi(e)!==t.component?!1:nd(e)===t.structuralPath}function NR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function rd(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function AR(e,t){return e.isObjectProperty()?CR(e.node)===t:!1}import*as Lh from"@babel/parser";import{arrayExpression as FR,booleanLiteral as DR,identifier as MR,jsxAttribute as BR,jsxExpressionContainer as jR,jsxIdentifier as $R,nullLiteral as UR,numericLiteral as VR,objectExpression as JR,objectProperty as KR,stringLiteral as id}from"@babel/types";import od from"@babel/generator";var TR=typeof od=="function"?od:od.default;function wR(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 OR(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 LR(e,t){return e.split(`
3
+ `).map(r=>OR(r,t)).join(`
4
+ `)}function Ua(e){let{ast:t,source:n}=e;try{let r=wR(n),i=TR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=LR(i,r)),{ok:!0,source:i}}catch(r){return fe(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Oh(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 Qi(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Oh(e),afterSourceHash:Oh(t),inverse:n.inverse}}}function et(e,t,n){let r=Ua({ast:e,source:t});return r.ok?Qi(t,r.source,n):r}function ut(e,t){let n=Wi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Va(e,t){return Ua({ast:e,source:t})}function XR(e,t,n){let r=De(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function ei(e,t,n){let r=XR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:fe(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Ur(e){return typeof e=="string"?id(e):typeof e=="number"?VR(e):typeof e=="boolean"?DR(e):e===null?UR():Array.isArray(e)?FR(e.map(t=>Ur(t))):JR(Object.entries(e).map(([t,n])=>{let r=KR(sd(t),Ur(n));return t==="__proto__"&&(r.computed=!0),r}))}function zR(e){return typeof e=="string"?id(e):jR(Ur(e))}function es(e,t){return BR($R(e),zR(t))}function Ja(e,t){try{let r=Lh.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:fe(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:fe(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function sd(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?MR(e):id(e)}function Ka(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ut(t,"jsx-node");if(!i.ok)return i.result;let s=De(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=HR(s.match.path)[r];if(!c)return fe(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]??"",p=l.match(/\s*$/)?.[0]??"";c.path.replaceWithMultiple([...d?[No.jsxText(d)]:[],No.jsxExpressionContainer(No.stringLiteral("")),...p?[No.jsxText(p)]:[]]);break}let u=WR(l,o);c.path.node.value=u,c.path.node.extra={rawValue:u,raw:u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/{/g,"&#123;").replace(/}/g,"&#125;")};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 et(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function HR(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=GR(r.get("expression"));o.length>0&&t.push(...o)}}return t}function WR(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function GR(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 ad}from"@babel/types";function Ao(e){let{source:t,locator:n}=e,r=ut(t,"jsx-node");if(!r.ok)return r.result;let o=De(r.ast,n);return o.ok?(YR(o.match.path),et(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function YR(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ad());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ad());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ad());return}e.remove()}import{cloneNode as ZR}from"@babel/types";function ti(e){let t=ut(e.source,"jsx-node");if(!t.ok)return t.result;let n=De(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=Ja(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(ZR(r.node,!0)),et(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as cP}from"@babel/types";import cd from"@babel/traverse";import*as Ce from"@babel/types";function ts(e,t,n){return`${e}::${t}::${n}`}var Q={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 qR=typeof cd=="function"?cd:cd.default;function Nn(e,t,n,r){if(!e.ok)return e;let o=Pn(n,t);if(!o)return e;let i=QR(t,o,r);return i?{...e,selectionRef:i}:e}function QR(e,t,n){let r=eP(e,t);if(!r)return;let o=n.sourceLocator?Fh(n.sourceLocator):void 0,i=n.targetParentLocator?Fh(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??nP(r)??i?.component??o?.component;if(!(!s||!a))return{key:ts(s,a,rP(r))}}function Fh(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function eP(e,t){let n=Uh(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Uh(e,t){let n=null;return qR(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Pn(e,t){if(!e)return null;if(Ce.isJSXElement(e))return aP(t,e)?Dh(e.children,t):e;if(Ce.isJSXFragment(e))return Dh(e.children,t);if(Ce.isJSXExpressionContainer(e)||Ce.isParenthesizedExpression(e)||Ce.isTSAsExpression(e)||Ce.isTSSatisfiesExpression(e)||Ce.isTSTypeAssertion(e)||Ce.isTSNonNullExpression(e))return Pn(e.expression,t);if(Ce.isLogicalExpression(e))return Pn(e.right,t);if(Ce.isConditionalExpression(e))return Pn(e.consequent,t)??Pn(e.alternate,t);if(Ce.isCallExpression(e)||Ce.isOptionalCallExpression(e))return Vh(e)?tP(e.arguments[0],t):null;if(Ce.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Pn(n,t);if(r)return r}return null}function Dh(e,t){for(let n of e){let r=Pn(n,t);if(r)return r}return null}function tP(e,t){return!e||!Ce.isArrowFunctionExpression(e)&&!Ce.isFunctionExpression(e)?null:Ce.isBlockStatement(e.body)?ns(e.body.body,t):Pn(e.body,t)}function ns(e,t){for(let n of e){if(Ce.isReturnStatement(n)){let r=Pn(n.argument,t);if(r)return r;continue}if(Ce.isBlockStatement(n)){let r=ns(n.body,t);if(r)return r;continue}if(Ce.isIfStatement(n)){let r=Mh(n.consequent,t);if(r)return r;let o=n.alternate?Mh(n.alternate,t):null;if(o)return o;continue}if(Ce.isSwitchStatement(n))for(let r of n.cases){let o=ns(r.consequent,t);if(o)return o}}return null}function Mh(e,t){return Ce.isBlockStatement(e)?ns(e.body,t):ns([e],t)}function nP(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(Ce.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&Ce.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 Bh=new WeakMap,jh=new WeakMap,ld=new WeakMap;function rP(e){let t=Bh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=oP(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Bh.set(e.node,o),o}function oP(e){let t=Jh(e.node.openingElement.name);return!t||ft(e)?null:/^[A-Z]/.test(t)?`component:${t}#${$h(e,t)}`:`${t}#${$h(e,t)}`}function $h(e,t){let n=iP(e);if(!n)return 0;let r=ld.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=ld.get(n.node);o||(o=new Map,ld.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of To(n))if(Jh(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 iP(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(ft(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function To(e){let t=jh.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(ft(o)){n.push(...To(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...To(o));continue}o.isJSXExpressionContainer()&&n.push(...rr(o.get("expression")))}return jh.set(e.node,n),n}function rr(e){if(e.isJSXElement())return ft(e)?To(e):[e];if(e.isJSXFragment())return To(e);if(e.isParenthesizedExpression())return rr(e.get("expression"));if(e.isLogicalExpression())return rr(e.get("right"));if(e.isConditionalExpression())return[...rr(e.get("consequent")),...rr(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:rr(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Vh(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?sP(n):[]}return[]}function sP(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ft(t)?To(t):[t];if(t.isJSXFragment())return To(t);if(t.isParenthesizedExpression())return rr(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return rr(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(...rr(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...rr(o)),n}return n}function Vh(e){let t=e.callee;return(Ce.isMemberExpression(t)||Ce.isOptionalMemberExpression(t))&&Ce.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function aP(e,t){let n=Uh(e,t);return n?ft(n):!1}function Jh(e){return Ce.isJSXIdentifier(e)?e.name:Ce.isJSXMemberExpression(e)?Kh(e):Ce.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Kh(e){return`${Ce.isJSXIdentifier(e.object)?e.object.name:Kh(e.object)}.${e.property.name}`}function Vr(e,t){if(t.parentPath===e&&t.listKey==="children"&&ud(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!ud(n))return null;let r=n;for(;r&&r!==e;){if(!ud(r)||!ft(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function ud(e){return e.isJSXElement()||e.isJSXFragment()}function An(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ut(t,"jsx-node");if(!a.ok)return a.result;let c=De(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return fe(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 fe(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=Ja(t,r.jsx);if(!u.ok)return u.result;let d=cP(u.node,!0),p=l.node.children,g={...s,targetParentLocator:n},m=b=>s?Nn(b,a.ast,d,g):b;if(o==="append")return p.push(d),m(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return p.unshift(d),m(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return fe(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=De(a.ast,i);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};let y=Vr(c.match.path,f.match.path);if(!y)return fe(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===f.match.path.node);return E===-1?fe(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,d),m(et(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as Xh from"@babel/parser";import{cloneNode as lP}from"@babel/types";function Xa(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ut(t,"jsx-node");if(!a.ok)return a.result;let c=uP(t,r);if(!c.ok)return c.result;let l=De(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return fe(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 fe(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=De(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=Vr(l.match.path,x.match.path);if(!E)return fe(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 fe(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=lP(c.node,!0),g=u.node.children,m={...s,targetParentLocator:n},f=x=>s?Nn(x,a.ast,p,m):x;if(o==="append")return g.push(p),f(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(p),f(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(x=>x===d);return y===-1?fe(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,p),f(et(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function uP(e,t){try{let r=Xh.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:fe(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:fe(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as dP,nullLiteral as dd}from"@babel/types";import*as Jr from"@babel/types";import*as zh from"@babel/types";function rs(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!zh.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function wo(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=ut(t,"jsx-node");if(!a.ok)return a.result;let c=De(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=De(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return fe(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 fe(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=De(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=b.match.path.isJSXElement()?rs(b.match.path,l.match.path):b.match.path,I=Vr(l.match.path,S);if(!I)return fe(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=I,d=S}else if(o==="before"||o==="after")return fe(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return fe(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?rs(c.match.path,l.match.path):c.match.path,m=dP(g.node,!0);if(!Jr.isJSXElement(m)&&!Jr.isJSXExpressionContainer(m)&&!Jr.isJSXFragment(m)&&!Jr.isJSXText(m))return fe(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let f=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 fe(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");fP(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(m),Nn(Va(a.ast,t),a.ast,m,x);if(o==="prepend")return y.unshift(m),Nn(Va(a.ast,t),a.ast,m,x);let E=p-(f!==-1&&f<p?1:0);return y.splice(o==="before"?E:E+1,0,m),Nn(Va(a.ast,t),a.ast,m,x)}function fP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(dd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(dd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(dd());return}e.remove()}import*as Hh from"@babel/parser";import{cloneNode as pP,nullLiteral as fd}from"@babel/types";function za(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=ut(t,"jsx-node");if(!c.ok)return c.result;let l=mP(t,s);if(!l.ok)return l.result;let u=De(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=De(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return fe(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 fe(t,"self-closing-element","Cannot move repeat child into self-closing element","jsx-node")}let p=d.match.path,g=null;if(i){let b=De(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=Vr(d.match.path,b.match.path);if(!S)return fe(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");p=S,g=b.match.path.node}else if(o==="before"||o==="after")return fe(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return fe(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let m=p.node,f=pP(l.node,!0);gP(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=m.children;if(o==="append")return x.push(f),Nn(et(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,f,y);if(o==="prepend")return x.unshift(f),Nn(et(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,f,y);let E=x.findIndex(b=>b===g);return E===-1?fe(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,f),Nn(et(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,f,y))}function mP(e,t){try{let r=Hh.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:fe(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:fe(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function gP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(fd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(fd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(fd());return}e.remove()}import{SiteEditSetPropsParamsSchema as hP,classifySiteEditPropertyName as yP}from"@vcp-dev/contracts";import*as ni from"@babel/types";function Ha(e){let t=hP.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return fe(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=ut(e.source,"jsx-node");if(!n.ok)return n.result;let r=ei(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=yP(a.name);if(c.owner!=="generic")return fe(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(ni.isJSXAttribute),s=new Map;for(let a of i){let c=xP(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 fe(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=es(a.name,a.value).value;c?c.value=l:o.attributes.push(es(a.name,a.value))}return et(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function xP(e){return ni.isJSXIdentifier(e.name)?e.name.name:ni.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as bP}from"@vcp-dev/contracts";import*as ge from"@babel/types";var Wh=["prefetch","replace","scroll","locale","onNavigate"],EP=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function SP(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>ge.isJSXAttribute(n)&&ge.isJSXIdentifier(n.name)&&EP.test(n.name.name)))return!0;t=t.parentPath}return!1}function Wa(e){let t=ut(e.source,"jsx-node");if(!t.ok)return t.result;let n=ei(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=bP.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return vr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=PP(s.name);if(!a)return vr(e.source,"Unsupported JSX link tag");if(s.attributes.some(ge.isJSXSpreadAttribute))return vr(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let m of s.attributes){if(!ge.isJSXAttribute(m))continue;let f=md(m);if(!f)return vr(e.source,"Unsupported JSX attribute name");let y=c.get(f)??[];y.push(m),c.set(f,y)}if([...c.values()].some(m=>m.length>1))return vr(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!RP(l))return vr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:kP(o,s.name);if(!u&&!d)return vr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&SP(o))return vr(e.source,"A link with an active event handler in its JSX ancestry cannot become an inert anchor");let p=null;if(e.link.kind==="internal-route")if(d)p=a;else{let m=_P(t.ast,o);if(!m.ok)return vr(e.source,m.reason);p=m.localName}if(d&&e.link.kind!=="internal-route"){let m=ge.jsxIdentifier("a");s.name=m,i.closingElement&&(i.closingElement.name=ge.jsxIdentifier("a")),CP(t.ast,d,o)}else p&&u&&(s.name=ge.jsxIdentifier(p),i.closingElement&&(i.closingElement.name=ge.jsxIdentifier(p)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Wh.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&Wh.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!ge.isJSXAttribute(m))return!0;let f=md(m);return!f||!g.has(f)}),e.link.kind!=="none"&&s.attributes.push(ge.jsxAttribute(ge.jsxIdentifier("href"),ge.stringLiteral(e.link.href))),IP(s,e.changes),et(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function IP(e,t){for(let n of t){let r=e.attributes.find(s=>ge.isJSXAttribute(s)&&md(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?ge.stringLiteral(n.value):ge.jsxExpressionContainer(pd(n.value)),i=ge.jsxAttribute(ge.jsxIdentifier(n.name),o);r&&ge.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function pd(e){return e===null?ge.nullLiteral():typeof e=="string"?ge.stringLiteral(e):typeof e=="number"?ge.numericLiteral(e):typeof e=="boolean"?ge.booleanLiteral(e):Array.isArray(e)?ge.arrayExpression(e.map(t=>pd(t))):typeof e=="object"?ge.objectExpression(Object.entries(e).map(([t,n])=>ge.objectProperty(ge.isValidIdentifier(t)?ge.identifier(t):ge.stringLiteral(t),pd(n)))):ge.nullLiteral()}function vP(e){return ge.isImportDefaultSpecifier(e)||ge.isImportSpecifier(e)&&e.importKind!=="type"&&(ge.isIdentifier(e.imported,{name:"default"})||ge.isStringLiteral(e.imported,{value:"default"}))}function Gh(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(ge.isIdentifier(e.node.imported,{name:"default"})||ge.isStringLiteral(e.node.imported,{value:"default"}))}function kP(e,t){if(!ge.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Gh(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function _P(e,t){let n=e.program.body.filter(c=>ge.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(vP);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=ge.importDefaultSpecifier(ge.identifier(s));if(r)r.specifiers.unshift(a);else{let c=ge.importDeclaration([a],ge.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&ge.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function CP(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Gh(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 RP(e){return!e.value||ge.isStringLiteral(e.value)}function PP(e){return ge.isJSXIdentifier(e)?e.name:null}function md(e){return ge.isJSXIdentifier(e.name)?e.name.name:null}function vr(e,t){return fe(e,"unsupported-syntax",t,"jsx-node")}import*as Bt from"@babel/types";import{classifySiteEditPropertyName as Yh}from"@vcp-dev/contracts";function Ga(e){let t=Yh(e.name),n=Yh(e.property);if(t.owner!=="generic"||n.owner!=="generic")return fe(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Zh(e.object))return fe(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return fe(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=ut(e.source,"jsx-node");if(!r.ok)return r.result;let o=ei(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Bt.isJSXAttribute(l)&&AP(l)===e.name);if(s.length>1)return fe(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=NP(e.object,e.property),c=s[0];if(c)c.value=Bt.jsxExpressionContainer(a);else{let l=es(e.name,"");l.value=Bt.jsxExpressionContainer(a),i.attributes.push(l)}return et(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function NP(e,t){return Zh(t)?Bt.memberExpression(Bt.identifier(e),Bt.identifier(t)):Bt.memberExpression(Bt.identifier(e),Bt.stringLiteral(t),!0)}function Zh(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function AP(e){return Bt.isJSXIdentifier(e.name)?e.name.name:Bt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as wP,identifier as os,importDeclaration as OP,importDefaultSpecifier as LP,importNamespaceSpecifier as FP,importSpecifier as DP,isImportDefaultSpecifier as qh,isImportNamespaceSpecifier as Qh,isImportSpecifier as ey,stringLiteral as MP}from"@babel/types";function Tn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!zP(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return fe(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=JP(r);if(!i.ok)return fe(t,"unsupported-syntax",i.message);let s=ut(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=HP(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(sy(y)));if(d.length===0)return Qi(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=KP(c.body),g=d.find(y=>p.has(gd(y)));if(g)return fe(t,"unsupported-syntax",`Import local binding already exists: ${gd(g)}`);let m=VP(d);if(m.reduce((y,x)=>y+x.length,0)!==d.length)return fe(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of m){if(!oy(ny(y)))return fe(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>BP(E,y));if(x)jP(x,y);else{let E=OP(ty(y),MP(n));XP(c.body,E),l.push(E)}}return et(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function BP(e,t){return e.importKind==="type"?!1:oy(UP($P(e),ny(t)))}function jP(e,t){let n=!1,r=new Set(e.specifiers.map(o=>hd(o)));for(let o of ty(t)){let i=hd(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return iy(e.specifiers),{changed:n}}function ty(e){let t=e.map(n=>{switch(n.kind){case"named":return DP(n.local?os(n.local):os(n.imported),os(n.imported));case"default":return LP(os(n.local));case"namespace":return FP(os(n.local));default:return n}});return iy(t),t}function ny(e){let t=ry();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 $P(e){let t=ry();for(let n of e.specifiers)qh(n)?t.defaultLocals.add(n.local.name):Qh(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function ry(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function UP(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function oy(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function iy(e){let t=[...e.filter(n=>qh(n)),...e.filter(n=>Qh(n)),...e.filter(n=>ey(n))];e.splice(0,e.length,...t)}function VP(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 JP(e){let t=new Map,n=new Map;for(let r of e){let o=sy(r);if(t.has(o))continue;let i=gd(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 KP(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(wP(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 XP(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 zP(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 sy(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 gd(e){return e.kind==="named"?e.local??e.imported:e.local}function HP(e,t){return e.importKind==="type"||ey(t)&&t.importKind==="type"?null:hd(t)}function hd(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 ri(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!GP(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return fe(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=ut(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 Qi(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>WP(u,d))),l.specifiers.length===0&&a.body.splice(c,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function WP(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 GP(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 is(e){let{source:t,locator:n,next:r}=e,o=Qa(t,n);return o.ok?(o.path.replaceWith(Ur(r)),et(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Ya(e){let{source:t,locator:n,index:r,value:o}=e,i=Qa(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?fe(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?fe(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Ur(o)),et(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):fe(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Za(e){let{source:t,locator:n,index:r}=e,o=Qa(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?fe(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?fe(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),et(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):fe(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function qa(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=Qa(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return fe(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return fe(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 fe(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),et(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function Qa(e,t){let n=ut(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=De(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 ec(e){let t=ut(e.source,"value");if(!t.ok)return t.result;let n=De(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return fe(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 fe(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ut.isObjectProperty(a)&&YP(a.key)===e.name);if(o.length>1)return fe(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ut.unaryExpression("void",Ut.numericLiteral(0)):Ur(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ut.objectProperty(sd(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return et(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function YP(e){return Ut.isIdentifier(e)?e.name:Ut.isStringLiteral(e)?e.value:Ut.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as ZP,isSiteEditRuntimeVoidElementTag as qP}from"@vcp-dev/contracts/site-edit-runtime-capability";function oi(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function QP(e,t,n){let r=oi(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(S=>({kind:S.kind,message:S.reason})),a=i.isOpaque,l=o.parentKey===null&&i.componentName==="Page",u=i.tag.toLowerCase(),d=i.tag!==u,p=!d&&qP(u),g=d||ZP(u),m=d&&i.childKeys.length>0&&!i.isPublicUiComponent,f=i.textSegments.length>0&&i.textSegments.some(S=>S.editable);p&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!p&&!g&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=f&&(!a||i.importedFrom==="next/link"),x=!i.isPublicUiComponent&&!p&&g&&(!a||m);return{composition:r,key:e,canUpdateText:y,canInsertChild:x,canMove:!l,canRemove:!l,constraints:s}}function tc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,QP(r,e,t));return n}function yd(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:je(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=eN(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:je(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Unable to locate JSX element for key ${t.identity.key}`}]};let r=n.node.openingElement,o=r.attributes.find(d=>d.type==="JSXAttribute"&&d.name.type==="JSXIdentifier"&&d.name.name==="className"),i={key:e.key,composition:e.route.composition,filePath:t.sourceFile,componentName:t.componentName,openingElementRange:cy(r),version:{documentVersion:e.route.graph.version,contentHash:je(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",c=n.get("openingElement").get("attributes").find(d=>d.node===o),l=c?.isJSXAttribute()?c.get("value"):null,u=l?.isJSXExpressionContainer()?tN(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:ay(e.route.source,o),valueRaw:s?ay(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:cy(o),diagnostics:[]}}function ly(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 eN(e,t){let n=er({source:e,profile:ko({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=De(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:nN(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function tN(e){let t=new Set,n=e;if(n.isIdentifier()){for(;n.isIdentifier();){let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isVariableDeclarator()||!r.path.get("id").isIdentifier({name:n.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||t.has(r.path.node))return;t.add(r.path.node);let o=r.path.get("init");if(!o.isExpression())return;n=o}if(n.isStringLiteral())return n.node.value;if(n.isTemplateLiteral()&&n.node.expressions.length===0)return n.node.quasis.map(r=>r.value.cooked??r.value.raw).join("")}}function uy(e){let t=er({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 ay(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function cy(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 nN(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function dy(){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 rN}from"node:crypto";import nc from"node:fs/promises";import xd from"node:path";import{setTimeout as oN}from"node:timers/promises";var iN={async mkdir(e,t){await nc.mkdir(e,t)},async writeFile(e,t,n){await nc.writeFile(e,t,n)},async rename(e,t){await nc.rename(e,t)},async rm(e,t){await nc.rm(e,t)}},sN=new Set(["EACCES","EBUSY","EPERM"]),aN=[10,20,40,80,160];async function cN(e,t,n){for(let r of aN)try{await e.rename(t,n);return}catch(o){if(!lN(o))throw o;await oN(r)}await e.rename(t,n)}function lN(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&sN.has(e.code)}async function rc(e,t,n=iN){let r=xd.dirname(e),o=xd.basename(e),i=xd.join(r,`.${o}.${process.pid}.${rN()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await cN(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import bd from"@babel/traverse";import*as P from"@babel/types";import*as He from"@babel/types";function or(e,t={}){if(He.isTSAsExpression(e)||He.isTSSatisfiesExpression(e)||He.isTSNonNullExpression(e)||He.isTypeCastExpression(e)||He.isParenthesizedExpression(e))return or(e.expression,t);if(He.isStringLiteral(e))return{status:"resolved",value:e.value};if(He.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(He.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(He.isNullLiteral(e))return{status:"resolved",value:null};if(He.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(He.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(He.isUnaryExpression(e)&&e.operator==="void"&&He.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(He.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||He.isSpreadElement(r))return{status:"unresolved"};let o=or(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(He.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!He.isObjectProperty(r)||r.computed||!He.isExpression(r.value))return{status:"unresolved"};let o=uN(r.key);if(o===null)return{status:"unresolved"};let i=or(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 He.isMemberExpression(e)||He.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function uN(e){return He.isIdentifier(e)?e.name:He.isStringLiteral(e)?e.value:He.isNumericLiteral(e)?String(e.value):null}var dN=typeof bd=="function"?bd:bd.default;function Gt(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 fN(e){return/^[A-Z]/.test(e)}function kd(e){let t=e.openingElement;return P.isJSXIdentifier(t.name)?t.name.name==="Fragment":P.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function si(e){return P.isJSXFragment(e)}function py(e){return P.isJSXIdentifier(e.name)?e.name.name:P.isJSXMemberExpression(e.name)?my(e.name):P.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function my(e){return P.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:P.isJSXMemberExpression(e.object)?`${my(e.object)}.${e.property.name}`:e.property.name}function pN(e){return e.split(".")[0]??e}function mN(e){let t=e;for(;t;){let n=t.node;if(P.isFunctionDeclaration(n)&&n.id||P.isVariableDeclarator(n)&&P.isIdentifier(n.id))return n.id.name;if(P.isExportDefaultDeclaration(n)){let r=n.declaration;if(P.isFunctionDeclaration(r)&&r.id)return r.id.name;if(P.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function gN(){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 hN(e){let t=new Map;for(let n of e.program.body){if(!P.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(P.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(P.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(P.isImportSpecifier(o)){let i=P.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function kr(e,t=[]){if(P.isIdentifier(e))return t.push(e.name),t;if(P.isObjectPattern(e)){for(let n of e.properties)P.isObjectProperty(n)?kr(n.value,t):P.isRestElement(n)&&kr(n.argument,t);return t}if(P.isArrayPattern(e)){for(let n of e.elements)n&&(P.isRestElement(n)?kr(n.argument,t):kr(n,t));return t}return P.isAssignmentPattern(e)?(kr(e.left,t),t):(P.isRestElement(e)&&kr(e.argument,t),t)}function $n(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function ss(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 yN(e,t,n){e.set(t,{resolved:!0,value:n})}function _d(e,t){e.set(t,{resolved:!1})}function gy(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 Ot(e,t,n){if(P.isTSAsExpression(e)||P.isTSSatisfiesExpression(e)||P.isTSNonNullExpression(e)||P.isTypeCastExpression(e)||P.isParenthesizedExpression(e))return Ot(e.expression,t,n);if(P.isLogicalExpression(e))return oc([Ot(e.left,t,n),Ot(e.right,t,n)]);if(P.isBinaryExpression(e))return oc([P.isExpression(e.left)?Ot(e.left,t,n):null,P.isExpression(e.right)?Ot(e.right,t,n):null]);if(P.isConditionalExpression(e))return oc([Ot(e.consequent,t,n),Ot(e.alternate,t,n)]);if(P.isTemplateLiteral(e))return oc(e.expressions.filter(P.isExpression).map(i=>Ot(i,t,n)));if(P.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!P.isMemberExpression(e)&&!P.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;P.isMemberExpression(o)||P.isOptionalMemberExpression(o);){if(o.computed)if(P.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(P.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&P.isExpression(o.property)){let i=Kr(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(!P.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return P.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:$n(e,t),base:o.name,path:r}:null}function oc(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 Cd(e,t,n){if(P.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&P.isExpression(r)?Ot(r,t,n):null}return P.isCallExpression(e)&&P.isMemberExpression(e.callee)&&!e.callee.computed&&P.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&P.isExpression(e.callee.object)?Cd(e.callee.object,t,n):Ot(e,t,n)}function Kr(e,t){if(P.isStringLiteral(e)||P.isNumericLiteral(e)||P.isBooleanLiteral(e))return e.value;if(P.isNullLiteral(e))return null;if(P.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(P.isIdentifier(e)){let n=ss(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return;let o=Kr(r,t);if(o===void 0)return;n.push(o)}return n}if(P.isObjectExpression(e)){let n={};for(let r of e.properties){if(!P.isObjectProperty(r)||r.computed||!P.isExpression(r.value))return;let o=null;if(P.isIdentifier(r.key)?o=r.key.name:P.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!P.isIdentifier(r.value))return;let s=ss(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Kr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(P.isMemberExpression(e)){let n=Ot(e,"",t);if(!n)return;let r=ss(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=gy(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(P.isCallExpression(e))return yy(e,t)??void 0}function hy(e,t,n){let r=Ot(e,n,t);if(!r)return P.isMemberExpression(e)||P.isBinaryExpression(e)||P.isLogicalExpression(e)||P.isConditionalExpression(e)||P.isCallExpression(e)?{value:$n(e,n),source:null}:null;let o=ss(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?gy(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 Ed(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:gN(),parentStack:[],valueScopes:i,importMap:o}}function Id(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of kr(o.id))_d(n,s);if(!P.isIdentifier(o.id)||!o.init||!P.isExpression(o.init))continue;let i=Kr(o.init,t);i!==void 0&&yN(n,o.id.name,i)}}function xN(e){let t=[];for(let n of e){if(P.isVariableDeclaration(n)){t.push(n);continue}P.isExportNamedDeclaration(n)&&n.declaration&&P.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function bN(e,t,n){let r=[],o=0;for(let i of e)if(P.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Gt(i),editable:!0,source:null})}else if(P.isJSXExpressionContainer(i)&&P.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Gt(i),editable:!0,source:null});else if(P.isJSXExpressionContainer(i)&&P.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:Gt(i),editable:!0,source:null}):r.push({index:o++,value:$n(s,n),sourceRange:Gt(i),editable:!0,source:Ot(s,n,t)})}else if(P.isJSXExpressionContainer(i)&&P.isExpression(i.expression)){let s=hy(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Gt(i),editable:!0,source:s.source})}return r}function EN(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!P.isJSXAttribute(i))continue;let s=IN(i.name);if(!s)continue;let a=$n(i,n);if(P.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Gt(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:Gt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(P.isJSXExpressionContainer(i.value)&&P.isExpression(i.value.expression)){let c=Kr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?yy(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Gt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=hy(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:NN(c),sourceRange:Gt(i),source:Ot(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=vN(i.value.expression,t),d=Ot(i.value.expression,n,t),p=l?.value??$n(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":p,sourceRange:Gt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function SN(e,t,n){return e.attributes.flatMap((r,o)=>!P.isJSXSpreadAttribute(r)||!P.isExpression(r.argument)?[]:[{raw:$n(r.argument,n),sourceRange:Gt(r),order:o,source:Ot(r.argument,n,t)}])}function IN(e){return P.isJSXIdentifier(e)?e.name:P.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function vN(e,t){return or(e,{resolveIdentifier(n){let r=ss(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=Kr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function yy(e,t){let n=ii(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function ii(e,t){if(P.isStringLiteral(e))return[e.value];if(P.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(P.isNullLiteral(e))return[];if(P.isBooleanLiteral(e))return e.value?null:[];if(P.isIdentifier(e)||P.isMemberExpression(e)){if(P.isIdentifier(e)&&e.name==="undefined")return[];let n=Kr(e,t);return typeof n=="string"?[n]:null}if(P.isConditionalExpression(e)){let n=ii(e.consequent,t),r=ii(e.alternate,t);return!n||!r?null:[...n,...r]}if(P.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Kr(e.left,t);return n===!1||n===null?[]:ii(e.right,t)}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return null;let o=ii(r,t);if(!o)return null;n.push(...o)}return n}if(P.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!P.isObjectProperty(r))return null;let o=_N(r.key);if(!o)return null;n.push(o)}return n}if(P.isCallExpression(e)){let n=kN(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!P.isExpression(o))return null;let i=ii(o,t);if(!i)return null;r.push(...i)}return r}return null}function kN(e){return P.isIdentifier(e)?e.name:P.isMemberExpression(e)&&P.isIdentifier(e.property)?e.property.name:null}function _N(e){return P.isIdentifier(e)?e.name:P.isStringLiteral(e)?e.value:null}function CN(e,t){let n=e.attributes.find(r=>P.isJSXAttribute(r)&&P.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!P.isJSXAttribute(n)||!P.isJSXExpressionContainer(n.value)?null:n.value.expression}function RN(e,t){for(let n of t){let r=CN(e,n);if(r)return r}return null}function PN(e){return P.isJSXIdentifier(e.name)?e.name.name:null}function NN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function AN(e){if(!P.isCallExpression(e)&&!P.isOptionalCallExpression(e))return null;let t=e.callee;return!P.isMemberExpression(t)&&!P.isOptionalMemberExpression(t)||!P.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!P.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function Sd(e){return P.isArrowFunctionExpression(e)||P.isFunctionExpression(e)}function TN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function wN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function fy(e,t,n,r){if(!e||!P.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:$n(e,n),collectionSource:Cd(e,n,r)};if(t){let i=t.params[0],s=t.params[1];P.isIdentifier(i)&&(o.itemParamName=i.name),P.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function _r(e,t,n){if(!e)return[];if(P.isJSXElement(e)){if(kd(e))return lc(e.children,t,n);let r=ac(e,t,n);return r?[r]:[]}return si(e)?cc(e,t,n):P.isParenthesizedExpression(e)?_r(e.expression,t,n):P.isExpression(e)?uc(e,t,n):[]}function ic(e,t,n){let r=new Map;for(let o of e.params)for(let i of kr(o))_d(r,i);t.valueScopes.push(r);try{if(!P.isBlockStatement(e.body))return _r(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return xy(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function xy(e,t,n){let r=[];for(let o of e){if(P.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Id([o],t,i);for(let s of o.declarations)P.isIdentifier(s.id)&&(P.isJSXElement(s.init)||P.isJSXFragment(s.init))&&r.push(..._r(s.init,t,n))}continue}r.push(...vd(o,t,n))}return r}function vd(e,t,n){if(P.isReturnStatement(e))return e.argument?_r(e.argument,t,n):[];if(P.isBlockStatement(e))return Oo(e.body,t,n);if(P.isIfStatement(e)){let r=P.isBlockStatement(e.consequent)?Oo(e.consequent.body,t,n):vd(e.consequent,t,n),o=e.alternate?P.isBlockStatement(e.alternate)?Oo(e.alternate.body,t,n):vd(e.alternate,t,n):[];return[...r,...o]}if(P.isSwitchStatement(e))return Oo(e.cases.flatMap(r=>r.consequent),t,n);if(P.isTryStatement(e)){let r=Oo(e.block.body,t,n);return e.handler&&r.push(...Oo(e.handler.body.body,t,n)),e.finalizer&&r.push(...Oo(e.finalizer.body,t,n)),r}return[]}function Oo(e,t,n){let r=new Map;t.valueScopes.push(r);try{return xy(e,t,n)}finally{t.valueScopes.pop()}}function sc(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Gt(r),sourceCandidates:i&&i.length>0?i:void 0})}function ON(e,t,n,r){let o=RN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:py(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!P.isJSXAttribute(s))continue;let a=PN(s);if(!a||!P.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!P.isJSXEmptyExpression(c)){if(TN(a)&&Sd(c)){let l=ic(c,n,r),u=fy(o,c,r,n);sc(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(wN(a)){let l=Sd(c)?ic(c,n,r):_r(c,n,r);sc(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!P.isJSXExpressionContainer(s)||!Sd(s.expression))continue;let a=ic(s.expression,n,r),c=fy(o,s.expression,r,n);sc(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function ac(e,t,n){let r=py(e.openingElement);if(r==="Fragment"||kd(e))return lc(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=fN(r),a;if(s){let S=t.ordinalTracker.getOrdinal(i,r);a=`component:${r}#${S}`}else{let S=t.ordinalTracker.getOrdinal(i,r);a=`${r}#${S}`}let c=o?t.elements.get(o.key)?.identity.structuralPath:void 0,l=c?`${c}/${a}`:a,u=ts(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,g=bN(e.children,t,n),m=EN(e.openingElement,t,n),f=SN(e.openingElement,t,n),y,x,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(pN(r));S&&(y=S.specifier,x=S.exportName,E=_o(S.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Gt(e),parentKey:i,childKeys:[],textSegments:g,attributes:m.length>0?m:void 0,attributeSpreads:f.length>0?f:void 0,boundaryKind:p,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),ON(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),LN(e.children,t,n),t.parentStack.pop()),u}function cc(e,t,n){return lc(e.children,t,n)}function lc(e,t,n){let r=[];for(let o of e)if(P.isJSXElement(o))if(kd(o))r.push(...lc(o.children,t,n));else{let i=ac(o,t,n);i&&r.push(i)}else si(o)?r.push(...cc(o,t,n)):P.isJSXExpressionContainer(o)&&r.push(...uc(o.expression,t,n));return r}function LN(e,t,n){for(let r of e)P.isJSXElement(r)?ac(r,t,n):si(r)?cc(r,t,n):P.isJSXExpressionContainer(r)&&uc(r.expression,t,n)}function FN(e){return e==="&&"||e==="||"||e==="??"}function uc(e,t,n){if(P.isJSXEmptyExpression(e))return[];let r=AN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:$n(r.collection,n),collectionSource:Cd(r.collection,n,t)};if(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];P.isIdentifier(u)&&(c.itemParamName=u.name),P.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Gt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a))&&l.childKeys.push(...ic(a,t,n)),l.childKeys}if(P.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:$n(e.test,n),conditionSource:Ot(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Gt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(..._r(e.consequent,t,n)),s.childKeys.push(..._r(e.alternate,t,n)),s.childKeys}if(P.isLogicalExpression(e)&&FN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:$n(e.left,n),conditionSource:Ot(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Gt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(..._r(e.right,t,n)),s.childKeys}if(P.isParenthesizedExpression(e))return uc(e.expression,t,n);if(P.isJSXElement(e)){let o=ac(e,t,n);return o?[o]:[]}return si(e)?cc(e,t,n):[]}function DN(e){let t=e.argument;return t&&(P.isExpression(t)||si(t))?t:null}function as(e,t){let n=[];for(let r of e){if(P.isReturnStatement(r)){let o=DN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(P.isIfStatement(r)){let o=P.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...as(o,r.test)),r.alternate){let i=P.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...as(i,r.test))}continue}if(P.isSwitchStatement(r))for(let o of r.cases){let i=o.test?P.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...as(o.consequent,i))}}return n}function dc(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function by(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(p=>p.specifier);if(!P.traverseFast(r,p=>{if(P.isJSXElement(p)||P.isJSXFragment(p))return P.traverseFast.stop}))return{graph:dc(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=hN(r);dN(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(p){let g=mN(p);if(!g)return;let m=p.node,f=[];if(P.isArrowFunctionExpression(m))P.isExpression(m.body)||si(m.body)?f=[{argument:m.body,statement:P.returnStatement(P.isExpression(m.body)?m.body:null)}]:P.isBlockStatement(m.body)&&(f=as(m.body.body));else{let I=m.body;P.isBlockStatement(I)&&(f=as(I.body))}if(f.length===0){p.skip();return}let y=new Map;Id(xN(r.program.body),Ed(t,g,s,a,u,[y]),y);let x=new Map;for(let I of m.params)for(let w of kr(I))_d(x,w);let E=P.isBlockStatement(m.body)?m.body.body:[],b=f[0]?.statement??null;for(let I of E){if(b&&I===b)break;P.isVariableDeclaration(I)&&Id([I],Ed(t,g,s,a,u,[y,x]),x)}let S=Ed(t,g,s,a,u,[y,x]);for(let I of f){let w=_r(I.argument,S,n);for(let C of w)c.includes(C)||c.push(C);if(I.condition){let C={kind:"conditional-branch",conditionExpression:$n(I.condition,n),conditionSource:Ot(I.condition,n,S)};sc(S,"conditional-region","",I.statement,w,[C])}}p.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 Rd(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function fc(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function Ey(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 ai(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??Fe,c=new Map,l=new Map,u=new Map,d=[],p=new Set,g=x=>{let E=`${x.path}\0${x.code}\0${x.message}\0${JSON.stringify(x.details??{})}`;p.has(E)||(p.add(E),d.push(x))},m=[{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:[]}))],f=new Set;for(;m.length>0;){let x=m.shift(),{file:E,source:b,depth:S,diagnosticEntryFile:I,importStack:w}=x;if(f.has(E))continue;f.add(E),c.set(E,b);let C=o.validationOnly&&S<i?o.validatedImports?.(E,b):void 0,N,R;if(C)N=dc(E),R=C;else{let J=a(E,b);if(!J.ok){g(fc(J.diagnostic,I,w));continue}u.set(E,J.module);let te=o.validationOnly&&S<i?{graph:dc(E),localImports:J.module.imports.map(Y=>Y.specifier)}:by(J.module);N=te.graph,R=te.localImports}let F=[...new Set([...N.elements.values()].map(J=>J.importedFrom).filter(J=>typeof J=="string"&&mt(J)))],$=F.length?await Ey(F,J=>Ca(E,J,r)):[],V=new Map(F.map((J,te)=>[J,$[te]]));for(let J of N.elements.values())if(J.importedFrom&&mt(J.importedFrom)){let te=J.importedFrom,Y=V.get(te);Y.ok?(J.importedFrom=Y.path,Er(Y.path)&&(J.isPublicUiComponent=!0)):_o(te,E)||g(fc(Y.diagnostic,I,Rd(w,E,te,Y.diagnostic.path)))}if(l.set(E,N),S>=i)continue;let U=await Ey(R,async J=>{if(eh(J))return null;let te=V.get(J)??await Ca(E,J,r);if(!te.ok)return _o(J,E)?null:{diagnostic:fc(te.diagnostic,I,Rd(w,E,J,te.diagnostic.path))};let Y=te.path;if(f.has(Y)||Er(Y))return null;let he=Rd(w,E,J,Y);try{let le=await n(Y);return{entry:{file:Y,source:le,depth:S+1,diagnosticEntryFile:I,importStack:he}}}catch(le){return{diagnostic:fc({path:Y,code:"import-read-failed",message:`Failed to read imported file: ${Y}`,details:{fromFile:E,specifier:J,reason:le instanceof Error?le.message:String(le)}},I,he)}}});for(let J of U)J&&"entry"in J?m.push(J.entry):J&&g(J.diagnostic)}let y=MN(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 MN(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 p=s.get(u)??[];s.set(u,[...p,...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 Sy(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 fA}from"@vcp-dev/contracts";import{createHash as BN,randomUUID as Md}from"node:crypto";import Et from"node:fs/promises";import It from"node:path";var Ty=new WeakMap;function ci(e){return Ty.get(e)?.()??e.readIndex()}var wn=1,Nd=1,jN=2,$N="index.json",UN="recovery.json",VN="transaction-journal.json",JN="document-version.json",gc={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Pe={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"},Ae=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Cr(){return{entries:new Map,blobSizes:new Map}}function pc(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)wy(n,r,t);return n}function wy(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 Oy(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 Ly(e,t={}){let n=sA(e),r=uA(t.limits),o=Pd(n),i=aA(n),s=await on(i),a=await on(o)||s;a||(await qN(n),await QN(n)),a||await dA(n);let c=Cr(),l=await yc(n,c),u=new Set(a?(await Ic(n)).map(E=>E.stageId):[]);a||await Cy(n,l.entryIds,c);let d=l.digest,p=pc(l.entryIds,c),g=async E=>{let{index:b,sizeBytes:S}=await fs(n);if(Uy(b,E),b.digest!==d){let I=Cr();await By(n,b.entryIds,I,S),p=pc(b.entryIds,I),d=b.digest}return{...vc(b),totalBytes:p.objectBytes+S}},m=async E=>{Bd(E),await g(),await ky(n,p,[E.entryId],E.blobIds,E.stageId),await hc(n,E.stageId)},f=async(E,b)=>{let S=await g(b);Dy(E,S.entryIds.length);let I=Cr();for(let w of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await ls(n,w,I);return S},y=async()=>{if(await on(o)||s)throw new Ae(Pe.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Ny(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new Ae(Pe.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await Ny(n);E<=b||await cs(Xy(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let S=await zN(E,r),I={schemaVersion:Nd,stageId:Md(),entryId:S.entryId,blobIds:S.blobs.map(w=>w.digest)};try{await HN(n,S),await GN(n,I,b.durableManifest!==!1)}catch(w){try{await m(I)}catch(C){throw new Ae(Pe.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw w}return{stageId:I.stageId,entryId:I.entryId,blobIds:I.blobIds}},async discardStage(E){await y(),wd(E);let b=await Ad(n,E);b&&await m(b)},async previewStagedAppend(E,b){await y();let S=await g(b);return(await Iy(n,r,E,S,p)).transition},async previewCursor(E,b){await y();let S=await f(E,b);return Fy(S,S.entryIds,E)},async publishStagedAppend(E,b,S){if(await y(),bc(E,"entryId"),S){wd(S);let R=await Ad(n,S);if(!R||R.entryId!==E)throw new Ae(Pe.INVALID_SCHEMA,"history stage does not match the published entry")}let I=await g(b),w=p,C=await Iy(n,r,E,I,w),N=await Py({rootDir:n,previousDigest:C.current.digest,entryIds:C.entryIds,cursor:C.cursor,readback:async()=>Ry(n,C.usage),afterWrite:async()=>{S?await hc(n,S):await ZN(n,E),await ky(n,C.usage,[...w.entries.keys()].filter(R=>!C.usage.entries.has(R)),[...w.blobs.keys()].filter(R=>!C.usage.blobs.has(R)))}});return p=C.usage,d=N.digest,N},async append(E){await y();let b=await g(),S=await x.stageAppend(E);try{return await x.publishStagedAppend(S.entryId,b.digest,S.stageId)}catch(I){throw await x.discardStage(S.stageId),I}},async readEntry(E){return bc(E,"entryId"),ls(n,E)},async readBlob(E){bc(E,"blobId");let b=await Hy(n,E),S=await us(b,Pe.NOT_FOUND,"blob");return Ky(S,E,b),S},async readIndex(){let E=Cr(),b=await yc(n,E);return p=pc(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await xc(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 on(o)||await on(i)}},async readUndoRedoIds(){let E=await xc(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,b){await y();let S=await f(E,b),I=await Py({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>Ry(n,p)});return d=I.digest,I},async markRecoveryRequired(E){await on(o)||await cs(Pd(n),{schemaVersion:wn,reason:cA(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await Et.rm(Pd(n),{force:!0})},async readTransactionJournal(){return await on(i)?mc(i):null},async writeTransactionJournal(E){await y(),zy(E);try{await cs(i,E)}catch(S){let I=await mc(i).catch(()=>null);if(I&&Buffer.from(sn(I)).equals(Buffer.from(sn(E))))return;throw I?new Ae(Pe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let b=await mc(i);if(!Buffer.from(sn(b)).equals(Buffer.from(sn(E))))throw new Ae(Pe.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await on(i)?await mc(i):null;if(b&&b.transactionId!==E)throw new Ae(Pe.INVALID_SCHEMA,"transaction journal changed concurrently");try{await Et.rm(i,{force:!0})}catch(S){if(!await on(i))return;throw S}if(await on(i))throw new Ae(Pe.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let S of u)await hc(n,S),u.delete(S);await eA(n);let E=Cr(),b=await yc(n,E);await Cy(n,b.entryIds,E),p=pc(b.entryIds,E),d=b.digest}};return Ty.set(x,()=>xc(n)),x}async function Iy(e,t,n,r,o){bc(n,"entryId");let i=Cr(),s=await ls(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))Oy(a,u);wy(a,s.id,i),c.push(s.id);let l=WN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:Fy(r,l.entryIds,l.cursor)}}function Fy(e,t,n){return Dy(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:KN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function KN(e,t){return Xr(sn({schemaVersion:wn,entryIds:e,cursor:t}))}function Dy(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new Ae(Pe.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function XN(e){if(!Un(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!gn(e.expectedIndexDigest)||!gn(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!gn(n)?!1:t===-1?n===null:gn(n)}async function zN(e,t){if(!e.kind.trim())throw new Ae(Pe.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new Ae(Pe.INVALID_JSON,"history blob name must not be empty");let l=iA(c.data),u=Xr(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:wn,kind:e.kind,manifest:e.manifest,blobs:r},i=sn({...o}),s=Xr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new Ae(Pe.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function HN(e,t){let n=Vd(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=>vy(Jd(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Xd(e,c.digest))),vy(n,sn(r),{kind:"entry",digest:t.entryId},Kd(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function vy(e,t,n,r){let o=await Fd(e)??(r?await Fd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new Ae(n.kind==="blob"?Pe.BLOB_CORRUPT:Pe.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Vy(e,t)}function WN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+sn($y(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new Ae(Pe.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");Oy(n,r.shift()),o-=1}}async function GN(e,t,n){Bd(t);let r=Ud(e,t.stageId);if(n){await cs(r,t);return}await oA(r,t)}async function Ad(e,t){let n=await Fd(Ud(e,t));if(n===null)return null;let r=ps(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Bd(r);if(o.stageId!==t)throw new Ae(Pe.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function Ic(e){let t=[];for(let n of await Sc($d(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);wd(r);let o=await Ad(e,r);o&&t.push(o)}return t}async function ky(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 Ic(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 _y(Vd(e,a),Kd(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await _y(Jd(e,a),Xd(e,a));await Dd(ms(e)),await Dd(gs(e))}async function hc(e,t){await Td(Ud(e,t)),await YN(e)}async function YN(e){try{await Et.rmdir($d(e))}catch(t){if(hs(t)||Un(t)&&t.code==="ENOTEMPTY")return;throw t}}async function ZN(e,t){for(let n of await Ic(e))n.entryId===t&&await hc(e,n.stageId)}async function Td(e){if(await Et.rm(e,{force:!0}),await on(e))throw new Ae(Pe.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function _y(e,t){await Td(e),await Td(t)}function Bd(e){if(!Un(e)||e.schemaVersion!==Nd||typeof e.stageId!="string"||!My(e.stageId)||!gn(e.entryId))throw new Ae(Pe.INVALID_SCHEMA,"history stage schema is invalid");let t=Jy(e.blobIds,"history stage blobIds");return{schemaVersion:Nd,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function wd(e){if(!My(e))throw new Ae(Pe.INVALID_PATH,"history stageId must be a UUID")}function My(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 Cy(e,t,n=Cr()){let r=new Set(t),o=new Set;for(let l of t){let u=await ls(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await Ic(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=ms(e),s=await Sc(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Ay(l.slice(0,-5));u&&!r.has(u)&&await Ec(It.join(i,l))}let a=gs(e),c=await Sc(a);for(let l of c){let u=Ay(l);u&&!o.has(u)&&await Ec(It.join(a,l))}}async function yc(e,t=Cr()){let{index:n,sizeBytes:r}=await fs(e),{totalBytes:o}=await By(e,n.entryIds,t,r);return{...vc(n),totalBytes:o}}async function Ry(e,t){let{index:n,sizeBytes:r}=await fs(e);return{...vc(n),totalBytes:t.objectBytes+r}}async function fs(e){let t=jd(e),n=await us(t,Pe.NOT_FOUND,"index"),r=ps(Buffer.from(n).toString("utf8"),"index");return{index:tA(r),sizeBytes:n.byteLength}}async function xc(e){return vc((await fs(e)).index)}function vc(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:wn,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function By(e,t,n,r){let o=0,i=new Set;o+=r??(await fs(e)).sizeBytes;for(let s of new Set(t)){let a=await ls(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 ls(e,t,n=Cr()){let r=n.entries.get(t);if(r)return r.entry;let o=await lA(e,t),i=await us(o,Pe.NOT_FOUND,"entry"),s=ps(Buffer.from(i).toString("utf8"),`entry ${t}`),a=nA(s);if(a.id!==t)throw new Ae(Pe.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Xr(sn({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new Ae(Pe.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 p=await Hy(e,d),g=await us(p,Pe.NOT_FOUND,"blob");return Ky(g,d,p),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),p=[],g=0,m=Array.from({length:Math.min(4,l.length)},async()=>{for(;g<l.length&&p.length===0;){let x=g++;try{d[x]=await u(l[x])}catch(E){p.push({index:x,error:E})}}}),f=await Promise.allSettled(m),y=p.sort((x,E)=>x.index-E.index)[0];if(y)throw y.error;for(let x of f)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 jy(e,t,n){await cs(jd(e),$y(t,n))}function $y(e,t){return{schemaVersion:wn,digest:Xr(sn({schemaVersion:wn,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Uy(e,t){if(t!==void 0&&e.digest!==t)throw new Ae(Pe.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Py(e){Uy(await xc(e.rootDir),e.previousDigest);let t=Xr(sn({schemaVersion:wn,entryIds:e.entryIds,cursor:e.cursor}));try{await jy(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new Ae(Pe.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await yc(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new Ae(Pe.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function qN(e){await Et.mkdir(e,{recursive:!0}),await Et.mkdir(ms(e),{recursive:!0}),await Et.mkdir(gs(e),{recursive:!0}),await Et.mkdir(ds(e),{recursive:!0})}async function QN(e){await Et.rm(ds(e),{recursive:!0,force:!0}),await Et.mkdir(ds(e),{recursive:!0})}async function eA(e){let t=ds(e);await Et.mkdir(t,{recursive:!0});for(let n of await Sc(t))n!=="stages"&&await Et.rm(It.join(t,n),{recursive:!0,force:!0})}function tA(e){if(!Un(e))throw new Ae(Pe.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==wn)throw new Ae(Pe.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Jy(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new Ae(Pe.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!gn(o))throw new Ae(Pe.INDEX_CORRUPT,"index digest is invalid");let i=Xr(sn({schemaVersion:wn,entryIds:t,cursor:r}));if(o!==i)throw new Ae(Pe.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:wn,digest:o,entryIds:t,cursor:r}}function nA(e){if(!Un(e))throw new Ae(Pe.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==wn)throw new Ae(Pe.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!gn(t))throw new Ae(Pe.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new Ae(Pe.ENTRY_CORRUPT,"entry kind is invalid");let r=Ld(e.manifest,"entry.manifest"),o=rA(e.blobs);return{id:t,schemaVersion:wn,kind:n,manifest:r,blobs:o}}function rA(e){if(!Array.isArray(e))throw new Ae(Pe.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Un(t))throw new Ae(Pe.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new Ae(Pe.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!gn(o))throw new Ae(Pe.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new Ae(Pe.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function cs(e,t){await Vy(e,sn(t))}async function oA(e,t){let n=It.dirname(e),r=It.basename(e),o=It.join(n,`.${r}.${process.pid}.${Md()}.tmp`);await Et.mkdir(n,{recursive:!0});try{await Et.writeFile(o,sn(t),{flag:"wx"}),await Et.rename(o,e)}finally{await Ec(o)}}async function Vy(e,t){let n=It.dirname(e),r=It.basename(e),o=It.join(n,`.${r}.${process.pid}.${Md()}.tmp`);await Et.mkdir(n,{recursive:!0});try{let i=await Et.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await Et.rename(o,e),await Dd(n)}finally{await Ec(o)}}function sn(e){return Buffer.from(JSON.stringify(Od(e)),"utf8")}function Od(e){if(Array.isArray(e))return e.map(t=>Od(t));if(Un(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Od(e[n]);return t}return e}function ps(e,t){try{return JSON.parse(e)}catch(n){throw new Ae(Pe.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Ld(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=>Ld(n,t));if(Un(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Ld(o,t);return n}break}throw new Ae(Pe.INVALID_JSON,`${t} must be JSON-serializable`)}function Jy(e,t){if(!Array.isArray(e))throw new Ae(Pe.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!gn(n))throw new Ae(Pe.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function bc(e,t){if(!gn(e))throw new Ae(Pe.INVALID_PATH,`${t} must be a sha256 digest`)}function gn(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Xr(e){return`sha256:${BN("sha256").update(e).digest("hex")}`}function iA(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function us(e,t,n){try{return await Et.readFile(e)}catch(r){throw new Ae(t,`${n} not found: ${e}`,{cause:r})}}async function Fd(e){try{return await Et.readFile(e)}catch(t){if(hs(t))return null;throw t}}function Ky(e,t,n){if(Xr(e)!==t)throw new Ae(Pe.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function on(e){try{return await Et.access(e),!0}catch(t){if(hs(t))return!1;throw t}}async function Ec(e){try{await Et.rm(e,{force:!0,recursive:!0})}catch{}}async function Dd(e){try{let t=await Et.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function Sc(e){try{return await Et.readdir(e)}catch(t){if(hs(t))return[];throw t}}function sA(e){if(typeof e!="string"||e.trim().length===0)throw new Ae(Pe.INVALID_ROOT,"history store rootDir must be a non-empty string");return It.resolve(e)}function jd(e){return It.join(e,$N)}function Pd(e){return It.join(e,UN)}function aA(e){return It.join(e,VN)}function Xy(e){return It.join(e,JN)}async function Ny(e){try{let t=await Et.readFile(Xy(e),"utf8"),n=ps(t,"document version");if(!Un(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new Ae(Pe.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(hs(t))return 0;throw t}}async function mc(e){let t=await us(e,Pe.RECOVERY_PENDING,"transaction journal"),n=ps(Buffer.from(t).toString("utf8"),"transaction journal");return zy(n),n}function zy(e){if(!Un(e)||e.schemaVersion!==jN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!XN(e.historyTransition)||!Array.isArray(e.files))throw new Ae(Pe.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Un(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!gn(t.preDigest)||t.postDigest!==null&&!gn(t.postDigest))throw new Ae(Pe.INVALID_SCHEMA,"transaction journal file digest is invalid")}function cA(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function ms(e){return It.join(e,"entries")}function gs(e){return It.join(e,"blobs")}function ds(e){return It.join(e,"tmp")}function $d(e){return It.join(ds(e),"stages")}function Ud(e,t){return It.join($d(e),`${t}.json`)}function Vd(e,t){return It.join(ms(e),`${Gy(t)}.json`)}function Jd(e,t){return It.join(gs(e),Gy(t))}function Kd(e,t){return It.join(ms(e),`${t}.json`)}function Xd(e,t){return It.join(gs(e),t)}async function lA(e,t){return Wy(Vd(e,t),Kd(e,t))}async function Hy(e,t){return Wy(Jd(e,t),Xd(e,t))}async function Wy(e,t){return await on(e)?e:await on(t)?t:e}function Gy(e){return e.slice(7)}function Ay(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return gn(t)?t:null}function Un(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hs(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function uA(e){return{maxEntries:e?.maxEntries??gc.maxEntries,maxSessionBytes:e?.maxSessionBytes??gc.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??gc.maxEntryBytes}}async function dA(e){let t=jd(e);await on(t)||await jy(e,[],-1)}var pA={affectedCompositions:[]};function ex(e){let t=null,n=new WeakMap;async function r(){return t??=mA(e),t}async function o(i){if(!i)return null;let s=zd(i);return s?gA(e,s):i}return{async prepareAppend(i){let s=await ci(e),a=await e.stageAppend(qy(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 ci(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 ci(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);Yy(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,li(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(zd(c.at(-1))!==zd(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Yy(l,i.historyTransition),Object.assign(a,li(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await ci(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,li(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(qy(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,li(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,li(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 Yy(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 zd(e){return typeof e=="string"?e:e?.historyId}async function mA(e){let t=await ci(e);return li(t)}function li(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function gA(e,t){let n=await e.readEntry(t),r=hA(n),o=r.provenance??pA;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 Zy(e,n,r.preSnapshots),postSnapshots:await Zy(e,n,r.postSnapshots)}}async function Zy(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(bA(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function qy(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=yA(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 hA(e){if(!nx(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:tx(t.provenance)}:{},preSnapshots:Qy(t.preSnapshots,"preSnapshots"),postSnapshots:Qy(t.postSnapshots,"postSnapshots")}}function yA(e){if(e.provenance!==void 0)return tx(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function tx(e){let t=fA.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 Qy(e,t){return e.map((n,r)=>{if(!nx(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&&!xA(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 xA(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function bA(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function nx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as EA}from"@vcp-dev/contracts";var rx={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 Hd(){let e=EA.safeParse(rx);return e.success?e.data:null}import{randomBytes as SA}from"node:crypto";import kc from"node:path";import{parse as ux}from"@babel/parser";import IA from"@babel/traverse";import*as dx from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Gd,PageResourceArtifactSchema as vA,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as kA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as _A,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as CA,parseComponentI18nResourcesJson as RA}from"@vcp-dev/contracts";var Yd="{{$INSTANCE}}",PA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,NA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Zd="components/site/generated",AA=/\.(?:tsx?|json)$/,TA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,wA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],OA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Wd=IA,LA=typeof Wd=="function"?Wd:Wd.default;async function qd(e){let t=vA.safeParse(e.artifact);if(!t.success)return St("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>SA(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=JA(r());if(!i)return St("Random instance suffix must be 8 lowercase hex chars.");let s=`${KA(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let b of n.pages){let S=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/${S}/page.tsx`})}let u=[],d=new Set,p=new Set,g=new Map,m=new Map,f=[],y=new Set(n.pages.flatMap(b=>b.components.map(S=>S.component_id)));for(let b of n.components){if(!y.has(b.component_id))continue;let S=ox({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!S.ok)return S;for(let I of S.files){let w=sx(I,d,u);if(w)return w}p.add(S.entry),m.set(S.entry,S.entryExport),g.set(b.component_id,S.entry)}for(let[b,S]of n.pages.entries()){let I=l[b],w=ox({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:I.route_file_path,pageTitle:I.title});if(!w.ok)return w;for(let C of w.files){let N=sx(C,d,u);if(N)return N}p.add(w.entry),m.set(w.entry,w.entryExport),f.push({entry:w.entry,declaredComponentIds:new Set(S.components.map(C=>C.component_id))})}let x=DA(u,p,s,g,f,m);if(!x.ok)return x;for(let b of u)if(await e.exists(b.file))return!b.file.startsWith("app/")&&o>1?qd({...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=MA(u);return E||(u.sort((b,S)=>b.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function ox(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:ix(o.pathTemplate,e.packageInstanceId);if(!s)return St("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=FA(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?jA(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??ix(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?St("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function FA(e,t,n,r){let o,i=e.replace(PA,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return St(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(NA,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return St(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Yd,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?St("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ix(e,t){let n=`${Zd}/${t}`;if(e.split(Yd).length>2)return null;let o=e.replace(Yd,t),i=`${Zd}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=kc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!AA.test(a)||TA.test(a)?null:a}function sx(e,t,n){return t.has(e.file)?St(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function DA(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${Zd}/${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 St("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Gd)&&!RA(g.content).success)return St("Materialization component i18n resources are invalid.",g.file);continue}try{let m=ux(g.content,{sourceType:"module",plugins:["jsx","typescript"]});l.set(g.file,m);for(let y of m.program.body)if((y.type==="ImportDeclaration"||y.type==="ExportAllDeclaration"||y.type==="ExportNamedDeclaration"&&y.source)&&y.source){let x=y.source.value,E=UA(g.file,x,s,a);if(!E.allowed)return St(`Materialization import is outside the controlled package: ${x}`,g.file);E.internalPath&&c.get(g.file).add(E.internalPath)}let f;if(LA(m,{Identifier(y){y.isReferencedIdentifier()&&OA.has(y.node.name)&&(f??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(f??="style element",y.stop())}}),f)return St(`Materialization source uses forbidden capability: ${f}`,g.file)}catch{return St("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return St("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return St("Materialization JSON files cannot be package entries.");for(let[g,m]of i){let f=l.get(g);if(!f||!BA(f,m))return St("Materialization entry does not declare its contracted export.",g)}let u=new Map([...r].map(([g,m])=>[m,g]));for(let g of o){let m=lx(g.entry,c);for(let f of g.declaredComponentIds){let y=r.get(f);if(!y||!m.has(y))return St(`Page entry does not reach declared component: ${f}`,g.entry)}for(let f of m){let y=u.get(f);if(y&&!g.declaredComponentIds.has(y))return St(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let m of lx(g,c))d.add(m);if(d.size!==e.length)return St("Every materialization file must be reachable from a package entry.");let p=VA(e,l,c);return p||{ok:!0}}function MA(e){if(e.length>kA)return St("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>_A)return St("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>CA?St("Page resource exceeds the aggregate content byte limit."):null}function BA(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 jA(e,t,n){let r;try{r=ux(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return St("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=ax(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&$A(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=ax(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 ax(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&dx.isExpression(t)?t:null}function $A(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function UA(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=cx(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:wA.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=kc.posix.normalize(kc.posix.join(kc.posix.dirname(e),t)),i=cx(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function cx(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 VA(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Gd))continue;let i=o.file.slice(0,-Gd.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return St("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 St("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function lx(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 JA(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function KA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function St(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as hT}from"node:crypto";import Pr from"node:path";import{parse as yT}from"@babel/parser";import xT from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Cc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as xx,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as bT,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as ET,SiteEditMaterializationSchema as ST,parseComponentI18nResourcesJson as IT}from"@vcp-dev/contracts";import{parse as sT}from"@babel/parser";import aT from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as cT,FormDefinitionIdSchema as lT}from"@vcp-dev/contracts";var px={colorMixPolicy:"always",includeExtendedColorFunctions:!0},mx=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,gx=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,XA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,zA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,HA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,WA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,GA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,YA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,ZA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,qA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,QA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,eT=/\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,tT=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,nT=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Qd(e,t){let n=_c([...On(e,XA),...On(e,zA),...On(e,HA),...On(e,t.includeRgbBackgroundImage?WA:GA),...t.includeExtendedColorFunctions?[...On(e,YA),...On(e,ZA)]:[]]),r=_c([...On(e,qA),...On(e,QA)]).filter(o=>t.colorMixPolicy==="always"||mx.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...On(e,eT).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...On(e,nT).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:_c(On(e,gx)),hardCodedSurfaceOccurrences:iT(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?rT(e):[]}}function rT(e){return _c(On(e,tT))}function On(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var fx=160,oT=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function iT(e){let t=new RegExp(gx.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=oT.exec(l),d=r(i.index),p=e.indexOf(`
6
+ `,i.index),g=e.slice(n[d]??0,p===-1?void 0:p).trim();o.push({token:a,variant:u?.[1]??"",alpha:c?Number(c[1]):null,line:d+1,snippet:g.length>fx?`${g.slice(0,fx-1)}\u2026`:g})}return o}function _c(e){return[...new Set(e)]}var uT=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],dT=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),hx=new Set(["require","module","exports","__dirname","__filename"]),ef=aT,fT=typeof ef=="function"?ef:ef.default;function nf(e,t={}){let n=[],r=pT(t.hostCapabilities),o=Qd(e,t.style??px),i;try{i=sT(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"&&gT(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(p=>p.code===u.code&&p.name===u.name&&p.source===u.source)||n.push(u)};return fT(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(tf(u.node))},OptionalMemberExpression(u){l(tf(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)&&lT.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&uT.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?mT(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||!dT.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:hx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:hx.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function pT(e){if(e==null)return null;let t=cT.safeParse(e);return t.success?t.data:null}function mT(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)):yx(n)===yx(o)})}function yx(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function gT(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function tf(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?tf(e.object):null}var kx="components/site/generated",bx="{{$INSTANCE}}",Rc=5,vT=/^[a-z][a-z0-9-]{0,48}$/,kT=/^[a-f0-9]{8}$/,Ex=/\.tsx?$/,_T=/\.json$/,CT=/\.(?:tsx?|json)$/,RT=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,rf=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),of=xT,PT=typeof of=="function"?of:of.default;function NT(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>xx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=KT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=ST.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=UT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${kx}.`,path:e.generatedRoot}};if(!_x(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=Ix(r.data.files),s=Ix(e.controlledFiles);if(!XT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>xx)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>bT)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>ET?{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 AT(e){let t=NT(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=_x(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Rc,e.maxAttempts??Rc));for(let i=0;i<o;i+=1){let s=VT(e.instanceNameGenerator?.()??hT(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=Rx(n,a),l=TT({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await OT(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 sf(e){let t=Math.max(1,Math.min(Rc,e.maxAttempts??Rc));for(let n=0;n<t;n+=1){let r=await AT({...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 TT(e){let t=wT(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=ys({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=ys({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=af({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 wT(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 OT(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function ys(e){if(e.pathTemplate.split(bx).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(bx,e.instanceName),n=JT(t);return n?Rx(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||!CT.test(n)||RT.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 af(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(_T.test(g.path)){if(g.path.endsWith(Cc)){let x=IT(g.content);if(!x.success)return Rr("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Rr("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let m;try{m=yT(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 f=nf(g.content,{hostCapabilities:o,protectedImportPrefixes:["@/components/site/generated/"],trustedManagedImports:e.trustedManagedImports,rejectInlineStyles:!1,rejectStyleElements:!0,themeStyleMode:e.preserveCapturedStyles?"report":"ignore",style:{colorMixPolicy:"always",includeExtendedColorFunctions:!0,includeRgbBackgroundImage:!0,rejectAnyRawColorLiteral:!1,rejectPrivateTokens:!1,rejectTailwindPalette:!1}}),y=FT(f.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,m)}for(let g of t){if(!Ex.test(g.path))continue;let m=c.get(g.path),f=null;if(PT(m,{ImportDeclaration(y){let x=Sx({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!x.allowed)f??={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&&!DT(y.node.source.value,i,s))f??={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(Cc))){let E=BT({importer:g.path,imported:x.internalPath,source:y.node.source.value,ast:m});E.ok?u.get(x.internalPath).add(g.path):(f??=E.error,y.stop())}},ExportAllDeclaration(y){f??={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=Sx({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!x.allowed||!x.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(f??={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"){f??={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"&&(f??={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"&&(f??={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"&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let x=vx(y.node);x&&rf.has(x)&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=vx(y.node);x&&rf.has(x)&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&rf.has(y.node.name)&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${y.node.name}.`,file:g.path},y.stop())},JSXAttribute(y){!e.preserveCapturedStyles||y.node.name.type!=="JSXIdentifier"||y.node.name.name!=="style"||LT(y.node.value)||(f??={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"&&(f??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&Pc(y.node.value)&&(f??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&Pc(y.node.value.cooked??y.node.value.raw)&&(f??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},JSXElement(y){let x=y.node.openingElement.name;e.preserveCapturedStyles&&x.type==="JSXIdentifier"&&["script","iframe","object","embed"].includes(x.name.toLowerCase())&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},y.stop())}}),f)return{ok:!1,error:f}}if(r.length===0)return Rr("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 Rr("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!Ex.test(g.path))return Rr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let m=c.get(g.path);if(!m)return Rr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!jT(m,g.export))return Rr("MATERIALIZATION_EXPORT_MISSING","Static prefab entry does not declare the manifest export.",g.path)}for(let[g,m]of u)if(m.size!==1)return Rr("MATERIALIZATION_IMPORT_FORBIDDEN","Each component .i18n.json file must have exactly one same-name Client Component static importer.",g);let p=new Set;for(let g of r)for(let m of $T(g.path,l))p.add(m);return p.size!==t.length?Rr("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Pc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function LT(e){return e?.type!=="JSXExpressionContainer"||e.expression.type!=="ObjectExpression"?!1:e.expression.properties.every(t=>{if(t.type!=="ObjectProperty"||t.computed)return!1;let n=t.key.type==="Identifier"?t.key.name:t.key.type==="StringLiteral"?t.key.value:null;if(!n||n==="__proto__"||n==="constructor"||n==="prototype"||Pc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Pc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function FT(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 Sx(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=Pr.posix.normalize(Pr.posix.join(Pr.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 DT(e,t,n){if(n===null)return!0;let r=MT(e);return r===null||t.has(r)&&n.has(r)}function MT(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 BT(e){let t=Pr.posix.dirname(e.importer),n=Pr.posix.dirname(e.imported),r=Pr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=Pr.posix.basename(e.imported).slice(0,-Cc.length),i=`./${r}${Cc}`;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 jT(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 $T(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 Rr(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function UT(e){let t=Cx(e);return t===kx?t:null}function VT(e){let t=e.trim().toLowerCase();return kT.test(t)?t:null}function _x(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 vT.test(t)?t:null}function Cx(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=Pr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function JT(e){let t=Cx(e);return!t||t!==e?null:t}function Rx(...e){return Pr.posix.join(...e)}function Ix(e){return new Set(e.map(t=>t.pathTemplate))}function KT(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 XT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function vx(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 Of}from"node:crypto";import Cf from"@babel/traverse";function cf(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}}function Nc(e){if(e.node.alternate||!zT(e.get("test")))return!1;let t=e.get("consequent"),n=t.isBlockStatement()?t.get("body"):[t];if(n.length!==1)return!1;let r=n[0];if(r.isThrowStatement())return!0;if(!r.isExpressionStatement())return!1;let o=r.get("expression");if(!o.isCallExpression()||o.node.arguments.length!==0)return!1;let i=o.get("callee");if(!i.isIdentifier())return!1;let s=i.scope.getBinding(i.node.name);if(!s?.constant||s.constantViolations.length>0||!s.path.isImportSpecifier()||s.path.node.importKind==="type")return!1;let a=s.path.node.imported,c=a.type==="Identifier"?a.name:a.value,l=s.path.parentPath;return!!(c==="notFound"&&l?.isImportDeclaration()&&l.node.importKind!=="type"&&l.node.source.value==="next/navigation")}function zT(e){let t=Px(e);return e.traverse({enter(n){Px(n)||(t=!1,n.stop())}}),t}function Px(e){if(e.isAssignmentExpression()||e.isUpdateExpression()||e.isAwaitExpression()||e.isYieldExpression()||e.isNewExpression()||e.isTaggedTemplateExpression()||e.isOptionalCallExpression()||e.isJSXElement()||e.isJSXFragment()||e.isFunction()||e.isUnaryExpression({operator:"delete"}))return!1;if(!e.isCallExpression())return!0;let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||n.length!==1)return!1;let r=t.get("object"),o=t.get("property");if(!r.isIdentifier()||!o.isIdentifier())return!1;if(r.node.name==="Object"&&o.node.name==="keys"&&!r.scope.getBinding("Object"))return!n[0].isSpreadElement();let i=r.scope.getBinding(r.node.name);return!!(o.node.name==="includes"&&n[0].isStringLiteral()&&i?.constant&&i.path.isVariableDeclarator()&&i.path.parentPath?.isVariableDeclaration({kind:"const"}))}import{createHash as hw}from"node:crypto";import jx from"node:path";import*as fi from"@babel/parser";import yf from"@babel/traverse";import xf from"@babel/generator";import*as ve from"@babel/types";import pf from"@babel/generator";import{parse as rw}from"@babel/parser";import mf from"@babel/traverse";import*as $e from"@babel/types";import{PortableInvocationBindingSchema as ow}from"@vcp-dev/contracts";import lf from"@babel/traverse";import*as Je from"@babel/types";var Nx=typeof lf=="function"?lf:lf.default;function Yt(e){let t=Tx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Ax(t,e.allowNonRenderingGuards):zr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function Ln(e){let t=HT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Ax(t.definition):t.kind==="imported"?!e.imported?.module&&!mt(t.specifier)?zr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?Yt({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):zr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):zr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):zr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Ax(e,t=!1){let n=qT(e.module.ast,e.node);if(!n)return zr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=wx(n,t);if(!r){let s=ew(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:zr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=Ox(r);return Tc(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:zr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function HT(e,t,n){let r={kind:"unresolved"};return Nx(e.ast,{JSXElement(o){if(!YT(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Je.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(WT(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=GT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function WT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function GT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&ff(t.node)?t.node:null}function YT(e,t){return e!=null&&e.start.line===t.startLine&&e.start.column===t.startColumn&&e.end.line===t.endLine&&e.end.column===t.endColumn}function Tx(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 p=Br(e.file,u,n),g=p?n.get(p):void 0;return g?Tx(g,d,n,i):null},a=u=>{let d=ZT(e,u);if(d)return{...d,module:e};for(let p of e.ast.program.body)if(!(!Je.isImportDeclaration(p)||p.importKind==="type")){for(let g of p.specifiers)if(g.local.name===u){if(Je.isImportDefaultSpecifier(g))return s(p.source.value,"default");if(Je.isImportSpecifier(g)&&g.importKind!=="type")return s(p.source.value,Ac(g.imported))}}return null};for(let u of e.ast.program.body){if(Je.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(ff(d))return{node:d,name:nw(d)??"default",module:e};if(Je.isIdentifier(d))return a(d.name)}if(!(!Je.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=tw(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Je.isExportSpecifier(d)&&d.exportKind!=="type"&&Ac(d.exported)===t)return u.source?s(u.source.value,Ac(d.local)):a(Ac(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Je.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(p=>p.node===u.node&&p.module.file===u.module.file)===d);return l.length===1?l[0]:null}function ZT(e,t){for(let n of e.ast.program.body){let r=Je.isExportNamedDeclaration(n)?n.declaration:n;if(Je.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Je.isVariableDeclaration(r)){for(let o of r.declarations)if(Je.isIdentifier(o.id)&&o.id.name===t&&ff(o.init))return{node:o.init,name:t}}}return null}function qT(e,t){let n=null;return Nx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function wx(e,t=!1){let n=e.get("body");if(!n.isBlockStatement())return n;let r=n.get("body"),o=r.at(-1);return!o?.isReturnStatement()||!o.get("argument").node||!r.slice(0,-1).every(i=>i.isVariableDeclaration()||i.isFunctionDeclaration()||QT(i)||t&&i.isIfStatement()&&Nc(i))?null:o.get("argument")}function QT(e){if(!e.isExpressionStatement())return!1;let t=e.get("expression");if(!t.isCallExpression())return!1;let n=t.get("callee");if(!n.isIdentifier())return!1;let r=n.scope.getBinding(n.node.name);if(!r?.constant||!r.path.isImportSpecifier())return!1;let o=r.path.node.imported,i=r.path.parentPath;if(!Je.isIdentifier(o,{name:"useEffect"})||!i?.isImportDeclaration()||i.node.source.value!=="react"||i.node.importKind==="type"||r.path.node.importKind==="type")return!1;let s=t.get("arguments")[0];return!!(s&&(s.isArrowFunctionExpression()||s.isFunctionExpression()))}function ew(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=uf(t.get("body"));if(!n||n.length<2)return null;let r=[],o=null;for(let i of n){if(!i.isJSXElement())return null;let s=i.node.openingElement.name;if(!Je.isJSXIdentifier(s)||!/^[A-Z]/.test(s.name))return null;let a=i.scope.getBinding(s.name);if(!a||a.constantViolations.length>0||o&&o!==a.path.node||(o=a.path.node,i.node.children.some(c=>!Je.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Je.isJSXSpreadAttribute(c)||Je.isJSXAttribute(c)&&Je.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function uf(e){for(let[t,n]of e.entries()){if(n.isVariableDeclaration()||n.isFunctionDeclaration())continue;if(n.isReturnStatement()){let a=n.get("argument");return a.node&&t===e.length-1?[a]:null}if(!n.isIfStatement())return null;let r=a=>uf(a.isBlockStatement()?a.get("body"):[a]),o=r(n.get("consequent")),i=n.get("alternate"),s=i.node?t===e.length-1?r(i):null:uf(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Tc(e,t){if(Ox(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&ft(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!Tc(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()||Tc(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Tc(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function df(e){return["base","link","meta","script","style","title"].includes(e)}function Ox(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Je.isJSXIdentifier(o)&&df(o.name)?(t=!0,!0):ft(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||!Je.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=wx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function tw(e,t){return Je.isFunctionDeclaration(e)?e.id?.name===t?t:null:Je.isVariableDeclaration(e)&&e.declarations.some(n=>Je.isIdentifier(n.id)&&n.id.name===t)?t:null}function ff(e){return Je.isFunctionDeclaration(e)||Je.isFunctionExpression(e)||Je.isArrowFunctionExpression(e)}function nw(e){return"id"in e&&e.id&&Je.isIdentifier(e.id)?e.id.name:null}function Ac(e){return Je.isIdentifier(e)?e.name:e.value}function zr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var gf=typeof pf=="function"?pf:pf.default,Lx=typeof mf=="function"?mf:mf.default,Dx=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),iw=new Set(["sourceOrder","source_order","originalOrder","original_order"]),sw=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"]),aw=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,cw=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function Wr(e){if(!Bx(e)||!Array.isArray(e.bindings))return Hr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=fw(e);if(!t||!cw.test(t))return Hr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Mx(e.targetBlockId);if(!n.ok)return n;let r=pw(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!aw.test(o))return Hr("INVOCATION_VALUE_UNRESOLVED","The route searchParams binding requires a safe local identifier.","searchParamsIdentifier");let i=[],s=[],a=new Set,c=!1,l=!1,u=0;for(let[p,g]of e.bindings.entries()){let m=ow.safeParse(g);if(!m.success)return Hr("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${p}`);let f=m.data;if(a.has(f.propName))return Hr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${f.propName}.`,`bindings.${p}.propName`);if(a.add(f.propName),iw.has(f.propName))return Hr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${p}`);if(Dx.has(f.propName)&&f.value.kind!=="target-block-id")return Hr("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${p}`);if(f.value.kind==="target-block-id"&&(u+=1,u>1))return Hr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${p}`);f.value.kind==="route-search-params"&&(c=!0),f.value.kind==="route-params"&&(l=!0),s.push(f),i.push($e.jsxAttribute($e.jsxIdentifier(f.propName),$e.jsxExpressionContainer(uw(f.value,n.value,o))))}let d=$e.jsxElement($e.jsxOpeningElement(dw(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:gf(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,requiresRouteParams:l,searchParamsIdentifier:c?o:null}}}function lw(e){if(!Bx(e)||e.jsx===void 0==(e.source===void 0))return ui("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Mx(e.targetBlockId);if(!t.ok)return ui("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return ui("BLOCK_METADATA_TARGET_INVALID","targetOrder must be a non-negative safe integer.","targetOrder");let n=e.jsx!==void 0,r,o;try{if(!n&&e.entryExport){let g=Fe("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=rw(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return ui("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=Yt({module:o,exportName:e.entryExport.kind==="default"?"default":e.entryExport.name});g.ok&&g.roots.length===1&&(s=g.roots[0],i.push(s.node))}else Lx(r,{JSXElement(g){Fx(g)||i.push(g.node)},JSXFragment(g){Fx(g)||i.push(g.node)}});if(i.length!==1)return ui("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=mw(a);if(!c)return ui("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one direct JSX element root.",n?"jsx":"source");let l=0,u=0,d=g=>{let m=gw(g.node.name);!m||!sw.has(m)||(m==="data-site-block-id"||m==="data-vcp-block-id"||Dx.has(m)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):Lx(r,{JSXAttribute:d}),c.openingElement.attributes.push($e.jsxAttribute($e.jsxIdentifier("data-site-block-id"),$e.stringLiteral(t.value)),$e.jsxAttribute($e.jsxIdentifier("data-site-block-order"),$e.jsxExpressionContainer($e.numericLiteral(e.targetOrder))));let p=n?gf(a,{jsescOption:{minimal:!0}}).code:gf(r,{jsescOption:{minimal:!0}}).code;return{ok:!0,plan:{kind:"portable-block-metadata",source:p,jsx:p,targetBlockId:t.value,targetOrder:e.targetOrder,removedSourceBlockIdCount:l,removedSourceOrderCount:u}}}function uw(e,t,n){return e.kind==="route-params"?$e.identifier("params"):e.kind==="route-search-params"?$e.identifier(n):e.kind==="target-block-id"?$e.stringLiteral(t):hf(e.value)}function hf(e){return e===null?$e.nullLiteral():typeof e=="string"?$e.stringLiteral(e):typeof e=="number"?$e.numericLiteral(e):typeof e=="boolean"?$e.booleanLiteral(e):Array.isArray(e)?$e.arrayExpression(e.map(t=>hf(t))):$e.objectExpression(Object.entries(e).map(([t,n])=>$e.objectProperty($e.stringLiteral(t),hf(n))))}function dw(e){let t=e.split("."),n=$e.jsxIdentifier(t[0]);for(let r of t.slice(1))n=$e.jsxMemberExpression(n,$e.jsxIdentifier(r));return n}function fw(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 Mx(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 pw(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 mw(e){if($e.isJSXElement(e))return e;let t=e.children.filter($e.isJSXElement),n=e.children.some(r=>$e.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function Fx(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function gw(e){return $e.isJSXIdentifier(e)?e.name:null}function Bx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function ui(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var bf=typeof xf=="function"?xf:xf.default,yw=typeof yf=="function"?yf:yf.default;function Ss(e){let t=Xx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=_f(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=Ew(n,o),s=Aw(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=xw(e);if(i){let m=Ef(e);return m.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:m.locator,sourceHash:m.sourceHash,node:a,placement:o.relation,replaceOriginal:n.container.kind==="starter-placeholder"}}}:m.result}let l=o.containerSourceRange??n.container.sourceRange,u=o.containerSourceHash??(Oc(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return xs("Route page composition does not expose a verifiable container boundary.");let d=Es(l),p=Ux(e.source,d,u,"Route page composition container");if(!p.ok)return p.result;let g=o.anchorSourceRange?Es(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return xs("Route page composition placement does not expose a verifiable anchor boundary.");let m=Ux(e.source,g,o.anchorSourceHash,"Route page composition anchor");if(!m.ok)return m.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 vf(e){let t=Fe(e.entryFile,e.source);if(!t.ok)return Gr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=Vn({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 Gr("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&&Oc(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,p)=>d+Jx(p,e.anchor.componentName),0);return u===0?[]:[{placement:l,matchCount:u}]}),o=r.reduce((l,u)=>l+u.matchCount,0);if(o===0)return Gr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Gr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=Ss({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=Is({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 Gr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=An({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return Gr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=zx({source:s,step:i.plan.serverParamsStep});if(!l.ok)return Gr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=Tn({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}}:Gr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Jx(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Jx(r,t),0)}function Gr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function xw(e){let t=kw(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 Is(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Lo(e.source,"Root expression rewrite requires an exact expression locator.");let t=Wi(e.source,"value");if(!t.ok)return Lo(e.source,t.diagnostic.message);let n=De(t.ast,e.locator);if(!n.ok)return Lo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Lo(e.source,"Resolved value locator does not point to an expression.");let o=di(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Lo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(ve.nullLiteral()),{ok:!0,source:bf(t.ast,{}).code};let i;try{i=fi.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Lo(e.source,s instanceof Error?s.message:String(s))}return!ve.isJSXElement(i)&&!ve.isJSXFragment(i)?Lo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(bw(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:bf(t.ast,{}).code})}function bw(e,t,n,r){if(ve.isNullLiteral(e)||r)return t;let o=ve.isJSXFragment(e)?[...e.children]:[ve.isJSXElement(e)?e:ve.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return ve.jsxFragment(ve.jsxOpeningFragment(),ve.jsxClosingFragment(),s)}function Lo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function kf(e){let t=Xx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=qx(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(Sw(n,o)){let f=Ef(e);return f.ok?e.operation==="remove-node"&&!$x(n,o.placementUnitKey)?xs("The last editable page unit cannot be deleted."):e.operation==="move-node"?xs("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:f.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:f.locator,sourceHash:f.sourceHash}}}:f.result}let s=Es(o.sourceRange),a=nr(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?[]:[bs(a.diagnostic)]}};if(di(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 f=Ef(e);return f.ok?$x(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}}}:xs("The last editable page unit cannot be deleted."):f.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||!vw(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=_f(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 p=Es(d),g=nr(e.source,p);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?[]:[bs(g.diagnostic)]}};if(di(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Vx("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let f=u.anchorSourceRange,y=u.anchorSourceHash;if(!f||!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=Es(f),E=nr(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?[]:[bs(E.diagnostic)]}}:di(e.source,E.match.node.start??null,E.match.node.end??null)!==y?Vx("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:p,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:p,placement:u.relation}}}}function $x(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Ew(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Oc(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 Sw(e,t){return e.container.kind!=="jsx-container"&&Oc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Ef(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=nr(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?[]:[bs(r.diagnostic)]}}}:di(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Kx("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Ux(e,t,n,r){let o=nr(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?[]:[bs(o.diagnostic)]}}}:di(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Kx(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Kx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function xs(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Vx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function bs(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Xx(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&&!Iw(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 Iw(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function vw(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function kw(e,t){let n=jx.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=jx.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Es(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function di(e,t,n){return t==null||n==null?null:`sha256:${hw("sha256").update(e.slice(t,n)).digest("hex")}`}function Oc(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 zx(e){let t;try{t=fi.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=_w(t,e.step);return n.ok?{ok:!0,source:bf(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function _w(e,t){let n=Yx(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=If(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."}:Wx(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Hx(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?Sf():Cw()),{ok:!0};let i=n.node.params[0],s=If(i);return s?(Rw(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function Cw(){return ve.objectPattern([ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0)])}function Sf(){let t=fi.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!ve.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!ve.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return ve.cloneNode(n,!0)}function Rw(e,t){let n=ve.objectProperty(ve.identifier("searchParams"),ve.identifier("searchParams"),!1,!0),r=e.properties.findIndex(ve.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Gx(e);if(!o){e.typeAnnotation=Sf().typeAnnotation;return}if(!ve.isTSTypeLiteral(o.typeAnnotation))return;let i=Sf().typeAnnotation;if(!i||!ve.isTSTypeAnnotation(i)||!ve.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!Pw(o.typeAnnotation)&&o.typeAnnotation.members.push(ve.cloneNode(s,!0))}function Pw(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Zx(t.key)==="searchParams")}function Nw(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 Aw(e){if(!e.invocation)return{ok:!0};let t=Wr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return wc(t.error.message);if(t.plan.requiresRouteParams)return wc("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=Tw(e.source,e.entryFile);if(!r.ok)return wc(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=Wr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return wc(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function wc(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function Tw(e,t){let n;try{n=fi.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=Yx(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Hx(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Hx(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=If(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Wx(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&&!ww(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function If(e){return!e||ve.isTSParameterProperty(e)?null:ve.isObjectPattern(e)?e:ve.isAssignmentPattern(e)&&ve.isObjectPattern(e.left)?e.left:null}function Wx(e){for(let t of e.properties)if(!(!ve.isObjectProperty(t)||t.computed||Zx(t.key)!=="searchParams"))return ve.isIdentifier(t.value)?t.value.name:ve.isAssignmentPattern(t.value)&&ve.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function ww(e){let t=Gx(e);return t?ve.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Gx(e){return e.typeAnnotation&&ve.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Yx(e){let t=null;return yw(e,{ExportDefaultDeclaration(n){if(t)return;let r=Nw(n,n.get("declaration"));r&&(t=r)}}),t}function Zx(e){return ve.isIdentifier(e)?e.name:ve.isStringLiteral(e)?e.value:null}var Ow=typeof Cf=="function"?Cf:Cf.default;function Vn(e){if(!e.ast)return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Uw(e.ast);if(!t)return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Jw(t);if(!n.ok)return Jn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=Xw(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Hw(r,t))return Jn(e,[Lt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return Pf(e,t,"virtual-route-root",r);if(zw(r)){let o=Zw({input:e,source:e.source,expression:r});return Rf(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ft(r)&&!ks(r)){let o=Tf(r),i=tb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Rf(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Gw(r);if(!o.ok)return Jn(e,[o.diagnostic]);let i=pi(o.path);if(i.unsupported)return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Ww(e.source,r,i.members))return Pf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ft(r);if(i.members.length===0&&s)return Pf(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=tb({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Rf(e,t,l,{kind:a,sourceKind:c},r)}return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function _f(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Lt("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:Lt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function qx(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Lt("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:Lt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function nb(e){return e.ok?Lw(e.projection):Fw(e.projection)}function Lw(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((f,y)=>rb(e,u,f,y,e.container.placementKey)),p=d.filter(({member:f})=>f.isBusinessMember).map(({sourceMember:f})=>Mw(l,f,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:f})=>f)),o.set(l,p);let m=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:m,businessMemberKeys:p.map(f=>f.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:Dw(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Fw(e){let t=e.diagnostics.map(Bw);return{status:"unsupported",version:e.version,composition:e.composition,reason:jw(e.diagnostics),diagnostics:t}}function Dw(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 rb(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)=>rb(e,t,a,c,i))]}function Mw(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Bw(e){return{code:$w(e),message:e.message}}function jw(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 $w(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 Uw(e){let t=null;return Ow(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=Vw(o.path);i&&(t=i,n.stop())}}),t}function Vw(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 Jw(e){let t=e.get("body");if(!t.isBlockStatement()){let s=vs(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Lt("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:Lt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Lt("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(!Kw(s)&&!Nc(s))return{ok:!1,diagnostic:Lt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(ob(s)||ib(s))return{ok:!1,diagnostic:Lt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=vs(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Lt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Kw(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(ob(o)||ib(o))return null;return r}function ob(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function ib(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function Xw(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=vs(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 zw(e){return e.isConditionalExpression()?Qx(vs(e.get("consequent")))&&Qx(vs(e.get("alternate"))):!1}function Qx(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function vs(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 Hw(e,t){if(e.isIdentifier())return eb(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return eb(n.node.name,t)}return!1}function eb(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 Ww(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Af(t)}function Af(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(!Af(t))return!1;continue}if(t.isJSXElement()&&!Af(t))return!1}return!0}function Gw(e){return{ok:!0,path:e}}function pi(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:wf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Fn(r.node.loc),businessMemberCount:0,parentSourceRange:Fn(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=pi(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=ks(o)?pi(o):null;n||=i?.unsupported??!1,t.push({...Tf(o,i?.members),sourceRange:Fn(r.node.loc),parentSourceRange:Fn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:wf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Fn(r.node.loc),businessMemberCount:1,parentSourceRange:Fn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ft(r)){let o=pi(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=ks(r)?pi(r):null;n||=o?.unsupported??!1,t.push({...Tf(r,o?.members),parentSourceRange:Fn(e.node.loc)})}}return{members:t,unsupported:n}}function Tf(e,t){let n=e.isJSXElement()&&ks(e)?t??pi(e).members:[],r=e.isJSXElement()&&!ks(e)&&!ft(e);return{memberKey:wf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Fn(e.node.loc),businessMemberCount:r?1:sb(n),parentSourceRange:Fn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Yw(e)}}function ks(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function Yw(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 sb(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Lc(e){return e.length===0?0:Math.max(1,sb(e))}function tb(e){let t=Fn(e.containerPath.node.loc),n=Lf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Dn(e.input,e.containerKind,e.sourceKind,t),o=Dn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Lc(e.members)<=1,memberCount:Lc(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Zw(e){let t=Fn(e.expression.node.loc),n=Lf(e.source,e.expression.node.start,e.expression.node.end),r=Dn(e.input,"virtual-route-root","atomic-expression",t),o=Dn(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:Dn(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 ab(e,t){let n=Fn(t.node.loc),r=Lf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Rf(e,t,n,r,o){let i=ab(e,o);if(!i)return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=qw(e,n,s),c=cf(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:lb(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 qw(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,p,g,m,f=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:Lc(m)<=1,memberCount:Lc(m),sourceRange:p,sourceHash:p?Nf(e.source,p):null,relation:l,containerSourceRange:f,containerSourceHash:f?Nf(e.source,f):null,anchorSourceRange:g,anchorSourceHash:g?Nf(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(l=>Dn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Dn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Dn(e,i,"placement-unit",l.sourceRange);r.push(o("before",Dn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Dn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function Pf(e,t,n,r){let o=ab(e,r);if(!o)return Jn(e,[Lt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Dn(e,n,"empty-container",void 0),s=Dn(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=cf([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:lb(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 Jn(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 Lt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Dn(e,t,n,r){return cb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function wf(e,t,n){return cb(["member",e,String(t??-1),String(n??-1)])}function cb(e){return`pc_${Of("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Lf(e,t,n){return t==null||n==null?null:`sha256:${Of("sha256").update(e.slice(t,n)).digest("hex")}`}function Nf(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:${Of("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Fn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function lb(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 uO}from"node:crypto";import*as Xn from"@babel/types";function ub(e){if(!e.path.isIdentifier())return{kind:"not-alias"};let t=e.path.scope.getBinding(e.path.node.name);if(!t)return{kind:"unbound"};if(t.constantViolations.length>0)return{kind:"reassigned"};let n=t.path;if(!n.isVariableDeclarator())return{kind:"not-alias"};if(e.aliases.has(n.node)||e.aliases.size>=(e.maxDepth??32))return{kind:"guard"};let r=n.get("init");return Array.isArray(r)||!r.node?{kind:"not-alias"}:{kind:"initializer",initializer:r,aliases:new Set(e.aliases).add(n.node)}}import Ff from"@babel/traverse";import*as mi from"@babel/types";var eO=typeof Ff=="function"?Ff:Ff.default,tO=32;function Kn(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=tO)return null;let o=new Set(r).add(e.ast),i;if(eO(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,p)=>{let g=Br(e.file,d,n),m=g?n.get(g):void 0;return m?Kn(m,p,n,o):null},a=d=>{let p=i.scope.getBinding(d);if(!p||p.constantViolations.length)return null;let g=p.path.parentPath;return g?.isImportDeclaration()?g.node.importKind==="type"?null:p.path.isImportDefaultSpecifier()?s(g.node.source.value,"default"):p.path.isImportSpecifier()&&p.path.node.importKind!=="type"?s(g.node.source.value,Fc(p.path.node.imported)):null:p.path.isVariableDeclarator()?p.path.get("init"):p.path},c=[],l=[];for(let d of i.get("body"))if(d.isExportDefaultDeclaration()&&t==="default"){let p=d.get("declaration");c.push(p.isIdentifier()?a(p.node.name):p)}else if(d.isExportNamedDeclaration()&&d.node.exportKind!=="type"){let p=d.get("declaration");p.node&&Object.hasOwn(mi.getBindingIdentifiers(p.node),t)&&c.push(a(t));for(let g of d.node.specifiers)mi.isExportSpecifier(g)&&g.exportKind!=="type"&&Fc(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Fc(g.local)):a(Fc(g.local)))}else d.isExportAllDeclaration()&&d.node.exportKind!=="type"&&t!=="default"&&l.push(d.node.source.value);if(c.length)return c.length===1?c[0]:null;let u=l.map(d=>s(d,t)).filter(d=>d!==null);return u.length===1?u[0]:null}function Fc(e){return mi.isIdentifier(e)?e.name:e.value}import*as Te from"@babel/types";var nO=32;function hn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=nO)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return _s(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return hn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Mf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=yn(e.node.property,e.node.computed),s=e.get("object"),a=hn(s,t,r);return i!==null&&a?Bc(a,i,t,r):null}if(e.isConditionalExpression())return _s([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return _s([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?hn(i,t,r):null}if(e.isCallExpression()&&Te.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!gi(i))return null;let s=i.path.isFunctionDeclaration()?i.path:i.path.isVariableDeclarator()?i.path.get("init"):null;if(!s||!(s.isFunctionDeclaration()||s.isFunctionExpression()||s.isArrowFunctionExpression())||s.node.async||s.node.generator)return null;let a=s,c=new Map(t),l=e.get("arguments");for(let[g,m]of a.get("params").entries()){if(!m.isIdentifier())return null;let f=l[g];if(!f?.isExpression())return null;let y=hn(f,t,r);if(!y)return null;let x=m.scope.getBinding(m.node.name);if(!x)return null;c.set(x.identifier,y)}let u=a.get("body"),d=u.isBlockStatement()?u.get("body")[0]:u;if(!d)return null;let p=d.isReturnStatement()?d.get("argument"):d;return p.node?hn(p,c,r):null}return[e]}function Mf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return _s(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=hn(o,t,n);if(!i)return null;let s=Df(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Bc(a,c,t,n),i):null}function Dc(e){if(!e.params.every(n=>Te.isIdentifier(n)||Te.isAssignmentPattern(n)&&Te.isIdentifier(n.left)&&Nr(n.right)))return!1;if(!Te.isBlockStatement(e.body))return Nr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Te.isReturnStatement(t)&&!!t.argument&&Nr(t.argument)}function gi(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return Dc(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Te.isArrowFunctionExpression(n)||Te.isFunctionExpression(n)?Dc(n):!1}function Nr(e){let t=!0;return Te.traverseFast(e,n=>{(Te.isCallExpression(n)&&!Mc(n)||Te.isOptionalCallExpression(n)||Te.isNewExpression(n)||Te.isAwaitExpression(n)||Te.isAssignmentExpression(n)||Te.isUpdateExpression(n)||Te.isUnaryExpression(n,{operator:"delete"})||Te.isYieldExpression(n)||Te.isTaggedTemplateExpression(n))&&(t=!1)}),t}function Mc(e){return Te.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Te.isStringLiteral(e.arguments[0])}function _s(e,t,n){let r=[];for(let o of e){let i=hn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Bc(e,t,n,r=new Set){let o=[];for(let i of e)if(i.isObjectExpression()){let s=i.get("properties");if(s.some(c=>!c.isObjectProperty()||c.node.computed))return null;let a=s.filter(c=>c.isObjectProperty()&&yn(c.node.key,!1)===t);if(a.length!==1||!a[0].isObjectProperty())return null;o.push(a[0].get("value"))}else if(i.isArrayExpression()&&/^(?:0|[1-9]\d*)$/u.test(t)){if(i.node.elements.some(a=>Te.isSpreadElement(a)))return null;let s=i.get("elements")[Number(t)];if(!s?.node||s.isSpreadElement())return null;o.push(s)}else return null;return _s(o,n,r)}function Bf(e,t){let n=hn(e,t);return!!(n?.length&&n.every(r=>Te.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function yn(e,t){return!t&&Te.isIdentifier(e)?e.name:Te.isStringLiteral(e)||Te.isNumericLiteral(e)?String(e.value):null}function Df(e,t){if(Te.isIdentifier(e))return e.name===t?[]:null;if(Te.isObjectPattern(e))for(let n of e.properties){if(!Te.isObjectProperty(n)||n.computed)continue;let r=yn(n.key,!1),o=Df(n.value,t);if(r!==null&&o)return[r,...o]}if(Te.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=Df(r,t);if(o)return[String(n),...o]}return null}function db(e,t=new Set,n){return fb(e.get("callee"),t,n)}function fb(e,t,n){if(t.has(e.node)||t.size>=32)return{kind:"guard"};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);if(!r)return{kind:"unknown"};if(t.has(r.path.node))return{kind:"guard"};let o=new Set(t).add(r.path.node),i=r.path.parentPath;if(i?.isImportDeclaration()&&n){let l=i.node.source.value;if(!(l.startsWith(".")||l.startsWith("@/")))return{kind:"unknown"};let u=r.path.scope.getProgramParent().path.node,d=[...n.values()].find(y=>y.ast.program===u),p=d&&Br(d.file,l,n),g=p?n.get(p):void 0,m=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?yn(r.path.node.imported,!1):null,f=g&&m&&i.node.importKind!=="type"?Kn(g,m,n):null;return f?hi(f,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=hi(s,o,n);if(a.kind!=="sources")return a;let c=[...a.sources];for(let l of r.constantViolations){if(!l.isAssignmentExpression({operator:"="}))return{kind:"guard"};let u=hi(l.get("right"),o,n);if(u.kind!=="sources")return{kind:"guard"};c.push(...u.sources)}return{kind:"sources",sources:c,aliases:a.aliases}}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let r=yn(e.node.property,e.node.computed),o=e.get("object"),i=hn(o);if(!i)return{kind:"unknown"};let s=[],a=new Set(t).add(e.node);for(let c of i){if(!c.isObjectExpression())return{kind:"unknown"};if(r===null||c.node.properties.some(d=>d.type!=="ObjectProperty"))return{kind:"guard"};let l=c.get("properties").filter(d=>d.isObjectProperty()&&yn(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=hi(l[0].get("value"),a,n);if(u.kind!=="sources")return{kind:"guard"};s.push(...u.sources),a=u.aliases}return{kind:"sources",sources:s,aliases:a}}return hi(e,new Set(t).add(e.node),n)}function hi(e,t,n){if(e.isIdentifier())return fb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return hi(e.get("expression"),t,n);if(!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression()))return{kind:"unknown"};let r=e,o=[];for(let s of r.get("params"))s.isAssignmentPattern()&&o.push(s.get("right")),s.traverse({AssignmentPattern(a){o.push(a.get("right"))}});let i=r.get("body");return i.isBlockStatement()?i.traverse({Function(s){s.skip()},ReturnStatement(s){let a=s.get("argument");a.node&&o.push(a),s.skip()}}):o.push(i),{kind:"sources",sources:o,aliases:t}}function $c(e,t){return JSON.stringify([t,e])}var oO=new Set;function yb(e,t){let n=new Map,r=[],o=new Map,i=(m,f)=>JSON.stringify([m,f.loc?.start.line,f.loc?.start.column,f.loc?.end.line,f.loc?.end.column]);for(let m of e.graph.elements.values()){let f=m.sourceRange;o.set(JSON.stringify([m.sourceFile,f.startLine,f.startColumn,f.endLine,f.endColumn]),m)}let s=m=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:m}),a=(m,f)=>!hb(f)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===m);function c(m,f,y,x,E,b=oO){if(m.isIdentifier())return x&&jc(m,x)?x.children.some(I=>c(I.path,I.file,y,I.substitution,E,b)):u({path:m,file:f,active:y,substitution:x,unknownIsRelevant:E,aliases:b});if(m.isCallExpression()||m.isOptionalCallExpression()){let I=m,w=db(I,b,e.parsedModules);return w.kind==="guard"||w.kind==="sources"&&w.sources.some(C=>c(C,[...e.parsedModules.values()].find(N=>N.ast.program===C.scope.getProgramParent().path.node)?.file??f,y,x,E,w.aliases))?!0:I.get("arguments").some(C=>c(C,f,y,x,E,b))||w.kind==="unknown"&&E}if(m.isJSXElement()){if(ft(m))return m.get("children").some($=>c($,f,y,x,E,b));let I=o.get(i(f,m.node));if(I){if(t.has(I.identity.key))return!0;if(I.boundaryKind==="component-boundary"&&!I.isPublicUiComponent){let $=e.parsedModules.get(I.sourceFile);if(!$)return!1;let V=Ln({module:$,componentName:I.tag,callSourceRange:I.sourceRange,...I.importedFrom?{imported:{file:I.importedFrom,module:e.parsedModules.get(I.importedFrom),exportName:I.exportName??I.tag,parsedModules:e.parsedModules}}:{}});return V.ok?V.metadataOnly?!1:l(V,m,I.sourceFile,y,x,b):V.diagnostic.code==="component-external-module-opaque"?Cs(m).some(U=>c(U,f,y,x,!1,b)):a($.file,V.diagnostic.code)}return m.get("children").some($=>c($,f,y,x,E,b))}let w=m.node.openingElement.name;if(!Xn.isJSXIdentifier(w))return!1;if(/^[a-z]/.test(w.name))return m.get("children").some($=>c($,f,y,x,E,b));let C=e.parsedModules.get(f),N=m.node.loc;if(!C||!N)return!1;let R=lO({path:m,file:f,componentName:w.name,parsedModules:e.parsedModules}),F=Ln({module:C,componentName:w.name,callSourceRange:{startLine:N.start.line,startColumn:N.start.column,endLine:N.end.line,endColumn:N.end.column},...R?{imported:R}:{}});return F.ok?F.metadataOnly?!1:l(F,m,f,y,x,b):F.diagnostic.code==="component-external-module-opaque"?Cs(m).some($=>c($,f,y,x,!1,b)):a(C.file,F.diagnostic.code)}if(m.isJSXFragment())return m.get("children").some(I=>c(I,f,y,x,E,b));if(m.isJSXExpressionContainer()||m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion())return c(m.get("expression"),f,y,x,E,b);let S=!1;return m.traverse({"CallExpression|OptionalCallExpression"(I){c(I,f,y,x,E,b)&&(S=!0),I.skip(),S&&I.stop()},ReferencedIdentifier(I){c(I,f,y,x,E,b)&&(S=!0),S&&I.stop()},JSXElement(I){c(I,f,y,x,E,b)&&(S=!0),I.skip(),S&&I.stop()},JSXFragment(I){c(I,f,y,x,E,b)&&(S=!0),I.skip(),S&&I.stop()}}),S?!0:E&&!Fo(m)}function l(m,f,y,x,E,b){let S=`${m.sourceFile}#${m.componentName}`;if(x.has(S))return!1;let I=new Set(x).add(S);return m.returnAlternatives?.some(w=>Cs(w).some(C=>c(C,m.sourceFile,I,null,!1,b)))||m.roots.some(w=>c(w,m.sourceFile,I,null,!1,b))?!0:pb(m.roots).kind==="none"?!1:gb(f).some(w=>c(w,y,I,E,!0,b))}function u(m){if(!m.path.isIdentifier())return m.unknownIsRelevant;let f=ub({path:m.path,aliases:m.aliases});return f.kind==="unbound"?m.unknownIsRelevant&&m.path.node.name!=="undefined":f.kind==="guard"||f.kind==="reassigned"?!0:f.kind==="not-alias"?m.unknownIsRelevant:c(f.initializer,m.file,m.active,m.substitution,m.unknownIsRelevant,f.aliases)?!0:jf(f.initializer).isIdentifier()?!1:m.unknownIsRelevant&&!Fo(f.initializer)}let d=(m,f,y,x,E,b)=>{if(m.isIdentifier()){c(m,f,x,b,!1)&&s(f);return}if(m.isJSXElement()){if(ft(m)){for(let w of m.get("children"))d(w,f,y,x,E,b);return}let S=o.get(i(f,m.node));if(!S)return;let I=S.identity.key;if(t.has(I)){E||s(f);let w=n.get(I)??[];w.push($c(I,y)),n.set(I,w)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let w=e.parsedModules.get(S.sourceFile);if(!w)return;let C=Ln({module:w,componentName:S.tag,callSourceRange:S.sourceRange,...S.importedFrom?{imported:{file:S.importedFrom,module:e.parsedModules.get(S.importedFrom),exportName:S.exportName??S.tag,parsedModules:e.parsedModules}}:{}});if(!C.ok){if(C.diagnostic.code==="component-external-module-opaque"){Cs(m).some(U=>c(U,f,x,b,!1))&&s(f);return}[...t].some(U=>e.graph.elements.get(U)?.sourceFile===w.file)&&!hb(C.diagnostic.code)&&s(w.file);return}if(C.metadataOnly)return;let N=`${C.sourceFile}#${C.componentName}`;if(x.has(N)){s(w.file);return}let R=new Set(x).add(N);C.returnAlternatives?.some(U=>Cs(U).some(J=>c(J,C.sourceFile,R,b,!1)))&&s(C.sourceFile);let F=pb(C.roots),$=cO(m);if(F.kind==="unproven"||F.kind==="supported"&&$){for(let U of gb(m))if(c(U,f,R,b,!0)){s(f);break}}let V=F.kind==="supported"&&!$?{bindingNode:F.bindingNode,children:m.get("children").map(U=>({path:U,file:f,substitution:b}))}:null;for(let U of C.roots)d(U,C.sourceFile,[...y,I],R,E,V);return}for(let w of m.get("children"))d(w,f,y,x,E,b);return}if(m.isJSXFragment()){for(let S of m.get("children"))d(S,f,y,x,E,b);return}if(m.isJSXExpressionContainer()){let S=m.get("expression");if(b&&!S.isJSXEmptyExpression()){let I=jf(S);if(jc(I,b)){for(let w of b.children)d(w.path,w.file,y,x,E,w.substitution);return}if(iO(S,b))for(let w of b.children)d(w.path,w.file,y,x,!1,w.substitution)}d(S,f,y,x,E,b);return}if(m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion()){d(m.get("expression"),f,y,x,E,b);return}c(m,f,x,b,!1)&&s(f),m.traverse({JSXElement(S){d(S,f,y,x,!1,b),S.skip()}})},p=e.parsedModules.get(e.entryFile);if(!p)return{occurrences:n,diagnostics:r};let g=Yt({module:p,exportName:"default",allowNonRenderingGuards:!0});if(!g.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let m of g.roots)d(m,p.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function jf(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function Fo(e){let t=jf(e);return t.isStringLiteral()||t.isNumericLiteral()||t.isBooleanLiteral()||t.isNullLiteral()||t.isBigIntLiteral()||t.isJSXElement()||t.isJSXFragment()?!0:t.isIdentifier()?t.node.name==="undefined"&&!t.scope.getBinding("undefined"):t.isTemplateLiteral()?t.node.expressions.length===0:t.isArrayExpression()?t.get("elements").every(n=>!n.node||Fo(n)):t.isConditionalExpression()?Fo(t.get("consequent"))&&Fo(t.get("alternate")):t.isLogicalExpression()?Fo(t.get("left"))&&Fo(t.get("right")):!1}function jc(e,t){if(!e.isIdentifier())return!1;let n=e.scope.getBinding(e.node.name);return!!(n&&(n.path.node===t.bindingNode||n.identifier===t.bindingNode))}function iO(e,t){if(jc(e,t))return!0;let n=!1;return e.traverse({Identifier(r){jc(r,t)&&(n=!0,r.stop())}}),n}function pb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?mb(n.get("left"),!0):mb(n,!1):{kind:"none"}}function mb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){ir(i.get("value"))&&(r=!0);continue}let s=i.node.key;(Xn.isIdentifier(s)?s.name:Xn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&ir(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>ir(i.get("value")))?{kind:"unproven"}:{kind:"none"};if(n.length===0)return r?{kind:"unproven"}:{kind:"none"};if(r)return{kind:"unproven"};let o=n[0].get("value");if(o.isIdentifier()){let i=o.scope.getBinding(o.node.name);return!i||i.path.node!==o.node&&i.identifier!==o.node?{kind:"unproven"}:i.constantViolations.length>0?{kind:"unproven"}:i.referencePaths.length===0?{kind:"none"}:i.referencePaths.every(s=>sO(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return ir(o)?{kind:"unproven"}:{kind:"none"}}if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return!n||n.referencePaths.length===0?{kind:"none"}:n.referencePaths.every(r=>aO(r))?{kind:"none"}:{kind:"unproven"}}return ir(e)?{kind:"unproven"}:{kind:"none"}}function ir(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?ir(e.get("left")):e.isRestElement()?ir(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?ir(t.get("value")):t.isRestElement()?ir(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?ir(t):!1):!0}function sO(e){let t=e.parentPath;for(;t&&(t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion());)t=t.parentPath;if(!t||!t.isJSXExpressionContainer())return!1;let n=t.parentPath;return!!(n&&(n.isJSXElement()||n.isJSXFragment()))}function aO(e){let t=e.parentPath;if(!t||!t.isMemberExpression()&&!t.isOptionalMemberExpression()||t.node.object!==e.node)return!1;let n=t.node.property;return t.node.computed?Xn.isStringLiteral(n)&&n.value!=="children":Xn.isIdentifier(n)&&n.name!=="children"}function cO(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(Xn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&xb(t.get("argument")))return!0}return!1}function gb(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes")){if(n.isJSXAttribute()){let r=n.node.name;if(!Xn.isJSXIdentifier(r)||r.name!=="children")continue;let o=n.get("value");o&&!Array.isArray(o)&&t.push(o);continue}if(n.isJSXSpreadAttribute()){let r=n.get("argument");xb(r)&&t.push(r)}}return t}function Cs(e){let t=e.get("children").map(n=>n);for(let n of e.get("openingElement").get("attributes"))if(n.isJSXSpreadAttribute())t.push(n.get("argument"));else if(n.isJSXAttribute()){let r=n.get("value");r&&!Array.isArray(r)&&t.push(r)}return t}function xb(e){if(e.isJSXElement()||e.isJSXFragment())return!0;let t=!1;return e.traverse({JSXElement(n){t=!0,n.stop()},JSXFragment(n){t=!0,n.stop()}}),t}function lO(e){let t=e.path.scope.getBinding(e.componentName);if(!t)return;let n=t.path;if(!n.isImportDefaultSpecifier()&&!n.isImportSpecifier())return;let r=n.parentPath;if(!r?.isImportDeclaration())return;let o=Br(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":Xn.isIdentifier(n.node.imported)?n.node.imported.name:n.node.imported.value;return{file:o,module:e.parsedModules.get(o),exportName:i,parsedModules:e.parsedModules}}function hb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Sb(e){let t=[],n=[];return Ib(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Ib(e,t,n,r,o,i,s,a,c,l=[]){if(l.length>1&&(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent)){c.push({code:"conditional-component-root-unproven",message:"Conditional returns require one proven local component definition.",file:e.sourceFile});return}if(e.boundaryKind!=="component-boundary"||e.isPublicUiComponent){if(df(e.tag))return;a.push({element:e,callChain:n,ownerNode:r,ownerMember:o,ownerCallChain:i});return}let u=t.parsedModules.get(e.sourceFile);if(!u){c.push({code:"component-module-unavailable",message:"The component source module is unavailable in the parsed graph.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}let d=Ln({module:u,componentName:e.tag,callSourceRange:e.sourceRange,...e.importedFrom?{imported:{file:e.importedFrom,module:t.parsedModules.get(e.importedFrom),exportName:e.exportName??e.tag,parsedModules:t.parsedModules}}:{}});if(!d.ok){c.push({...d.diagnostic,structuralPath:e.identity.structuralPath});return}if(d.metadataOnly)return;let p=d.sourceFile,g=`${p}#${d.componentName}`;if(s.has(g)){c.push({code:"component-call-cycle",message:"A component call cycle cannot be expanded safely.",file:e.sourceFile,structuralPath:e.identity.structuralPath});return}if(d.roots.length===0){c.push({code:"component-root-empty",message:"A component call has no statically addressable JSX root.",file:p,structuralPath:e.identity.structuralPath});return}let m=[...n,{sourceFile:e.sourceFile,component:e.tag,exportName:e.exportName??e.tag,callLocator:{key:e.identity.key,structuralPath:e.identity.structuralPath,sourceRange:e.sourceRange},...l.length>1?{alternativeLocators:l.map(E=>({key:E.identity.key,structuralPath:E.identity.structuralPath,sourceRange:E.sourceRange}))}:{}}],f=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let x=[];for(let E of d.returnAlternatives??[]){let b=Eb(E),S=b?bb(t.graph,p,b):[];if(S.length!==1){c.push({code:"conditional-component-root-unproven",message:"A conditional call site is absent or ambiguous in the source graph.",file:p});return}x.push(S[0])}for(let E of d.roots){let b=Eb(E),S=b?bb(t.graph,p,b):[];if(S.length!==1){c.push({code:S.length?"component-root-ambiguous":"component-root-unresolved",message:"The component root could not be matched to one source graph node.",file:p,structuralPath:e.identity.structuralPath});continue}Ib(S[0],t,m,f,d.roots.length>1?S[0]:o,d.roots.length>1?m:i,y,a,c,x)}}function bb(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 Eb(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 Uc(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!kb(e.projection.composition,e.composition)||e.graph.composition&&!kb(e.graph.composition,e.composition))return{roots:[],diagnostics:[Rs("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[Rs("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(Rs("route-member-not-addressable",e.entryFile));continue}let s=fO(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(Rs(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=Sb({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=yb(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=$c(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(Rs("render-occurrence-unproven",i.element.sourceFile))}return{roots:dO(n,e.composition,o.occurrences),diagnostics:t}}function dO(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:uO("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf($c(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=vb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(vb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function vb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function fO(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 kb(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Rs(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as pO,SiteEditPageBlockDescriptorSchema as mO,SiteEditSourcePathSchema as Cb}from"@vcp-dev/contracts";function Vc(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}),_b(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function _b(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}),_b(s,t,n,r,o))}}function Ps(e){let t=[],n={...e.graph,composition:e.composition},r=tc(Vc(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=yO(a,e.graph),p=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!Cb.safeParse(a.sourceFile).success||!d||!p||!Cb.safeParse(d).success){t.push($f("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push($f("block-key-ambiguous",a.sourceFile));continue}let g=je(u.source),m=mO.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:xO(a,e),capabilities:gO(c,r),...hO(c,r)});if(!m.success){t.push($f("page-block-descriptor-invalid",a.sourceFile));continue}let f=m.data;o.push(f),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:f,root:a,ownerFile:d,ownerSourceHash:je(p.source),ownerSourceContent:p.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=pO.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 gO(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 hO(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 yO(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 xO(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 $f(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Uf from"@babel/traverse";import{BlockRenderRefSchema as bO,SiteEditPageBlockPositionSchema as EO,SiteEditPageBlockTargetSchema as SO}from"@vcp-dev/contracts";var IO=typeof Uf=="function"?Uf:Uf.default;function yi(e,t,n,r){if(!SO.safeParse(t).success)return an("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return an("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return an("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!bO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?an("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:an("INVALID_TARGET","The page block target was not found.")}function Jc(e,t){if(!EO.safeParse(t).success)return an("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return an("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return an("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return an("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 an("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=Rb(n);if(!i)return an("INVALID_TARGET","The operation owner call site is unavailable.");let s=Pb(n,i);if(s===void 0)return an("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||!vO(Pb(u,Rb(u)),s))return an("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return an("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 Rb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Pb(e,t){if(!t)return;let n=Fe(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(IO(n.module.ast,{JSXElement(i){let s=Vf(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=Vf(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Vf(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 vO(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 Vf(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 an(e,t){return{ok:!1,code:e,message:t}}import Tb from"node:path";import{SiteEditSourcePathSchema as LO}from"@vcp-dev/contracts";import Kc from"node:path";import Jf from"@babel/traverse";import*as Yr from"@babel/types";import{SiteEditSourcePathSchema as Nb,SiteEditPageBlockTargetSchema as kO}from"@vcp-dev/contracts";var _O=typeof Jf=="function"?Jf:Jf.default;function Ab(e){if(!e.operationId)return _t("INVALID_PARAMS","An operationId is required.");if(!kO.safeParse(e.target).success)return _t("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 _t("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return _t("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return _t("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return _t("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Nb.safeParse(t).success)return _t("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return _t("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(je(n)!==e.binding.ownerSourceHash)return _t("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||je(r)!==e.binding.descriptor.source.contentHash)return _t("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 _t("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 _t("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return _t("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=RO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?ti({source:n,locator:CO(e.binding),node:{jsx:i.value.jsx}}):An({source:n,locator:Kf(o.parentLocator),anchorLocator:Kf(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return _t("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=Tn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return _t("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 CO(e){return Kf(e.ownerLocator)}function Kf(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 RO(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}>`}}:_t("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return _t("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=PO(t,e.component.source,r);if(!o)return _t("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=Fe(t,n);if(!i.ok)return _t("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=NO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??TO(wO(e.component.exportName,o),AO(i.module.ast)),c=OO(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 PO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Kc.posix.normalize(Kc.posix.join(Kc.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=>Nb.safeParse(i).success&&n.has(i))??null:null}function NO(e,t,n){for(let r of e)if(!(!Yr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Yr.isImportDefaultSpecifier(o)||n!=="default"&&Yr.isImportSpecifier(o)&&(Yr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function AO(e){let t=new Set;return _O(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function TO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function wO(e,t){let r=(e==="default"?Kc.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 OO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return _t("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return _t("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return _t("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function _t(e,t){return{ok:!1,code:e,message:t}}function wb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Xc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&LO.safeParse(i.path).success))return Xc("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 Xc("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 Xc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=DO(t,e.materialization.entry.path),r=Ab({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:FO(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 FO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function DO(e,t){let n=Tb.posix.relative(Tb.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Xc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as HO}from"@vcp-dev/contracts";import Yz from"node:fs";import qz from"node:path";var MO=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Ns(e){let t=e.map(r=>zO(r.path)),n=BO(t);return n?t.filter(r=>$O(n,r)).map(r=>({routeId:UO(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Xf(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=XO(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function BO(e){return e.some(r=>r.startsWith("app/")&&!jO(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function jO(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function $O(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return MO.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function UO(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(JO).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function VO(e){return e.startsWith("(")&&e.endsWith(")")}function JO(e){return!e||e.startsWith("@")||e.startsWith("_")||VO(e)?null:KO(e)}function KO(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function XO(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function zO(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var As=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function cn(e,t={}){throw new As("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function zf(e){return HO.safeParse(e).success||cn("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Ob(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||cn("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return cn("invalid-template-key",{path:e})}return zf(t)!==e&&cn("noncanonical-template-key",{path:e}),t}function WO(e){let t=Xf(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("(")||GO(r)&&!Lb(r)))&&cn("invalid-public-route",{routeId:e}),t}function GO(e){return e.includes("[")||e.includes("]")}function Lb(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function Fb(e){return e.some(Lb)}function Db(e,t,n="app"){n!=="app"&&n!=="src/app"&&cn("invalid-app-root");let r=WO(e),o=zf(t),i=Fb(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))&&cn("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Mb(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Bb(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===".")&&cn("invalid-file-path",{path:i}),n.has(i)&&cn("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Hc(e){let t=Bb(e.files),n=Ns([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new As("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(!Mb(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||cn("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=Fb(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,p=Ob(u),g=d.length?`/${d.join("/")}`:"/";Db(g,p,a).templateEntryFile!==i&&cn("candidate-path-mismatch",{path:i,routeId:g});let f=r.get(g);(!f||!f.startsWith(`${a}/`))&&cn("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:p,entryFile:i,canonicalEntryFile:f,appRoot:a})}return o.sort((i,s)=>zc(i.routeId,s.routeId)||zc(i.templateId,s.templateId))}function Wc(e){let t=Bb(e.files),n=Hc({files:t}),r=Ns([...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)=>zc(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:zc(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function YO(e){let t=Xf(e.selector.routeId),n=Wc({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&cn("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||cn("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function zc(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as xL}from"@vcp-dev/contracts";import{parse as uL}from"@babel/parser";import{parse as mH}from"@babel/parser";import{FormBlockIdSchema as hH,FormSpecV1Schema as yH}from"@vcp-dev/contracts";import{posix as aH}from"node:path";import ZO from"@babel/traverse";var Hf=ZO,lH=typeof Hf=="function"?Hf:Hf.default,uH=Symbol("unknown-member");var Ts="components/site/generated/forms",bH=`${Ts}/vcp-form-runtime.tsx`,Gc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",EH=new RegExp(`^${Ts}/form-(${Gc})\\.spec\\.ts$`),SH=new RegExp(`^${Ts}/form-(${Gc})\\.tsx$`),IH=new RegExp(`^@/${Ts}/form-(${Gc})$`),vH=new RegExp(`(?:^|/)${Ts}/form-(${Gc})(?:\\.tsx?)?$`);var kH=Symbol("invalid-literal");import{createHash as RH}from"node:crypto";import{posix as NH}from"node:path";import{parse as TH}from"@babel/parser";import{FormSpecV1Schema as OH}from"@vcp-dev/contracts";var LH=Symbol("dynamic");import{parse as qO}from"@babel/parser";function Yc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var QO=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function jb(e){let t=QO.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 eL(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function $b(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function tL(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Wf(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(Wf);if(t?.type==="ObjectExpression"){let n={};for(let r of Yc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=$b(r.key);if(!o)throw new Error("unsupported object key");n[o]=Wf(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Gf(e,t){let n=[],r=jb(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=qO(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 Yc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Yc(u.declarations)){let p=d.id;p?.type==="Identifier"&&p.name==="PAGE_SEO"&&(i=d.init)}}if(i==null)return{found:!1,seo:null,diagnostics:n};let s=tL(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 Yc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=$b(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=eL(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=Wf(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 nL}from"@babel/parser";var Ub=["page","anchor","external","email","phone","group","file"],rL=["link","cta"],Jb=["description","badge","iconKey"],Yf=["label","targetType","href","role","openInNewTab","nofollow","children",...Jb],oL=new Set(Yf);function Os(e){return Array.isArray(e)?e:[]}function ws(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function iL(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Vb(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Zf(e){let t=[],n;try{n=nL(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 Os(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Os(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 Os(r.elements).forEach((i,s)=>{let a=Kb(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Kb(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 Os(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=iL(l.key);u&&(r[u]=l.value)}let o=ws(r.label),i=ws(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Ub.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Ub.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 Jb){if(r[l]===void 0)continue;let u=ws(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))oL.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 ${Yf.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=[];Os(r.children.elements).forEach((u,d)=>{let p=Kb(u,`${t}.children[${d}]`,n);p&&l.push(p)}),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=ws(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=ws(r.role);if(c!==void 0&&(rL.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Vb(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=Vb(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 sL}from"@babel/parser";function Ls(e){return Array.isArray(e)?e:[]}function Xb(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function aL(e){let t;try{t=sL(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Ls(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Ls(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=Xb(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 qf(e,t){let n=zb(t);if(!n)return{status:"unsupported",source:e};let r=aL(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Zf(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Ls(l.elements);for(let[d,p]of u.entries()){if(lL(p,n)){let m=u[d+1],f=u[d-1],y=p.start,x=p.end;if(typeof y!="number"||typeof x!="number")continue;if(m&&typeof m.start=="number")s.push({start:y,end:m.start});else if(f&&typeof f.end=="number")s.push({start:f.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=cL(p);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 cL(e){if(e.type==="ObjectExpression")for(let t of Ls(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Xb(t.value)}}function zb(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function lL(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Ls(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"&&zb(n??"")===t}import{estimateNavLabelWidth as KH}from"@vcp-dev/contracts";import{parse as HH}from"@babel/parser";function Mn(e,t){let n;try{n=uL(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(N){let R=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:R?.line??1}]}}let r=n.program,o=xn(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=N=>{if(N?.type==="FunctionDeclaration"){let R=N.id;R?.type==="Identifier"&&typeof R.name=="string"&&s.set(R.name,N);return}if(N?.type==="VariableDeclaration")for(let R of xn(N.declarations)){let F=R.id,$=R.init;F?.type==="Identifier"&&typeof F.name=="string"&&$&&(Zr($)?s.set(F.name,$):$.type==="Identifier"&&typeof $.name=="string"&&a.set(F.name,$.name))}};for(let N of o){if(N.type==="ImportDeclaration"){let R=N.source?.value;if(typeof R!="string")continue;for(let F of xn(N.specifiers)){let $=F.local;if(!($?.type!=="Identifier"||typeof $.name!="string")){if(F.type==="ImportDefaultSpecifier")i.set($.name,{source:R,exportName:"default"});else if(F.type==="ImportNamespaceSpecifier")i.set($.name,{source:R,exportName:"*"});else if(F.type==="ImportSpecifier"){let V=F.imported,U=V?.type==="Identifier"&&typeof V.name=="string"?V.name:V?.type==="StringLiteral"&&typeof V.value=="string"?V.value:"";U&&i.set($.name,{source:R,exportName:U})}}}continue}N.type==="ExportNamedDeclaration"?l(N.declaration):l(N)}for(let N of o){if(N.type==="ExportDefaultDeclaration"){let $=N.declaration;$&&Zr($)?c.set("default",$):$?.type==="Identifier"&&typeof $.name=="string"&&c.set("default",$.name);continue}if(N.type!=="ExportNamedDeclaration")continue;let R=N.declaration;if(R?.type==="FunctionDeclaration"){let $=R.id;$?.type==="Identifier"&&typeof $.name=="string"&&c.set($.name,$.name)}else if(R?.type==="VariableDeclaration")for(let $ of xn(R.declarations)){let V=$.id;V?.type==="Identifier"&&typeof V.name=="string"&&c.set(V.name,V.name)}let F=N.source?.value;for(let $ of xn(N.specifiers)){let V=Gb($.local),U=Gb($.exported);if(!(!V||!U))if(typeof F=="string"){let J=`#re-export:${U}`;i.set(J,{source:F,exportName:V}),c.set(U,J)}else c.set(U,V)}}let u=new Set,d=[],p=new Set,g=[],m=new Set,f=[],y=new Map,x=!1,E=[],b=new Map,S=new Map,I=(N,R="rendered")=>{let F=Wb(N,i);if(!F)return!1;let $=`${F.source}\0${F.exportName}`;if(R==="uncertain")return!p.has($)&&!m.has($)&&(m.add($),g.push({source:F.source,export_name:F.exportName})),!0;if(!p.has($)&&(p.add($),d.push({source:F.source,export_name:F.exportName}),m.delete($))){let V=g.findIndex(U=>U.source===F.source&&U.export_name===F.exportName);V>=0&&g.splice(V,1)}return!0},w=(N,R="rendered",F=[])=>{let $=`${R}\0${ep(F)}`,V=b.get(N)??new Set,U=S.get(N)??new Set;if(V.has($)||U.has(R))return;V.add($),b.set(N,V),U.add(R),S.set(N,U);let J=new Map(s),te=new Map,Y=[],he=(O,D=!1)=>{if(Zc(O)){if(!D&&Zr(O)){if(O.type==="FunctionDeclaration"){let H=O.id;H?.type==="Identifier"&&typeof H.name=="string"&&J.set(H.name,O)}return}if(O.type==="VariableDeclarator"){let H=O.id,j=O.init;H?.type==="Identifier"&&typeof H.name=="string"&&j&&(Zr(j)?J.set(H.name,j):te.set(H.name,j))}else if(O.type==="ReturnStatement"){let H=O.argument;H&&Y.push(H)}if(O.type==="CallExpression"){let H=O.callee;if(H?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:O.loc?.start.line??1}),Fs(H)==="cms.forms.getConfig"){let j=xn(O.arguments)[0];j?.type==="StringLiteral"&&typeof j.value=="string"&&j.value.trim()?R==="rendered"?u.add(j.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:O.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:O.loc?.start.line??1})}}for(let[H,j]of Object.entries(O))if(H!=="loc")if(Array.isArray(j))for(let z of j)he(z);else he(j)}};he(N,!0);let le=new Set,Me=new Set,Ye=(O,D=R,H=F)=>{if(!(!Zc(O)||Zr(O))){if(O.type==="Identifier"&&typeof O.name=="string"){let j=te.get(O.name),z=`${D}\0${O.name}\0${ep(H)}`;j&&!le.has(z)&&!Me.has(O.name)?(le.add(z),Me.add(O.name),Ye(j,D,H),Me.delete(O.name)):I(O.name,D);return}if(O.type==="CallExpression"){let j=O.callee,z=xn(O.arguments),L=Fs(j),G=j?.type==="Identifier"&&typeof j.name=="string"?i.get(j.name):void 0;if(D==="rendered"&&(L==="createElement"||L.endsWith(".createElement")||G?.source==="react"&&G.exportName==="createElement")&&z[0]?.type==="StringLiteral"&&z[0].value==="form"&&(x=!0),j?.type==="Identifier"&&typeof j.name=="string"){let A=J.get(j.name);if(A){w(A,D,H);return}}if(j&&Zr(j)){w(j,D,H);return}if(pL(j)){for(let A of z)if(Zr(A))w(A,D,H);else if(A.type==="Identifier"&&typeof A.name=="string"){let q=J.get(A.name);q&&w(q,D,H)}return}for(let A of z)mL(A)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:A.loc?.start.line??1});return}if(O.type==="JSXElement"){let j=O.openingElement,z=j?Hb(H,dL(j)):H;Ye(j,D,z);for(let L of xn(O.children))Ye(L,D,z);return}if(O.type==="JSXOpeningElement"){let j=qc(O.name);D==="rendered"&&j==="form"&&(x=!0);let z=j?Wb(j,i):void 0;if(D==="rendered"&&z&&typeof O.start=="number"){let L=`${z.source}\0${z.exportName}\0${O.start}`,G=y.get(L);if(!G){let A=gL(O).get("formBlockId");G={source:z.source,export_name:z.exportName,start_offset:O.start,...typeof A=="string"?{static_form_block_id:A}:{}},y.set(L,G),f.push(G)}H.length>0&&(G.static_render_blockers=Hb(G.static_render_blockers??[],H))}if(j&&!I(j,D)){let L=J.get(j);L?w(L,D,H):te.has(j)?Ye(te.get(j),D,H):fL(j)||/^[A-Z]/.test(j)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${j} from a static import.`,file_path:t.filePath??"",line:O.loc?.start.line??1})}for(let L of xn(O.attributes))Ye(L,"uncertain",H);return}if(O.type==="JSXAttribute"){let j=O.value,z=j?.type==="JSXExpressionContainer"?j.expression:j;z&&Zr(z)?w(z,"uncertain",H):Ye(z,"uncertain",H);return}for(let[j,z]of Object.entries(O))if(!(j==="loc"||j==="closingElement"))if(Array.isArray(z))for(let L of z)Ye(L,D,H);else Ye(z,D,H)}},pt=N.body;pt&&pt.type!=="BlockStatement"&&Y.push(pt);for(let O of Y)Ye(O);U.delete(R)},C=c.get(t.exportName);if(typeof C=="string"){let N=C,R=new Set;for(;a.has(N)&&!R.has(N);)R.add(N),N=a.get(N);if(!I(N)){let F=s.get(N);F?w(F):E.push(Yb(t))}}else C?w(C):E.push(Yb(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:f,renders_native_form:x,diagnostics:E}}function ep(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function Hb(e,t){return[...new Map([...e,...t].map(r=>[ep([r]),r])).values()]}function dL(e){let t=new Map;for(let a of xn(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Zb(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=qc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:yL(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Qf(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 xn(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,Qf(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=Qf(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(p=>d.has(p.split(":").at(-1)))&&o(`className=${u}`)}return r}function Qf(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"&&xn(e.expressions).length===0)return xn(e.quasis)[0]?.value?.cooked}}function Wb(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 fL(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function Zr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function pL(e){let t=Fs(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 mL(e){let t=!1;return tp(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Fs(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Gb(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Yb(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Fs(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=Fs(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function gL(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=Zb(o.name);i&&t.set(i,hL(o.value))}return t}function hL(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 Zb(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function yL(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function tp(e,t){if(Zc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)tp(o,t);continue}tp(r,t)}}}function Zc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function qc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=qc(t.object),r=qc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function xn(e){return Array.isArray(e)?e.filter(t=>Zc(t)):[]}var bL="components/site/generated/",Ds=[".tsx",".ts",".jsx",".js"];function qb(e){if(e.expectedUrlPath===xL)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(Ns(Object.keys(e.files).map(f=>({path:f}))).map(f=>f.entryFile)),n=Object.entries(e.files).filter(([f,y])=>{let x=f.replace(/\\/g,"/");if(!t.has(x))return!1;let E=Gf(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 f=Hc({files:new Map(Object.entries(e.files))});for(let y of f)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(f){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:f instanceof Error?f.message:"Invalid page template source."}}let i=EL(e.files);if(!i.ok)return i.error;let s=i.graph,a=kL(o,s),c=_L(o,a,s),l=[...a].filter(f=>!c.has(f)).sort((f,y)=>f.localeCompare(y)),u=[...o,...[...c].sort((f,y)=>f.localeCompare(y))],d=new Set(u),p=u.map(f=>({operation:"delete",file:f})),g=[],m=[];for(let[f,y]of Object.entries(e.files))if(!d.has(f)){if(y.includes("NAV_ITEMS")){let x=qf(y,e.expectedUrlPath);x.status==="removed"?(p.push({operation:"upsert",file:f,content:x.source}),g.push(f)):x.status==="unsupported"&&m.push(`unsupported_navigation:${f}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&m.push(`preserved_link:${f}`)}return{ok:!0,edits:p,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:m}}function EL(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")||!SL(r))continue;let s=Fe(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(IL(c))continue;let l=Qn(r,c),u=vL(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 SL(e){let t=e.toLowerCase();return Ds.some(n=>t.endsWith(n))}function IL(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!Ds.some(n=>e.endsWith(n)))}function vL(e,t){let n=e.replace(/\\/g,"/");return(Ds.some(o=>n.endsWith(o))?[n]:[...Ds.map(o=>`${n}${o}`),...Ds.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function kL(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(bL)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function _L(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 QE from"@babel/parser";import*as We from"@babel/types";import*as hl from"node:path";import*as ot from"@babel/types";function Qb(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 sr(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Do(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ot.isObjectPattern(n)||ot.isArrayPattern(n))return Do(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(RL(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Do(e,t,n=!1){return ot.isIdentifier(e)?e.name===t&&n:ot.isObjectPattern(e)?e.properties.some(r=>ot.isObjectProperty(r)?Do(r.value,t,n):Do(r.argument,t,n)):ot.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ot.isRestElement(r)?r.argument:r;return Do(o,t,n)}):ot.isAssignmentPattern(e)?Do(e.left,t,!0):ot.isRestElement(e)?Do(e.argument,t,n):!1}function xi(e,t){if(e.path.isObjectPattern()){if(t){let r=zn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:sr(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:sr(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=eE(r),i=!1,s=o?o.initBinding&&np(o.initBinding)?(i=sr(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=xi(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=zn(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||sr(e)}}}}let n=AL(e);if(n){let r=CL(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||sr(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=PL(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:sr(e)}}let i=Ms(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:sr(e)}:null}if(np(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:sr(e)}}return null}function CL(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=eE(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=np(i)?(a=sr(i),[...s]):(()=>{let u=xi(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=zn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||sr(t)}:null}function eE(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=TL(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function np(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function RL(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function PL(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=zn(i.node,t);if(a)return a}return null}function tE(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Qc(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=Ms(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=NL(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Ms(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 Qc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Ms(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&zn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Qc(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=Qc(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=Qc(r,t);if(o)return o}}return null}function zn(e,t,n=[]){if(ot.isIdentifier(e))return e.name===t?n:null;if(ot.isObjectPattern(e)){for(let r of e.properties)if(ot.isObjectProperty(r)){let o=Ms(r);if(!o)continue;let i=zn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ot.isRestElement(r)){let o=zn(r.argument,t,n);if(o)return o}}if(ot.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=ot.isRestElement(o)?o.argument:o,s=zn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ot.isAssignmentPattern(e)?zn(e.left,t,n):null}function NL(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function AL(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 Ms(e){return e.computed?null:ot.isIdentifier(e.key)?e.key.name:ot.isStringLiteral(e.key)?e.key.value:null}function TL(e){let t=[],n=e;for(;ot.isMemberExpression(n);){if(n.computed)if(ot.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(ot.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(ot.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return ot.isIdentifier(n)?{base:n.name,path:t}:null}import*as aE from"@babel/parser";import ip from"@babel/traverse";import*as bi from"@babel/types";import*as Ue from"@babel/types";var nE=new WeakMap;function nl(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?el(n,t):null}if(e.isMemberExpression()){let n=ML(e.node),r=wL(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?el(o,[...r,...t]):null}return e.isAwaitExpression()||op(e.node)?qr(jL(e.node),t,"awaited or fetched expression"):null}function wL(e){let t=[],n=e;for(;Ue.isMemberExpression(n);){if(n.computed)if(Ue.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ue.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ue.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ue.isIdentifier(n)?t:null}function el(e,t=[],n){let r=OL(e,t);if(r)return r;let o=LL(e,t,n);if(o)return o;let i=FL(e,t,n);return i||null}function js(e){return e?.kind==="api-source"}function OL(e,t){if(e.path.isVariableDeclarator()&&Ue.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&rp(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return qr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Ue.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Ue.isObjectProperty(c)&&iE(c)==="data"&&Bs(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&rp(a.node))return qr(e.identifier.name,t,"query hook data binding")}let n=DL(e);if(!n||iE(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()||!rp(i.node)?null:qr(e.identifier.name,t,"query hook data binding")}function LL(e,t,n){if(e.path.isVariableDeclarator()&&Ue.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!oE(c.node))return null;let[l,u]=e.path.node.id.elements;return!Ue.isIdentifier(l)||l.name!==e.identifier.name||!Ue.isIdentifier(u)?null:rE(e,u.name,n)?qr(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()||!oE(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Ue.isIdentifier(a)&&rE(e,a.name,n)?qr(e.identifier.name,t,"state setter is updated by API data"):null}function FL(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()?qr(e.identifier.name,t,"awaited binding result"):op(o.node,n)?qr(e.identifier.name,t,"fetch-backed binding result"):null:null}function DL(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 Bs(e,t){return Ue.isIdentifier(e)?e.name===t:Ue.isAssignmentPattern(e)?Bs(e.left,t):Ue.isObjectPattern(e)?e.properties.some(n=>Ue.isObjectProperty(n)?Bs(n.value,t):Bs(n.argument,t)):Ue.isArrayPattern(e)?e.elements.some(n=>!!n&&Bs(Ue.isRestElement(n)?n.argument:n,t)):!1}function rE(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=nE.get(n);c||(c=new WeakMap,nE.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){op(c.node)&&(r=!0),(BL(c.node.callee,t)||c.node.arguments.some(l=>Ue.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function rp(e){let t=rl(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function oE(e){return rl(e.callee)==="useState"}function op(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=tl(e,o=>Ue.isCallExpression(o)&&rl(o.callee)==="fetch");return t?.set(e,r),r}function ML(e){let t=e;for(;Ue.isMemberExpression(t);)t=t.object;return Ue.isIdentifier(t)?t.name:null}function iE(e){return e.computed?null:Ue.isIdentifier(e.key)?e.key.name:Ue.isStringLiteral(e.key)?e.key.value:null}function rl(e){return Ue.isIdentifier(e)?e.name:Ue.isMemberExpression(e)&&Ue.isIdentifier(e.property)?e.property.name:null}function BL(e,t){return tl(e,n=>Ue.isIdentifier(n)&&n.name===t)}function tl(e,t){if(t(e))return!0;let n=Ue.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(Ue.isNode(i)&&tl(i,t))return!0;continue}if(Ue.isNode(o)&&tl(o,t))return!0}return!1}function jL(e){return Ue.isIdentifier(e)?e.name:Ue.isCallExpression(e)?rl(e.callee)??"api":Ue.isAwaitExpression(e)?"awaited-api":"api"}function qr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:$L(e,t),reason:n}}function $L(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var cE=typeof ip=="function"?ip:ip.default;function lE(e,t){let n=dE(e);if(!n)return{allowed:!0};let r=!1;return cE(n,{CallExpression(o){if(!fE(o.node,t.sourceRange)||!UL(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||js(nl(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function uE(e,t){let n=dE(e);if(!n)return{allowed:!0};let r=!1;return cE(n,{JSXExpressionContainer(o){fE(o.node,t.sourceRange)&&(bi.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 dE(e){try{return aE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function UL(e){let t=e.callee;return bi.isMemberExpression(t)&&bi.isIdentifier(t.property)&&t.property.name==="map"}function fE(e,t){let n=e.loc;return n?sE({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&sE({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function sE(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 pe from"@babel/types";import*as pE from"@babel/parser";import sp from"@babel/traverse";import*as ht from"@babel/types";import*as Ei from"node:path";var Hn=typeof sp=="function"?sp:sp.default;function jt(e){try{return pE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function ap(e){return e.computed?ht.isStringLiteral(e.key)||ht.isNumericLiteral(e.key)?String(e.key.value):null:VL(e.key)}function VL(e){return ht.isIdentifier(e)?e.name:ht.isStringLiteral(e)||ht.isNumericLiteral(e)?String(e.value):null}function Mo(e){return ht.isParenthesizedExpression(e)||ht.isTSAsExpression(e)||ht.isTSSatisfiesExpression(e)||ht.isTSNonNullExpression(e)||ht.isTSTypeAssertion(e)?Mo(e.expression):ht.isExpression(e)?e:null}function cp(e){if(ht.isIdentifier(e))return[e.name];if((ht.isMemberExpression(e)||ht.isOptionalMemberExpression(e))&&!e.computed&&ht.isIdentifier(e.property)){let t=Mo(e.object),n=t?cp(t):null;return n?[...n,e.property.name]:null}return null}function Bo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Ei.normalize(Ei.join(Ei.dirname(e),t)).replace(/\\/g,"/"):t}function bn(e,t){return ol(e)===ol(t)}function ol(e){let t=Si(e);return t.endsWith("/index")?t.slice(0,-6):t}function Si(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function hE(e,t,n){let r=EE(e,t);if(SE(e,r),IE(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 Hn(e,{JSXElement(s){CE(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:il(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 yE(e,t){let n=new Map,r=i=>{let s=Ii(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 JL(i,n))o=r(s)||o}return[...n.values()]}function JL(e,t){let n=[],r=KL(e,t);for(let o of e.ast.program.body){if(pe.isExportDefaultDeclaration(o)&&pe.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=$s(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(pe.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Bo(e.file,o.source.value);for(let s of o.specifiers){if(pe.isExportNamespaceSpecifier(s)){let l=Qr(s.exported);for(let u of t.values())bn(u.file,i)&&n.push({file:e.file,namespace:lp(l,u.namespace),exportName:u.exportName});continue}if(!pe.isExportSpecifier(s))continue;let a=Qr(s.local),c=[...t.values()].filter(l=>bn(l.file,i)&&jo(l.namespace,a));if(c.length>0){let l=Qr(s.exported);for(let u of c){let d=$s(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(Ii({file:i,exportName:a}))&&n.push({file:e.file,exportName:Qr(s.exported)})}continue}if(pe.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!pe.isExportSpecifier(i))continue;let s=Qr(i.local),a=r.get(s)??[];if(a.length>0){let c=Qr(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=$s(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(pe.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Bo(e.file,o.source.value),s=o.exported;if(s){let a=Qr(s);for(let c of t.values())bn(c.file,i)&&n.push({file:e.file,namespace:lp(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())bn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function lp(e,t){return t?`${e}.${t}`:e}function jo(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function $s(e,t,n){return!jo(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function KL(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(!pe.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Bo(e.file,i.source.value);for(let a of i.specifiers){if(pe.isImportDefaultSpecifier(a)){let c=t.get(Ii({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>bn(u.file,s)&&jo(u.namespace,"default"));for(let u of l){let d=$s(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(pe.isImportSpecifier(a)){let c=Qr(a.imported),l=[...t.values()].filter(d=>bn(d.file,s)&&jo(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(Ii({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(pe.isImportNamespaceSpecifier(a))for(let c of t.values())bn(c.file,s)&&r(a.local.name,{...c,namespace:lp(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(pe.isVariableDeclaration(i))for(let s of i.declarations){if(!pe.isIdentifier(s.id)||!s.init)continue;let a=Mo(s.init);if(!a||!pe.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(Ii));for(let d of c){let p=$s(d.namespace,a.name,s.id.name),g=p?{...d,namespace:p}:d,m=Ii(g);u.has(m)||(r(s.id.name,g),u.add(m),o=!0)}}}return n}function Ii(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${ol(e.file)}#${t}`}function Qr(e){return pe.isIdentifier(e)?e.name:e.value}function xE(e,t){for(let n of e.program.body){if(pe.isExportDefaultDeclaration(n)){let o=n.declaration;if((pe.isFunctionDeclaration(o)||pe.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(pe.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!pe.isExportNamedDeclaration(n))continue;let r=n.declaration;if((pe.isFunctionDeclaration(r)||pe.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(pe.isVariableDeclaration(r)){for(let o of r.declarations)if(pe.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!pe.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:pe.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function dp(e){let t=XL(e),n=[],r=IE(e.ast,t);return Hn(e.ast,{JSXElement(o){bn(e.file,e.sourceFile)&&il(o)===e.sourceComponent||CE(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function bE(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function EE(e,t){let n=bE();return Hn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function XL(e){let t=bE();return bn(e.file,e.sourceFile)&&zL(t,EE(e.ast,e.sourceComponent)),Hn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Bo(e.file,o),s=e.componentIdentities.filter(a=>bn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(pe.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),pe.isImportDefaultSpecifier(a)){let l=s.filter(u=>jo(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=gE(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(pe.isImportSpecifier(a)){let l=pe.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>jo(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let g=gE(p,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(pe.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)}}}}}),SE(e.ast,t),t}function zL(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 SE(e,t){Hn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Mo(n.node.init);if(r){if(pe.isIdentifier(n.node.id)){let o=$o(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&up(t,i,o);return}if(pe.isObjectPattern(n.node.id)){let o=$o(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&_E(n.node.id,o.namespaceMembers,t,n)}}}})}function IE(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Hn(e,{ReferencedIdentifier(r){if(n){r.stop();return}HL(r)||!r.isIdentifier()||!vE(r,t)||WL(r,t)||GL(r)||(n=!0,r.stop())}}),n}function HL(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 vE(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)&&$o(r.node,t,r)?r:null}function WL(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!mE(e,r))return!1;let o=vE(e,t);if(!o)return!1;if(Mo(r.node)===o.node)return!!$o(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&mE(e,a)&&!!$o(a.node,t,a)}function GL(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function mE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function $o(e,t,n){let r=Mo(e);if(!r)return null;if(pe.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(pe.isObjectExpression(r))return YL(r,t,n);let o=cp(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?kE(s,o.slice(1).join(".")):null}function YL(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!pe.isObjectProperty(i))continue;let s=ap(i);if(!s||!pe.isExpression(i.value)){pe.isExpression(i.value)&&(o||=$o(i.value,t,n)!==null);continue}let a=$o(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 kE(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 up(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 _E(e,t,n,r){for(let o of e.properties){if(pe.isRestElement(o)){if(pe.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&up(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!pe.isObjectProperty(o))continue;let i=ap(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=kE(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=pe.isAssignmentPattern(o.value)?o.value.left:o.value;if(pe.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&up(n,c,s);continue}if(pe.isObjectPattern(a)&&s.namespaceMembers.size>0){_E(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function gE(e,t){if(!jo(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 CE(e,t){let n=e.node.openingElement.name;if(pe.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=RE(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 RE(e){if(pe.isJSXIdentifier(e))return[e.name];if(pe.isJSXMemberExpression(e)){let t=RE(e.object);return t?[...t,e.property.name]:null}return null}function il(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()&&pe.isIdentifier(n.node.id))return n.node.id.name}return null}function PE(e,t){let n=jt(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=dp({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 nt(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 tt(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function ar(e,t){let n=tt(e);return!!(n&&En(t,n))}function En(e,t){return t.start>=e.start&&t.end<=e.end}function Bn(e,t){let n=De(e,nt(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:sl(e,t)}function vi(e,t){let n=tt(t);return n?e.slice(n.start,n.end):""}function NE(e,t){return e.start===t.start&&e.end===t.end}function sl(e,t){let n=null;return Hn(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 al(e,t){return fp(e,t).length>0}function cl(e,t){let n=tt(e.node),r=tt(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()&&!ZL(o,n,r)))return!0;o=o.parentPath}return!1}function ZL(e,t,n){let r=tt(e.node.consequent);if(r&&En(r,t)&&!En(r,n))return!1;let o=e.node.alternate?tt(e.node.alternate):null;return!(o&&En(o,t)&&!En(o,n))}function fp(e,t){let n=tt(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=tt(o.node.consequent),a=tt(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()&&pp(o.node.operator)){let s=tt(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 pp(e){return e==="&&"||e==="||"||e==="??"}function AE(e,t){let n=tt(e.consequent);if(n&&En(n,t))return n;let r=tt(e.alternate);return r&&En(r,t)?r:null}function TE(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=>Si(a.file)));if(!t.has(Si(e.sourceFile))||!t.has(Si(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(Si(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=xE(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=jt(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=yE(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=dp({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!bn(s.file,e.targetFile)||il(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 rF}from"@vcp-dev/contracts";function ll(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 Us();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Us();let u=qL(a,l,o?.instanceCount);if(!u)return Us();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"?Us():{ok:!0,target:{kind:"jsx-attribute"}}}function Us(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function qL(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 cr from"@babel/types";import{SiteEditSetPropsParamsSchema as QL}from"@vcp-dev/contracts";function wE(e){let t=e.changes??(e.change?[e.change]:[]);if(!QL.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Vs("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Vs("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=ut(e.source,"value");if(!o.ok)return Vs("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=De(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Vs("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?eF(r):tF(c.match.path.node,r.name);if(!l)return Vs("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 eF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function tF(e,t){let n=e.properties.filter(i=>cr.isObjectProperty(i)&&nF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!cr.isExpression(r.value))return null;let o=or(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function nF(e){return cr.isIdentifier(e)?e.name:cr.isStringLiteral(e)?e.value:cr.isNumericLiteral(e)?String(e.value):null}function Vs(e,t){return{ok:!1,errorCode:e,reason:t}}function OE(e){if(e.change.name!=="className"&&e.change.name!=="class")return Js("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Js("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Js("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Js("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 Js("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 Js(e,t){return{ok:!1,errorCode:e,reason:t}}async function FE(e){let t=rF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return eo("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 eo("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 oF(e,r);if(o){if(!o.ok)return eo("owner-plan-failed",o.reason);LE(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return eo("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return eo("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(aF(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=ll({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return eo(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){mp(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=wE({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return eo("repeat-target-failed",l.reason);LE(n,l.steps);continue}mp(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:iF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),sF(n)?eo("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function oF(e,t){return t.name!=="className"&&t.name!=="class"?null:OE({node:e.node,change:t,classNameSource:e.classNameSource})}function iF(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 sF(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 LE(e,t){for(let n of t)mp(e,{...n,order:e.length})}function mp(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 aF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?gp(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function gp(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)=>gp(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=>gp(n[i],r[i]))}return!1}function eo(e,t){return{ok:!1,errorCode:e,reason:t}}import*as _i from"@babel/types";import*as Ee from"@babel/types";function hp(e,t,n){let r=Bn(t,n);return r?lr(e,r):null}function lr(e,t){let n=t.findParent(f=>f.isArrowFunctionExpression()||f.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(f=>f===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(!Ee.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=vi(e,u.node),p=r.node.params.map(f=>vi(e,f)),g=tt(i.node),m=tt(r.node);return!d||p.some(f=>f.length===0)||!g||!m?null:{callStart:g.start,callEnd:g.end,callbackStart:m.start,callbackEnd:m.end,collectionExpression:d,callbackParams:p,mapOperator:Ee.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:ul(u.node),callbackPath:r,collectionPath:u}}function Ks(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function cF(e,t){let n=tt(e.node);return n?lF(t).some(r=>{let o=tt(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function lF(e){let t=e.callbackPath.node.body;return Ee.isBlockStatement(t)?to(t.body):no(t)}function to(e){let t=[];for(let n of e){if(Ee.isReturnStatement(n)){n.argument&&t.push(...no(n.argument));continue}if(Ee.isBlockStatement(n)){t.push(...to(n.body));continue}if(Ee.isIfStatement(n)){let r=Ee.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...to(r)),n.alternate){let o=Ee.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...to(o))}continue}if(Ee.isSwitchStatement(n)){for(let r of n.cases)t.push(...to(r.consequent));continue}Ee.isTryStatement(n)&&(t.push(...to(n.block.body)),n.handler&&t.push(...to(n.handler.body.body)),n.finalizer&&t.push(...to(n.finalizer.body)))}return t}function no(e){return Ee.isJSXElement(e)?uF(e)?DE(e.children):[e]:Ee.isJSXFragment(e)?DE(e.children):Ee.isParenthesizedExpression(e)||Ee.isTSAsExpression(e)||Ee.isTSSatisfiesExpression(e)||Ee.isTSNonNullExpression(e)||Ee.isTSTypeAssertion(e)?no(e.expression):Ee.isConditionalExpression(e)?[...no(e.consequent),...no(e.alternate)]:Ee.isLogicalExpression(e)&&pp(e.operator)?no(e.right):[]}function DE(e){return e.flatMap(t=>Ee.isJSXElement(t)||Ee.isJSXFragment(t)?no(t):Ee.isJSXExpressionContainer(t)&&(Ee.isJSXElement(t.expression)||Ee.isJSXFragment(t.expression)||Ee.isConditionalExpression(t.expression)||Ee.isLogicalExpression(t.expression))?no(t.expression):[])}function uF(e){let t=e.openingElement.name;return Ee.isJSXIdentifier(t)?t.name==="Fragment":Ee.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function ME(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function ul(e){return!(Ee.isIdentifier(e)||Ee.isThisExpression(e)||Ee.isMemberExpression(e)||Ee.isOptionalMemberExpression(e)||Ee.isCallExpression(e)||Ee.isOptionalCallExpression(e))}function BE(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(Ee.isMemberExpression(n)||Ee.isOptionalMemberExpression(n))&&Ee.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function ki(e,t){let n=jt(e);if(!n)return t.isRepeatItemRoot===!0;let r=De(n,nt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:sl(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=lr(e,o);return i?cF(o,i):t.isRepeatItemRoot===!0}function jE(e,t){let n=jt(e);if(!n)return!1;let r=De(n,nt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:sl(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(Ee.isMemberExpression(s)||Ee.isOptionalMemberExpression(s))&&Ee.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as at from"@babel/types";function yp(e){if(at.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(at.isJSXMemberExpression(e)){let t=e;for(;at.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function dF(e,t){let n=tt(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||ar(a.path.node,n)||ro(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=yp(i.node.name);s&&o(s,i)}}),[...r].sort()}function xp(e,t,n){let r=jt(e);if(!r)return{ok:!0};let o=De(r,nt(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=De(r,nt(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=rs(o.match.path,i.match.path);if(al(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=dF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function UE(e){let t=e;for(;at.isTSQualifiedName(t);)t=t.left;return at.isIdentifier(t)?t.name:null}function Xs(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function dl(e){let t=[],n=r=>{if(r){if(at.isIdentifier(r)){t.push(r.name);return}if(at.isObjectPattern(r)){for(let o of r.properties){if(at.isRestElement(o)){n(o.argument);continue}at.isObjectProperty(o)&&n(o.value)}return}if(at.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(at.isAssignmentPattern(r)){n(r.left);return}if(at.isRestElement(r)){n(r.argument);return}at.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function bp(e,t){let n=tt(e.node),r=tt(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=$E(e),i=$E(t);if(!o||!i||!NE(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=AE(s.node,n);if(a&&!En(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=tt(s.node.right);if(a&&En(a,n)&&!En(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())&&BE(s)){let a=tt(s.node.body)??tt(s.node);if(a&&!En(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 $E(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?tt(t.node.argument):null;if(t.isArrowFunctionExpression()&&(at.isJSXElement(t.node.body)||at.isJSXFragment(t.node.body)||at.isConditionalExpression(t.node.body)||at.isLogicalExpression(t.node.body)))return tt(t.node.body);t=t.parentPath}return null}function ro(e,t,n){return n.scope.getBinding(t)===e}function Ep(e,t,n,r={}){if(!r.preserveConditionalBoundary&&al(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=tt(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>dl(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||ar(u.path.node,o)||i.has(u.path.node)||ro(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=yp(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Sp(e,t,n){let r=tt(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>dl(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Xs(e,s=>{let a=s.scope.getBinding(s.node.name);!a||ar(a.path.node,r)||o.has(a.path.node)||ro(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function VE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>dl(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)||ro(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(_i.isIdentifier(l))o(l.name,c);else{let u=UE(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Ip(e,t){let n=tt(e.node),r=new Set;return Xs(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&ar(i.path.node,n)||ro(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 JE(e){let t=[];for(let n of e.callbackPath.node.params){if(_i.isIdentifier(n)){t.push(n.name);continue}if(_i.isRestElement(n)&&_i.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 KE(e,t){return{...e,callbackParams:t}}function vp(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function zs(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 XE(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 Uo(e){return{file:e.file,component:e.component}}function fF(e){return e.target.kind==="node"?e.target.key:null}function pF(e){return"kind"in e&&e.kind==="page-composition"}function ml(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function fl(e){return!pF(e)&&!ml(e)}function Pp(e,t){let n=hl.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=hl.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function kp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=nr(n,nt(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Ap(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 mF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function gF(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 _p(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function hF(e){let t=hE(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=bp(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=yF({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=eS(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?ul(o):!0}}}function yF(e){let t=tt(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||ar(a.path.node,t))return;let c=EF(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=IF(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=xF(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=Ip(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}ro(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:vF(e.source,t,[...n.values()])}}function xF(e,t){if(t.length===0)return e;let n=eS(e);if(!n)return null;let r=ul(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=bF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function bF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function EF(e,t,n){let r=SF(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=xi(t,o);if(!i)return null;let s=r?.range??tt(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function SF(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!ar(n.node,t)||n.node.computed||!We.isIdentifier(n.node.property))return null;let r=tt(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function IF(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()&&We.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=vi(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 vF(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 eS(e){try{let n=QE.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=We.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&We.isExpression(r)?r:null}catch{return null}}function kF(e){let t=tt(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||ar(s.path.node,t))return;let a=zE(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=zE(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!_F(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 Xs(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 _F(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 zE(e,t,n){let r=CF(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Bo(t,i),a=i.startsWith(".")?Pp(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=We.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 CF(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function HE(e,t,n,r){let o=fp(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=vi(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=RF(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${NF(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function RF(e,t){return PF(e.node)?t:`(${t})`}function PF(e){return We.isIdentifier(e)||We.isThisExpression(e)||We.isSuper(e)||We.isMemberExpression(e)||We.isOptionalMemberExpression(e)||We.isCallExpression(e)||We.isOptionalCallExpression(e)||We.isBooleanLiteral(e)||We.isNumericLiteral(e)||We.isStringLiteral(e)||We.isNullLiteral(e)||We.isUnaryExpression(e)}function NF(e){return e.trim().startsWith("<")?e:`(${e})`}var AF={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 pl(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=AF[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 TF(e,t){for(let n of e.program.body){if(!We.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>We.isImportDefaultSpecifier(o));if(r&&We.isImportDefaultSpecifier(r))return r.local.name}return null}function wF(e,t,n){for(let r of e.program.body){if(!We.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>We.isImportSpecifier(i)&&(We.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&We.isImportSpecifier(o))return o.local.name}return null}function WE(e){let t=new Set;return Hn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function GE(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function OF(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Ap(e),o=jt(t);if(n.exportName!=="default"){let a=o?wF(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?GE(r,WE(o)):r;return{localName:c,importStep:Cp(e,c)}}if(!o)return{localName:r,importStep:Cp(e,r)};let i=TF(o,n.source);if(i)return{localName:i};let s=GE(r,WE(o));return{localName:s,importStep:Cp(e,s)}}function LF(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Ap(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 FF(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?DF(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function DF(e){return Object.fromEntries(Object.entries(e).filter(t=>Np(t[1])))}function Np(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Np):typeof e=="object"?Object.values(e).every(Np):!1}function Cp(e,t=Ap(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 YE(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 MF(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Ci(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Tp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Hs(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:Tp(e,t.slice(0,n)),index:r.index}}return null}function Rp(e,t){return e.locator?e.collectionPathMap?.[t]?Tp(e.locator,e.collectionPathMap[t]):Hs(e.locator)?jF(e.locator,$F(t,e.collectionIndexMap)):null:null}function BF(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:tS(o,t)}function tS(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=tS(r,t);return o===void 0?void 0:{[n.name]:o}}function jF(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},Tp(e,i)}return null}function $F(e,t){return t?.[e]??e}function ZE(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 UF(e,t){return VF(e.root,t.root)&&KF(e.path??[],t.path??[])}function VF(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&&JF(e.sourceRange,t.sourceRange)}}function JF(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function KF(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 gl=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:Ci(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:Ci(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:Ci(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:Ci(t.kind,t.params.kind)};let r=t;if(ml(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!fl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=YE(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:Ci(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:Ci(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=fF(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):qE(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 qE(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:nt(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?FE({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 m=Rp(u,i.instanceIndex);if(!m)return{ok:!1,errorCode:"invalid-params",reason:"apply-style-draft could not resolve the selected repeat item"};g=m}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:nt(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=Rp(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:nt(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=jt(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=De(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!mF(a.match.path))return{ok:!0,value:r};let c=gF(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=Rp(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=jt(this.graph.getFileContent(t));if(!o)return!1;let i=De(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 p=Hs(d.locator);if(p)return this.buildPlan(t,n,[{order:0,file:d.file,type:"remove-bound-array-item",locator:p.locator,index:p.index}],o)}return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed node removal requires a writable array target"}}let s=zs(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:nt(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||PE(n,t)>1)return null;let r=Pp(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(!fl(n.params.position))return ml(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=zs(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 p=this.getRepeatBackedTemplateStructureReason(r);if(p)return{ok:!1,errorCode:"unsupported-operation",reason:p};let g=lE(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 m=pl(r,n.params.node);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let f=[],y=0,x=n.params.node.kind==="component-call"?OF(n.params.node,this.graph.getFileContent(r.file)):void 0,E=x?.importStep;return E&&f.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),f.push({order:y++,file:r.file,type:"insert-child",parentLocator:nt(r),node:{jsx:LF(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?nt(i):void 0}),this.buildPlan(t,n,f,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!fl(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:FF(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(!fl(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=Hs(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=BF(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"?ZE(0,a.collectionIndexMap):ZE(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=zs(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 ki(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:")||jE(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&&ki(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=jt(c);if(!l)return null;let u=Bn(l,r),d=Bn(l,o);if(!u||!d)return null;let p=lr(c,u),g=lr(c,d);if(!Ks(p,g))return null;if(a&&(s==="before"||s==="after")){let f=Bn(l,a),y=f?lr(c,f):null;if(!Ks(p,y))return null}if(cl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=xp(c,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:nt(r),targetParentLocator:nt(o),placement:s,anchorLocator:a?nt(a):void 0,selectionContext:Uo(o)}],i):{ok:!1,errorCode:"unsupported-operation",reason:m.reason??`Cannot move node because it depends on bindings outside the target scope: ${m.bindingNames.join(", ")}`}}planRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ki(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=jt(c);if(!l)return null;let u=Bn(l,r),d=Bn(l,o);if(!u||!d)return null;let p=lr(c,u);if(!p)return null;let g=lr(c,d);if(Ks(p,g))return null;if(g&&!ME(g,p))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=hp(c,l,a);if(g&&!Ks(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=pl(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let m=kp(this.graph,r);if(!m)return{ok:!1,errorCode:"locator-miss",reason:"Cannot move repeat-backed child outside its repeat template without preserving the repeat expression"};if(cl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let f=HE(c,u,d,m);for(let b of f.conditionPaths){let S=Sp(b,d,p);if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${S.bindingNames.join(", ")}`}}let y=Ep(u,d,p,{preserveConditionalBoundary:f.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=VE(p,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=p;if(r.component!==o.component){let b=hF({source:c,ast:l,sourceContext:p,sourceNode:r,targetParent:o,targetParentPath:d});if(!b.ok)return{ok:!1,errorCode:"unsupported-operation",reason:b.reason};E=b.context}else{let b=Ip(p.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:nt(r),targetParentLocator:nt(o),placement:s,anchorLocator:a?nt(a):void 0,repeatExpression:vp(E,f.sourceJsx),selectionContext:Uo(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ki(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=jt(c),d=jt(l);if(!u||!d)return null;let p=TE({knownSourceFiles:this.graph.getKnownSourceFiles?.(),routeEntryFiles:this.graph.getRouteEntryFiles?.(),sourceAst:u,sourceFile:r.file,targetFile:o.file,sourceComponent:r.component,targetComponent:o.component});if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let g=Bn(u,r),m=Bn(d,o);if(!g||!m)return null;let f=bp(p.callSitePath,m);if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let y=lr(c,g);if(!y)return null;if(lr(l,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child into a different repeat template"};if(a&&(s==="before"||s==="after")&&hp(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 R=pl(o,{kind:"native-tag",tag:r.tag});if(R)return{ok:!1,errorCode:"unsupported-operation",reason:R}}let E=kp(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(cl(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=HE(c,g,m,E);for(let R of b.conditionPaths){let F=Sp(R,m,y);if(!F.ok)return{ok:!1,errorCode:"unsupported-operation",reason:`Cannot move repeat-backed child because its condition depends on bindings outside the target scope: ${F.bindingNames.join(", ")}`}}let S=Ep(g,m,y,{preserveConditionalBoundary:b.conditionPaths.length>0});if(!S.ok)return{ok:!1,errorCode:"unsupported-operation",reason:S.reason??`Cannot move repeat-backed child because it depends on callback-local bindings: ${S.bindingNames.join(", ")}`};let I=kF({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:m});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};let w=JE(y);if(!w.ok)return{ok:!1,errorCode:"unsupported-operation",reason:w.reason};let C=KE(y,w.callbackParams),N=[{order:0,file:r.file,type:"remove-node",locator:nt(r),removeWhitespace:!0}];for(let R of I.imports)N.push({order:N.length,file:o.file,type:"add-import",moduleSpecifier:R.moduleSpecifier,imports:R.imports});return N.push({order:N.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:nt(o),expression:vp(C,b.sourceJsx),placement:s,anchorLocator:a?nt(a):void 0,selectionContext:Uo(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(ml(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,S=this.graph.getNode(b.anchorKey);if(!S||r.file!==S.file||r.component!==S.component)return{ok:!1,errorCode:"locator-miss",reason:"Source sibling move requires a sibling in the same component file"};let I=this.graph.getFileVersion(r.file);if(n.documentVersion!==I)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${I})`};let w=this.graph.getFileContent(r.file),C=jt(w),N=C?Bn(C,r):null,R=C?Bn(C,S):null,F=N?.parentPath,$=R?.parentPath;if(!N||!R||!F||!$||F.node!==$.node||!F.isJSXFragment()&&!(F.isJSXElement()&&ft(F)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let V=F.node.loc;return V?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:nt(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:V.start.line,startColumn:V.start.column,endLine:V.end.line,endColumn:V.end.column}},placement:b.relation,anchorLocator:nt(S),selectionContext:Uo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=YE(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(MF(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,S=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:S?.kind==="external-entry"?S.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,p=this.graph.getTextProvenance?.(r.key,0)??null,g=zs(r,c,p);if(g&&!_p(g)&&!XE(r,s,c,p))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,S=await this.graph.getTextWriteTarget(d.key,0);if(b?.kind==="value-binding"&&S?.kind==="value-binding"&&b.locator&&S.locator){let I=Hs(b.locator),w=Hs(S.locator);if(I&&w&&b.file===S.file&&UF(I.locator,w.locator)){let C=I.index,N=w.index,R=u==="before"?N-(C<N?1:0):N+(C<N?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:I.locator,fromIndex:C,toIndex:R}],o)}}}if(r.isRepeatItemRoot&&ki(this.graph.getFileContent(r.file),r))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed item outside its collection"};let m=this.getRepeatBackedTemplateStructureReason(r),f=_p(g)?g:m;if(f&&_p(f)){let b=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(b)return b;let S=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(S)return S;let I=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return I||{ok:!1,errorCode:"unsupported-operation",reason:f}}if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};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=pl(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=xp(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:nt(r),targetParentLocator:nt(s),placement:u,anchorLocator:d?nt(d):void 0,selectionContext:Uo(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=kp(this.graph,r)??`<${r.component} />`,p=uE(u,r);if(!p.allowed)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason??"Cannot move subtree across files"};if(c.push({order:l++,file:r.file,type:"remove-node",locator:nt(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,y={moduleSpecifier:Pp(o.file,r.importedFrom),imports:r.exportName==="default"?[{kind:"default",local:m}]:[{kind:"named",imported:r.exportName,local:m===r.exportName?void 0:m}]};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:nt(o),node:{jsx:d},placement:s,anchorLocator:a?nt(a):void 0,selectionContext:Uo(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:nt(o),node:{jsx:d},placement:s,anchorLocator:a?nt(a):void 0,selectionContext:Uo(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:je(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 qE(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 Bp from"@babel/generator";import{parse as oD,parseExpression as iD}from"@babel/parser";import*as k from"@babel/types";import*as ur from"@babel/types";import wp from"@babel/generator";import*as it from"@babel/types";var XF=typeof wp=="function"?wp:wp.default,zF=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,HF=/^((?:https?:)?\/\/)[^/@\s]+@/i,WF=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function rS(e,t){let n=Sn(e.callee);if(!n)return null;if(n==="fetch")return Op(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(nS(r))return Op(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(nS(r))return Op(e.arguments[0],r,t,["ky client contract"])}return null}function Op(e,t,n,r){if(!e||it.isSpreadElement(e)||it.isJSXNamespacedName(e))return qF(t,n,r,"missing url argument");let o=Ws(e);return{sourceKind:ZF(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 Ws(e){if(it.isStringLiteral(e))return Vo(e.value);if(it.isTemplateLiteral(e))return Vo(GF(e));if(it.isBinaryExpression(e)&&e.operator==="+"){let t=Ws(e.left),n=Ws(e.right);return!t&&!n?void 0:Vo(`${t??Lp(e.left)}${n??Lp(e.right)}`)}if(it.isMemberExpression(e)){let t=oS(e);if(t)return`env:${t}`}if(!(it.isCallExpression(e)&&Sn(e.callee)==="new URL")){if(it.isNewExpression(e)&&it.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!it.isSpreadElement(t)?Ws(t):void 0,o=n&&!it.isSpreadElement(n)?Ws(n):void 0;return o&&r?Vo(`${o} + ${r}`):r??o}if(it.isIdentifier(e))return`:${e.name}`}}function GF(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+=Lp(r))}return t}function Lp(e){if(it.isIdentifier(e))return`:${e.name}`;if(it.isMemberExpression(e)){let t=oS(e);if(t)return`env:${t}`}return`:${YF(e)}`}function YF(e){return XF(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Vo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(HF,"$1<redacted>@").replace(WF,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?zF.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function ZF(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 qF(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function nS(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function oS(e){return!it.isMemberExpression(e.object)||!it.isIdentifier(e.object.object,{name:"process"})||!QF(e.object.property,"env")?null:it.isIdentifier(e.property)?e.property.name:it.isStringLiteral(e.property)?e.property.value:null}function QF(e,t){return it.isIdentifier(e)&&e.name===t}function Sn(e){if(it.isIdentifier(e))return e.name;if(it.isMemberExpression(e)){let t=Sn(e.object),n=it.isIdentifier(e.property)?e.property.name:it.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var eD=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),tD=new Set(["getConfig","submit"]);function dr(e,t){let n=iS(Sn(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!eD.has(i))return null;let s=Fp(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(!tD.has(i))return null;let s=Fp(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=Fp(e,0)??nD(e,0,"path")??"/cms/:path",s=rD(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 iS(e,t){if(!e)return null;let n=e.indexOf("."),r=n<0?e:e.slice(0,n),o=n<0?"":e.slice(n),i=t.imports?.get(r);return i?i.importedName==="cms"&&/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/.test(i.source)?`cms${o}`:i.importedName==="collections"&&/^(?:src\/)?lib\/cms\/collections\.[cm]?[jt]s$/.test(i.source)?`cms.collections${o}`:!o&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(i.importedName)&&/^(?:src\/)?lib\/cms\/client\.[cm]?[jt]s$/.test(i.source)?i.importedName:null:null}function sS(e,t){let n=Sn(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 yl(e,t){let n=Sn(e.callee),r=t?iS(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function Fp(e,t){let n=e.arguments[t];return ur.isStringLiteral(n)?n.value:null}function nD(e,t,n){let r=e.arguments[t];if(!ur.isObjectExpression(r))return null;for(let o of r.properties)if(ur.isObjectProperty(o)&&!o.computed&&(ur.isIdentifier(o.key)&&o.key.name===n||ur.isStringLiteral(o.key)&&o.key.value===n)&&ur.isStringLiteral(o.value))return o.value.value;return null}function rD(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function xl(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as At from"@babel/types";var Dp=new WeakMap;function In(e,t){let n=Dp.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;At.isMemberExpression(u)||At.isOptionalMemberExpression(u);)u=u.object;return At.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,At.traverseFast(e,l=>{if(!At.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(At.getBindingIdentifiers(l.id)))r.has(d)||(r.add(d),i=!0)});let s=l=>{let u=o(l);return u?r.has(u):Object.keys(At.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;At.traverseFast(e,l=>{(At.isAssignmentExpression(l)&&s(l.left)||At.isUpdateExpression(l)&&s(l.argument)||At.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=Dp.get(e)??new Map;return c.set(t,a),Dp.set(e,c),a}function aS(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 p={fromFile:s,exportName:a,targetFile:c,maxImportDepth:l,pending:d},g=t.get(s)??new Map,m=g.get(a)??new Map,f=m.get(c)??new Map;return f.set(l,p),m.set(c,f),g.set(a,m),t.set(s,g),n.add(p),d.catch(()=>{r(p)}),d}}}import*as Zt from"@babel/types";import{posix as Mp}from"node:path";function Ri(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Zt.isBooleanLiteral(e))return e.value;if(Zt.isUnaryExpression(e,{operator:"!"})){let l=Ri(e.argument,t,r);return l===void 0?void 0:!l}if(Zt.isLogicalExpression(e)){let l=Ri(e.left,t,r),u=Ri(e.right,t,r);if(e.operator==="&&")return l===!1||u===!1?!1:l===!0?u:void 0;if(e.operator==="||")return l===!0||u===!0?!0:l===!1?u:void 0}if(!Zt.isCallExpression(e)||!Zt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Mp.normalize(Mp.join(Mp.dirname(t.file),o.source)):o?.source;if(o?.importedName==="isProductionBuildPhase"&&/(?:^|\/)lib\/cms\/build-sample(?:\.[jt]s)?$/.test(i??""))return!1;let s=t.functions.get(e.callee.name);if(!s||n.has(s))return;let a=Zt.isExpression(s.body)?s.body:s.body.body.length===1&&Zt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Zt.isExpression(a))return;let c=s.params.flatMap(l=>Zt.isIdentifier(l)?[l.name]:[]);return Ri(a,{file:t.file,imports:new Map([...t.imports].filter(([l])=>!c.includes(l))),functions:new Map([...t.functions].filter(([l])=>!c.includes(l)))},r.add(s))}var q2=typeof Bp=="function"?Bp:Bp.default,yS=new WeakMap;function xS(e){let t=new Map;return yS.set(t,new Map([...e].map(n=>[n.file,n]))),t}var sD={maxFunctionDepth:8,maxImportDepth:6},aD=new Set(["src","href","alt","poster","content","title","aria-label"]),cS=new WeakMap;function cD(e,t,n){let r=cS.get(t.fileCache);r||(r=new WeakMap,cS.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 p={element:d,order:u++};d.importedFrom&&d.exportName&&o.imported.push(p);let g=o.local.get(d.sourceFile);g||(g=new Map,o.local.set(d.sourceFile,g));let m=g.get(d.tag)??[];m.push(p),g.set(d.tag,m)}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 Pl(e){if(!e.element.textSegments.some(s=>s.source||s.value.includes("("))&&!(e.element.attributes??[]).some(s=>(s.source||s.syntaxKind==="expression"&&s.resolution?.status!=="resolved")&&uS(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=Kp(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...sD,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:OS(n,e.element.componentName),scopeFunction:Xp(n,e.element.componentName)};await bS(e.element.componentName,e.graph,r);let o=[];o.push(...await fD(e.element,e.graph,r),...await pD(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await mD(s,e.element,e.graph,r);a&&o.push(Cl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=uS(s,e.element);if(!a)continue;let c=await IS(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&Ko(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Nl(e.element.sourceRange))?.openingElement.attributes.find(d=>k.isJSXAttribute(d)&&k.isJSXIdentifier(d.name,{name:s.name}));k.isJSXExpressionContainer(u?.value)&&k.isExpression(u.value.expression)&&!kS(u.value.expression,e.element,e.graph)&&(c=await gt(u.value.expression,r))}c&&o.push(Cl(c,a,s.name))}let i=CD(o).sort(TS);return{hasDynamicData:i.length>0,bindings:i}}async function bS(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 cD(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 lD(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 SS(l.sourceFile,n);if(!d)continue;let p=ao(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=OS(d,l.componentName),p.scopeFunction=Xp(d,l.componentName),p.lexicalContext=void 0,await bS(l.componentName,t,p);let g=await uD(l,t,p);for(let[m,f]of g){if(!f)continue;let y=a.get(m)??[];y.push(f),a.set(m,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Jp(u);d.length===1&&c.set(l,d[0])}dD(o,c,n)}var lS=new WeakMap;function lD(e,t,n,r){let o=lS.get(r.fileCache);return o||(o=aS(),lS.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>ES(e,t,n,r))}async function ES(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 SS(e,r))?.imports.get(t);if(!s||!mt(s.source))return!1;let a=await Hp(e,s.source,r.exists);return a?a===n?!0:ES(a,s.importedName,n,r,o):!1}async function uD(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Nl(e.sourceRange));if(o)for(let s of o.openingElement.attributes)!k.isJSXAttribute(s)||!k.isJSXIdentifier(s.name)||!k.isJSXExpressionContainer(s.value)||!k.isExpression(s.value.expression)||r.set(s.name.name,s.value.expression);let i=new Map;for(let[s,a]of r){let c=e.attributes?.find(d=>d.name===s)?.source??null,u=(c?Ko(c.base,e,t):null)?await Al(c,e,t,n):kS(a,e,t)?null:await gt(a,n);u&&i.set(s,u)}return i}function Nl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function SS(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 Kp(e,r,t.fileCache)}function dD(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,_l(Object.fromEntries(t),n.file));return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=t.get(r.key.name);if(!o)continue;let i=k.isAssignmentPattern(r.value)?r.value.left:r.value;k.isIdentifier(i)&&n.paramSources.set(i.name,Vt(o))}}function uS(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":aD.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function fD(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 Tl(i.collectionSource,n);s&&r.push(Cl(oo(s),"repeat-region",i.collectionExpression))}return r}async function pD(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 Tl(i.conditionSource,n);s&&r.push(Cl(oo(s),"conditional-region",i.conditionExpression))}return r}async function mD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Nl(t.sourceRange))?.children.find(s=>k.isJSXExpressionContainer(s)&&s.loc?.start.line===e.sourceRange.startLine&&s.loc.start.column===e.sourceRange.startColumn&&s.loc.end.line===e.sourceRange.endLine&&s.loc.end.column===e.sourceRange.endColumn);return k.isJSXExpressionContainer(i)&&k.isCallExpression(i.expression)&&yl(i.expression)?vS(i.expression,t,n,r):null}return IS(e.source,t,n,r)}async function IS(e,t,n,r){return e&&Ko(e.base,t,n)?Al(e,t,n,r):Tl(e,r)}async function Al(e,t,n,r,o){if(!e)return null;let i=Ko(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?Ko(s.base,t,n,i.region):null)?await Al(s,t,n,r,i.region):s?await Tl(s,r):await gD(i.candidate.collectionExpression,t,n,r,i.region);return c?Gs(c,e.path,!0):null}async function gD(e,t,n,r,o){let i;try{i=iD(e,{plugins:["typescript","jsx"]})}catch{return null}return vS(i,t,n,r,o)}async function vS(e,t,n,r,o){let i=ao(r.analysis,r),s=new Set;k.traverseFast(e,a=>{k.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=Ko(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await Al({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return gt(e,i)}function Ko(e,t,n,r){let o=t.identity.key,i=null;for(;o;){for(let s of n.regions){if(s.kind!=="repeat-region"||!s.childKeys.includes(o)||r&&!dS(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||dS(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function dS(e,t){let n=e.startLine-t.startLine||e.startColumn-t.startColumn,r=e.endLine-t.endLine||e.endColumn-t.endColumn;return n<=0&&r>=0&&(n<0||r>0)}function kS(e,t,n){let r=!1;return k.traverseFast(e,o=>{!r&&k.isIdentifier(o)&&Ko(o.name,t,n)&&(r=!0)}),r}async function Tl(e,t){if(!e)return null;let n=await Up(e.base,t);return n?Gs(n,e.path,!1):null}async function Up(e,t){let n=t.paramSources.get(e);if(n)return Vt(n);if(t.variableCache.has(e))return RD(t.variableCache.get(e)??null);let r=so(e,t);if(r&&r!==t)return Up(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await yD(e,t);if(o)return t.variableCache.set(e,Vt(o)),t.resolvingVariables.delete(e),o;let i=t.scopeVariables?.has(e),s=i?t.scopeVariables.get(e):r?null:t.analysis.variables.get(e);if(s){let c=k.isArrayExpression(s)&&s.elements.length===0?await hD(e,t):await gt(s,t);return t.variableCache.set(e,c?Vt(c):null),t.resolvingVariables.delete(e),c}if(i||r)return t.resolvingVariables.delete(e),t.variableCache.set(e,null),null;let a=t.analysis.imports.get(e);if(a&&t.importDepth<t.options.maxImportDepth){let c=await zp(a,t);if(c){let l=ao(c,t,{importDepth:t.importDepth+1}),u=LS(a,c);if(u){let g=(await Jo(u,[],l)).returnSource;return t.variableCache.set(e,g?Vt(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let p=await gt(d,l);return t.variableCache.set(e,p?Vt(p):null),t.resolvingVariables.delete(e),p}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function so(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>io(n).includes(e))?t:t.lexicalContext?so(e,t.lexicalContext):void 0}function bl(e,t,n=new Set){if(k.isIdentifier(e)){let s=so(e.name,t);if(s&&s!==t)return bl(e,s,n)}if(n.has(e))return null;if(n.add(e),k.isStringLiteral(e))return e.value;if(!k.isIdentifier(e))return null;let r=so(e.name,t),o=t.paramArguments.get(e.name);if(o)return bl(o.expression,o.context,n);let i=t.scopeVariables?.has(e.name)?t.scopeVariables.get(e.name):r?null:t.analysis.variables.get(e.name);return i?bl(i,t,n):null}function fr(e,t,n=new Set){if(n.has(e))return null;let r=new Set(n).add(e);if(k.isStringLiteral(e))return e.value;if(k.isNumericLiteral(e))return String(e.value);if(k.isIdentifier(e)){if(/token|secret|password|authorization|cookie|credential/i.test(e.name))return":redacted";let o=so(e.name,t),i=o??t,s=i.paramArguments.get(e.name),a=i.scopeVariables?.has(e.name)?i.scopeVariables.get(e.name):o?null:i.analysis.variables.get(e.name);return(s?fr(s.expression,s.context,r):a?fr(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=fr(e.left,t,r),i=fr(e.right,t,r);return o!==null&&i!==null?o+i:null}if(k.isTemplateLiteral(e)){let o=e.quasis[0]?.value.cooked??"";for(let[i,s]of e.expressions.entries()){if(!k.isExpression(s))return null;o+=(fr(s,t,r)??":param")+(e.quasis[i+1]?.value.cooked??"")}return o}if(k.isCallExpression(e)&&k.isIdentifier(e.callee)&&["encodeURIComponent","decodeURIComponent"].includes(e.callee.name)&&k.isExpression(e.arguments[0])){let o=fr(e.arguments[0],t,r);if(o===null||o.startsWith(":"))return o;try{return e.callee.name==="encodeURIComponent"?encodeURIComponent(o):decodeURIComponent(o)}catch{return null}}return k.isTSAsExpression(e)||k.isTSNonNullExpression(e)||k.isParenthesizedExpression(e)?fr(e.expression,t,r):null}async function hD(e,t){let n=t.scopeFunction;if(!n)return null;let r=[],o=!1,i=0,s=u=>{let d=!1;return k.traverseFast(u,p=>{k.isIdentifier(p,{name:e})&&(d=!0)}),d},a=u=>{let d=u;for(;k.isMemberExpression(d);)d=d.object;return k.isIdentifier(d,{name:e})},c=async(u,d)=>{if(!o){if(k.isFunction(u)){s(u)&&(o=!0);return}if(k.isVariableDeclarator(u)&&(io(u.id).includes(e)&&i++,u.init&&s(u.init)&&(o=!0)),(k.isAssignmentExpression(u)||k.isUpdateExpression(u))&&a(k.isAssignmentExpression(u)?u.left:u.argument)){o=!0;return}if(k.isUnaryExpression(u,{operator:"delete"})&&a(u.argument)){o=!0;return}if(k.isCallExpression(u)){if(k.isMemberExpression(u.callee)&&k.isIdentifier(u.callee.object,{name:e})){if(!k.isIdentifier(u.callee.property,{name:"push"})||u.callee.computed||!u.arguments.length){o=!0;return}for(let p of u.arguments){let g=k.isSpreadElement(p)?p.argument:p,m=k.isExpression(g)?await gt(g,d):null;m?r.push($p(m)):o=!0}return}if(u.arguments.some(p=>s(p))){o=!0;return}}if(k.isForOfStatement(u)){let p=await gt(u.right,d),g=ao(d.analysis,d),m=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;p&&m&&vl(m,$p(p),g),await c(u.body,g);return}for(let p of k.VISITOR_KEYS[u.type]??[]){let g=u[p];for(let m of Array.isArray(g)?g:[g])k.isNode(m)&&await c(m,d)}}};await c(n.body,t);let l=Jp(r);return!o&&i===1&&l.length===1?oo(l[0]):null}async function yD(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 gt(o,t);if(i)return i}return null}async function gt(e,t){if(k.isIdentifier(e))return Up(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?sS(e,{file:t.file}):null;if(n)return NS(n);let r=await xD(e,t);if(!r)return null;let o=_D(e);return Gs(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?gt(e.argument,t):null;if((k.isCallExpression(e)||k.isOptionalCallExpression(e))&&(k.isMemberExpression(e.callee)||k.isOptionalMemberExpression(e.callee))&&!e.callee.computed&&k.isIdentifier(e.callee.property)&&["trim","trimStart","trimEnd"].includes(e.callee.property.name)&&e.arguments.length===0&&k.isExpression(e.callee.object))return Ni(await gt(e.callee.object,t));if(k.isCallExpression(e))return CS(e,t);if(k.isObjectExpression(e)){let n=await PS(e,t);return Object.keys(n).length>0?_l(n,t.file):null}if(k.isArrayExpression(e)){let n={};for(let[r,o]of e.elements.entries()){if(!k.isExpression(o))continue;let i=await gt(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?_l(n,t.file):null}if(k.isConditionalExpression(e)){let n=await gt(e.consequent,t),r=await gt(e.alternate,t);return Ni(mS(n,r))}if(k.isLogicalExpression(e)){let n=await gt(e.left,t),r=await gt(e.right,t);return Ni(mS(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?gt(e.expression,t):null}async function xD(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?gt(n,t):null}async function _S(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=so(e,t);if(r){if(r.scopeFunction&&In(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&k.isIdentifier(s.expression)?_S(s.expression.name,s.context,n+1):null}let o=t.analysis.imports.get(e);if(!o||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(o.importedName)||In(t.analysis.ast,e))return null;let i=await Hp(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function CS(e,t){let n=e.arguments[0],r=k.isExpression(n)?bl(n,t):null,i=Sn(e.callee)?.split(".")[0],s=i?await _S(i,t):null,a=r!==null&&!k.isStringLiteral(n)?{...e,arguments:[k.stringLiteral(r),...e.arguments.slice(1)]}:e;if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&k.isObjectExpression(n)){let x=RS(n,"path"),E=x&&fr(x,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>k.isObjectProperty(b)&&Ti(b)==="path"?{...b,value:k.stringLiteral(Vo(E))}:b)},...e.arguments.slice(1)]})}let c=dr(a,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map});if(c){if(s&&["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(s.importedName)&&c.endpointPattern==="/content/by-url"&&k.isObjectExpression(n)){let x=fS(n,"query"),E=k.isObjectExpression(x)?fS(x,"path"):null,b=E&&fr(E,t),S=b&&xl(b);S&&(c.collection=S,c.evidence.push({file:t.file,reason:"CMS collection namespace from the actual content request path"}))}if(k.isMemberExpression(e.callee)){let x=await Ar(e.callee,t);if(x&&!El(x.node))return null;if(x&&El(x.node)){let E=await jp(e,t,{node:x.node,context:x.context});return E&&{...E,...E.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&k.isExpression(n)){let x=fr(n,t);x?.startsWith("/")&&(c.endpointPattern=Vo(x))}return NS(c)}if(Sn(e.callee)==="Promise.all"&&k.isArrayExpression(n))return gt(n,t);if(yl(e)){if(!yl(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!k.isExpression(e.callee))return null;let x=await Ar(e.callee,t);if(x)return El(x.node)?jp(e,t,{node:x.node,context:x.context}):null;let E=e.arguments[0];if(E&&k.isExpression(E))return Ni(await gt(E,t))}let l=await bD(e,t);if(l)return l;let u=rS(e,{file:t.file});if(u)return{sourceKind:u.sourceKind,sourceType:"api-field",endpointPattern:u.endpointPattern,valuePath:u.valuePath,confidence:u.confidence,readonly:!0,evidence:u.evidence};let d=await SD(e,t);if(d)return d;let p=await ID(e,t);if(p)return p;let g=await vD(e,t);if(g)return g;let m=await jp(e,t);if(m)return m;let f=[];for(let x of e.arguments)if(k.isExpression(x)){let E=await gt(x,t);E&&f.push(E)}let y=Jp(f);return y.length===1?Ni(y[0]):null}async function bD(e,t){let n=Sn(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=ED(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await Ai(s.name,t);if(a)return(await Jo(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return Sl(t.file,`${n} without static options`);let o=RS(r,"queryFn");if(!o)return Sl(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await Ai(o.name,t);return i?(await Jo(i.node,[],i.context)).returnSource:Sl(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Jo(o,[],t)).returnSource:k.isCallExpression(o)?CS(o,t):null}function RS(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Ti(n)===t)return n.value}return null}function fS(e,t){let n=new Set;for(let i of e.properties){if(!k.isObjectProperty(i)||i.computed)return null;let s=Ti(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>k.isObjectProperty(i)&&Ti(i)===t);if(r.length!==1)return null;let o=r[0];return k.isObjectProperty(o)&&k.isExpression(o.value)?o.value:null}function ED(e,t,n){return k.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 SD(e,t){if(!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property))return null;let n=e.callee.property.name;if(!["map","filter","slice","sort","toSorted","reverse","toReversed"].includes(n))return null;let r=k.isExpression(e.callee.object)?await gt(e.callee.object,t):null;if(!r)return null;if(n!=="map")return oo(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await Ai(o.name,t);if(!i)return oo(r);let s=await Jo(i.node,[r],i.context);return{...oo(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Jo(o,[r],t);return{...oo(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return oo(r)}async function ID(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:gt(e.callee.object,t)}async function vD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:Ni(await gt(e.callee.object,t))}async function jp(e,t,n){let r=n;if(!r&&k.isIdentifier(e.callee))r=await Ai(e.callee.name,t)??void 0;else if(!r&&k.isMemberExpression(e.callee)){let s=await Ar(e.callee,t);s&&El(s.node)&&(r={node:s.node,context:s.context})}if(!r)return null;let o=[];for(let s of e.arguments){if(!k.isExpression(s)){o.push(Sl(t.file,`unsupported argument for ${Sn(e.callee)??"call"}`));continue}let a=await gt(s,t);o.push(a)}return(await Jo(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function El(e){return k.isFunctionDeclaration(e)||Rl(e)||k.isObjectMethod(e)&&e.kind==="method"}async function Ar(e,t,n=new Set){let r={node:null,context:t};if(n.has(e)||n.size>=32)return r;let o=new Set(n).add(e);if(k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e))return Ar(e.expression,t,o);if(k.isIdentifier(e)){let i=so(e.name,t),s=i??t;if(In(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Ar(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Ar(c,s,o);if(i)return null;let l=s.analysis.functions.get(e.name);if(l)return{node:l,context:s};let u=s.analysis.imports.get(e.name);if(!u||s.importDepth>=s.options.maxImportDepth)return null;let d=await zp(u,s);return d?Ar(k.identifier(u.importedName),ao(d,s,{importDepth:s.importDepth+1}),o):null}if(k.isMemberExpression(e)&&k.isExpression(e.object)){let i=e.computed?k.isStringLiteral(e.property)?e.property.value:null:k.isIdentifier(e.property)?e.property.name:null;if(!i)return null;let s=await Ar(e.object,t,o);if(!s)return null;if(!k.isObjectExpression(s.node))return{node:null,context:s.context};if(s.node.properties.some(l=>k.isSpreadElement(l)||l.computed))return{node:null,context:s.context};let a=s.node.properties.filter(l=>(k.isObjectMethod(l)||k.isObjectProperty(l))&&(k.isIdentifier(l.key)?l.key.name:k.isStringLiteral(l.key)?l.key.value:null)===i);if(a.length===0)return null;if(a.length!==1)return{node:null,context:s.context};let c=a[0];return k.isObjectMethod(c)?c.kind==="method"?{node:c,context:s.context}:null:k.isObjectProperty(c)&&k.isExpression(c.value)?Ar(c.value,s.context,o):null}return{node:e,context:t}}async function Ai(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Rl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return Ai(r.expression.name,r.context,n)}let o=t.analysis.functions.get(e);if(o)return{node:o,context:t};let i=t.analysis.imports.get(e);if(!i||t.importDepth>=t.options.maxImportDepth)return null;let s=await zp(i,t);if(!s)return null;let a=ao(s,t,{importDepth:t.importDepth+1}),c=LS(i,s);return c?{node:c,context:a}:Ai(i.importedName,a)}async function Jo(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=ao(n.analysis,n,{functionDepth:n.functionDepth+1}),i=n.analysis.functionParents.get(e),s=n;for(;s&&(s.analysis!==n.analysis||s.scopeFunction!==i);)s=s.lexicalContext;o.lexicalContext=s,o.paramSources=new Map,o.paramArguments=new Map,o.scopeVariables=n.analysis.functionVariables.get(e),o.scopeFunction=e,e.params.forEach((d,p)=>{for(let y of io(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=k.isAssignmentPattern(d)?d.left:d,m=r?.arguments[p];k.isIdentifier(g)&&k.isExpression(m)&&r&&o.paramArguments.set(g.name,{expression:m,context:r.context});let f=t[p];f&&vl(d,$p(f),o)});let a=kD(e,o),c=null,l,u=!1;for(let d of a){let p=ao(n.analysis,o);if(k.isObjectExpression(d)){l={...l??{},...await PS(d,p)},c=c??_l(l,n.file);continue}let g=await gt(d,p);if(g){if(!c){c=g;continue}let m=Vp(c,g);if(!m){u=!0,c=null;continue}c=m}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function vl(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Vt(t));return}if(k.isAssignmentPattern(e)){vl(e.left,t,n);return}if(k.isObjectPattern(e))for(let r of e.properties){if(!k.isObjectProperty(r)||r.computed||!k.isIdentifier(r.key))continue;let o=Gs(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&vl(i,o,n)}}function kD(e,t){if(k.isArrowFunctionExpression(e)&&k.isExpression(e.body))return[e.body];let n=[],r=e.body;if(!k.isBlockStatement(r))return n;let o=i=>{if(k.isFunction(i)&&i!==e)return;if(k.isReturnStatement(i)){i.argument&&k.isExpression(i.argument)&&n.push(i.argument);return}if(k.isIfStatement(i)){let a=Ri(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!so(c,t))),functions:t.analysis.functions});if(a!==void 0){a?o(i.consequent):i.alternate&&o(i.alternate);return}}let s=k.VISITOR_KEYS[i.type];for(let a of s??[]){let c=i[a];if(Array.isArray(c))for(let l of c)k.isNode(l)&&o(l);else k.isNode(c)&&o(c)}};return o(r),n}async function PS(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Ti(r);if(!o||!k.isExpression(r.value))continue;let i=await gt(r.value,t);i&&(n[o]=i)}return n}function Ti(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function _D(e){let t=[],n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);){let r=n.property;n.computed?k.isStringLiteral(r)?t.unshift({kind:"property",name:r.value}):k.isNumericLiteral(r)&&t.unshift({kind:"index",index:r.value}):k.isIdentifier(r)&&t.unshift({kind:"property",name:r.name}),n=n.object}return k.isIdentifier(n),t}function Gs(e,t,n){if(t.length===0)return Vt(e);let r=t[0],o=r?.kind==="property"?r.name:r?String(r.index):null;if(e.fieldMap&&o!==null){let s=e.fieldMap[o];return s?Gs(s,t.slice(1),n):null}let i=Vt(e);if(i.sourceType==="cms-field"){let s=t.filter(c=>c.kind==="property").map(c=>c.name);if(s[0]==="data"&&s[1]==="items")return i.valuePath=Pi(i.valuePath,"data.items[]"),i.cmsFieldRoot=!1,i;let a=s[0]==="fields"?0:s[0]==="data"&&s[1]==="fields"?1:-1;return a>=0?(a===1&&(i.valuePath=Pi(i.valuePath,"data")),i.fieldPath=Pi(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Pi(i.fieldPath,s.join(".")),i):(i.valuePath=Pi(i.valuePath,pS(t)),i)}return i.valuePath=Pi(i.valuePath,pS(t)),i}function pS(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Pi(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function NS(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 oo(e){let t=Vt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function $p(e){let t=Vt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Ni(e){return e?{...Vt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function mS(e,t){return e?t?Vp(e,t):Vt(e):t?Vt(t):null}function Vp(e,t){if(kl(e)!==kl(t))return null;let n=wS(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Jp(e){let t=new Map;for(let n of e){let r=kl(n),o=t.get(r);t.set(r,o?Vp(o,n):Vt(n))}return[...t.values()]}function kl(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,kl(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 _l(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 Sl(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Cl(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 AS(e){let t=[...e].sort(TS),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 CD(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 TS(e,t){return gS(e.targetKind)-gS(t.targetKind)||wS(e.confidence,t.confidence)||hS(e.sourceKind)-hS(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function gS(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function hS(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function wS(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Kp(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=yS.get(n)?.get(e),i=o?.source===t?o.ast:oD(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,functionParents:new WeakMap},a=[],c=[];k.traverse(i,{enter(d){switch(k.isFunction(d)&&(s.functionParents.set(d,a.at(-1)??null),a.push(d)),d.type){case"CallExpression":c.push(d);break;case"JSXElement":{let p=d.loc;if(!p)return;let g=Nl({startLine:p.start.line,startColumn:p.start.column,endLine:p.end.line,endColumn:p.end.column});s.jsxElementsByRange.has(g)||s.jsxElementsByRange.set(g,d);break}case"ImportDeclaration":{let p=d.source.value;for(let g of d.specifiers)k.isImportSpecifier(g)&&k.isIdentifier(g.local)?s.imports.set(g.local.name,{source:p,importedName:k.isIdentifier(g.imported)?g.imported.name:g.imported.value,localName:g.local.name,isDefault:!1}):k.isImportDefaultSpecifier(g)&&s.imports.set(g.local.name,{source:p,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 p=a.at(-1),g=p&&(k.isFunctionDeclaration(p)||k.isFunctionExpression(p)||k.isArrowFunctionExpression(p)||k.isObjectMethod(p))?p:null,m=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,m);for(let[f,y]of Il(d.id,k.isExpression(d.init)?d.init:null))m.set(f,y);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&Sn(d.init.callee)==="useState"){let[f,y]=d.id.elements;k.isIdentifier(f)&&k.isIdentifier(y)&&s.stateSetters.set(f.name,y.name)}k.isIdentifier(d.id)&&Rl(d.init)&&s.functions.set(d.id.name,d.init);break}case"ExportNamedDeclaration":{let p=d.declaration,g=d.source?.value;if(g)for(let m of d.specifiers){if(!k.isExportSpecifier(m))continue;let f=k.isIdentifier(m.exported)?m.exported.name:m.exported.value,y=m.local.name;s.imports.set(f,{source:g,importedName:y,localName:f,isDefault:y==="default"})}if(k.isFunctionDeclaration(p)&&p.id?.name&&s.functions.set(p.id.name,p),k.isVariableDeclaration(p))for(let m of p.declarations)k.isIdentifier(m.id)&&Rl(m.init)&&s.functions.set(m.id.name,m.init);break}case"ExportDefaultDeclaration":{let p=d.declaration;if((k.isFunctionDeclaration(p)||k.isFunctionExpression(p)||k.isArrowFunctionExpression(p))&&s.functions.set("default",p),k.isIdentifier(p)){let g=s.functions.get(p.name);g&&s.functions.set("default",g)}break}}},exit(d){k.isFunction(d)&&a.pop()}});let l=new Set(s.stateSetters.values()),u=(d,p)=>{let g=s.stateSetterCandidates.get(d)??[];g.push(p),s.stateSetterCandidates.set(d,g)};if(l.size>0)for(let d of c){let p=k.isIdentifier(d.callee)?d.callee.name:null;p&&l.has(p)&&k.isExpression(d.arguments[0])&&u(p,d.arguments[0]);let g=new Set;for(let m of d.arguments)k.isIdentifier(m)&&m.name!==p&&l.has(m.name)&&g.add(m.name);for(let m of g)u(m,d)}return n.set(e,s),s}function Il(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?Il(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?Il(n,t?k.memberExpression(t,k.numericLiteral(r),!0):null):[]):k.isObjectPattern(e)?e.properties.flatMap(n=>{if(!k.isObjectProperty(n)||n.computed)return[];let r=Ti(n);return r?Il(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function io(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?io(t.value):io(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?io(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?io(e.left):k.isRestElement(e)?io(e.argument):[]}function Rl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function OS(e,t){let n=Xp(e,t);return n?e.functionVariables.get(n):void 0}function Xp(e,t){return e.functions.get(t)??e.functions.get("default")}async function zp(e,t){let n=await Hp(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Kp(n,r,t.fileCache)}function LS(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Hp(e,t,n){return mt(t)?Io(e,t,n):null}function ao(e,t,n={}){return{file:e.file,analysis:e,readFile:t.readFile,exists:t.exists,fileCache:t.fileCache,options:t.options,variableCache:new Map,functionDepth:n.functionDepth??t.functionDepth,importDepth:n.importDepth??t.importDepth,paramSources:new Map(t.paramSources),paramArguments:e===t.analysis?new Map(t.paramArguments):new Map,resolvingVariables:new Set,resolvingComponentProps:t.resolvingComponentProps,scopeVariables:e===t.analysis?t.scopeVariables:void 0,scopeFunction:e===t.analysis?t.scopeFunction:void 0,lexicalContext:e===t.analysis?t.lexicalContext:void 0}}function RD(e){return e?Vt(e):null}function Vt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Vt(n)]))}:{}}}import*as Gp from"@babel/parser";import Wp from"@babel/traverse";import*as Se from"@babel/types";import{classifySiteEditPropertyName as PD}from"@vcp-dev/contracts";var Yp=typeof Wp=="function"?Wp:Wp.default;function Zp(e){let t=PD(e.propertyName);if(t.owner!=="generic")return vn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return vn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return vn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return vn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Gp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return vn("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=ND(r,e.element.sourceRange);if(!o)return vn("repeat-not-found","The selected element is not inside a supported map repeat");if(!Se.isIdentifier(o.callback.params[0]))return vn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=AD(r,o.collection,e.file,e.sources);if(!i)return vn("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||!Se.isObjectExpression(x)||!$S(x))return vn("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 vn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let p=n.instanceIndex;if(p>=d)return vn("index-out-of-range",`Selected repeat instance ${p} is outside the source collection`);let g=s.elements[p];if(!g||!Se.isObjectExpression(g))return vn("unsafe-collection","Selected repeat item is not an object");let m=DD(e.element,e.propertyName),f=LD(g,e.propertyName);return f?{ok:!0,sourceFile:c,templateFile:e.file,collectionLocator:a,parentObjectLocators:u,selectedParentObjectLocator:u[p],sourceItemIndex:p,sourceItemPath:l[p],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:f,selectedResolution:FD(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:vn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function ND(e,t){let n=[];return Yp(e,{CallExpression(r){let o=FS(r.node);o&&MS(o.callback,t)&&n.push({...o,span:DS(r.node)})},OptionalCallExpression(r){let o=FS(r.node);o&&MS(o.callback,t)&&n.push({...o,span:DS(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function FS(e){let t=e.callee;if(!Se.isMemberExpression(t)&&!Se.isOptionalMemberExpression(t)||t.computed||!Se.isIdentifier(t.property)||t.property.name!=="map"||!Se.isExpression(t.object))return null;let n=e.arguments[0];return!n||!Se.isExpression(n)||!Se.isArrowFunctionExpression(n)&&!Se.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function AD(e,t,n,r){let o=Ys(t);if(o&&Se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:VS(o)}},sourceFile:n};if(!Se.isIdentifier(t))return null;let i=[];if(Yp(e,{VariableDeclarator(s){Se.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Ys(i[0].init);return!s||!Se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return TD(e,t.name,n,r)}function TD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!Se.isImportDeclaration(o))continue;let i=o.specifiers.find(p=>p.local.name===t);if(!i||!Se.isStringLiteral(o.source)||!Se.isImportSpecifier(i))continue;let s=OD(n,o.source.value,r);if(!s)return null;let a=Se.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Gp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=wD(l,a),d=u?Ys(u):null;return!d||!Se.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function wD(e,t){let n=null;return Yp(e,{VariableDeclarator(r){n||!Se.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!Se.isExpression(r.node.init)||(n=r.node.init)}}),n}function OD(e,t,n){let r=Qn(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 Ys(e){return Se.isParenthesizedExpression(e)?Ys(e.expression):Se.isTSAsExpression(e)?jS(e.typeAnnotation)?Ys(e.expression):null:Se.isTSSatisfiesExpression(e)?null:e}function jS(e){return Se.isTSTypeReference(e)&&Se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function $S(e){return e.properties.every(t=>!Se.isObjectProperty(t)||t.computed||!Se.isExpression(t.value)?!1:wl(t.value))}function wl(e){if(Se.isTSAsExpression(e)&&jS(e.typeAnnotation))return wl(e.expression);if(Se.isTSSatisfiesExpression(e))return!1;if(Se.isArrayExpression(e))return e.elements.every(n=>!n||Se.isSpreadElement(n)||!Se.isExpression(n)?!1:wl(n));if(Se.isObjectExpression(e))return $S(e);let t=or(e);return t.status==="resolved"||t.status==="undefined"}function LD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&US(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Se.isExpression(r.value)?wl(r.value)?"static":Se.isIdentifier(r.value)||Se.isMemberExpression(r.value)?"binding":null:null:"missing"}function FD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&US(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Se.isExpression(r.value)?{status:"undefined"}:or(r.value)}function DD(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function US(e){return Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)?e.value:Se.isNumericLiteral(e)?String(e.value):null}function VS(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 DS(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function MS(e,t){let n=VS(e);return BS(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&BS(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function BS(e,t,n,r){return e===n?t-r:e-n}function vn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as EM}from"@vcp-dev/contracts";import*as ke from"@babel/types";import ta from"node:path";import*as ae from"@babel/types";import*as WS from"@babel/parser";import qp from"@babel/traverse";import*as Ne from"@babel/types";function Ll(e,t){let n=[],r=e;for(;Ne.isMemberExpression(r);){if(r.computed)if(Ne.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Ne.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Ne.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Ne.isIdentifier(r)||r.name!==t?null:n}function JS(e){if(Ne.isIdentifier(e))return{base:e.name,path:[]};if(!Ne.isMemberExpression(e))return null;let t=[],n=e;for(;Ne.isMemberExpression(n);){if(n.computed)if(Ne.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ne.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Ne.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Ne.isIdentifier(n)?{base:n.name,path:t}:null}function qt(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 pr=Symbol("not-closed-literal");function Ol(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:pr;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Ol(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Ne.isSpreadElement(n))return pr;let r=Ol(n);if(r===pr)return pr;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Ne.isObjectProperty(n)||n.computed||n.shorthand||!Ne.isExpression(n.value))return pr;let r=Ne.isIdentifier(n.key)?n.key.name:Ne.isStringLiteral(n.key)?n.key.value:null;if(!r)return pr;let o=Ol(n.value);if(o===pr)return pr;t[r]=o}return t}default:return pr}}function KS(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let p=Ol(i);if(p!==pr)return p;if(!Ne.isTemplateLiteral(i)){if(Ne.isTSAsExpression(i)||Ne.isTSSatisfiesExpression(i)||Ne.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(Ne.isIdentifier(i)){let g=s.getBinding(i.name);if(!g)return;let m=await t({currentFile:a,binding:g,readFile:c,exists:l,fileCache:u,visited:d});return m?.kind==="static"?m.value:void 0}if(Ne.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||Ne.isSpreadElement(m))return;let f=await r(m,s,a,c,l,u,d);if(f===void 0)return;g.push(f)}return g}if(Ne.isObjectExpression(i)){let g={};for(let m of i.properties){if(!Ne.isObjectProperty(m)||m.computed)return;let f=null;if(Ne.isIdentifier(m.key)?f=m.key.name:Ne.isStringLiteral(m.key)&&(f=m.key.value),!f)return;if(m.shorthand){if(!Ne.isIdentifier(m.value))return;let x=await r(m.value,s,a,c,l,u,d);if(x===void 0)return;g[f]=x;continue}if(!Ne.isExpression(m.value))return;let y=await r(m.value,s,a,c,l,u,d);y!==void 0&&(g[f]=y)}return g}if(Ne.isMemberExpression(i)){let g=await o(i,s,a,c,l,u,d);if(!g)return;let m=s.getBinding(g.base);if(!m)return;let f=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:d});return!f||f.kind!=="static"?void 0:qt(f.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!Ne.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(Ne.isIdentifier(i))return{base:i.name,path:[]};if(!Ne.isMemberExpression(i))return null;let p=[],g=i;for(;Ne.isMemberExpression(g);){if(g.computed){let m=g.property;if(Ne.isNumericLiteral(m))p.unshift({kind:"index",index:m.value});else if(Ne.isStringLiteral(m))p.unshift({kind:"property",name:m.value});else{let f=Ne.isExpression(m)?await n(m,s,a,c,l,u,d):void 0;if(typeof f=="string")p.unshift({kind:"property",name:f});else if(Number.isInteger(f))p.unshift({kind:"index",index:f});else return null}}else{if(!Ne.isIdentifier(g.property))return null;p.unshift({kind:"property",name:g.property.name})}g=g.object}return Ne.isIdentifier(g)?{base:g.name,path:p}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var GS=typeof qp=="function"?qp:qp.default,XS=new WeakMap;function YS(e){try{return WS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Fl(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=YS(n);return e.set(t,{source:n,ast:o}),o}function Dl(e,t){return Qp(Zs(e).expressionRanges,t,!1)}function ZS(e,t){return Zs(e).exactExpressions.get(qS(t))??null}function Ml(e,t){return Qp(Zs(e).jsxRanges,t,!0)}function Zs(e){let t=XS.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return GS(e,{Expression(r){let o=r;n.expressions.push(o);let i=zS(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=qS(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=zS(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(HS),n.jsxRanges.sort(HS),XS.set(e,n),n}function zS(e,t){let n=qs(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function qS(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function HS(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Qp(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 qs(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 wi(e,t){if(t)return em(e,t);let n=JS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function em(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Qs(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Zs(e).expressions){if(em(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function QS(e,t,n,r){return Qp(Zs(e).expressionRanges,r,!0,o=>em(o.node,t)===n)}function Oi(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function ea(e){let t=null;if(GS(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Wn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=YS(o),s={source:o,ast:i};return n.set(e,s),s}function MD(e){return ae.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:ae.isMemberExpression(e.callee)&&ae.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function BD(e){if(!ae.isNewExpression(e)||!ae.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!ae.isIdentifier(e.arguments[0])||!ae.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!ae.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!ae.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(ae.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(ae.isIfStatement(i)&&ae.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=ae.isIfStatement(i)?i.test:null,c=a&&ae.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=ae.isIfStatement(i)?ae.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=ae.isReturnStatement(s)?s.argument:null;return!a||!ae.isLogicalExpression(a,{operator:"&&"})||!ae.isBinaryExpression(a.left,{operator:"==="})||!ae.isUnaryExpression(a.left.left,{operator:"typeof"})||!ae.isIdentifier(a.left.left.argument,{name:r.name})||!ae.isStringLiteral(a.left.right,{value:"string"})||!ae.isUnaryExpression(c,{operator:"!"})||!ae.isBinaryExpression(c.argument,{operator:"in"})||!ae.isIdentifier(c.argument.left,{name:r.name})||!ae.isIdentifier(c.argument.right,{name:n.name})||!ae.isReturnStatement(l)||!ae.isIfStatement(i)||i.alternate||!ae.isCallExpression(u)||!ae.isMemberExpression(u.callee)||!ae.isIdentifier(u.callee.object,{name:"Reflect"})||!ae.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!ae.isIdentifier(u.arguments[0],{name:n.name})||!ae.isIdentifier(u.arguments[1],{name:r.name})||!ae.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function jD(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()||!ae.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 eI(e,t){let n=jD(e.path);if(!n)return null;let r=xi(e,t);return r?{...n,...r}:null}function tI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function tm(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 nm(e,t){for(let n of e.program.body){if(t==="default"&&ae.isExportDefaultDeclaration(n))return ae.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(ae.isExportNamedDeclaration(n)){if(n.declaration){if(ae.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(ae.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((ae.isFunctionDeclaration(n.declaration)||ae.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((ae.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&ae.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 nI(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(f){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:I}=f,w=`${y}::${x.kind}::${x.identifier.name}`;if(I.has(w))return null;I.add(w);try{let C=await a({currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:I});if(C)return C;if(x.path.isImportSpecifier()||x.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:x,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,fileCache:S,visited:I});if(x.kind==="param")return null;if(x.path.isVariableDeclarator()){let N=x.path.node.init;if(!N||!ae.isExpression(N))return null;let R=BD(N);if(R&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let V=x.path.scope.getBinding(R),U=V?await s({...f,binding:V}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let F=x.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let V=await t({currentFile:y,expressionPath:F,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});if(V)return V;if(F.isCallExpression()){let U=await n({currentFile:y,callPath:F,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});if(U)return U}}let $=await r(N,x.path.scope,y,E,b,S,I);return $===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:$,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let N=x.path.parentPath.node.declaration;if(!ae.isExpression(N))return null;let R=await r(N,x.path.scope,y,E,b,S,I);return R===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:R,sourceKind:"binding"}}return null}finally{I.delete(w)}}async function a(f){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:I}=f;if(!x.path.isVariableDeclarator()||!x.path.get("id").isArrayPattern())return null;let w=x.path,C=w.node.init;if(!C||!ae.isCallExpression(C))return null;let N=MD(C);if(!N||!ae.isArrayPattern(w.node.id)||w.node.id.elements.findIndex(U=>ae.isIdentifier(U)&&U.name===x.identifier.name)!==0)return null;let F=N==="useReducer"?1:0,$=C.arguments[F];if(!$||!ae.isExpression($))return null;let V=await r($,w.scope,y,E,b,S,I);return V===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:N},value:V,sourceKind:"binding"}}async function c(f){let y=f.expressionPath.scope.getBinding(f.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!f.graph)return null;let x=eI(y,f.sourceInfo);if(!x)return null;let E=[...f.graph.elements.values()].filter(S=>tI(S,f.currentFile,x.componentName,x.exportName));if(!E.length)return null;let b=[];for(let S of E){if(S.sourceFile!==E[0].sourceFile||S.componentName!==E[0].componentName||S.attributeSpreads?.length)return null;let I=await Wn(S.sourceFile,f.readFile,f.fileCache),w=I.ast?Ml(I.ast,S.sourceRange):null;if(!w)return null;let C=w.parentPath;for(;C&&!C.isFunction();){if(C.isJSXElement()){let J=C.node.openingElement.name;if(!ae.isJSXIdentifier(J)||!/^[a-z]/.test(J.name))return null}else if(!C.isJSXFragment()&&!C.isReturnStatement()&&!C.isBlockStatement())return null;C=C.parentPath}if(!C)return null;let N=w.get("openingElement").get("attributes").filter(J=>J.isJSXAttribute()&&ae.isJSXIdentifier(J.node.name,{name:x.propName}));if(N.length!==1)return null;let R=N[0];if(!R?.isJSXAttribute())return null;let F=R.get("value"),$=F.isJSXExpressionContainer()?F.get("expression"):F;if(!$.isExpression())return null;let V=await r($.node,$.scope,S.sourceFile,f.readFile,f.exists,f.fileCache,f.visited),U=V===void 0?void 0:qt(V,x.remainingPath);if(U===void 0)return null;b.push(U)}return b}async function l(f){let y=eI(f.binding,f.sourceInfo);if(!y||!f.graph)return null;let x=["component-prop",f.currentFile,f.binding.identifier.start??f.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(f.visited.has(x))return null;f.visited.add(x);try{return await u(f,y,f.graph)}finally{f.visited.delete(x)}}async function u(f,y,x){let E=[...x.elements.values()].filter(R=>tI(R,f.currentFile,y.componentName,y.exportName));if(E.length!==1)return null;let b=E[0],S=b.attributes?.find(R=>R.name===y.propName);if(S&&!S.source){let R=await d({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:f.readFile,fileCache:f.fileCache});if(R)return tm(R,{componentName:y.componentName,propName:y.propName,file:b.sourceFile})}if(!S?.source){let R=await p({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(R)return tm(R,{componentName:y.componentName,propName:y.propName,file:b.sourceFile});let F=tE(f.binding,y.componentName,y.propName);if(!F||F.propName!==y.propName)return null;let $=await r(F.expressionPath.node,F.expressionPath.scope,f.currentFile,f.readFile,f.exists,f.fileCache,f.visited);if($===void 0)return null;let V=y.remainingPath;return V.length>0&&qt($,V)===void 0?null:{kind:"value",file:f.currentFile,root:{kind:"binding",name:y.propName},path:V,sourceKind:"binding",semanticKind:"component-prop",displayExpression:F.displayPath,chainPrefix:[{kind:"component-prop",file:f.currentFile,displayName:F.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let I=await Wn(b.sourceFile,f.readFile,f.fileCache);if(!I.ast)return null;let w=QS(I.ast,I.source,S.source.expression,S.sourceRange)??Qs(I.ast,I.source,S.source.expression);if(!w)return null;let C={...S.source,expression:Oi(S.source.expression,y.remainingPath),path:[...S.source.path,...y.remainingPath]},N=await o({currentFile:b.sourceFile,expressionPath:w,sourceInfo:C,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});return N?tm(N.kind==="external"?N:{...N,displayExpression:C.expression},{componentName:y.componentName,propName:y.propName,file:b.sourceFile}):null}async function d(f){let y=await Wn(f.caller.sourceFile,f.readFile,f.fileCache);if(!y.ast)return null;let x=Ml(y.ast,f.caller.sourceRange);if(!x)return null;let E=x.get("openingElement").get("attributes").find(w=>w.isJSXAttribute()&&w.node.name.type==="JSXIdentifier"&&w.node.name.name===f.propName);if(!E?.isJSXAttribute())return null;let b=E.get("value"),S=b.isStringLiteral()?b:b.isJSXExpressionContainer()?b.get("expression"):null;if(!S?.isExpression())return null;let I=qs(S.node);return I?{kind:"value",file:f.caller.sourceFile,root:{kind:"expression",sourceRange:I},path:f.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:f.propName,editMode:"upstream",diagnostics:[]}:null}async function p(f){let y=await Wn(f.caller.sourceFile,f.readFile,f.fileCache);if(!y.ast)return null;let x=Ml(y.ast,f.caller.sourceRange);if(!x)return null;let E=x.get("openingElement");for(let b of E.get("attributes")){if(!b.isJSXSpreadAttribute())continue;let S=b.get("argument");if(!S.isExpression())continue;let I=await i({expression:S.node,scope:S.scope,source:y.source,currentFile:f.caller.sourceFile,readFile:f.readFile,exists:f.exists,fileCache:f.fileCache,visited:f.visited});if(!I)continue;let w=[{kind:"property",name:f.propName},...f.remainingPath],C={...I,expression:Oi(I.expression,w),path:[...I.path,...w]},N=await o({currentFile:f.caller.sourceFile,expressionPath:S,sourceInfo:C,readFile:f.readFile,exists:f.exists,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:f.fileCache,visited:f.visited});if(N)return N.kind==="external"?N:{...N,displayExpression:C.expression}}return null}async function g(f){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:I}=f,w=x.path.parentPath;if(!w||!w.isImportDeclaration())return null;let C=w.node.source.value;if(typeof C!="string")return null;let N=await Io(y,C,b);if(!N)return null;if(x.path.isImportDefaultSpecifier()){let J=await Wn(N,E,S),te=J.ast?nm(J.ast,"default"):null,Y=await m({file:N,exportName:"default",readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});return!Y||Y.kind!=="static"?null:{kind:"static",file:te?.kind==="default-expression"?Y.file:N,root:te?.kind==="default-expression"?Y.root:{kind:"default-export"},value:Y.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let R=x.path.node.imported,F=ae.isIdentifier(R)?R.name:R.value,$=await Wn(N,E,S),V=$.ast?nm($.ast,F):null,U=await m({file:N,exportName:F,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});return U?U.kind==="external"?U:{kind:"static",file:V?.kind==="re-export"?U.file:N,root:V?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==V?.name?U.root:{kind:"named-export",name:F},value:U.value,sourceKind:"imported-binding"}:null}async function m(f){let{file:y,exportName:x,readFile:E,exists:b,fileCache:S,visited:I}=f,w=`export::${y}::${x}`;if(!I.has(w)){I.add(w);try{let C=await Wn(y,E,S);if(!C.ast)return;let N=nm(C.ast,x);if(!N)return;if(N.kind==="default-expression"){let V=N.expression;if(!V||!ae.isIdentifier(V))return;let U=ea(C.ast).getBinding(V.name);return U?await s({currentFile:y,binding:U,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I})??void 0:void 0}if(N.kind==="re-export"){if(!N.source||!N.name)return;let V=await Io(y,N.source,b);return V?m({...f,file:V,exportName:N.name}):void 0}let R=N.name;if(!R)return;let F=ea(C.ast).getBinding(R);return F?await s({currentFile:y,binding:F,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I})??void 0:void 0}finally{I.delete(w)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as be from"@babel/types";function om(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=zn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!$D(s,r)?null:{callPath:s,basePath:i}}function $D(e,t){let n=e.node.callee;return!be.isMemberExpression(n)||!be.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function sI(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:nl(r,t)}function rI(e,t){return e?be.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function oI(e,t,n,r,o){let i=be.isExpression(e.body)?e.body:e.body.body.find(a=>be.isReturnStatement(a))?.argument;if(!i||!be.isExpression(i))return;let s=rm(i,t,n,r,o);return typeof s=="number"?s:void 0}function rm(e,t,n,r,o){if(be.isNumericLiteral(e)||be.isStringLiteral(e)||be.isBooleanLiteral(e))return e.value;if(be.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(be.isMemberExpression(e)){let i=Ll(e,t);if(i)return qt(r,i);let s=Ll(e,n);return s?qt(o,s):void 0}if(be.isBinaryExpression(e)&&e.operator==="-"){let i=be.isExpression(e.left)?rm(e.left,t,n,r,o):void 0,s=be.isExpression(e.right)?rm(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function UD(e){if(be.isExpression(e.body))return e.body;for(let t of e.body.body)if(be.isReturnStatement(t)&&t.argument&&be.isExpression(t.argument))return t.argument;return null}function VD(e,t,n){let r=Xo(e,t,n);return typeof r=="boolean"?r:void 0}function Xo(e,t,n){if(be.isStringLiteral(e)||be.isNumericLiteral(e)||be.isBooleanLiteral(e))return e.value;if(be.isNullLiteral(e))return null;if(be.isIdentifier(e))return e.name===t?n:void 0;if(be.isMemberExpression(e)){let r=Ll(e,t);return r?qt(n,r):void 0}if(be.isUnaryExpression(e)&&e.operator==="!"){let r=Xo(e.argument,t,n);return r===void 0?void 0:!r}if(be.isLogicalExpression(e)){let r=Xo(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Xo(e.right,t,n);if(e.operator==="||")return r||Xo(e.right,t,n)}if(be.isBinaryExpression(e)){let r=be.isExpression(e.left)?Xo(e.left,t,n):void 0,o=be.isExpression(e.right)?Xo(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 aI(e){let t=[],n=e;for(;be.isMemberExpression(n)||be.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(be.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(be.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(be.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(be.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return be.isIdentifier(n)?{base:n.name,segments:t}:null}function cI(e){return e.some(t=>t.kind==="dynamic")}function iI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function lI(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 JD(e,t){let n=[],r=[];for(let o of t){let i=qt(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 uI(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(m){let{currentFile:f,callPath:y,readFile:x,exists:E,fileCache:b,visited:S}=m,I=y.node.callee;if(!be.isMemberExpression(I)||!be.isIdentifier(I.property)||I.property.name!=="map")return null;let w=y.get("callee");if(!w.isMemberExpression())return null;let C=w.get("object");if(Array.isArray(C)||!C.isExpression())return null;let N=await a({currentFile:f,expressionPath:C,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});return!N||!Array.isArray(N.value)||N.value.length===0?null:N}async function a(m){let{currentFile:f,expressionPath:y,readFile:x,exists:E,fileCache:b,visited:S}=m;if(y.isIdentifier()){let I=y.scope.getBinding(y.node.name);if(!I)return null;let w=await t({currentFile:f,binding:I,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});return w?.kind==="static"?w:null}if(y.isCallExpression())return l({currentFile:f,callPath:y,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let I=y.get("expression");if(!Array.isArray(I)&&I.isExpression())return a({...m,expressionPath:I})}if(y.isArrayExpression()){let I=qs(y.node);if(!I)return null;let w=await n(y.node,y.scope,f,x,E,b,S);return Array.isArray(w)?{kind:"static",file:f,root:{kind:"expression",sourceRange:I},value:w,sourceKind:"binding"}:null}if(y.isMemberExpression()){let I=await r({expression:y.node,scope:y.scope,currentFile:f,readFile:x,exists:E,fileCache:b,visited:S});if(!I)return null;let w=await o({currentFile:f,expressionPath:y,sourceInfo:I,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(!w||w.kind==="external")return null;let C=await c({currentFile:f,expressionPath:y,provenance:w,readFile:x,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:b,visited:S});if(!C||C.kind!=="static")return null;if(w.collectionPathMap?.length){let R=JD(C.value,w.collectionPathMap);if(R)return{kind:"static",file:w.file,root:w.root,value:R.value,sourceKind:w.sourceKind,collectionPathMap:R.collectionPathMap}}let N=qt(C.value,w.path);return Array.isArray(N)?{kind:"static",file:w.file,root:w.root,value:N,sourceKind:w.sourceKind,pathPrefix:w.path,collectionIndexMap:w.collectionIndexMap,collectionPathMap:w.collectionPathMap}:null}return null}async function c(m){let{provenance:f}=m;if(f.root.kind==="binding"){let b=m.expressionPath.scope.getBinding(f.root.name);if(!b&&f.file!==m.currentFile){let S=await Wn(f.file,m.readFile,m.fileCache);b=S.ast?ea(S.ast).getBinding(f.root.name):void 0}return b?await t({currentFile:f.file,binding:b,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited}):null}if(f.root.kind!=="expression")return null;let y=await Wn(f.file,m.readFile,m.fileCache);if(!y.ast)return null;let x=ZS(y.ast,f.root.sourceRange);if(!x)return null;let E=await n(x.node,x.scope,f.file,m.readFile,m.exists,m.fileCache,m.visited);return E===void 0?null:{kind:"static",file:f.file,root:f.root,value:E,sourceKind:f.sourceKind}}async function l(m){return await u(m)??await d(m)??await p(m)}async function u(m){let{callPath:f}=m,y=f.node.callee;if(!be.isMemberExpression(y)||!be.isIdentifier(y.property)||y.property.name!=="filter")return null;let x=f.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:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!b||!Array.isArray(b.value))return null;let[S]=f.node.arguments;if(!be.isArrowFunctionExpression(S)&&!be.isFunctionExpression(S))return null;let I=S.params[0];if(!be.isIdentifier(I))return null;let w=UD(S);if(!w)return null;let C=[],N=[],R=[];for(let[F,$]of b.value.entries()){let V=VD(w,I.name,$);if(typeof V!="boolean")return null;if(V){C.push($),N.push(b.collectionIndexMap?.[F]??F);let U=b.collectionPathMap?.[F];U&&R.push(U)}}return{...b,value:C,pathPrefix:b.pathPrefix,collectionIndexMap:N,...R.length>0?{collectionPathMap:R}:{}}}async function d(m){let{callPath:f}=m,y=f.node.callee;if(!be.isMemberExpression(y)||!be.isIdentifier(y.property)||y.property.name!=="slice")return null;let x=f.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:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!b||!Array.isArray(b.value))return null;let[S,I]=f.node.arguments,w=rI(S,0),C=rI(I,b.value.length);if(w===null||C===null)return null;let N=Math.max(0,w<0?b.value.length+w:w),R=Math.max(0,C<0?b.value.length+C:C),F=b.value.map((V,U)=>b.collectionIndexMap?.[U]??U).slice(N,R),$=b.collectionPathMap?.slice(N,R);return{...b,value:b.value.slice(N,R),pathPrefix:b.pathPrefix,collectionIndexMap:F,...$?{collectionPathMap:$}:{}}}async function p(m){let{callPath:f}=m,y=f.node.callee;if(!be.isMemberExpression(y)||!be.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let x=f.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:m.currentFile,expressionPath:E,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!b||!Array.isArray(b.value))return null;let[S]=f.node.arguments;if(!be.isArrowFunctionExpression(S)&&!be.isFunctionExpression(S))return null;let[I,w]=S.params;if(!be.isIdentifier(I)||!be.isIdentifier(w))return null;let C=b.value.map((R,F)=>({value:R,sourceIndex:b.collectionIndexMap?.[F]??F,originalIndex:F})),N=[...C];for(let R of C)for(let F of C)if(oI(S,I.name,w.name,R.value,F.value)===void 0)return null;return N.sort((R,F)=>{let $=oI(S,I.name,w.name,R.value,F.value)??0;return $===0?R.originalIndex-F.originalIndex:$}),{...b,value:N.map(R=>R.value),pathPrefix:b.pathPrefix,collectionIndexMap:N.map(R=>R.sourceIndex),...b.collectionPathMap?{collectionPathMap:N.map(R=>b.collectionPathMap?.[R.originalIndex]).filter(R=>!!R)}:{}}}async function g(m){let f=null,y=!1,x,E=[];for(let S of m.segments){if(S.kind!=="dynamic")continue;let I=await r({expression:S.expression,scope:m.expressionPath.scope,source:m.fileCache.get(m.currentFile)?.source,currentFile:m.currentFile,readFile:m.readFile,exists:m.exists,fileCache:m.fileCache,visited:m.visited});if(!I)return null;let w=om(m.expressionPath,I.base),C;if(w){y=!0;let N=await s({currentFile:m.currentFile,callPath:w.callPath,readFile:m.readFile,exists:m.exists,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:m.fileCache,visited:m.visited});if(!N||!Array.isArray(N.value))return null;C=N.value.map((R,F)=>{let $=qt(N.value,[{kind:"index",index:F},...w.basePath,...I.path]);return iI($)}),x??=N.collectionIndexMap}else{let N=await i({...m,sourceInfo:I});if(!N)return null;C=N.map(iI)}if(C.some(N=>N===null)||f!==null&&f!==C.length)return null;f=C.length,E.push(C)}if(f===null||f===0)return null;let b=[];for(let S=0;S<f;S+=1){let I=[...m.rootPath],w=0;for(let C of m.segments){if(C.kind==="dynamic"){let N=E[w]?.[S];if(!N)return null;I.push(N),w+=1;continue}I.push({...C})}b.push(I)}return{sourceKind:y||f>1?"repeat-template":"binding",...x?{collectionIndexMap:x}:{},collectionPathMap:b}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:KD,evaluateStaticExpression:Bl}=KS({resolveBindingTarget:e=>jl(e)}),{resolveRepeatCollectionTarget:XD,resolveCollectionCallTarget:zD,resolveDynamicMemberPathMap:HD}=uI({resolveBindingTarget:e=>jl(e),evaluateStaticExpression:Bl,buildExpressionSourceInfo:mr,resolveSourceInfoProvenance:jn,resolveComponentPropValues:e=>YD(e)}),{resolveExportValue:WD,resolveComponentPropBinding:GD,resolveComponentPropValues:YD,resolveBindingTarget:jl}=nI({resolveExternalExpression:dm,resolveCollectionCallTarget:zD,evaluateStaticExpression:Bl,resolveSourceInfoProvenance:jn,buildExpressionSourceInfo:mr});function bI(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var dI=new WeakMap;function ZD(e){let t=dI.get(e);return t||(t=new WeakMap,dI.set(e,t)),t}function fI(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 EI(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Fl(s,t,n);if(!a)return null;let c=Dl(a,r.sourceRange);if(!c)return null;let l=await mr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let p=await gm({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 p?am(p,wi(c.node,n)):null}let u=new Set,d=await bM({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?am(d,l.expression):null}async function Li(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Fl(i,t,n);if(!s)return null;let a=e.sourceRange?Dl(s,e.sourceRange):e.expression!==void 0?Qs(s,n,e.expression):null;if(!a)return null;let c=$l(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await mr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await jn({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 PI({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 am(d,e.expression??wi(c.node,n))}async function um(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Fl(i,t,n);if(!s)return kn("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?qD({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}):QD({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function mr(e){if(ke.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!ke.isMemberExpression(e.expression))return null;let t=await KD(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:wi(e.expression,e.source),base:t.base,path:t.path}:null}function am(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 qD(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Dl(r,o.sourceRange),u=l?await mr({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 pI(t,o.value);let p=await gm({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 p?p.kind==="external"?xI(t,p):lm(t,wi(l.node,n),p):eM({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return kn("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await jn({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 p=cm(l.node);if(p)return kn(p.code,p.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=cm(g.path.node.init);if(m)return kn(m.code,m.message)}return g?.path.isVariableDeclarator()&&ke.isCallExpression(g.path.node.init)?tM("unsupported-expression",_I(g.path.node.init,e.functionCallContracts)):kn("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?xI(t,d):lm(t,u.expression,d)}async function QD(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return kn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Qs(r,n,o.conditionExpression);if(!l)return kn("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await jn({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 kn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return kn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=lm(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 pI(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 eM(e){let t=await II(e);if(t.length===0)return kn("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(nM(e.expression))return SI(t);if(kI(e.expression))return kn("unsupported-expression","i18n helpers require a static message id string");if(ke.isMemberExpression(e.expression)&&e.expression.computed&&!ke.isNumericLiteral(e.expression.property)&&!ke.isStringLiteral(e.expression.property))return kn("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return kn(n.code,n.message)}function kn(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function tM(e,t){return SI([{code:e,message:t}])}function SI(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function nM(e){return ke.isCallExpression(e)||ke.isConditionalExpression(e)||ke.isLogicalExpression(e)||ke.isBinaryExpression(e)}function na(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 II(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=cm(t);if(l)return[l];if(ke.isCallExpression(t))return[{code:"unsupported-expression",message:_I(t,c)}];if(ke.isMemberExpression(t)&&t.computed){let u=t.property;if(!ke.isNumericLiteral(u)&&!ke.isStringLiteral(u)){if(!ke.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let p=await Bl(u,n,r,o,i,s,a);if(typeof p!="string"&&!Number.isInteger(p))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}]}}return ke.isBinaryExpression(t)?na([...await im(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):ke.isLogicalExpression(t)?na([...await im(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"}]):ke.isConditionalExpression(t)?na([...await im(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 cm(e){return kI(e)?mI("i18n helpers require a static message id string"):aM(e)?mI("CMS helpers require static entry id and field path string arguments"):null}async function im(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await II({...t,expression:o}));return r}function rM(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:[oM(e.sourceType)]}}async function dm(e){for(let n of dM){if(!gI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return yI(hI(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(!gI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return yI(hI(r),e.externalAdapters)}return null}function oM(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function iM(e){return{code:"external-source-readonly",message:e}}function mI(e){return{code:"unsupported-expression",message:e}}function fm(e){return!e||!ke.isCallExpression(e)?null:ke.isIdentifier(e.callee)?e.callee.name:ke.isMemberExpression(e.callee)&&!e.callee.computed&&ke.isIdentifier(e.callee.object)&&ke.isIdentifier(e.callee.property)?`${e.callee.object.name}.${e.callee.property.name}`:null}function gI(e,t){if(!t||t.length===0)return!0;let n=fm(e.node);return n?t.includes(n):!1}function hI(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:na(e.diagnostics??[])}:{match:e,diagnostics:[]}}function yI(e,t){let n=rM(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:na([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function sM(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!ke.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!ke.isStringLiteral(n)||!ke.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 aM(e){return!!e&&ke.isCallExpression(e)&&ke.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!ke.isStringLiteral(e.arguments[0])||!ke.isStringLiteral(e.arguments[1]))}function vI(e){if(!(!e||!ke.isCallExpression(e))){if(ke.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&ke.isStringLiteral(t)?t.value:null}if(ke.isMemberExpression(e.callee)&&!e.callee.computed&&ke.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&ke.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!ke.isObjectExpression(t))return null;for(let n of t.properties)if(ke.isObjectProperty(n)&&!n.computed&&(ke.isIdentifier(n.key)&&n.key.name==="id"||ke.isStringLiteral(n.key)&&n.key.value==="id")&&ke.isStringLiteral(n.value))return n.value.value;return null}}}function kI(e){return vI(e)===null}async function cM(e,t,n){let r=new Set,o=ta.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=ta.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"]:[ta.posix.join(i,"locales"),ta.posix.join(i,"messages")];for(let a of s){let c=ta.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function lM(e){let t=vI(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await cM(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function uM(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!ke.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!ke.isExpression(n))return null;let o=await Bl(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:[iM("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var dM=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>sM(e)},{helperNames:["apiField"],resolve:e=>uM(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>lM({currentFile:e,expressionPath:t,exists:n})}];function pm(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function xI(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 lm(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=xM(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 fM=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function mm(e,t){let n=[...fM,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function _I(e,t){let n=e.callee;return ke.isIdentifier(n)&&mm(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 gm(e){let t=await dm(e);if(t)return t;let n=await CI({...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 mr({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 jn({...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 hM(e)}async function CI(e){let t=await Gn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=$l(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:pm(t.provenance)}async function Gn(e){let t=$l(e.expressionPath),n=gM(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 mr({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 jn({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 mr({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 jn({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 Gn({...e,expressionPath:r,allowComposed:!0}),a=await Gn({...e,expressionPath:o,allowComposed:!1}),c=await Gn({...e,expressionPath:i,allowComposed:!1});return sm(s,a,c)}if(t.isCallExpression())return pM({...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 Gn({...e,expressionPath:r,allowComposed:!0}),s=await Gn({...e,expressionPath:o,allowComposed:!0});return sm(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 Gn({...e,expressionPath:r,allowComposed:!0}),s=await Gn({...e,expressionPath:o,allowComposed:!0});return sm(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Gn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function $l(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 pM(e){let t=fm(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:Gn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(ke.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Gn({...e,expressionPath:o,allowComposed:!1})}}return null}function sm(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!mM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function mM(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 gM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function hM(e){if(!e.expressionPath.isCallExpression())return null;let t=fm(e.expressionPath.node);if(!t)return null;let n=mm(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 RI({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?pm(i):null}async function RI(e){let t=await dm({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 mr({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 jn({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 gm({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 yM(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!ke.isCallExpression(t))return null;let n=t.callee;if(!ke.isIdentifier(n))return null;let r=mm(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 RI({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?pm(a):null}function xM(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=Oi(t,e.path);return{sourceId:o,displayPath:o}}async function bM(e){let t=e.segment.source;return t?jn({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 jn(e){let t=e.sourceInfo,n=om(e.expressionPath,t.base);if(n){let l=await XD({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 f=sI(n.callPath,[...n.basePath,...t.path]);return js(f)?fI(e.currentFile,f.sourceId,f.displayPath):null}let u=lI(l,[...n.basePath,...t.path]),d=l.collectionIndexMap?.[0]??0,p=[...l.pathPrefix??[],{kind:"index",index:d},...n.basePath,...t.path],g=[{kind:"index",index:0},...n.basePath,...t.path];return qt(l.value,g)===void 0?null:{kind:"value",file:l.file,root:l.root,path:u?.[0]??p,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 Io(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await WD({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(!p||p.kind==="external")return null;let g=t.path.slice(1);return qt(p.value,g)===void 0?null:{kind:"value",file:p.file,root:p.root,path:g,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=Qb(r);if(o){let l=o.expressionPath,u=await mr({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 jn({...e,expressionPath:l,sourceInfo:{...u,expression:Oi(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 p=await PI({...e,expressionPath:$l(l),memberSuffix:t.path});if(p?.kind==="value")return p}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await CI({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 GD({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 yM({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=el(r,t.path,ZD(e.fileCache));if(js(s))return fI(e.currentFile,s.sourceId,s.displayPath);let a=await jl({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:qt(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 PI(e){let t=aI(e.expressionPath.node);if(!t||!cI(t.segments))return null;let n=await jn({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 HD({...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 jl({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>qt(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:wi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function NI(e){let t=EM(e.propertyName);if(t.owner==="blocked")return co(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return co(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 co("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 IM(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 co("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}:co("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?co("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):SM(e,s.attribute)}async function SM(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Li({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}}:co("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 Li({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"?co("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 IM(e,t){let n=t.source?.expression;if(!n)return;let r=await Li({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:vM(r,e.propertyName)}}function vM(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 co(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function AI(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(zo(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=>RM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>kM({...r,graph:e},n)}function kM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=CM(n,r,o,t),a=s?.tag??(zo(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=NM(s),u=AM(n,r,o,i,s),d=_M(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:PM(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:TM(d),alternativeStrategies:wM(d)}}function _M(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return hm(e,n)?"instance":!zo(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function CM(e,t,n,r){if(zo(t.tag))return t;let o=hm(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function RM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function PM(e,t){return zo(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function NM(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 AM(e,t,n,r,o){let i=new Set,s=hm(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&&zo(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function hm(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(zo(r.tag))return r;n=r.parentKey}return null}function zo(e){return/^[A-Z]/.test(e)}function TM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function wM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function OI(e){let t=e.isRepeat??(e.graph?UM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=$M(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>OM({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:VM(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 OM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=LM(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:ll({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=FM(t,n,l,e.isRepeat),d=c?BM(c,e.element,t.name):void 0,p=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=p.length>0?MM(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",f=jM(t,n,r);if(p.length===0&&f.length===0){let y=s.find(({result:x})=>!x.ok)?.result;y&&!y.ok&&f.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:m,allowedWriteScopes:p,...d?{effectiveWriteTarget:d}:{},diagnostics:f}}function LM(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 FM(e,t,n,r){return n?TI(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:TI(DM(e))}function DM(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 TI(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function MM(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 BM(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:wI({...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:wI(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function jM(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 $M(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function UM(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 wI(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 VM(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 JM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var KM=160;function LI(e,t,n,r={}){let o=oi(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 FI(e,t,n,r,o,i,s,a,c,l,u){let d=oi(t),p=t.elements.get(e),g=n.nodes.get(e),m=r.get(e);if(!p||!g||!m)throw new Error(`Node not found: ${e}`);let f=$I(p.textSegments,s),y=UI(e,t,p,m,f),x=f?WM(f):void 0,E=GM(i,f),b=p.textSegments.map(C=>({index:C.index,value:C.value,editable:VI(C,m,s?.get(C.index)??null),source:o.get(C.index)??null})),S=BI(p,t),I=p.childKeys.map(C=>{let N=t.elements.get(C);return N?{key:C,tag:N.tag,label:N.tag}:null}).filter(C=>C!==null),w=[];if(p.parentKey){let C=t.elements.get(p.parentKey);if(C)for(let N of C.childKeys){if(N===e)continue;let R=t.elements.get(N);R&&w.push({key:N,tag:R.tag,label:R.tag})}}return{composition:d,key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:MI(p),label:p.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:x,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:b,boundaryKind:p.boundaryKind,isOpaque:p.isOpaque,ancestors:S,children:I,siblings:w}}function DI(e,t,n,r,o,i,s,a){let c=oi(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 p=$I(l.textSegments,i),g=XM(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:MI(l),label:l.tag,capabilities:UI(e,t,l,d,p),provenanceChain:p?{editMode:p.editMode,diagnostics:p.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let f=o.get(m.index);return{index:m.index,editable:VI(m,d,i?.get(m.index)??null),source:f?{kind:f.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:BI(l,t)}}function XM(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 MI(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:zM(e.sourceRange),structuralPath:e.identity.structuralPath,...HM(e.textSegments)}}function BI(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 zM(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function HM(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,KM)}:{}}function jI(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 $I(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function UI(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&&JI(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 VI(e,t,n){return!e.editable||!t.canUpdateText?!1:n?JI(n.editMode):!0}function JI(e){return e==="direct"||e==="proxy"||e==="upstream"}function WM(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 GM(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}:JM(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 ym=["set-class-name-source","apply-style-draft"];function KI(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:ym,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:ym,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:ym}}import XI from"node:path";function bm(){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 HI(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=QM(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 Ul(e){let t=()=>YM(e);return e.mutex?e.mutex.runExclusive(t):t()}async function YM(e){let t=await HI(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=ZM(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 xm({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 xm({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 xm({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 zI("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return zI("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 ZM(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 xm(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:qM(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 zI(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function qM(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 QM(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)||XI.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=XI.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 eB=50,tB=8*1024*1024;function ZI(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??eB),s=Math.max(0,t.maxUndoBytes??tB);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(C){let N=[...C.steps].sort((J,te)=>J.order-te.order),R=N.filter(J=>J.type!=="invoke-external-adapter");if(R.length!==N.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let F=new Set(R.map(J=>J.file)),$=await E(F),V=new Map($.map(J=>[J.file,J.exists===!1?"":J.content])),U;for(let J of R){let te=YI(J,V.get(J.file)??"");if(!te.ok)return{ok:!1,errorCode:te.errorCode,reason:te.reason};V.set(J.file,te.source),U=te.selectionRef??U}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...V].map(([J,te])=>({operation:"upsert",file:J,content:te,baseContentHash:$.find(Y=>Y.file===J)?.sha256??null}))},...U?{selectionRef:U}:{}}}async function c(C){let N=[...C.steps].sort((Y,he)=>Y.order-he.order),R=N.filter(Y=>Y.type!=="invoke-external-adapter"),F=N.filter(Y=>Y.type==="invoke-external-adapter"),$=new Set(R.map(Y=>Y.file));if(R.length>0&&F.length>0)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(R.length===0)return y(C,F);let V=await E($),U=new Map;for(let Y of V)U.set(Y.file,Y.exists===!1?"":Y.content);let J;for(let Y of R){let he=U.get(Y.file)??"",le=YI(Y,he);if(!le.ok)return{ok:!1,operationId:C.operationId,errorCode:le.errorCode,reason:le.reason,rolledBack:!1};U.set(Y.file,le.source),le.selectionRef&&(J=le.selectionRef)}let te=await S([...U].map(([Y,he])=>({file:Y,content:he,exists:!0,version:0,sha256:je(he)})),V);return te.ok===!1?{ok:!1,operationId:C.operationId,errorCode:te.rolledBack?"writeback-failed":"rollback-failed",reason:te.reason,rolledBack:te.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:V,postSnapshots:te.snapshots,plan:C}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...te.snapshots.map(Y=>Y.version)),affectedFiles:[...$],...J?{selectionRef:J}:{}})}async function l(C){let N=new Set(C.edits.map(te=>te.file)),R=await E(N),F=x(C,R);if(F)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:F.reason,affectedFiles:[F.file],rolledBack:!1};let $=new Map(R.map(te=>[te.file,te])),V=C.edits.find(te=>te.operation==="create-only"&&$.get(te.file)?.exists!==!1);if(V)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${V.file}`,affectedFiles:[V.file],rolledBack:!1};let U=C.edits.map(te=>te.operation==="delete"?{file:te.file,content:"",exists:!1,version:0}:{file:te.file,content:te.content,exists:!0,version:0,sha256:je(te.content)}),J=await S(U,R,new Set(C.edits.filter(te=>te.operation==="create-only").map(te=>te.file)));return J.ok===!1?{ok:!1,operationId:C.operationId,errorCode:J.rolledBack?"writeback-failed":"rollback-failed",reason:J.reason,rolledBack:J.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:R,postSnapshots:J.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:R}}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...J.snapshots.map(te=>te.version)),affectedFiles:[...N]})}async function u(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let N=await S(C.preSnapshots,C.postSnapshots);return N.ok===!1?{ok:!1,operationId:C.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...N.snapshots.map(R=>R.version)),affectedFiles:C.preSnapshots.map(R=>R.file)})}async function d(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let N=await S(C.postSnapshots,C.preSnapshots);return N.ok===!1?{ok:!1,operationId:C.operationId,errorCode:N.rolledBack?"writeback-failed":"rollback-failed",reason:N.reason,rolledBack:N.rolledBack}:(r.pop(),n.push(C),p(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...N.snapshots.map(R=>R.version)),affectedFiles:C.postSnapshots.map(R=>R.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((C,N)=>C+m(N),0)}function m(C){return f(C.preSnapshots)+f(C.postSnapshots)}function f(C){return C.reduce((N,R)=>N+R.file.length+R.content.length,0)}async function y(C,N){let R=[];for(let F of N){let $=F.capability??"write-text",V=o.find(J=>J.sourceType===F.sourceType&&(F.adapterId===void 0||J.adapterId===F.adapterId)&&(J.capabilities===void 0||J.capabilities.includes($)));if(!V)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${F.sourceType}`,rolledBack:!1};let U=await V.execute(F);if(!U.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:U.reason??`External adapter failed for ${F.sourceType}`,rolledBack:!1};R.push(F.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:R}}function x(C,N){if(C.conflictPolicy!=="compare-and-swap")return null;let R=new Map(N.map(F=>[F.file,F]));for(let F of C.edits){if(F.operation==="create-only")continue;if(F.baseContentHash===void 0)return{file:F.file,reason:`Source file ${F.file} is missing baseContentHash. Reopen the file before saving.`};let $=R.get(F.file),V=F.baseContentHash;if(V===null){if($?.exists!==!1)return{file:F.file,reason:`Source file ${F.file} was created or changed before save.`};continue}if(!V)return{file:F.file,reason:`Source file ${F.file} is missing baseContentHash. Reopen the file before saving.`};if($?.exists===!1||$?.sha256!==V)return{file:F.file,reason:`Source file ${F.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(C){let N=[];for(let R of C)N.push(await b(R));return N}async function b(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let R=Math.max(1,e.getVersion(C)),F=await e.readFile(C);return{file:C,content:F,version:R,exists:!0,sha256:je(F)}}async function S(C,N,R=new Set){let F=[];try{for(let $ of C){if(R.has($.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive($.file,$.content)}else await I($);let V=e.bumpVersion($.file);F.push($.file),$.version=V}}catch($){let V=await w(N.filter(J=>F.includes(J.file)));if(V.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${V.failedFiles.join(", ")}: ${GI($)}`,rolledBack:!1,instanceConflict:WI($)};let U=WI($);return{ok:!1,reason:`${U?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${GI($)}`,rolledBack:!0,instanceConflict:U}}return{ok:!0,snapshots:C.map(nB)}}async function I(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function w(C){let N=[];for(let R of C)try{await I(R),e.bumpVersion(R.file)}catch{N.push(R.file)}return N.length===0?{ok:!0}:{ok:!1,failedFiles:N}}}function WI(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function nB(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:je(e.content)}:{}}}function GI(e){return e instanceof Error?e.message:String(e)}function YI(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 Jt(Tn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Jt(ri({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Jt(Ao({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Jt(An({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Jt(Ka({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Jt(is({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Jt(is({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Jt(Ya({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Jt(Xa({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Jt(Za({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Jt(qa({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Jt(wo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Jt(za({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 rB(e,t);case"set-property-changes":return Jt(Ha({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return Jt(Wa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return Jt(Ga({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Jt(ec({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function rB(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!uy(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!==je(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:ly({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Jt(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 Vl,SiteEditCompositionContextSchema as oB,SiteEditCompositionSelectorSchema as iB}from"@vcp-dev/contracts";var Qt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function qI(e,t){throw new Qt("INVALID_COMPOSITION",e,{value:t})}function Jl(e){let t=oB.safeParse(e);return t.success?t.data:qI("Invalid SiteEditCompositionContext.",e)}function QI(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Jl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Qt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Vl(u);if(n.has(d))throw new Qt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new Qt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:p});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 Qt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Jl(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Qt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Vl(u);if(!n.has(d))throw new Qt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Qt("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=iB.safeParse(l);if(!u.success)return qI("Invalid SiteEditCompositionSelector.",l);let d=t.filter(({context:p})=>p.routeId===u.data.routeId&&(u.data.templateId===void 0?p.effectiveTemplateId===void 0:p.effectiveTemplateId===u.data.templateId));if(d.length===1)return d[0];throw d.length>1?new Qt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Qt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Jl(l),d=Vl(u),p=n.get(d);if(!p)throw new Qt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Jl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Qt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Vl(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new Qt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(f=>f.entryFile===l.entryFile);if(g)throw new Qt("DUPLICATE_COMPOSITION",`Entry file ${l.entryFile} is registered more than once.`,{entryFile:l.entryFile,context:g.context});let m={context:u,entryFile:l.entryFile,key:d};return t.push(m),n.set(d,m),m}function c(l){let u=n.get(l);if(!u)return;n.delete(l);let d=t.findIndex(p=>p.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 Em(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 ev(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 sB,stripSiteEditRepeatInstanceKeys as tv}from"@vcp-dev/contracts";function nv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=tv(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 aB(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 Kl(e){return e?.map(t=>({...t}))}function Sm(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Kl(e.collectionPathMap?.[t])??Kl(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:Kl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Kl(o)??[])}}function rv(e,t,n){let r=new Set;for(let g of t.regions)if(g.kind==="repeat-region")for(let m of g.childKeys)r.add(m);if(r.size===0)return e;let o=new Map(e.entries.map(g=>[g.key,g])),i=[],s=new Map,a=(g,m)=>sB(g,m),c=(g,m,f)=>{let y=o.get(g);if(!y)return a(g,f);let x=a(g,f),E={...y,key:x,parentKey:m,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(b=>l(b,f,x)),x},l=(g,m,f)=>{if(!r.has(g))return[c(g,f,m)];let y=d(g,m),x=[];for(let E=0;E<y;E+=1)x.push(c(g,f,[...m,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 m=d(g,[]);for(let f=0;f<m;f+=1)c(g,null,[f])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,m){let f=new Set;for(let y of p(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 cB(E))b.length<=m.length||lB(b,m)&&f.add(b[m.length])}}return f.size>0?f.size:aB(n.get(g))}function p(g){let m=s.get(g);if(m)return m;let f=[g],y=o.get(g);for(let x of y?.childKeys??[])f.push(...p(x));return s.set(g,f),f}}function ov(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function iv(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((tv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function cB(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 lB(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 sv(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 av(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 cv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function uB(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var ra=class extends Error{constructor(t){let n=t.map(cv);super(uB(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function lv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof ra?{routeId:e,message:n,diagnostics:t.diagnostics.map(cv)}:{routeId:e,message:n}}function Im(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function vm(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function oa(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function uv(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Xl(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 dv(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 xB=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,bB=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],fv=32,Hl=256;function EB(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var pv={maxEntries:50,maxBytes:8*1024*1024};function SB(){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 rc(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 mv(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 IB(){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>pv.maxEntries||vB(e)>pv.maxBytes;)e.shift()}}function vB(e){return e.reduce((t,n)=>t+kB(n),0)}function kB(e){return gv(e.preSnapshots)+gv(e.postSnapshots)+_B(e.provenance)}function _B(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function gv(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function hv(e,t){return{key:fB(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 Wl=class extends Error{constructor(t){super(t.reason),this.result=t}},Ho=class extends Error{constructor(t){super(Im(t)),this.failedRoutes=t}};function yv(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=ln(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(ln(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function CB(e,t,n){if(!n)return;let r=ln(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 RB=/\.(?:[cm]?[jt]sx?)$/i,PB=/\.json$/i,NB=/\.(?:css|scss|sass)$/i,AB=/\.mdx$/i,TB=/\.ya?ml$/i;function wB(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 OB(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function LB(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=vv(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(FB(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 FB(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function vv(e){return Array.isArray(e)?{files:e}:e}function DB(e){if(!mB(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!==hB||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=pB(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(RB.test(e.path)){let t=er({source:e.content,profile:ko({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(PB.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${tn(t)}`,details:{path:e.path}}}if(NB.test(e.path)){let t=xv({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(AB.test(e.path)){let t=xv({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(TB.test(e.path))try{yB(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${tn(t)}`,details:{path:e.path}}}return{ok:!0}}function xv({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 p=e[d]??"",g=e[d+1]??"";if(n==="mdx"&&l&&e.startsWith("```",d)){c=!c;let m=e.indexOf(`
8
+ `,d);if(m===-1){l=!0;break}d=m,l=!0;continue}if(c){l=p===`
9
+ `||p==="\r";continue}if(s){p==="*"&&g==="/"&&(s=!1,d+=1),l=p===`
10
+ `||p==="\r";continue}if(a){p===`
11
+ `||p==="\r"?(a=!1,l=!0):l=!1;continue}if(o){if(i)i=!1;else if(p==="\\")i=!0;else if(p===o)o=null;else if(n==="css"&&(p===`
12
+ `||p==="\r"))return Fi(t,`Unterminated string literal in ${t}.`);l=p===`
13
+ `||p==="\r";continue}if(p==="/"&&g==="*"){s=!0,d+=1,l=!1;continue}if(n==="mdx"&&p==="/"&&g==="/"){a=!0,d+=1,l=!1;continue}if(p==="'"||p==='"'||n==="mdx"&&p==="`"){o=p,l=!1;continue}if(p==="{"||p==="("||p==="["){r.push({char:p,offset:d}),l=!1;continue}if(p==="}"||p===")"||p==="]"){let m=p==="}"?"{":p===")"?"(":"[",f=r.pop();if(!f||f.char!==m)return Fi(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
14
+ `||p==="\r"}if(s)return Fi(t,`Unterminated block comment in ${t}.`);if(o)return Fi(t,`Unterminated string literal in ${t}.`);if(c)return Fi(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Fi(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Fi(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Gl(e){let t="idle",n=e.fileSystem??SB(),r=dy(),o=QI({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?ex(e.historyStore):IB()),u=ZI(n,{externalAdapters:e.externalAdapters}),d=new Map,p=Sy(Hl),g=new Set,m=0,f=e.historyStore?.recoveryRequired??!1,y=bm(),x=I();function E(h){return(zl.isAbsolute(h)?zl.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function b(h,_){let v=zl.posix.dirname(h),T=_.replace(/\.(?:tsx?|jsx?)$/i,""),K=zl.posix.relative(v,T);return K.startsWith(".")?K:`./${K}`}function S(h,_){return h.startLine===_.startLine&&h.startColumn===_.startColumn&&h.endLine===_.endLine&&h.endColumn===_.endColumn}async function I(){let h=e.historyStore;if(h)try{let _=await h.readTransactionJournal();if(!_)return;let v=await h.readIndex(),T=await Promise.all(_.files.map(async X=>await n.exists(X.path)?je(await n.readFile(X.path)):null));if(dv({journal:_,index:v,observedFileDigests:T})!=="ambiguous"){await h.clearTransactionJournal(_.transactionId);let X=await h.readStatus();X.recoveryRequired||(await h.cleanupTmp(),X=await h.readStatus()),f=X.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${_.transactionId} at phase ${_.phase}`),f=!0}catch(_){f=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${tn(_)}`).catch(()=>{})}}function w(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let _=hv(h.context,h.entryFile);i.set(h.key,_),C(_,_.dependencyFiles)}function C(h,_){let v=new Set(_);N(h),h.dependencyFiles=v;for(let T of h.dependencyFiles){let K=s.get(T);K||(K=new Set,s.set(T,K)),K.add(h.key)}}function N(h){for(let _ of h.dependencyFiles){let v=s.get(_);v&&(v.delete(h.key),v.size===0&&s.delete(_))}h.dependencyFiles.clear()}function R(h){let _=new Set;for(let v of h)for(let T of s.get(v)??[])_.add(T);return _}function F(h){for(let _ of h)if(!s.has(_))return!1;return!0}async function $(h,_,v,T,K,X){let ee=new Map,ne=AI(h),de=bI(K.values()),oe=xS(K.values()),re=typeof X.exists=="function"?me=>X.exists(me):async()=>!1;for(let[me,Ie]of h.elements){let Be=_.nodes.get(me);if(!Be)continue;let xe=v.get(Ie.sourceFile)??T.get(Ie.sourceFile),Xe=new Map,Le=new Map,Z=new Map,ue=[];for(let dt of Ie.textSegments){if(!xe){Xe.set(dt.index,null);continue}let Hi=await EI({file:Ie.sourceFile,source:xe,segment:dt,readFile:mn=>X.readFile(mn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mn,adapterId:So,capabilities:Mu})=>({sourceType:mn,adapterId:So,capabilities:Mu})),functionCallContracts:e.functionCallContracts,fileCache:de}),en=await um({file:Ie.sourceFile,source:xe,target:{kind:"text-segment",segment:dt},readFile:mn=>X.readFile(mn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:mn,adapterId:So,capabilities:Mu})=>({sourceType:mn,adapterId:So,capabilities:Mu})),functionCallContracts:e.functionCallContracts,fileCache:de}),Rn=wB(Hi);Xe.set(dt.index,Rn),Le.set(dt.index,Hi),Z.set(dt.index,en),ue.push({editable:dt.editable,source:Rn})}let Re=new Map,Ve=new Map;if(xe)for(let dt of Ie.attributes??[]){let Hi=await Li({file:Ie.sourceFile,source:xe,sourceRange:dt.sourceRange,expression:dt.source?.expression??dt.value,sourceInfo:dt.source,readFile:Rn=>X.readFile(Rn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Rn,adapterId:mn,capabilities:So})=>({sourceType:Rn,adapterId:mn,capabilities:So})),functionCallContracts:e.functionCallContracts,fileCache:de}),en=await NI({element:Ie,file:Ie.sourceFile,source:xe,propertyName:dt.name,readFile:Rn=>X.readFile(Rn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Rn,adapterId:mn,capabilities:So})=>({sourceType:Rn,adapterId:mn,capabilities:So})),functionCallContracts:e.functionCallContracts,fileCache:de});Ve.set(dt.name,en),Re.set(dt.name,Hi)}let ze=jI(OB(Be.writeTarget),ue),bt=ne({key:me,element:Ie,provenances:Z}),Dr=KI(Ie),qn=xe?await Pl({element:Ie,graph:h,file:Ie.sourceFile,source:xe,readFile:dt=>X.readFile(dt),exists:re,fileCache:oe}):void 0,Eo=h.regions.find(dt=>dt.kind==="conditional-region"&&dt.childKeys.includes(me)),$t,Cn=Eo?.sourceCandidates?.[0];if(xe&&Eo&&Cn?.kind==="conditional-branch"){let dt=await um({file:Ie.sourceFile,source:xe,target:{kind:"conditional-branch",candidate:Cn},readFile:en=>X.readFile(en),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:en,adapterId:Rn,capabilities:mn})=>({sourceType:en,adapterId:Rn,capabilities:mn})),functionCallContracts:e.functionCallContracts,fileCache:de});$t={currentBranch:Eo.childKeys.indexOf(me)<=0?"then":"else",availableBranches:Eo.childKeys.length>1?["then","else"]:["then"],conditionExpression:Cn.conditionExpression,provenance:{finalSource:dt.finalSource?{kind:dt.finalSource.kind,file:dt.finalSource.file,displayPath:dt.finalSource.displayPath}:null,chain:dt.chain.map(en=>({kind:en.kind,file:en.file,displayName:en.displayName,canEditHere:en.canEditHere})),confidence:dt.confidence,editMode:dt.editMode,diagnostics:dt.diagnostics.map(en=>({code:en.code,message:en.message}))}}}ee.set(me,{textSources:Xe,textTargets:Le,elementPropertyTargets:Re,propertyProvenances:Ve,isRepeat:qB(me,h),provenances:Z,writeTarget:ze,componentSemantic:bt,styleSource:Dr,conditional:$t,dynamicData:qn})}return ee}function V(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function U(h,_){let v=o.initialVersions.get(h.key)??0;for(let T of _.values())v=Math.max(v,T);return Math.max(v,h.graph?.version??0)}function J(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function te(h){try{return J(o.resolveSelector(h.composition).key)}catch{return 0}}async function Y(h,_,v=n,T={}){let K=await ai(h,_,X=>v.readFile(X),X=>v.exists(X),{additionalEntries:await le(h,v),...T});if(K.diagnostics.length>0)throw new ra(K.diagnostics);return T.validationOnly||p.remember(K.parsedModules.values()),K}async function he(h,_,v={}){let T=i.get(h);if(!T)return null;let K=v.sourceCache??vm(d,[]),X=v.fileSystem??Em(n),{graph:ee,allSources:ne,parsedModules:de,entryModule:oe}=await Y(T.entryFile,_,X,{version:T.graph?.version??1}),re=new Map;for(let $t of ne.keys())re.set($t,V($t));let me=Math.max(U(T,re),v.minimumVersion??0);v.changed&&me<=(T.graph?.version??0)&&(me=(T.graph?.version??0)+1),ee.version=me;for(let[$t,Cn]of ne)Xl(K,$t,Cn,Hl);let Ie=await Me(T.composition,T.entryFile,ne,K,X);ee.routeId=T.routeId,ee.composition=T.composition;let Be=Vc(ee),xe=tc(Be,ee),Xe=await $(ee,Be,ne,K,de,X);D(xe,Xe);let Le=O(ee,xe,Xe),Z=pt(Xe),ue=rv(LI(ee,Be,xe,{canUpdateTextByKey:Le,dynamicDataSummaryByKey:Z}),ee,Xe),Re=Vn({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:me,source:_,ast:oe?.ast}),Ve=nb(Re),ze=null,bt=[];if(Re.ok){BB(ue,ee,Re.projection,de);let $t=Uc({composition:T.composition,entryFile:T.entryFile,graph:ee,parsedModules:de,projection:Re.projection});if($t.diagnostics.length===0){let Cn=Ps({composition:T.composition,entryFile:T.entryFile,graph:ee,parsedModules:de,projection:Re.projection,documentVersion:me,roots:$t.roots});Cn.diagnostics.length===0&&(ze=Cn,bt=Cn.descriptors)}}let Dr={...ue,composition:T.composition,pageBlocks:bt,...Ie?{styleContext:Ie}:{},pageComposition:Ve},qn=new Set([T.entryFile,...ne.keys()]);if(Ie){qn.add(Ie.entryCss.path);for(let $t of Ie.stylesheets)qn.add($t.path)}let Eo={...T,dependencyFiles:qn,graph:ee,topology:Be,capabilities:xe,document:Dr,pageBlockIndex:ze,pageComposition:Ve,pageCompositionProjection:Re.projection,pagePlacementByKey:Re.ok?Re.projection.placementByKey:null,pagePlacementUnitByKey:Re.ok?Re.projection.placementUnitByKey:null,pageUnitByKey:Re.ok?Re.projection.unitByKey:null,pagePlacementsByUnitKey:Re.ok?Re.projection.placementsByUnitKey:null,documentIndex:nv(Dr),detailProjections:Xe,fileVersions:re,styleContext:Ie};if(v.publish===!1)return Eo;for(let $t of qn){let Cn=ne.get($t)??K.get($t);Cn!==void 0&&(Xl(d,$t,Cn,Hl),g.delete($t))}return C(T,qn),Object.assign(T,Eo),T}async function le(h,_=n){let v=[];for(let T of zB(h))typeof _.exists=="function"&&await _.exists(T)&&v.push({file:T,source:await _.readFile(T)});return v}async function Me(h,_,v,T,K){let X=[];for(let[re,me]of v){if(km(re)){X.push(re);continue}for(let Ie of WB(me)){let Be=Iv(re,Ie);Be&&X.push(Be)}}if(!X.length){for(let re of HB(_))if(await K.exists(re)){X.push(re);break}}let ee=new Map,ne=ZB(X).slice(0,fv);for(;ne.length>0&&ee.size<fv;){let re=ne.shift();if(ee.has(re)||!km(re))continue;let me=await Ye(re,T,K);if(me!==null){ee.set(re,{path:re,content:me});for(let Ie of GB(me)){let Be=Iv(re,Ie);Be&&!ee.has(Be)&&!ne.includes(Be)&&ne.push(Be)}}}let de=[...ee.values()].map(re=>({...re,hash:je(re.content)})),oe=de[0];return oe?{composition:h,revision:je(JSON.stringify(de.map(({path:re,hash:me})=>({path:re,hash:me})))),entryCss:oe,stylesheets:de.slice(1)}:null}async function Ye(h,_,v){let T=_.get(h);if(T!==void 0)return T;if(!await v.exists(h))return null;let K=await v.readFile(h);return Xl(_,h,K,Hl),K}function pt(h){let _=new Map;for(let[v,T]of h)T.dynamicData?.bindings.length&&_.set(v,AS(T.dynamicData.bindings));return _}function O(h,_,v){let T=new Map;for(let[K,X]of h.elements){if(!_.get(K)?.canUpdateText){T.set(K,!1);continue}let ne=v.get(K),de=X.textSegments.some(oe=>{if(!oe.editable)return!1;let re=ne?.provenances.get(oe.index)??null;return!re||H(re)});T.set(K,de)}return T}function D(h,_){for(let[v,T]of _){let K=h.get(v);K?.canUpdateText&&T.dynamicData?.bindings.some(X=>X.readonly&&(X.targetKind==="text"||X.targetKind==="richtext"))&&h.set(v,{...K,canUpdateText:!1})}}function H(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function j(h,_={}){let v=[...new Set(h)],T=_.affectedCompositionKeys!==void 0,K=T?new Set(_.affectedCompositionKeys):R(v);if(!T&&(K.size===0||!F(v)))for(let oe of i.values())_e(oe,v)&&K.add(oe.key);let X=!T&&K.size===0&&v.some(Sv),ee=_.publish===!1?vm(d,v):void 0,ne={rebuiltRoutes:[],failedRoutes:[],..._.publish===!1?{candidateRouteStates:[],candidateSourceCache:ee}:{}},de=Em(n);for(let oe of i.values())if(!(_.excludedCompositionKeys?.has(oe.key)||!(K.has(oe.key)||X)))try{let me=!!oe.graph,Ie=await de.readFile(oe.entryFile),Be=await he(oe.key,Ie,{..._,fileSystem:de,...ee?{sourceCache:ee}:{}});Be?.graph&&(ne.rebuiltRoutes.push({documentChanged:me,composition:oe.composition,routeId:oe.routeId,version:Be.graph.version}),ne.candidateRouteStates?.push({composition:oe.composition,key:oe.key,routeId:oe.routeId,state:Be}))}catch(me){ne.failedRoutes.push({...lv(oe.routeId,me),composition:oe.composition})}return ne}function z(h){let _=[...new Set(h)],v=R(_);if(v.size>0&&F(_))return[...v];for(let T of i.values())_e(T,_)&&v.add(T.key);return[...v]}function L(h){let _=new Set(z(h));return o.entries.filter(v=>_.has(v.key)).map(v=>v.context)}function G(h){return[...new Set(z(h))].sort((v,T)=>v<T?-1:v>T?1:0).map(v=>o.getByKey(v)?.context).filter(v=>v!==void 0)}function A(h,_){let v=new Set(z(_)),T=h.provenance?.affectedCompositions??[];if(T.length===0)return v;if([...new Set(T.map(X=>o.resolveContext(X).key))].some(X=>!v.has(X)))throw new Error("History provenance does not match the affected composition index.");return v}function q(h,_){let v=h.composition??h.provenance?.initiatingComposition;if(v){let X=o.resolveContext(v);return{context:X.context,key:X.key}}let T=[...new Set(z(_))];if(T.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${T.length}).`);let K=o.getByKey(T[0]);if(!K)throw new Error("Legacy history entry references an unknown affected composition.");return{context:K.context,key:K.key}}function ce(h,_){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:v,version:T}of _.rebuiltRoutes)r.emit({type:"document-changed",composition:v,version:T});for(let{composition:v,message:T}of _.failedRoutes)r.emit({type:"graph-error",composition:v,message:T})}function _e(h,_){return _.some(v=>h.dependencyFiles.has(v)||h.entryFile===v||h.graph?.fileIndex.has(v))}function qe(h){for(let _ of h)a.add(_);c||w()||(c=(async()=>{t="building";let _=!1;try{for(;a.size>0;){if(w())return;await Ke(),await y.runExclusive(async()=>{if(m>0||w())return;let v=[...a];a.clear();let T=await rt(v);if(T.length===0)return;let K=z(T);for(let ne of K){let de=i.get(ne)?.composition;de&&r.emit({type:"graph-invalidated",composition:de})}let{rebuiltRoutes:X,failedRoutes:ee}=await j(T,{changed:!0});for(let{documentChanged:ne,composition:de,version:oe}of X)r.emit({type:"graph-ready",composition:de,version:oe}),ne&&r.emit({type:"document-changed",composition:de,version:oe});for(let{composition:ne,message:de}of ee)_=!0,r.emit({type:"graph-error",composition:ne,message:de})})}}finally{c=null,t!=="disposed"&&(t=!_&&[...i.values()].some(v=>v.graph)?"ready":"idle"),a.size>0&&qe([])}})())}async function Ke(){for(;m>0;)await new Promise(h=>setTimeout(h,0))}async function rt(h){let _=[];for(let v of new Set(h)){let T=d.get(v);if(T===void 0){if(g.has(v)&&!await n.exists(v))continue;g.delete(v),_.push(v);continue}try{await n.readFile(v)!==T&&(g.delete(v),_.push(v))}catch(K){if(!MB(K))try{if(await n.exists(v))continue}catch{continue}g.add(v),_.push(v)}}return _}function vt(h){uv(d,h);for(let _ of h)_.exists===!1?g.add(_.file):g.delete(_.file)}function pn(h){g.clear();for(let _ of h)g.add(_)}async function Pt(h){let _=await rt(h);if(_.length===0)return;let v=z(_);for(let X of v){let ee=i.get(X)?.composition;ee&&r.emit({type:"graph-invalidated",composition:ee})}let{rebuiltRoutes:T,failedRoutes:K}=await j(_,{changed:!0});for(let{documentChanged:X,composition:ee,version:ne}of T)r.emit({type:"graph-ready",composition:ee,version:ne}),X&&r.emit({type:"document-changed",composition:ee,version:ne});for(let{composition:X,message:ee}of K)r.emit({type:"graph-error",composition:X,message:ee})}async function Or(h,_){let v=Qo(h,_);if(!v?.graph)return;let T=ln(h)??h,K=v.graph.elements.get(T);K&&await Pt([K.sourceFile])}async function br(h){let _=new Set;if(h.target.kind==="node"){let v=Qo(h.target.key,h.composition),T=ln(h.target.key)??h.target.key,K=v?.graph?.elements.get(T);K&&_.add(K.sourceFile)}else if(h.target.kind==="route"){let v=i.get(o.resolveSelector(h.target.composition).key);v&&_.add(v.entryFile)}else if(h.target.kind==="page-unit"){let v=i.get(o.resolveSelector(h.target.composition).key);v&&_.add(v.entryFile)}else if(h.target.kind==="page-block"){let v=i.get(o.resolveSelector(h.target.composition).key),T=v?.pageBlockIndex?.bindings.get(h.target.blockKey);if(T&&(_.add(T.ownerFile),_.add(T.descriptor.source.file)),v?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let K=v.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);K&&(_.add(K.ownerFile),_.add(K.descriptor.source.file))}}else if(h.target.kind==="source-file")_.add(h.target.path);else if(h.target.kind==="source-batch")for(let v of h.target.paths)_.add(v);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let v=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let T of v){let K=Qo(T,h.composition),X=ln(T)??T,ee=K?.graph?.elements.get(X);ee&&_.add(ee.sourceFile)}}await Pt(_)}async function Mt(h){if(h.params.kind!=="source-edit")return Ou(h,"invalid-params","source-edit requires source-edit params");for(let _ of h.params.edits){let v=DB(_);if(!v.ok)return Ou(h,v.errorCode,v.message,v.details)}m+=1;try{let _=await z_(h.params.edits);if(!_.ok)return Ou(h,_.errorCode,_.message,_.details);await br(h);let v={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(T=>T.operation==="delete"?{operation:"delete",file:T.path,baseContentHash:T.baseContentHash??null}:{operation:"upsert",file:T.path,baseContentHash:T.baseContentHash??null,content:T.content})};return await Fr({request:h,filePlan:v})}catch(_){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:Q.INTERNAL_ERROR,message:tn(_)}}}finally{m-=1}}async function Lr(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return se(h,Q.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let _=await Gi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(T=>T.materialization.files.map(K=>({path:K.pathTemplate,content:K.content}))),...h.params.artifact.pages.flatMap(T=>T.materialization.files.map(K=>({path:K.pathTemplate,content:K.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!_.ok)return se(h,Q.MATERIALIZATION_REJECTED,_.message);let v=await qd({artifact:h.params.artifact,exists:T=>n.exists(T)});return v.ok?await Fr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:v.files},output:{kind:"insert-page-resource",package_instance_id:v.packageInstanceId,pages:v.pages},historyPolicy:"none"}):se(h,v.code==="MATERIALIZATION_CONFLICT"?Q.MATERIALIZATION_CONFLICT:Q.MATERIALIZATION_REJECTED,v.message,v.path?{path:v.path}:void 0)}catch(_){return se(h,Q.INTERNAL_ERROR,tn(_))}finally{m-=1}}async function zi(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return se(h,Q.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return se(h,Q.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let _=vv(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(_.truncated)return se(h,Q.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:_.truncated.reasons});let v=_.files.filter(({path:ee})=>/\.(?:tsx?|jsx?)$/.test(ee)),T=Object.fromEntries(await Promise.all(v.map(async({path:ee})=>[ee,await n.readFile(ee)]))),K=qb({expectedUrlPath:h.params.expectedUrlPath,files:T});if(!K.ok)return se(h,K.code==="HOME_PAGE_LOCKED"?Q.HOME_PAGE_LOCKED:K.code==="ROUTE_NOT_FOUND"?Q.ROUTE_NOT_FOUND:Q.PLAN_FAILED,K.message);let X=await Promise.all(K.edits.map(async ee=>({...ee,baseContentHash:je(await n.readFile(ee.file))})));return Fr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:X},output:{kind:"delete-page-source",deleted_files:K.deletedFiles,updated_files:K.updatedFiles,preserved_shared_files:K.preservedSharedFiles,warnings:K.warnings},historyPolicy:"none"})}catch(_){return se(h,Q.INTERNAL_ERROR,tn(_))}finally{m-=1}}async function $_(h,_){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return se(h,Q.UNSUPPORTED_OPERATION,"Only page-unit insert-child and replace-node materialization are supported by this transaction.");if(h.params.kind!=="insert-child"&&h.params.kind!=="replace-node"||h.kind!==h.params.kind)return se(h,Q.INVALID_PARAMS,"Page-unit materialization operation kind must match its params.");if(h.params.kind==="insert-child"){if(!("kind"in h.params.position)||h.params.position.kind!=="page-composition")return se(h,Q.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return se(h,Q.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let v=_.document,T=_.pageCompositionProjection;if(!v||v.pageComposition?.status!=="supported"||!T||T.status!=="supported")return se(h,Q.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==v.version||T.documentVersion!==v.version)return se(h,Q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${v.version}).`);let K=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!K)return se(h,Q.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let X=h.params.kind==="insert-child"?h.params.position:null,ee=await Gi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:K.files.map(oe=>({path:oe.pathTemplate,content:oe.content})),exists:oe=>n.exists(oe),readFile:oe=>n.readFile(oe)});if(!ee.ok)return se(h,Q.MATERIALIZATION_REJECTED,ee.message);let ne=await mv(n,Object.keys(K.projectDependencies??{})),de=await sf({manifest:K,generatedRoot:"components/site/generated",controlledFiles:K.files.map(oe=>({pathTemplate:oe.pathTemplate})),exists:oe=>n.exists(oe),availableHostDependencies:ne,hostCapabilities:Hd(),commit:async oe=>{let re=await n.readFile(_.entryFile),me=_.document,Ie=_.pageCompositionProjection;if(!me||me.pageComposition?.status!=="supported"||me.version!==h.documentVersion||!Ie||Ie.status!=="supported"||Ie.documentVersion!==me.version)return{ok:!0,data:se(h,Q.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Be=oe.entry.path,xe=Q_(oe.instanceName),Xe,Le=[];if(h.params.kind==="insert-child"){if(!X||!("kind"in X)||X.kind!=="page-composition")return{ok:!0,data:se(h,Q.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ve=Ss({routeId:_.routeId,entryFile:_.entryFile,currentDocumentVersion:me.version,expectedDocumentVersion:h.documentVersion,source:re,projection:Ie,placementKey:X.placementKey,component:{source:Be,exportName:oe.entry.export.kind==="default"?"default":oe.entry.export.name,localName:xe}});if(!Ve.ok)return{ok:!0,data:se(h,Du(Ve.error.code),Ve.error.message,{diagnostics:Ve.error.diagnostics})};let ze=Ve.plan.rewriteStep,bt;switch(ze.kind){case"insert-root-expression":bt=Is({source:re,locator:ze.locator,expectedSourceHash:ze.sourceHash,action:{kind:"insert",jsx:ze.node.jsx,placement:ze.placement,replaceOriginal:ze.replaceOriginal}});break;case"insert-child":bt=An({source:re,locator:ze.parentLocator,node:ze.node,placement:ze.placement,...ze.anchorLocator?{anchorLocator:ze.anchorLocator}:{}});break;default:bt={ok:!1,source:re,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(ze)}`}}}if(!bt.ok)return{ok:!0,data:se(h,Q.AST_PARSE_ERROR,bt.diagnostic.message)};Xe=bt.source}else{let Ve=kf({routeId:_.routeId,composition:_.composition,entryFile:_.entryFile,currentDocumentVersion:me.version,expectedDocumentVersion:h.documentVersion,source:re,projection:Ie,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Ve.ok)return{ok:!0,data:se(h,Du(Ve.error.code),Ve.error.message,{diagnostics:Ve.error.diagnostics})};let ze=Ve.plan.rewriteStep,bt;switch(ze.kind){case"replace-root-expression":bt=Is({source:re,locator:ze.locator,expectedSourceHash:ze.sourceHash,action:{kind:"replace",jsx:`<${xe} />`}});break;case"replace-node":bt=ti({source:re,locator:ze.locator,node:{jsx:`<${xe} />`}});break;default:bt={ok:!1,source:re,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${ze.kind}`}}}if(!bt.ok)return{ok:!0,data:se(h,Q.AST_PARSE_ERROR,bt.diagnostic.message)};let Dr=await wu({routeState:_,placementUnitKey:h.target.placementUnitKey,source:re,mutatedSource:bt.source});Xe=Dr.source,Le=await Promise.all(Dr.files.map(async qn=>({operation:"delete",file:qn,baseContentHash:je(await n.readFile(qn))})))}let Z=Tn({source:Xe,moduleSpecifier:b(_.entryFile,Be),imports:oe.entry.export.kind==="default"?[{kind:"default",local:xe}]:[{kind:"named",imported:oe.entry.export.name,local:xe}]});if(!Z.ok)return{ok:!0,data:se(h,Q.AST_PARSE_ERROR,Z.diagnostic.message)};let ue=oe.files.map(Ve=>({operation:"create-only",file:Ve.path,content:Ve.content})),Re=[{operation:"upsert",file:_.entryFile,content:Z.source,baseContentHash:je(re)},...ue,...Le];m+=1;try{let Ve=await Fr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:_.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Re}});return!Ve.ok&&Ve.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ve.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ve}}finally{m-=1}}});return de.ok?de.data:se(h,de.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?Q.MATERIALIZATION_CONFLICT:Q.MATERIALIZATION_REJECTED,de.error.message,{materializationCode:de.error.code})}async function U_(h,_){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return se(h,Q.UNSUPPORTED_OPERATION,"Only page-block insert-child and replace-node use this materialization transaction.");if(h.params.kind!==h.kind||h.kind==="replace-node"&&h.params.kind!=="replace-node"||h.kind==="insert-child"&&h.params.kind!=="insert-child")return se(h,Q.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let v=_.document,T=_.pageBlockIndex;if(!v||!T||T.diagnostics.length>0)return se(h,Q.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==v.version||T.documentVersion!==v.version)return se(h,Q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${v.version}).`);let K=yi(T,h.target,h.documentVersion,h.selectionRef);if(!K.ok)return se(h,Ia(K.code),K.message);let X=K.binding;if(!(h.kind==="insert-child"?X.descriptor.capabilities.insert:X.descriptor.capabilities.replace)){let xe=X.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return se(h,Q.UNSUPPORTED_OPERATION,xe)}let ne=(h.kind==="insert-child",h.params);if(ne.kind!==h.kind)return se(h,Q.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let de=ne.node;if(de.kind!=="component-call"||!de.materialization)return se(h,Q.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let oe;if(ne.kind==="insert-child"){let xe=ne.position;if(!("kind"in xe&&xe.kind==="block-boundary"))return se(h,Q.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(xe.documentVersion!==h.documentVersion)return se(h,Q.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let Xe=Jc(T,xe);if(!Xe.ok)return se(h,Ia(Xe.code),Xe.message);oe=Xe.boundary}let re=de.materialization,me=await Gi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:re.files.map(xe=>({path:xe.pathTemplate,content:xe.content})),exists:xe=>n.exists(xe),readFile:xe=>n.readFile(xe)});if(!me.ok)return se(h,Q.MATERIALIZATION_REJECTED,me.message);let Ie=await mv(n,Object.keys(re.projectDependencies??{})),Be=await sf({manifest:re,generatedRoot:"components/site/generated",controlledFiles:re.files.map(xe=>({pathTemplate:xe.pathTemplate})),exists:xe=>n.exists(xe),availableHostDependencies:Ie,hostCapabilities:Hd(),commit:async xe=>{let Xe=_.document,Le=_.pageBlockIndex;if(!Xe||!Le||Xe.version!==h.documentVersion||Le.documentVersion!==Xe.version||!Le.bindings.has(X.blockKey))return{ok:!0,data:se(h,Q.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let Z=Le.bindings.get(X.blockKey);if(!Z||Z.ownerFile!==X.ownerFile||Z.ownerSourceHash!==X.ownerSourceHash||Z.sourceHash!==X.sourceHash)return{ok:!0,data:se(h,Q.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let ue=new Set([X.ownerFile,X.descriptor.source.file,...oe?[oe.ownerFile,oe.anchorLocator.file,...oe.parentLocator?[oe.parentLocator.file]:[]]:[]]),Re=new Map;try{for(let ze of ue)Re.set(ze,await n.readFile(ze))}catch{return{ok:!0,data:se(h,Q.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ve=wb({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:X,...oe?{boundary:oe}:{},operation:ne.kind,materialization:xe,files:Re});if(!Ve.ok){let ze=X_(Ve.code);return{ok:!0,data:se(h,ze,Ve.message,{materializationCode:Ve.code})}}m+=1;try{let ze=await Fr({request:h,filePlan:Ve.plan});return!ze.ok&&ze.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:ze.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:ze}}finally{m-=1}}});return Be.ok?Be.data:se(h,Be.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?Q.MATERIALIZATION_CONFLICT:Q.MATERIALIZATION_REJECTED,Be.error.message,{materializationCode:Be.error.code})}async function V_(h,_){if(h.kind!=="move-node"&&h.kind!=="remove-node")return se(h,Q.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let v=_.document,T=_.pageCompositionProjection;if(!v||v.pageComposition?.status!=="supported"||!T||T.status!=="supported")return se(h,Q.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==v.version||T.documentVersion!==v.version)return se(h,Q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${v.version}).`);let K=await n.readFile(_.entryFile),X=kf({routeId:_.routeId,composition:_.composition,entryFile:_.entryFile,currentDocumentVersion:v.version,expectedDocumentVersion:h.documentVersion,source:K,projection:T,placementUnitKey:h.target.placementUnitKey,operation:h.kind,targetPlacement:h.kind==="move-node"&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="page-composition"?h.params.target:void 0});if(!X.ok)return se(h,Du(X.error.code),X.error.message,{diagnostics:X.error.diagnostics});let ee=X.plan.rewriteStep,ne;switch(ee.kind){case"move-node":ne=wo({source:K,locator:ee.locator,targetParentLocator:ee.targetParentLocator,placement:ee.placement,...ee.anchorLocator?{anchorLocator:ee.anchorLocator}:{}});break;case"remove-node":ne=Ao({source:K,locator:ee.locator});break;case"remove-root-expression":ne=Is({source:K,locator:ee.locator,expectedSourceHash:ee.sourceHash,action:{kind:"remove"}});break;default:ne={ok:!1,source:K,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${ee.kind}`}}}if(!ne.ok)return se(h,Q.AST_PARSE_ERROR,ne.diagnostic.message);let de=ne.source,oe=[];if(h.kind==="remove-node"){let me=await wu({routeState:_,placementUnitKey:h.target.placementUnitKey,source:K,mutatedSource:de});de=me.source,oe=await Promise.all(me.files.map(async Ie=>({operation:"delete",file:Ie,baseContentHash:je(await n.readFile(Ie))})))}let re=[{operation:"upsert",file:_.entryFile,content:de,baseContentHash:je(K)},...oe];m+=1;try{return await Fr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:_.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:re}})}finally{m-=1}}async function J_(h,_){if(h.kind!=="move-node"&&h.kind!=="remove-node")return se(h,Q.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let v=_.document,T=_.pageBlockIndex;if(!v||!T||T.diagnostics.length>0)return se(h,Q.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==v.version||T.documentVersion!==v.version)return se(h,Q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${v.version}).`);let K=yi(T,h.target,h.documentVersion,h.selectionRef);if(!K.ok)return se(h,Ia(K.code),K.message);let X=K.binding;if(X.documentVersion!==v.version)return se(h,Q.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?X.descriptor.capabilities.move:X.descriptor.capabilities.remove)){let Le=X.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return se(h,Q.UNSUPPORTED_OPERATION,Le)}if(h.kind==="remove-node"){let Le=[...i.values()].filter(Z=>Z.dependencyFiles.has(X.ownerFile));if(Le.includes(_)||Le.push(_),Le.some(Z=>!Z.pageBlockIndex||Z.pageBlockIndex.descriptors.length<=1))return se(h,Q.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let ne=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return se(h,Q.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===X.blockKey)return se(h,Q.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Le=Jc(T,h.params.target);if(!Le.ok)return se(h,Ia(Le.code),Le.message);let Z=T.bindings.get(h.params.target.anchorBlockKey);if(!Z||!X.descriptor.siblingBlockKeys.includes(Z.blockKey)||!Z.descriptor.siblingBlockKeys.includes(X.blockKey)||Z.ownerFile!==X.ownerFile||Z.root.ownerNode.kind!==X.root.ownerNode.kind||Z.root.ownerNode.key!==X.root.ownerNode.key||Z.root.parentStructuralPath!==X.root.parentStructuralPath)return se(h,Q.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(ne=Le.boundary,ne.ownerFile!==X.ownerFile||ne.sourceHash!==X.ownerSourceHash||!ne.parentLocator)return se(h,Q.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let de=X.ownerFile,oe=await n.readFile(de);if(je(oe)!==X.ownerSourceHash)return se(h,Q.VERSION_STALE,"The page-block owner source changed after resolution.");let re=X.descriptor.source.file===de?oe:await n.readFile(X.descriptor.source.file);if(je(re)!==X.descriptor.source.contentHash)return se(h,Q.VERSION_STALE,"The selected page-block source changed after resolution.");let me=K_(X),Ie=h.kind==="remove-node"?Ao({source:oe,locator:me}):wo({source:oe,locator:me,targetParentLocator:Tu(ne.parentLocator),anchorLocator:Tu(ne.anchorLocator),placement:ne.placement});if(!Ie.ok)return se(h,Q.AST_PARSE_ERROR,Ie.diagnostic.message);let Be=Ie.source,xe=[];if(h.kind==="remove-node"&&X.root.ownerNode.kind==="route-member"&&X.root.callChain.length>0&&X.descriptor.placementUnitKey){let Le=await wu({routeState:_,placementUnitKey:X.descriptor.placementUnitKey,source:oe,mutatedSource:Be});Be=Le.source,xe=Le.files}let Xe=[{operation:"upsert",file:de,content:Be,baseContentHash:X.ownerSourceHash},...await Promise.all(xe.map(async Le=>({operation:"delete",file:Le,baseContentHash:je(await n.readFile(Le))})))];m+=1;try{return await Fr({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Xe}})}finally{m-=1}}function K_(h){return Tu(h.ownerLocator)}function Tu(h){return{kind:"jsx-node",strategy:"source-range",sourceRange:h.sourceRange,...h.structuralPath&&h.componentName?{expectedIdentity:{file:h.file,component:h.componentName,structuralPath:h.structuralPath}}:{}}}function Ia(h){return h==="VERSION_STALE"?Q.VERSION_STALE:h==="INVALID_PARAMS"?Q.INVALID_PARAMS:Q.INVALID_TARGET}function X_(h){return h==="VERSION_STALE"?Q.VERSION_STALE:h==="INVALID_PARAMS"?Q.INVALID_PARAMS:h==="INVALID_TARGET"?Q.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?Q.MATERIALIZATION_REJECTED:Q.UNSUPPORTED_OPERATION}async function wu(h){let _={source:h.mutatedSource,files:[]},v=h.routeState.graph,T=h.routeState.pageCompositionProjection;if(!v||!T||T.status!=="supported"||!n.listFiles)return _;let X=T.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!X)return _;let ee=[...v.elements.values()].find(Z=>Z.sourceFile===h.routeState.entryFile&&Z.importedFrom&&S(Z.sourceRange,X));if(!ee?.importedFrom||!ee.exportName)return _;let ne=E(ee.importedFrom),de="components/site/generated/";if(!ne.startsWith(de))return _;let oe=ne.slice(de.length).split("/")[0];if(!oe||!/-[0-9a-f]{8}$/i.test(oe))return _;let re=`${de}${oe}`;if([...v.elements.values()].filter(Z=>Z.sourceFile===h.routeState.entryFile&&E(Z.importedFrom??"")===ne).length!==1)return _;let Ie=await n.listFiles({maxFiles:5e3,maxDepth:32}),Be=Array.isArray(Ie)?Ie:Ie.files;if(!Array.isArray(Ie)&&Ie.truncated)return _;let xe=Be.map(({path:Z})=>Z).filter(Z=>Z===re||Z.startsWith(`${re}/`));if(xe.length===0||!xe.includes(ne))return _;for(let{path:Z}of Be)if(!(Z===h.routeState.entryFile||Z===re||Z.startsWith(`${re}/`)))try{if((await n.readFile(Z)).includes(oe))return _}catch{return _}let Xe=b(h.routeState.entryFile,ne),Le=ri({source:h.mutatedSource,moduleSpecifier:Xe,imports:ee.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:ee.exportName}]});return Le.ok?Le.source.includes(oe)?{source:Le.source,files:[]}:{source:Le.source,files:xe.sort((Z,ue)=>Z.localeCompare(ue))}:_}async function z_(h){if(n.getFileInfo){for(let ee of h)if(await n.exists(ee.path)&&await n.getFileInfo(ee.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${ee.path}`,details:{path:ee.path}}}for(let ee of h){if(ee.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(ee.path))continue;let ne=await n.exists(ee.path)?await qu(n,ee.path):null;if(ne?.ok){let de=dB(ne.content,ee.content);if(!de.ok)return{ok:!1,errorCode:"invalid-params",message:de.message,details:{path:ee.path,code:de.code}}}}let _=H_(h);if(_.length===0)return{ok:!0};let v=LB(n,h),T=new Map,K=(ee,ne)=>{let de=T.get(ee);if(de?.source===ne)return de.result;let oe=Fe(ee,ne);return T.set(ee,{source:ne,result:oe}),oe},X;try{X=await ev(_,async ee=>{let ne=i.get(ee);return ne?[...(await Y(ne.entryFile,await v.readFile(ne.entryFile),v,{validationOnly:!0,parseModule:K,validatedImports:p.getImports})).parsedModules.values()]:[]})}catch(ee){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${tn(ee)}`,details:{compositionKeys:_}}}for(let ee of X)p.remember(ee);return{ok:!0}}function H_(h){return h.map(v=>v.path).some(Sv)?[...i.keys()]:[]}function Ou(h,_,v,T){let K=ia(_);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:K,message:v,...T?{details:T}:{}}}}async function Lu(h){let _=[];for(let v of new Set(h))_.push(await W_(v));return _}async function W_(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,V(h)),exists:!1};let v=await n.readFile(h);return{file:h,content:v,version:Math.max(1,V(h)),exists:!0,sha256:je(v)}}async function Kg(h,_,v,T){if(!e.historyStore)return null;let K=new Map(_.map(ne=>[ne.file,ne])),X=new Map(v.map(ne=>[ne.file,ne])),ee=[...new Set([...K.keys(),...X.keys()])].sort().map(ne=>{let de=K.get(ne),oe=X.get(ne);return{path:ne,preDigest:de?.exists===!1||!de?null:je(de.content),postDigest:oe?.exists===!1||!oe?null:je(oe.content)}});return{schemaVersion:2,transactionId:`${h}:${T.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:T,files:ee}}async function Xg(h){return!h||!e.historyStore||await e.historyStore.writeTransactionJournal(h),h}async function qo(h){h&&e.historyStore&&await e.historyStore.clearTransactionJournal(h.transactionId)}async function Fu(h,_){let v=[];try{for(let T of h)await zg(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),v.push(T.file)}catch(T){let K=await G_(_.filter(X=>v.includes(X.file)));return K.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${tn(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${K.failedFiles.join(", ")}: ${tn(T)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(Y_)}}async function zg(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function G_(h){let _=[];for(let v of h)try{await zg(v),typeof n.bumpVersion=="function"&&n.bumpVersion(v.file)}catch{_.push(v.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}function Y_(h){let _=h.exists!==!1;return{file:h.file,content:_?h.content:"",version:h.version,exists:_,..._?{sha256:je(h.content)}:{}}}async function Fr(h){return y.runExclusive(()=>Z_(h))}async function Z_(h){let _=h.filePlan.edits.map(Z=>Z.file),v=o.resolveSelector(h.request.composition),T=v.context,K=h.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:G(_)},X=await Lu(_),ee=new Map(X.filter(Z=>Z.exists!==!1).map(Z=>[Z.file,Z.content])),ne=Wg(),de=new Map(d),oe=new Set(g),re=new Set([...i.values()].filter(Z=>h.filePlan.edits.some(ue=>ue.operation==="delete"&&ue.file===Z.entryFile)).map(Z=>Z.key)),me=h.filePlan.edits.map(Z=>Z.operation==="delete"?{file:Z.file,content:"",version:0,exists:!1}:{file:Z.file,content:Z.content,version:0,exists:!0,sha256:je(Z.content)}),Ie={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(Z=>Z.operation==="delete"?{kind:"delete",path:Z.file}:{kind:Z.operation==="create-only"?"create-only":"upsert",path:Z.file,content:Z.content})},Be=null,xe=!1,Xe=await Ul({overlay:ee,exists:Z=>n.exists(Z),plan:Ie,buildCandidate:async({plan:Z})=>({plan:Z}),prepareHistory:async()=>{let Z=h.historyPolicy==="none"?null:await l.prepareAppend({composition:o.resolveSelector(h.request.composition).context,operationId:h.request.id,kind:h.request.kind,target:h.request.target,preSnapshots:X,postSnapshots:me,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...K?{provenance:K}:{}}),ue=Z?.historyTransition?Z.historyTransition:e.historyStore?EB(await e.historyStore.readIndex()):null;if(e.historyStore&&!ue)throw new Error("Durable history did not provide an exact index transition.");return Be=await Kg(h.request.id,X,me,ue),Be=await Xg(Be),{history:Z,historyTransition:ue}},reverify:async()=>{},writeCandidate:async()=>{let Z=await u.executeFilePlan(h.filePlan);if(!Z.ok)throw new Wl(Z);return{postSnapshots:await Lu(Z.affectedFiles),affectedFiles:Z.affectedFiles,internalResultVersion:Z.resultVersion}},validateCandidate:async({candidate:Z,receipt:ue})=>{let Re=await j(ue.affectedFiles,{changed:!0,minimumVersion:ue.internalResultVersion,publish:!1,excludedCompositionKeys:re});if(Re.failedRoutes.length>0)throw new Ho(Re.failedRoutes);let Ve=Yg(ne,Re.candidateRouteStates??[]),ze=Gg(Ve,v.key);return{...Z,rebuild:Re,routeSnapshots:Ve,resultVersion:ze,...yv(h.selectionRef,Ve.map(bt=>bt.state.document))?{selectionRef:yv(h.selectionRef,Ve.map(bt=>bt.state.document))}:{}}},publishCandidate:async({candidate:Z,history:ue,receipt:Re})=>{ue?.history&&(await l.publishPrepared(ue.history),xe=!0);let Ve=Z.resultVersion??Re.internalResultVersion;return{composition:T,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Ve,affectedFiles:Re.affectedFiles,fileChanges:Re.postSnapshots.map(ze=>({path:ze.file,operation:ze.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...Z.selectionRef?{selectionRef:Z.selectionRef}:{}}},swapCandidate:({candidate:Z,receipt:ue})=>{Z.routeSnapshots&&va(Z.routeSnapshots),Z.rebuild?.candidateSourceCache&&oa(d,Z.rebuild.candidateSourceCache),vt(ue.postSnapshots)},finalizeCandidate:async()=>{await qo(Be);for(let Z of re)i.delete(Z)},emitCommitted:({candidate:Z,published:ue})=>{ce(ue,Z.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:Z,receipt:ue})=>{if(xe)throw new Error("history was published before transaction finalization failed");if(ue){let Re=await Fu(X,ue.postSnapshots);if(!Re.ok)throw new Error(Re.reason)}va(ne),oa(d,de),pn(oe),Z?.history&&await l.discardPrepared?.(Z.history),await qo(Be)}});if(Xe.ok)return Xe.published;if(Xe.stage==="precheck"||Xe.stage==="build")try{await qo(Be)}catch(Z){let ue=await _a(tn(Z));return se(h.request,ue,"Unable to clear an uncommitted transaction journal.")}if(Xe.recoveryRequired){let Z=await _a(Xe.reason);return se(h.request,Z===Q.RECOVERY_PERSIST_FAILED?Z:Q.ROLLBACK_FAILED,Xe.reason)}let Le=Xe.error;return Le instanceof Wl?{...se(h.request,ia(Le.result.errorCode),Le.result.reason),...Le.result.affectedFiles?{affectedFiles:Le.result.affectedFiles}:{}}:Le instanceof Ho?se(h.request,Q.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Im(Le.failedRoutes)}`,{failedRoutes:Le.failedRoutes}):se(h.request,qg(Xe.stage),tn(Le))}async function Hg(h){return y.runExclusive(async()=>{let _=h==="undo"?await l.prepareUndo():await l.prepareRedo();return _?q_(h,_):{composition:o.entries[0].context,requestId:h,kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:o.initialVersions.get(o.entries[0].key)??0,error:{code:Q.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function q_(h,_){let v=_.entry,T=h==="undo"?v.preSnapshots:v.postSnapshots,K=h==="undo"?v.postSnapshots:v.preSnapshots,X=T.map(ue=>ue.file),{context:ee,key:ne}=q(v,X),de=await Lu(X),oe=new Map(de.filter(ue=>ue.exists!==!1).map(ue=>[ue.file,ue.content])),re=J(ne),me=Wg(),Ie=new Map(d),Be=new Set(g),xe=null,Xe=!1,Le,Z=await Ul({overlay:oe,plan:{operationId:`${h}:${v.operationId}`,intents:T.map(ue=>ue.exists===!1?{kind:"delete",path:ue.file}:{kind:"upsert",path:ue.file,content:ue.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(xe=await Kg(`${h}:${v.operationId}`,de,T,_.historyTransition),xe=await Xg(xe),_),reverify:async()=>{},writeCandidate:async()=>{let ue=await Fu(T,K);if(!ue.ok)throw new Error(ue.reason);return{snapshots:ue.snapshots}},validateCandidate:async({candidate:ue})=>{Le=A(v,X);let Re=await j(X,{changed:!0,minimumVersion:re+1,publish:!1,affectedCompositionKeys:Le});if(Re.failedRoutes.length>0)throw new Ho(Re.failedRoutes);let Ve=Yg(me,Re.candidateRouteStates??[]),ze=Gg(Ve,ne);return{...ue,rebuild:Re,routeSnapshots:Ve,resultVersion:ze}},publishCandidate:async({candidate:ue,history:Re,receipt:Ve})=>{if(!Re)throw new Error("history cursor intent is missing");await l.publishPrepared(Re),Xe=!0;let ze=ue.resultVersion??re+1;return{composition:ee,requestId:h,kind:v.kind,target:v.target,ok:!0,resultVersion:ze,affectedFiles:X,fileChanges:Ve.snapshots.map(bt=>({path:bt.file,operation:bt.exists===!1?"delete":"upsert"})),...v.output?{output:v.output}:{}}},swapCandidate:({candidate:ue,receipt:Re})=>{ue.routeSnapshots&&va(ue.routeSnapshots),ue.rebuild?.candidateSourceCache&&oa(d,ue.rebuild.candidateSourceCache),vt(Re.snapshots)},finalizeCandidate:async()=>{await qo(xe)},emitCommitted:({candidate:ue,published:Re})=>ce(Re,ue.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:ue,receipt:Re})=>{if(Xe)throw new Error("history cursor was published before transaction finalization failed");if(Re){let Ve=await Fu(K,Re.snapshots);if(!Ve.ok)throw new Error(Ve.reason)}va(me),oa(d,Ie),pn(Be),ue&&await l.discardPrepared?.(ue),await qo(xe)}});if(Z.ok)return Z.published;if(Z.stage==="precheck"||Z.stage==="build")try{await qo(xe)}catch(ue){let Re=await _a(tn(ue));return{composition:ee,requestId:h,kind:v.kind,target:v.target,ok:!1,resultVersion:re,error:{code:Re,message:"Unable to clear an uncommitted transaction journal."}}}if(Z.recoveryRequired){let ue=await _a(Z.reason);return{composition:ee,requestId:h,kind:v.kind,target:v.target,ok:!1,resultVersion:re,affectedFiles:X,error:{code:ue===Q.RECOVERY_PERSIST_FAILED?ue:Q.ROLLBACK_FAILED,message:Z.reason}}}return{composition:ee,requestId:h,kind:v.kind,target:v.target,ok:!1,resultVersion:re,affectedFiles:X,error:{code:Z.error instanceof Ho?Q.ROUTE_REBUILD_FAILED:qg(Z.stage),message:tn(Z.error),...Z.error instanceof Ho?{details:{failedRoutes:Z.error.failedRoutes}}:{}}}}function Wg(){return[...i.values()].map(h=>({composition:h.composition,key:h.key,routeId:h.routeId,state:{...h,dependencyFiles:new Set(h.dependencyFiles),fileVersions:new Map(h.fileVersions)}}))}function Gg(h,_){return h.find(T=>T.key===_)?.state.graph?.version??o.initialVersions.get(_)??0}function Yg(h,_){let v=new Map(h.map(T=>[T.key,T]));for(let T of _)v.set(T.key,T);return[...v.values()]}function va(h){for(let _ of i.values())N(_);for(let _ of h){let v={..._.state,dependencyFiles:new Set(_.state.dependencyFiles),fileVersions:new Map(_.state.fileVersions)};i.set(_.key,v),C(v,v.dependencyFiles)}}async function ka(h){let _=i.get(h);if(!_)throw new Error(`Composition not found: ${h}`);if(_.graph)return;let v=await n.readFile(_.entryFile);await he(h,v)}function Qo(h,_){let v=i.get(o.resolveSelector(_).key)??null;return!v||!Zg(v,h)?null:v}function Zg(h,_){if(h.documentIndex?.entriesByKey.has(_)||h.graph?.elements.has(_))return!0;let v=ln(_);return v&&v!==_?h.graph?.elements.has(v)===!0:!1}function se(h,_,v,T){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:_,message:v,...T?{details:T}:{}}}}function qg(h){return h==="validate"?Q.ROUTE_REBUILD_FAILED:h==="publish"?Q.HISTORY_COMMIT_FAILED:Q.WRITE_IO_ERROR}async function _a(h){if(f=!0,!l.markRecoveryRequired)return Q.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),Q.RECOVERY_REQUIRED}catch{return Q.RECOVERY_PERSIST_FAILED}}function Q_(h){let v=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return v?`Prefab${v}`:"GeneratedPrefab"}function Du(h){return h==="VERSION_STALE"?Q.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?Q.CROSS_PAGE_MOVE_UNSUPPORTED:Q.UNSUPPORTED_OPERATION}async function Qg(h){if(h.target.kind==="route"){let v=i.get(o.resolveSelector(h.target.composition).key)??null;return v?(v.graph||await ka(v.key),v):se(h,Q.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let v=i.get(o.resolveSelector(h.target.composition).key)??null;return v?(v.graph||await ka(v.key),v):se(h,Q.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let v=i.get(o.resolveSelector(h.target.composition).key)??null;return v?(v.graph||await ka(v.key),v):se(h,Q.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return se(h,Q.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let _=i.get(o.resolveSelector(h.composition).key)??null;return _?(_.graph||await ka(_.key),Zg(_,h.target.key)?_:se(h,Q.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):se(h,Q.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(),p.clear(),g.clear()},registerComposition(h,_){let v=o.register({context:h,entryFile:_}),T=i.get(v.key);if(T?.entryFile===_)return;T&&N(T);let K=hv(v.context,_);i.set(v.key,K),C(K,K.dependencyFiles),r.emit({type:"graph-invalidated",composition:v.context})},unregisterComposition(h){let _=o.resolveSelector(h),v=i.get(_.key);v&&(N(v),i.delete(_.key),o.unregister(_.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:_.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let _=o.resolveSelector(h),v=i.get(_.key);if(!v)throw new Error(`Composition not registered: ${_.key}`);if(v.graph)t="ready";else{t="building";try{let T=await n.readFile(v.entryFile);await he(_.key,T),t="ready",r.emit({type:"graph-ready",composition:_.context,version:i.get(_.key)?.graph?.version??0})}catch(T){throw t="idle",r.emit({type:"graph-error",composition:_.context,message:tn(T)}),T}}},getDocument(h){let _=o.resolveSelector(h),v=i.get(_.key);if(!v)throw new Error(`Composition not registered: ${_.key}`);if(!v.document)throw new Error(`Composition not built: ${_.key}`);return v.document},async getHistoryStatus(){await x;let h=await l.getStatus?.();return h?{...h,recoveryRequired:f}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:f}},getObjectEditContext(h,_,v){let T=Qo(h,_),K=ln(h)??h;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let X=T.detailProjections.get(K);if(X){let ee=T.graph.elements.get(K);if(!ee)throw new Error(`Key not found: ${h}`);let ne=CB(h,K,v),de=new Map;if(X.isRepeat&&ne?.instanceIndex!==void 0)for(let me of ee.attributes??[])de.set(me.name,Zp({file:ee.sourceFile,source:d.get(ee.sourceFile)??"",element:ee,propertyName:me.name,selectionRef:ne,graph:T.graph,sources:d}));let oe=OI({element:ee,graph:T.graph,source:d.get(ee.sourceFile),documentVersion:T.graph.version,selectionRef:v,isRepeat:X.isRepeat,propertyProvenance:X.propertyProvenances,repeatTargets:de}),re=DI(K,T.graph,T.topology,T.capabilities,X.textSources,X.provenances,X.dynamicData,oe);return h===K?re:av(re,h,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,_){let v=Qo(h,_),T=ln(h)??h;if(v?.graph&&v.topology&&v.capabilities&&v.detailProjections){let K=v.detailProjections.get(T);if(K){let X=FI(T,v.graph,v.topology,v.capabilities,K.textSources,K.writeTarget,K.provenances,K.conditional,K.componentSemantic,K.styleSource,K.dynamicData);return h===T?X:sv(X,h,v.document??null,v.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,_){let v=Qo(h,_),T=ln(h)??h;if(!v?.graph)throw new Error(`Key not found: ${h}`);let K=v.graph.elements.get(T);if(!K)throw new Error(`Key not found: ${h}`);let X=d.get(K.sourceFile);if(X===void 0)throw new Error(`Source not loaded: ${K.sourceFile}`);return yd({key:T,route:{composition:v.composition,routeId:v.routeId,graph:v.graph,source:X}})},refreshSourceForKey:Or,async execute(h){if(await x,f)return se(h,Q.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return Mt(h);if(h.kind==="insert-page-resource")return Lr(h);if(h.kind==="delete-page-source")return zi(h);let _=await Qg(h);if("ok"in _)return _;await br(h);let v=await Qg(h);if("ok"in v)return v;let T=v;if(h.target.kind==="page-unit"){let re=h;return h.kind==="insert-child"||h.kind==="replace-node"?$_(re,T):h.kind==="move-node"||h.kind==="remove-node"?V_(re,T):se(h,Q.UNSUPPORTED_OPERATION,"Only page-unit insert-child, replace-node, move-node, and remove-node are currently supported by the page composition transaction.")}if(h.target.kind==="page-block"){let re=h;return h.kind==="insert-child"||h.kind==="replace-node"?U_(re,T):h.kind==="move-node"||h.kind==="remove-node"?J_(re,T):se(h,Q.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let X=h.params,ee=h.target.kind==="node"?h.target.key:null;if(X.kind==="move-node"&&"kind"in X.target&&X.target.kind==="source-sibling"){let re=X.target,me=ee?T.document?.entries.find(ue=>ue.key===ee):null,Ie=T.document?.entries.find(ue=>ue.key===re.anchorKey),Be=me?.pageCompositionActionScope,xe=Be?.kind==="source-siblings"?Be.siblingKeys:null,Xe=xe?.indexOf(me?.key??"")??-1,Le=xe?.indexOf(re.anchorKey)??-1,Z=re.relation==="before"?Xe-1:Xe+1;if(!me||!Ie||!xe||Xe<0||Le!==Z||Ie.pageCompositionActionScope?.kind!=="source-siblings"||Ie.pageCompositionActionScope.siblingKeys.length!==xe.length||Ie.pageCompositionActionScope.siblingKeys.some((ue,Re)=>ue!==xe[Re])||!me.operationSummary.canMove)return se(h,Q.INVALID_TARGET,"Source sibling move is unavailable because the current source sibling scope or adjacent anchor no longer matches.")}if(!T.graph||!T.topology||!T.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:h.target.kind==="route"?Q.ROUTE_NOT_FOUND:Q.NODE_NOT_FOUND,message:h.target.kind==="route"?"Composition not ready for route target.":h.target.kind==="node"?`Target key not found: ${h.target.key}`:`${h.kind} source target execution is not implemented yet.`}};let ne=KB(T,T.graph,T.capabilities,d,i),de=await new gl(ne).plan(h);if(!de.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:ia(de.errorCode),message:de.reason}};let oe=de.plan;if(oe.steps.length===0)return h.kind==="set-props"?{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:te(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:Q.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(oe.steps.some(me=>me.type==="invoke-external-adapter")){let me=await u.execute(oe);if(!me.ok)return se(h,ia(me.errorCode),me.reason);let Ie={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(te(h),me.resultVersion),affectedFiles:me.affectedFiles,...me.selectionRef?{selectionRef:me.selectionRef}:{}};return ce(Ie,{rebuiltRoutes:[],failedRoutes:[]}),Ie}let re=await u.prepareRewritePlan(oe);return re.ok?await Fr({request:h,filePlan:re.filePlan,...re.selectionRef?{selectionRef:re.selectionRef}:{}}):se(h,ia(re.errorCode),re.reason)}catch(re){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:te(h),error:{code:Q.INTERNAL_ERROR,message:tn(re)}}}finally{m-=1}},async undo(h){if(await x,f)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:J(o.entries[0].key),error:{code:Q.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await Hg("undo")}finally{m-=1}},async redo(h){if(await x,f)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:J(o.entries[0].key),error:{code:Q.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await Hg("redo")}finally{m-=1}},notifyFileChanged(h){qe([h])},getAffectedCompositions(h){return L(h)},subscribe(h){return r.subscribe(h)}}}function MB(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function BB(e,t,n,r){let o=new Map,i=new Map,s=(d,p,g)=>{let m=d.get(p)??new Set,f=m.size;return m.add(g),d.set(p,m),m.size!==f},a=(d,p)=>{if(!d.importedFrom)return!1;if(d.exportName==="default")return s(i,d.importedFrom,p);let g=s(o,`${d.importedFrom}#${d.tag}`,p);return d.exportName&&d.exportName!==d.tag&&(g=s(o,`${d.importedFrom}#${d.exportName}`,p)||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 p=n.placements.find(m=>m.members.some(f=>f.sourceRange!==null&&sa(d.sourceRange,f.sourceRange)));if(!p)continue;let g=p.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 p=c(d);if(p)for(let g of p)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 p=ln(d.key)??d.key,g=t.elements.get(d.key)??t.elements.get(p);if(!g)continue;if(g.sourceFile===n.entryFile){if(n.container.sourceRange&&sa(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(sa(g.sourceRange,E.sourceRange)||JB(E.sourceRange,g.sourceRange))));if(y){d.pageCompositionUnitKey=y.placementUnitKey;continue}}let m=o.get(`${g.sourceFile}#${g.componentName}`);if(m){m.size===1&&(d.pageCompositionUnitKey=m.values().next().value);continue}let f=i.get(g.sourceFile);f?.size===1&&(d.pageCompositionUnitKey=f.values().next().value)}jB(e,t,n,r)}function jB(e,t,n,r){let o=new Map(e.entries.map(p=>[p.key,p])),i=e.entries.filter(p=>{let g=p.pageCompositionUnitKey;return g?p.parentKey?o.get(p.parentKey)?.pageCompositionUnitKey!==g:!0:!1}),s=new Map,a=(p,g)=>{s.set(p,Math.min(2,(s.get(p)??0)+g))},c=p=>n.placements.some(g=>g.members.some(m=>m.sourceRange!==null&&sa(p.sourceRange,m.sourceRange)));for(let p of t.elements.values())p.sourceFile!==n.entryFile||!p.importedFrom||!/^[A-Z]/.test(p.tag)||!c(p)||a(`${p.importedFrom}#${p.exportName??p.tag}`,1);let l=[...t.elements.values()].flatMap(p=>p.sourceFile!==n.entryFile&&p.importedFrom&&/^[A-Z]/.test(p.tag)?[{owner:`${p.sourceFile}#${p.componentName}`,ownerDefault:`${p.sourceFile}#default`,target:`${p.importedFrom}#${p.exportName??p.tag}`}]:[]);for(let p=0;p<=l.length;p+=1){let g=!1;for(let m of l){let f=s.get(m.owner)??s.get(m.ownerDefault)??0;if(!f)continue;let y=s.get(m.target)??0,x=Math.min(2,y+f);x!==y&&(s.set(m.target,x),g=!0)}if(!g)break}let u=p=>s.get(`${p.sourceFile}#${p.componentName}`)??s.get(`${p.sourceFile}#default`)??0;for(let p of i){p.pageCompositionActionScope={kind:"unavailable"};let g=t.elements.get(p.key);p.pageCompositionUnitKey&&g?.sourceFile===n.entryFile&&(p.pageCompositionActionScope={kind:"route-unit"})}let d=new Map;for(let p of i){let g=t.elements.get(p.key);if(!g||g.sourceFile===n.entryFile||p.key!==(ln(p.key)??p.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let f=De(m.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!f.ok||!f.match.path.isJSXElement())continue;let y=f.match.path,x=y.parentPath;if(!x||!x.isJSXFragment()&&!(x.isJSXElement()&&ft(x))){u(g)===1&&bv(y)&&(p.pageCompositionActionScope={kind:"route-unit"});continue}if(!bv(x))continue;let E=d.get(x.node)??[];E.push({entry:p,element:g,parentPath:x}),d.set(x.node,E)}for(let p of d.values()){let g=p[0];if(!g)continue;let m=g.entry.pageCompositionUnitKey,f=[],y=!!(m&&u(g.element)===1);for(let E of g.parentPath.node.children){if($B(E))continue;if(!UB(E)){y=!1;break}let b=[...t.elements.values()].find(I=>I.sourceFile===g.element.sourceFile&&I.componentName===g.element.componentName&&sa(I.sourceRange,VB(E))),S=b?o.get(b.identity.key):null;if(!b||!S||S.parentKey||S.pageCompositionUnitKey!==m||u(b)!==1){y=!1;break}f.push(S)}if(!y||f.length!==p.length||p.some(({entry:E})=>!f.some(b=>b.key===E.key)))continue;if(f.length===1){f[0].pageCompositionActionScope={kind:"route-unit"};continue}if(f.length<2)continue;let x=f.map(E=>E.key);for(let E of f)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:x}}}function bv(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function $B(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function UB(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function VB(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 sa(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function JB(e,t){return Ev(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&Ev(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function Ev(e,t,n,r){return e!==n?e-n:t-r}function KB(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 p=t.elements.get(u);for(let g of p?.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),p=t.elements.get(d.baseKey);return p?l(u,p):null},getChildNodes(u){let d=c(u),g=e.documentIndex?.entriesByKey.get(u)?.childKeys;if(g)return g.map(f=>{let y=ln(f)??f,x=t.elements.get(y);return x?l(f,x):null}).filter(f=>f!==null);let m=t.elements.get(d.baseKey);return m?m.childKeys.map(f=>{let y=t.elements.get(f);return y?l(f,y):null}).filter(f=>f!==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),p=n.get(d.baseKey);return p?{...p,key:u,constraints:p.constraints.map(g=>({...g})),...p.editModes?{editModes:{...p.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),p=t.elements.get(d.baseKey),g=p?r.get(p.sourceFile):void 0;return!p||g===void 0?null:yd({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 p=c(u);return Sm(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return Sm(e.detailProjections?.get(p.baseKey)?.elementPropertyTargets.get(d)??null,p.repeatIndex)},getPropertyState(u,d,p){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return null;let y=e.detailProjections?.get(g.baseKey)?.propertyProvenances.get(d);if(y)return y;let x=m.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:m.sourceFile,sourceRange:x.sourceRange}}:(m.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,p){let g=c(u),m=t.elements.get(g.baseKey);if(!m)return{ok:!1,errorCode:"repeat-not-found",reason:`Node not found: ${u}`};let f=p?{...p,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return Zp({file:m.sourceFile,source:r.get(m.sourceFile)??"",element:m,propertyName:d,selectionRef:f,graph:t,sources:r})},getTextProvenance(u,d){let p=c(u);return e.detailProjections?.get(p.baseKey)?.provenances.get(d)??null}};function c(u){let d=gB(u);return d?{baseKey:d.baseKey,repeatIndex:iv(e.document??null,u,d.baseKey,e.documentIndex)??ov(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=ln(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(p),isBoundary:!1,importedFrom:d.importedFrom,exportName:d.exportName,isRepeatItemRoot:i.has(p),repeatOwnerKey:i.get(p)??s.get(p),attributes:d.attributes?.map(m=>({name:m.name,value:m.value,source:m.source?{expression:m.source.expression,base:m.source.base,path:m.source.path.map(f=>({...f}))}:null,resolvedValue:m.resolvedValue}))}}}var XB={"stale-version":Q.VERSION_STALE,"capability-denied":Q.CAPABILITY_REJECTED,"invalid-params":Q.INVALID_PARAMS,"locator-miss":Q.LOCATOR_FAILED,"route-not-found":Q.ROUTE_NOT_FOUND,"unsupported-operation":Q.UNSUPPORTED_OPERATION,"invalid-target":Q.INVALID_TARGET,"ast-error":Q.AST_PARSE_ERROR,"writeback-failed":Q.WRITE_IO_ERROR,"rollback-failed":Q.RECOVERY_REQUIRED,unknown:Q.INTERNAL_ERROR};function ia(e){return XB[e]}function tn(e){return e instanceof Error&&e.message?e.message:String(e)}function Sv(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function zB(e){let t=Wo(e);if(!xB.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=>bB.map(a=>`${s}/${a}`))}function HB(e){let n=Wo(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function WB(e){return kv(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function GB(e){return kv(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function kv(e,t){let n=[];for(let r of e.matchAll(t)){let o=_v(r[1]??"");o&&n.push(o)}return n}function Iv(e,t){let n=_v(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Wo(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Wo(`${YB(e)}/${n}`):n.startsWith("/")?Wo(n.slice(1)):km(n)?Wo(n):null}function _v(e){return e.split(/[?#]/,1)[0]?.trim()??""}function km(e){return/\.css$/i.test(e)}function YB(e){let t=Wo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function ZB(e){return Array.from(new Set(e))}function Wo(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 qB(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 Yl=class{constructor(t){this.options=t,this.fileSystem=new Yi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return wa(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 Oa(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return Da(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return Ma(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ba(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=ej.safeParse(t);if(!n.success)return{result:Ta(t,n.error.issues.map(i=>i.message))};let r=new Yi(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:Ro(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=tj.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>nj(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 Gl({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=La(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 nj(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:je(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:je(e.before)},fullContent:e.after}}function rj(e){return new Yl(e)}import{SiteEditOperationRequestSchema as sj}from"@vcp-dev/contracts";import Yn from"node:fs/promises";import nn from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as oj,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as ij}from"@vcp-dev/contracts";var Zl=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Gl({...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 Da(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return Ma(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ba(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 Yn.readFile(nn.join(n,r),"utf8")},async readFileBytes(r){return Yn.readFile(nn.join(n,r))},async getFileInfo(r){let o=nn.join(n,...r.split("/"));try{let i=await Yn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await rc(nn.join(n,r),o)},async createExclusive(r,o){let i=nn.join(n,r);await Yn.mkdir(nn.dirname(i),{recursive:!0});let s=await Yn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Yn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Yn.rm(nn.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=nn.join(n,i),a=nn.dirname(nn.join(n,o));for(;a!==s&&a.startsWith(`${s}${nn.sep}`);){try{await Yn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=nn.dirname(a);continue}break}a=nn.dirname(a)}},async exists(r){try{return await Yn.access(nn.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...ij,...oj],i=[],s=new Set,a=new Set,c=0;for(let d of o)await u(d,i,1);let l=i.sort((d,p)=>d.path.localeCompare(p.path));return a.size>0?{files:l,truncated:{reasons:[...a]}}:{files:l};async function u(d,p,g){if(r.maxDepth!==void 0&&g>r.maxDepth){a.add("max-depth");return}let m=nn.join(n,...d.split("/")),f;try{f=await Yn.lstat(m)}catch{return}if(f.isSymbolicLink())return;if(f.isFile()){let x=f.ino>0?`${String(f.dev)}:${String(f.ino)}`:null;if(x&&s.has(x))return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}if(r.maxTotalBytes!==void 0&&c+f.size>r.maxTotalBytes){a.add("max-total-bytes");return}x&&s.add(x),p.push({path:d,sizeBytes:f.size}),c+=f.size;return}if(!f.isDirectory())return;if(r.maxFiles!==void 0&&p.length>=r.maxFiles){a.add("max-files");return}let y=await Yn.readdir(m,{withFileTypes:!0});for(let x of y)x.isSymbolicLink()||await u(`${d}/${x.name}`,p,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 _m(e){return new Zl(e)}var ql=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=_m({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=La(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:wa(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:Oa(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=sj.safeParse(r);if(!o.success)return Ta(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:Ro(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:Ro(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:Ro(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 aj(e){return new ql(e)}import{GeneratedSiteCapabilitiesSchema as pj}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as cj}from"@vcp-dev/contracts";function Di(e){let t=uj(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)?Tr(e.node,"platform-managed","controlled platform package"):t?dj(e.node.path,t)?Tr(e.node,"host-public","declared Starter runtime dependency"):Tr(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Tr(e.node,"unknown","trusted host capability contract is invalid"):Cv(e.node.path,n)?Tr(e.node,"platform-managed","controlled platform path"):t?Pv(e.node.path,t.generated_sections_path)?Tr(e.node,"private","site-generated section path"):Cv(e.node.path,t.public_paths)?Tr(e.node,"host-public","declared Starter public path"):Tr(e.node,"private","site-local file outside host public paths"):Tr(e.node,"unknown","trusted host capability contract is invalid")}function lj(e){return e.nodes.map(t=>Di({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Tr(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function uj(e){let t=cj.safeParse(e);return t.success?t.data:null}function dj(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function Cv(e,t){return t.some(n=>Pv(e,n))}function Pv(e,t){let n=fj(t),r=Nv(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):Rv(r)===Rv(n)}function fj(e){return Nv(e.split("#",1)[0]??e)}function Nv(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function Rv(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function Ql(e){let t=pj.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=Di({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=mj(n).sort(gj);return{complete:o.length===0,nodes:r.sort(hj),edges:[...e.closure.edges].sort(yj),errors:o}}function mj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function gj(e,t){return _n(e.path,t.path)||_n(e.code,t.code)||_n(e.specifier??"",t.specifier??"")||_n(e.message,t.message)}function hj(e,t){return _n(e.path,t.path)||_n(e.kind,t.kind)||_n(e.ownership,t.ownership)||_n(e.status,t.status)}function yj(e,t){return _n(e.from,t.from)||_n(e.target??"",t.target??"")||_n(e.specifier??"",t.specifier??"")||_n(e.kind,t.kind)||_n(e.resolution,t.resolution)}function _n(e,t){return e<t?-1:e>t?1:0}var Av={helper:"text",tsType:"string"},Cm={helper:"images",tsType:"MediaItem[]",importName:"MediaItem"},Tv={helper:"image",tsType:"MediaItem | null",importName:"MediaItem"},wv=/(gallery|galleries|images|photos|pics|pictures|album|attachments|files|media)$/i;function xj(e,t,n){switch(e){case"text":case"date":return Av;case"richtext":return{helper:"richtext",tsType:"{ __html: string }"};case"number":return{helper:"num",tsType:"number | null"};case"boolean":return{helper:"bool",tsType:"boolean"};case"select":return{helper:"selected",tsType:"string | null"};case"multi_select":case"tags":return{helper:"list",tsType:"string[]"};case"media_list":return t==="Image"||wv.test(n)?Cm:Tv;case"category_list":return{helper:"category",tsType:"CategoryItem[]",importName:"CategoryItem"};case"url_object":return{helper:"url",tsType:"string"};case"phone_object":return{helper:"phone",tsType:"string"};case"date_range":return{helper:"dateRange",tsType:"{ start: string; end: string } | null"};default:return null}}function Rm(e,t,n){if(n){let r=xj(n,e,t);if(r)return{...r}}switch(e){case"Description":return{helper:"richtext",tsType:"{ __html: string }"};case"Num":case"Slider":return{helper:"num",tsType:"number | null"};case"Boolean":return{helper:"bool",tsType:"boolean"};case"DropdownSelection":case"RadioButton":return{helper:"selected",tsType:"string | null"};case"Checkbox":case"Tag":case"Label":return{helper:"list",tsType:"string[]"};case"Image":case"Avatar":case"Video":case"File":case"Audio":return{...wv.test(t)?Cm:Tv};case"Category":return{helper:"category",tsType:"CategoryItem[]",importName:"CategoryItem"};case"Url":return{helper:"url",tsType:"string"};case"Phone":case"Landline":return{helper:"phone",tsType:"string"};case"DateRange":return{helper:"dateRange",tsType:"{ start: string; end: string } | null"};default:return{...Av}}}function Pm(e,t,n={}){let r=`${Ej(e)}View`,o=t.filter(l=>l.front_display!=="forbidden").map(l=>{let u={key:bj(l.name)?`${l.name}_field`:l.name,source:l.name,...Rm(l.cms_type,l.name,l.value_shape)};return n.forceMultiMedia?.has(l.name)?{...u,helper:"images",tsType:"MediaItem[]",importName:"MediaItem"}:u}),i=[...new Set(o.map(l=>l.importName).filter(Boolean))],s=i.length?n.inferFieldTypesFromCms?i.map(l=>`type ${l} = ReturnType<typeof cms.field.${l==="MediaItem"?"images":"category"}>[number];`).join(`
15
+ `)+`
16
+ `:`import type { ${i.join(", ")} } from "@/lib/cms/field";
17
+ `:"",a=o.map(l=>` ${l.key}: ${l.tsType};`).join(`
18
+ `),c=o.map(l=>` ${l.key}: cms.field.${l.helper}(d.${l.source}),`).join(`
19
+ `);return`// Auto-generated by connect_dynamic_collection \u2014 do not edit by hand. slug=${e}
20
+ import { cms } from "@/lib/cms";
21
+ import type { CollectionRecord, CmsSeo } from "@/lib/cms";
22
+ ${s}
23
+ export interface ${r} {
24
+ id: number;
25
+ url: string | null;
26
+ seo: CmsSeo | null;
27
+ ${a}
28
+ }
29
+
30
+ export function to${r}(rec: CollectionRecord): ${r} {
31
+ const d = rec.fields;
32
+ return {
33
+ id: rec.id,
34
+ url: rec.url ?? null,
35
+ seo: rec.seo ?? null,
36
+ ${c}
37
+ };
38
+ }
39
+ `}function bj(e){return e==="id"||e==="url"||e==="seo"}function Ej(e){return e.replace(/(^|[-_])([a-z0-9])/g,(t,n,r)=>r.toUpperCase())}import{createHash as Ru}from"node:crypto";import{BlockRenderRefSchema as uU,GeneratedSiteCapabilitiesSchema as dU,PORTABLE_AUDITED_PLACEHOLDER_SVG as Fg,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as I_,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as fU,SiteEditPageBlockTargetSchema as pU,SiteEditPortableExportResultSchema as mU}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as Sj,SiteIdSchema as Ij,SnapshotIdSchema as vj}from"@vcp-dev/contracts";async function Am(e){if(!Ij.safeParse(e.site_id).success||!vj.safeParse(e.base_snapshot_id).success||!Sj.safeParse(e.target).success)return gr("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!_j(e.composition,e.target.composition))return gr("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(!Nm(u))return gr("INVALID_PARAMS","Snapshot contains an unsafe source path.");let p=typeof d=="string"?d:kj(u,d);p!==null&&(n.set(u,p),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,p))}let r;try{r=Wc({files:n})}catch{return gr("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 gr("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return gr("INVALID_TARGET","The selected composition entry is unavailable.");let s=await ai(o.entryFile,i,async u=>{if(!Nm(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=>Nm(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return gr("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=Vn({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 gr("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=Uc({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return gr("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Ps({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?{...gr("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...yi(l,e.target,e.document_version,e.selection_ref),index:l}}function kj(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 Nm(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function _j(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function gr(e,t){return{ok:!1,code:e,message:t}}import{createHash as jj}from"node:crypto";import aa from"node:path";import Lm from"@babel/generator";import{parse as $j}from"@babel/parser";import Uj from"@babel/traverse";import*as B from"@babel/types";import{SiteEditSourcePathSchema as Vj}from"@vcp-dev/contracts";import*as rn from"@babel/types";var Ov=[".tsx",".ts",".jsx",".js"],Cj=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 uo(e){let t=Nj(e.files),n=Fv(e.max_depth??32,"max_depth"),r=Fv(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(Bv).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 f of o)if(!(!f||l.has(f))){if(!Mi(f,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:f,message:"Portable source closure node budget was exhausted."});continue}l.add(f),d.push({path:f,depth:0})}for(;d.length>0;){let f=d.shift();if(u.has(f.path))continue;u.add(f.path);let y=t.get(f.path);if(y===void 0){let w=o.includes(f.path)?"SOURCE_ENTRY_UNRESOLVED":Bi(f.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";lo(i,{path:f.path,kind:Bi(f.path)?"asset":"source",depth:f.depth,status:"unresolved"}),a.push({code:w,path:f.path,message:`Portable source closure could not read ${f.path}.`});continue}let x=Bi(f.path)?"asset":"source";if(x==="asset"){let w=Aj(f.path,y);lo(i,{path:f.path,kind:x,depth:f.depth,status:w?"parse-failed":"complete"}),w&&a.push(w);continue}let E=wm(y),b=Fe(f.path,E);if(!b.ok){lo(i,{path:f.path,kind:x,depth:f.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:f.path,message:b.diagnostic.message});continue}let S=Pj(b.module.ast),I=!1;for(let w of S){let C=Rj({from:f.path,depth:f.depth,reference:w,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(C.edge),C.next&&(C.next.depth>n?I=!0:!u.has(C.next.path)&&!l.has(C.next.path)&&(l.add(C.next.path),d.push(C.next))),C.depthExhausted&&(I=!0)}lo(i,{path:f.path,kind:x,depth:f.depth,status:I?"depth-exhausted":"complete"}),I&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:f.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let p=[...i.values()].sort(Dj),g=Lj(s).sort(Mj),m=Fj(a).sort(Bj);return{entry_files:o.sort(hr),nodes:p,edges:g,errors:m,complete:m.length===0,budget:{max_depth:n,max_nodes:r}}}function Rj(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(!mt(t.specifier)){let o=wj(t.specifier);return Mi(o,e.discovered,e.maxNodes)?(lo(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=Om(e.from,t.specifier);if(jv(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}.`}),Mi(n,e.discovered,e.maxNodes)?lo(e.nodes,{path:n,kind:Bi(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=Mv(e.from,t.specifier,e.files);if(!r){let o=Bi(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}.`}),Mi(n,e.discovered,e.maxNodes)?lo(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=Bi(r)?"asset":"source";return Mi(r,e.discovered,e.maxNodes)?lo(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 Mi(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 Pj(e){let t=[];for(let n of e.program.body)rn.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):rn.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):rn.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return Tm(e.program,n=>{if(rn.isCallExpression(n)&&rn.isImport(n.callee)){let r=n.arguments[0];rn.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}rn.isTSImportType(n)&&t.push({specifier:rn.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),Oj(t)}function Tm(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)Dv(r)&&Tm(r,t);else Dv(n)&&Tm(n,t)}function Kt(e,t,n){let r=Om(e,t);return!mt(t)||jv(e,t,r)?null:Mv(e,t,n)}function Mv(e,t,n){let r=Om(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(Tj(o))return null;for(let i of Ov){let s=`${o}${i}`;if(n.has(s))return s}for(let i of Ov){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Om(e,t){let n=Qn(e,t);return Bv(n)}function Bv(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 Nj(e){return e instanceof Map?e:new Map(Object.entries(e))}function wm(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function Aj(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(wm(t)))return{code:"SOURCE_ASSET_INVALID",path:e,message:"Stylesheet dependencies or escaped/dynamic CSS are not statically closed."};if(e.replace(/[?#].*$/u,"").toLowerCase().endsWith(".json"))try{JSON.parse(wm(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function lo(e,t){let n=e.get(t.path);(!n||Lv(t.status)>Lv(n.status))&&e.set(t.path,t)}function Mi(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function Lv(e){return e==="complete"?1:0}function Bi(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&Cj.has(n)}function Tj(e){return/\.[a-z0-9]+$/iu.test(e)}function wj(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function Oj(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 Lj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Fj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Dj(e,t){return hr(e.path,t.path)||hr(e.kind,t.kind)}function Mj(e,t){return hr(e.from,t.from)||hr(e.target??"",t.target??"")||hr(e.specifier??"",t.specifier??"")||hr(e.kind,t.kind)}function Bj(e,t){return hr(e.path,t.path)||hr(e.code,t.code)||hr(e.specifier??"",t.specifier??"")}function hr(e,t){return e<t?-1:e>t?1:0}function Fv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function Dv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function jv(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("/")}var Fm=Uj,$m=typeof Fm=="function"?Fm:Fm.default,Jj=typeof Lm=="function"?Lm:Lm.default,$v=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),Xv=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),zv=new Set(["Boolean","Number","String"]),Kj=new Set(["assign","values","entries"]);function Um(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!jm(r))return Xt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!Vj.safeParse(t.source_file).success)return Xt("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 Xt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Xt("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 Xt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=ru(n,t.source_file);return i===null||!Kv(t,i)?Xt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):eu({entryFile:r,entryContent:i,files:n,selection:t})}let o=ru(n,t.source_file);if(o===null||!Kv(t,o))return Xt("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 eu({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!jm(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return Xt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=Wr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Xt("SOURCE_NOT_PORTABLE",r,"The collection invocation has unsupported bindings.");let a=s.plan.requiresRouteSearchParams?"{searchParams}: {searchParams?: Promise<Record<string, string | string[] | undefined>>}":"",c=`import PortableCollection from ${JSON.stringify(`@/${i.replace(/\.[cm]?[jt]sx?$/u,"")}`)};
15
40
  export default function PortableCollectionEntry(${a}) { return ${s.plan.jsx}; }
16
- `;return yl({entryFile:r,entryContent:c,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?Rt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):mB(t,o,n)}function mB(e,t,n){let r;try{r=lB(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(A){return Rt("SOURCE_PARSE_FAILED",e.source_file,A instanceof Error?A.message:String(A))}let o=gB(r,e);if(o.length!==1)return Rt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(A=>A.isFunction());if(!s||!Zv(s.node))return Rt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=OB(a);if(!c.ok)return Rt("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=new Set;for(let A of r.program.body){if(!O.isImportDeclaration(A)||A.specifiers.length||A.importKind==="type")continue;let w=A.source.value,L=w.startsWith(".")||w.startsWith("@/")?Sl(e.source_file,w,n):null;if(!L?.endsWith(".css"))return Rt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(L)||l.imports.add(A),u.add(L)}let d=hB(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(yB(i,i.node,a,d.value,e,c.translationBinding??null,l,n),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(A=>O.isVariableDeclaration(A)&&A.declarations.some(w=>O.isIdentifier(w.id,{name:c.translationBinding}))))return Rt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let f=MB(r,"__vcpPortableProps"),g=O.cloneNode(i.node,!0),p=[];for(let A of[...l.imports].sort(Jp)){let w=TB(A,e.source_file,e.entry_file,n);if(!w.ok)return{complete:!1,errors:[w.error]};p.push(w.node)}let m=[...l.moduleDeclarations].sort(Jp).map(A=>O.cloneNode(A,!0)),y=[...l.functionDeclarations].sort(Jp).map(A=>O.cloneNode(A,!0)),b=O.returnStatement(g),S=[...l.props].filter(([A])=>!A.startsWith("@")).map(([A,w])=>O.variableDeclaration("const",[O.variableDeclarator(O.identifier(A),O.memberExpression(O.identifier(f),O.identifier(w)))]));l.propsObjectName&&S.push(O.variableDeclaration("const",[O.variableDeclarator(O.identifier(l.propsObjectName),O.identifier(f))]));let x=O.blockStatement([...S,...y,b]),E=l.props.size?[AB(f)]:[],k=O.functionDeclaration(O.identifier("PortableBlockEntry"),E,x),v=O.program([...p,...m,k,O.exportDefaultDeclaration(O.identifier("PortableBlockEntry"))]);v.directives=r.program.directives.map(A=>O.cloneNode(A,!0));let I=fB(O.file(v),{jsescOption:{minimal:!0}}).code,N={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return yl({entryFile:e.entry_file,entryContent:I,files:n,selection:e,sourceMapping:N,invocationBindings:DB(e,l.props)})}function gB(e,t){let n=[];return Wp(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function hB(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:dt("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(O.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!O.isObjectPattern(o))return{ok:!1,error:dt("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!O.isObjectProperty(i)||i.computed||!(O.isIdentifier(i.key)||O.isStringLiteral(i.key))||!(O.isIdentifier(i.value)||O.isAssignmentPattern(i.value)&&O.isIdentifier(i.value.left)))return{ok:!1,error:dt("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=O.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=O.isIdentifier(a)?a.name:O.isAssignmentPattern(a)&&O.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function yB(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=p=>{let m=l.get(p);if(m!==void 0)return m;let y=xB(n,r,p,o,a);return l.set(p,y),y||s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${p} is mutated or escapes its proven invocation value.`)),y},d=p=>{let m=p.node.name,y=p.scope.getBinding(m);if(!y){Mv.has(m)||s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${m}.`));return}if(!xl(y.path.node,t)){if(r.bindingByLocalName.has(m)&&y.scope===n.scope){let b=r.bindingByLocalName.get(m);jv(o,b)?u(b)&&s.props.set(m,b):s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${b} has no proven invocation binding.`));return}if(r.propsParameter&&y.path.node===r.propsParameter&&p.parentPath?.isMemberExpression()&&p.parentPath.node.object===p.node){let b=p.parentPath.node,S=!b.computed&&O.isIdentifier(b.property)?b.property.name:b.computed&&O.isStringLiteral(b.property)?b.property.value:null;S&&jv(o,S)?u(S)&&(s.propsObjectName=m,s.props.set(`@${m}.${S}`,S)):s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${m}.`));return}c.has(y)||(c.add(y),Bv(y,n,o,s,d,f,a))}},f=(p,m)=>{let y=Yv(p);if(!y||/^[a-z]/u.test(y.name))return;let b=m.scope.getBinding(y.name);if(!b){Mv.has(y.name)||s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(b)||xl(b.path.node,t)||(c.add(b),Bv(b,n,o,s,d,f,a))};(p=>{p.isIdentifier()&&p.isReferencedIdentifier()&&d(p),p.isJSXElement()&&f(p.node.openingElement.name,p),p.traverse({ReferencedIdentifier(m){d(m)},JSXOpeningElement(m){f(m.node.name,m)},CallExpression(m){Gv(m,i)||s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(m){s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),m.stop()},UpdateExpression(m){s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),m.stop()},NewExpression(m){s.errors.push(dt("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),m.stop()}})})(e)}function Bv(e,t,n,r,o,i,s){let a=e.path;if(FB(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}if(e.constantViolations.length>0){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(IB(e)){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new bl(s),l=new Map,u=a.parentPath,d=u?.isImportDeclaration(),f=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let y=Sl(n.source_file,u.node.source.value,s),b=y?c.get(y):void 0,S=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?Ht(a.node.imported,!1):null,x=b&&S&&u.node.importKind!=="type"?Sr(b,S,c):null,E=x?zt(x):null;if(!E?.length){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,E),f=E.every(k=>k.isFunctionDeclaration()||k.isFunctionExpression()||k.isArrowFunctionExpression())}else d&&(f=e.referencePaths.every(y=>y.parentPath?.isJSXOpeningElement()||y.parentPath?.isJSXClosingElement()||y.parentPath?.isCallExpression()&&y.parentPath.node.callee===y.node));if((d&&!f||bB(e))&&!As(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let g=a.isImportDeclaration()?a:a.findParent(y=>y.isImportDeclaration());if(g?.isImportDeclaration()){r.imports.add(g.node);return}let p=a.isVariableDeclarator()?a:a.findParent(y=>y.isVariableDeclarator());if(p?.isVariableDeclarator()){let y=p.parentPath,b=p.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!b.node||!oo(p.node.id)||!oo(b.node)&&!LB(b)){r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let x=y.findParent(k=>k.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,E=O.variableDeclaration("const",[O.cloneNode(p.node,!0)]);$v(x,E,p.node),p.traverse({ReferencedIdentifier(k){k.isIdentifier()&&o(k)},JSXOpeningElement(k){i(k.node.name,k)}});return}let m=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(m?.isFunctionDeclaration()&&ec(m.node)){let b=m.findParent(S=>S.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;$v(b,O.cloneNode(m.node,!0),m.node),m.traverse({ReferencedIdentifier(S){S.isIdentifier()&&o(S)},JSXOpeningElement(S){i(S.node.name,S)}});return}r.errors.push(dt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function bB(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=PB(n.node);return O.isFunctionExpression(r)||O.isArrowFunctionExpression(r)||O.isCallExpression(r)&&tc(r)?!1:!Hd(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Wd(i,new Map))}var bl=class extends Map{constructor(t){super(),this.files=t,this.attempted=new Set}has(t){return this.files.has(t)}get(t){let n=super.get(t);if(n||this.attempted.has(t)||this.attempted.size>=64)return n;this.attempted.add(t);let r=El(this.files,t);if(r===null)return;let o=De(t,r);if(o.ok)return super.set(t,o.module),o.module}};function xB(e,t,n,r,o){let i=r.invocation?.bindings.find(l=>l.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let l=O.file(O.program([O.expressionStatement(O.valueToNode(i.value.value))]));Wp(l,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,c={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new bl(o)};if(t.propsParameter)return Xp(e,n,s,c);for(let[l,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(l);if(!d||(a.set(d.identifier,s),!As(d,c,!0)))return!1}return!0}function EB(e,t){if(Wd(e,t.inputs))return!0;let n=e.parentPath;if(!n)return!1;let r=n.isJSXExpressionContainer()?n.parentPath:n;if(!r)return!1;let o=r.isJSXAttribute()||r.isJSXSpreadAttribute()?r.parentPath:r.isJSXElement()?r.get("openingElement"):null;if(r.isJSXFragment())return!0;if(!o?.isJSXOpeningElement())return!1;let i=o.node.name;if(O.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!O.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=SB(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=zt(e,t.inputs);if(!c)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of c){if(!d.isObjectExpression())return!1;for(let f of d.node.properties){if(!O.isObjectProperty(f)||f.computed)return!1;let g=Ht(f.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let f=nc(c,d,t.inputs);return f!==null&&Xp(s,d,f,a)})}let l=r.isJSXAttribute()&&O.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return Xp(s,l,c,a)}function SB(e,t){let n=e.node.name;if(!O.isJSXIdentifier(n))return null;let r=e.scope.getBinding(n.name);if(!r||r.constantViolations.length)return null;if(r.path.isFunctionDeclaration())return r.path;if(r.path.isVariableDeclarator()){let d=r.path.get("init");return d.isFunctionExpression()||d.isArrowFunctionExpression()?d:null}let o=r.path.parentPath;if(!o?.isImportDeclaration())return null;let i=o.node.source.value,s=o.node.loc?.filename;if(!s||!(i.startsWith(".")||i.startsWith("@/")))return null;let a=Sl(s,i,t.files);if(!a)return null;let c=t.modules.get(a);if(!c)return null;let l=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?Ht(r.path.node.imported,!1):null;if(!l)return null;let u=Xt({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function Xp(e,t,n,r){let o=e.get("params")[0];if(!o)return!0;let i=new Map(r.inputs);if(o.isObjectPattern()){let a=!0;for(let c of o.get("properties")){if(!c.isObjectProperty()||c.node.computed){if(Object.keys(c.getBindingIdentifiers()).some(f=>c.scope.getBinding(f)?.referencePaths.length))return!1;continue}if(Ht(c.node.key,!1)!==t)continue;let l=c.get("value");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u)return!1;i.set(u.identifier,n),a=As(u,{...r,inputs:i},!0)&&a}return a}if(!o.isIdentifier())return!1;let s=o.scope.getBinding(o.node.name);return!s||s.constantViolations.length?!1:s.referencePaths.every(a=>{let c=a.parentPath;if(!(c?.isMemberExpression()||c?.isOptionalMemberExpression())||c.node.object!==a.node)return!1;let l=Ht(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),zv(c,{...r,inputs:i},!0))})}function As(e,t,n){if(t.bindings.has(e))return!0;if(t.activeBindings.has(e)||t.bindings.size+t.activeBindings.size>=128||e.constantViolations.length>0)return!1;let r={...t,activeBindings:new Set(t.activeBindings).add(e)},o=e.referencePaths.every(i=>zv(i,r,n));return o&&t.bindings.add(e),o}function Yp(e,t,n){let r=e.node.id;if(O.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?As(o,t,n):!1}if(O.isObjectPattern(r)||O.isArrayPattern(r)){let o=[];return ci(r,o)?vB(o,e,t):!1}return!1}function ci(e,t){if(O.isRestElement(e))return ci(e.argument,t);if(O.isIdentifier(e))return t.push(e.name),!0;if(O.isAssignmentPattern(e))return ci(e.left,t);if(O.isObjectPattern(e)){for(let n of e.properties){if(O.isRestElement(n)){if(!ci(n.argument,t))return!1;continue}if(!O.isObjectProperty(n)||n.computed||!(O.isIdentifier(n.key)||O.isStringLiteral(n.key)||O.isNumericLiteral(n.key))||!ci(n.value,t))return!1}return!0}if(O.isArrayPattern(e)){for(let n of e.elements)if(n&&!ci(n,t))return!1;return!0}return!1}function vB(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?As(o,n,!0):!1})}function IB(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=Xv(t);if(!r)return!1;let o=n.parentPath;return!!(Jv(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function Jv(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?xl(e.node,t.node.left):!1}function Xv(e){let t=zp(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=zp(t.parentPath);return{current:t,memberAccess:n}}function zv(e,t,n){if(!RB(e,t))return!1;let{current:r,memberAccess:o}=Xv(e),i=r.parentPath;if(!i)return!1;if(i.isVariableDeclarator()&&i.node.init===r.node){let s=i.parentPath;return!s?.isVariableDeclaration()||s.node.kind!=="const"?!1:Yp(i,t,o||n)}return Jv(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:kB(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?EB(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?_B(r,o,n,t):i.isJSXAttribute()||i.isJSXSpreadAttribute()||i.isObjectMethod()||i.isReturnStatement()||i.isArrowFunctionExpression()?o||n:i.isTemplateLiteral()&&i.parentPath?.isTaggedTemplateExpression()?!1:(o||n)&&(i.isBinaryExpression()||i.isUnaryExpression()||i.isTemplateLiteral())}function kB(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(O.isIdentifier(r)){if(Kv.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!Bo(i)?!1:Ps(e,n,new Set)}if(!O.isMemberExpression(r)&&!O.isOptionalMemberExpression(r)||!O.isIdentifier(r.property))return!1;let o=Zp(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Ps(e,n,new Set):Vv.get(o.name)?.has(r.property.name)??!1?Wv(e)?Ps(e,n,new Set):!0:!1}function _B(e,t,n,r){let o=Hv(e);return o.kind==="declarator"?Yp(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function Hv(e){let t=zp(e),n=!0,r=!1;for(;;){let o=t.parentPath;if(!o)return r?{kind:"escape"}:{kind:"read"};if(o.isTSAsExpression()||o.isTSTypeAssertion()||o.isTSNonNullExpression()||o.isTSSatisfiesExpression()||o.isParenthesizedExpression()){t=o;continue}if((o.isMemberExpression()||o.isOptionalMemberExpression())&&o.node.object===t.node){t=o;continue}if(o.isConditionalExpression()){if(o.node.test===t.node)return{kind:"read"};t=o;continue}if(o.isLogicalExpression()||o.isAwaitExpression()){t=o;continue}if(o.isSequenceExpression()){let i=o.node.expressions;if(i[i.length-1]!==t.node)return{kind:"read"};t=o;continue}if(o.isVariableDeclarator()&&o.node.init===t.node)return{kind:"declarator",declarator:o,directValue:n};if(o.isObjectProperty()&&o.node.value===t.node){r=!0,n=!1,t=o;continue}if(o.isObjectExpression()||o.isArrayExpression()){r=!0,n=!1,t=o;continue}if(o.isSpreadElement()){r=!0,n=!1,t=o;continue}return o.isCallExpression()||o.isOptionalCallExpression()?o.node.callee===t.node?{kind:"escape"}:{kind:"call",call:o}:o.isNewExpression()?{kind:"escape"}:o.isJSXExpressionContainer()||o.isJSXAttribute()||o.isJSXSpreadAttribute()||o.isReturnStatement()||o.isArrowFunctionExpression()?r?{kind:"escape"}:{kind:"read"}:r?{kind:"escape"}:{kind:"read"}}}function Ps(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=Hv(e);return r.kind==="declarator"?Yp(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:Wv(r.call)?Ps(r.call,t,n):NB(r.call):!0}function RB(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!Zv(n.node))return!0;let r=CB(n);return!r||!Bo(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Ps(i,t,new Set)})}function CB(e){let t=e.node,n=null;if(O.isFunctionDeclaration(t)?n=t.id?.name??null:(O.isArrowFunctionExpression(t)||O.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&O.isIdentifier(e.parentPath.node.id)&&(n=e.parentPath.node.id.name),!n)return null;let r=[e.scope.getBinding(n),e.scope.parent?.getBinding(n),e.parentPath?.scope.getBinding(n)];for(let o of r)if(o&&(o.path.node===t||o.path.node===e.parentPath?.node))return o;return null}function Wv(e){let t=e.node.callee;if(O.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&Bo(r))}if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=Zp(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&pB.has(t.property.name)}function NB(e){let t=e.node.callee;if(O.isIdentifier(t))return Kv.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!O.isMemberExpression(t)&&!O.isOptionalMemberExpression(t)||!O.isIdentifier(t.property))return!1;let n=Zp(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:Vv.get(n.name)?.has(t.property.name)??!1}function zp(e){let t=e;for(;t.parentPath&&(t.parentPath.isTSAsExpression()||t.parentPath.isTSTypeAssertion()||t.parentPath.isTSNonNullExpression()||t.parentPath.isTSSatisfiesExpression()||t.parentPath.isParenthesizedExpression());)t=t.parentPath;return t}function PB(e){let t=e;for(;t&&(O.isTSAsExpression(t)||O.isTSTypeAssertion(t)||O.isTSNonNullExpression(t)||O.isTSSatisfiesExpression(t)||O.isParenthesizedExpression(t));)t=t.expression;return t&&O.isExpression(t)?t:null}function Zp(e){return!e.computed&&O.isIdentifier(e.object)?e.object:null}function AB(e){let t=O.identifier(e);return t.typeAnnotation=O.tsTypeAnnotation(O.tsTypeReference(O.identifier("Record"),O.tsTypeParameterInstantiation([O.tsStringKeyword(),O.tsAnyKeyword()]))),t}function yl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=Mr({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>dt(BB(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=El(t,i.path);if(s===null)return Rt("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 TB(e,t,n,r){let o=O.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=Sl(t,i,r);if(!s)return{ok:!1,error:dt("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=wB(n,s)}return{ok:!0,node:o}}function Sl(e,t,n){let r=t.startsWith("@/")?t.slice(2):Ns.posix.normalize(Ns.posix.join(Ns.posix.dirname(e),t));if(!Hp(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 wB(e,t){let n=Ns.posix.relative(Ns.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function OB(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!O.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!O.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"||!O.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!O.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 Gv(e,t){let n=e.node.callee;if(O.isImport(n))return!1;if(t&&O.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>O.isStringLiteral(o))){let o=e.scope.getBinding(t);if(o&&o.constantViolations.length>0)return!1;let i=o?.path.isVariableDeclarator()?o.path:o?.path.findParent(a=>a.isVariableDeclarator()),s=i?.isVariableDeclarator()?i.node.init:null;return!!(O.isCallExpression(s)&&tc(s))}if(!O.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?Bo(r):!1}function LB(e){return e.isCallExpression()&&Gv(e,null)&&O.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>O.isExpression(t)&&oo(t))}function Yv(e){return O.isJSXIdentifier(e)?O.isValidIdentifier(e.name)?O.identifier(e.name):null:O.isJSXMemberExpression(e)?Yv(e.object):null}function FB(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>O.isObjectPattern(n)&&n.properties.some(r=>O.isObjectProperty(r)&&O.isIdentifier(r.value,{name:e.node.name}))))}function xl(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 Zv(e){return O.isFunction(e)}function jv(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function DB(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function MB(e,t){let n=new Set;Wp(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function $v(e,t,n){if(typeof n.start=="number"){if([...e].some(r=>r.start===n.start))return;t.start=n.start}e.add(t)}function Jp(e,t){return(e.start??0)-(t.start??0)}function El(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 Uv(e,t){let n=cB("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function Hp(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function BB(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 Rt(e,t,n){return{complete:!1,errors:[dt(e,t,n)]}}function dt(e,t,n){return{code:e,path:t,message:n}}import{createHash as EI}from"node:crypto";import um from"node:path";import dm from"@babel/traverse";import*as ze from"@babel/types";import{GeneratedSiteCapabilitiesSchema as Aj,SiteEditSourcePathSchema as Tj}from"@vcp-dev/contracts";import{parse as Pl}from"@babel/parser";import*as V from"@babel/types";import{PortableCollectionRecipeFactsSchema as dj}from"@vcp-dev/contracts";import{parse as jr}from"@babel/parser";import qp from"@babel/traverse";import*as M from"@babel/types";import{createHash as jB}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as $B,generateDetailBreadcrumb as UB}from"@vcp-dev/contracts";function Ts(e){try{let t=typeof e=="string"?e:e instanceof Uint8Array?new TextDecoder("utf-8",{fatal:!0}).decode(e):null;return t!==null&&!t.includes("\0")?t:null}catch{return null}}var nm=typeof qp=="function"?qp:qp.default;function rm(e){let t=fI(e.files),n=(g,p,m)=>({complete:!1,relation:null,errors:[{code:g,path:p,message:m}]}),r=zn(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(!WB(o,r,"listStrict"))return{complete:!0,relation:null,errors:[]};if(!tI(e.list_entry_file,r,t))return n("RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",e.list_entry_file,"The selected list must be reached by one proven rendered component call.");let i=HB(o,r),s=i?ws(r,o,i,"listStrict",t):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.keys()].filter(uI),c=a.find(g=>typeof t.get(g)!="string");if(c)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let l=a.flatMap(g=>{let p=t.get(g);if(typeof p!="string")return[];let m=ws(g,p,i,"getByUrlStrict",t,e.detail_prefix??`/${i}`);return m&&Il(m.ast,e.detail_prefix??`/${i}`)!==null?[m]:[]});if(l.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let u=l[0];if(u.adapter_source!==s.adapter_source||u.interface_name!==s.interface_name)return n("RELATED_COLLECTION_ADAPTER_UNPROVEN",u.path,"The list and detail routes do not share the selected collection adapter and view interface.");let d=Fn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let p=zn(u.path,g.source,t),m=p?t.get(p):void 0;return!p||typeof m!="string"||!iI(m,g.export_name)||!vl(m,u.adapter_source,u.interface_name)?[]:[{path:p,export_name:g.export_name}]});if(d.length!==1)return n("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",u.path,"The collection detail route does not prove one private detail view.");let f=d[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:u.path,detail_view_file:f.path,detail_view_export:f.export_name},errors:[]}}function tI(e,t,n,r=!1){let o=Ts(n.get(e));if(o===null)return!1;let i=De(e,o);if(!i.ok)return!1;let s=Xt({module:i.module,exportName:"default",allowNonRenderingGuards:r});if(!s.ok||s.metadataOnly)return!1;let a=Fn(o,{filePath:e,exportName:"default"}),c=new Set(a.rendered_component_openings.filter(u=>!u.static_render_blockers?.length).map(u=>u.start_offset)),l=u=>{let d=0,f=g=>{if(g.isJSXElement()){let p=g.get("openingElement"),m=p.node.name;if(!M.isJSXIdentifier(m))return;if(!/^[a-z]/u.test(m.name)){let y=p.scope.getBinding(m.name),b=y?.path.parentPath;y?.constant&&b?.isImportDeclaration()&&b.node.importKind!=="type"&&(y.path.isImportDefaultSpecifier()||y.path.isImportSpecifier()&&y.path.node.importKind!=="type"&&M.isIdentifier(y.path.node.imported,{name:"default"}))&&typeof p.node.start=="number"&&c.has(p.node.start)&&zn(e,b.node.source.value,n)===t&&d++;return}if(VB(p.node))return}for(let p of g.get("children"))if(p.isJSXElement()||p.isJSXFragment())f(p);else if(p.isJSXExpressionContainer()){let m=p.get("expression");(m.isJSXElement()||m.isJSXFragment())&&f(m)}};for(let g of u)f(g);return d};return s.returnAlternatives?s.returnAlternatives.every(u=>l([u])===1):l(s.roots)===1}function VB(e){if(!M.isJSXIdentifier(e.name)||["template","noscript","script","style","head","dialog","details"].includes(e.name.name))return!0;for(let t of e.attributes){if(M.isJSXSpreadAttribute(t)||!M.isJSXIdentifier(t.name))return!0;let n=t.name.name;if(["style","dangerouslySetInnerHTML"].includes(n)||n==="className"&&!M.isStringLiteral(t.value)&&(!M.isJSXExpressionContainer(t.value)||!M.isStringLiteral(t.value.expression)))return!0;if(["hidden","inert","aria-hidden"].includes(n)){let r=t.value;if(n==="aria-hidden"&&M.isStringLiteral(r,{value:"false"})||M.isJSXExpressionContainer(r)&&M.isBooleanLiteral(r.expression,{value:!1}))continue;return!0}}return!1}function om(e){let t=fI(e.files),n=[],r=[],o=[],i=e.host_capabilities!==void 0||e.trusted_host_file_hashes!==void 0,s=new Map(e.files instanceof Map?e.files.entries():Object.entries(e.files)),a=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."});for(let S of e.source_closure.nodes)S.kind==="source"&&typeof t.get(S.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:S.path,message:"A selected source is missing or is not valid UTF-8 text."});Qp(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Qp(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Qp(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),i&&e.list_route_required===void 0&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"A trusted collection analysis must prove whether the caller is a list route."});let c=e.list_route_required??!i,l=c&&lI(e.collection.list_entry_file);c&&!l&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"The collection caller is not a Next App Router page."}),l&&em(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),uI(e.collection.detail_entry_file)?em(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key}):n.push({code:"RELATED_DETAIL_ROUTE_UNPROVEN",path:e.collection.detail_entry_file,message:"The collection detail must be an App Router slug page."});let u=Mr({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!$B.safeParse(e.host_capabilities).success)n.push({code:"RELATED_HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Related-entry ownership requires a valid trusted host contract."});else for(let S of u.nodes){if(S.kind==="external"||ii({node:S,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!nj(S.path))continue;d.add(S.path);let E=s.get(S.path),k=E===void 0?null:`sha256:${jB("sha256").update(E).digest("hex")}`;(!k||e.trusted_host_file_hashes?.get(S.path)!==k)&&n.push({code:"RELATED_HOST_IMPLEMENTATION_UNPROVEN",path:S.path,message:"A related host source requires trusted matching Snapshot provenance."})}for(let S of u.nodes)S.kind==="source"&&typeof t.get(S.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:S.path,message:"A detail source is missing or is not valid UTF-8 text."});u.complete||n.push(...u.errors.map(S=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:S.path,message:S.message})));let f=u.nodes.find(S=>S.path===e.collection.detail_view_file);!f||f.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."}):d.has(e.collection.detail_view_file)?n.push({code:"RELATED_DETAIL_VIEW_NOT_PRIVATE",path:e.collection.detail_view_file,message:"A collection detail entry must be site-owned source."}):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"});let g=i?KB(e.collection,t,s):null;for(let S of u.nodes)if(S.kind!=="external"&&S.path!==e.collection.detail_entry_file&&S.path!==e.collection.detail_view_file&&!d.has(S.path)&&!(!l&&S.path===e.collection.list_entry_file)){if(tj(S.path,e.collection)){if(i&&S.path!==g){n.push({code:"RELATED_MANAGED_SOURCE_UNPROVEN",path:S.path,message:"A related generated source cannot be omitted based on its pathname alone."});continue}em(o,{path:S.path,kind:S.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}rj(S.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:S.path,export:{kind:"default"},purpose:"i18n-companion"})}let p=t.get(e.collection.detail_view_file);typeof p=="string"&&QB(p,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=ej(e.page_template,t,n));let m=e.trusted_schema===void 0?null:JB(e,t,n,e.trusted_schema),y=sj(r).map((S,x)=>({key:cj(S,x),pathTemplate:S.path,export:S.export,purpose:S.purpose,requirementKey:e.collection.requirement_key})),b=lj(n).sort(uj);return{complete:b.length===0,entries:y.sort((S,x)=>S.pathTemplate.localeCompare(x.pathTemplate)||S.purpose.localeCompare(x.purpose)||S.key.localeCompare(x.key)),managed_requirements:o.sort(aj),thin_entry_plan:a,collection_wiring:m,errors:b}}function KB(e,t,n){let r=t.get(e.detail_entry_file);if(typeof r!="string")return null;let o=ws(e.detail_entry_file,r,e.slug,"getByUrlStrict",t);if(!o)return null;let i=Il(o.ast,`/${e.slug}`),s=sI(o,t,i);if(!i||!s||s==="unproven")return null;let a=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!tI(o.path,a,t,!0))return null;let c=n.get(a);return c===void 0?null:[void 0,{variant:"floating",shape:"bar"},{variant:"floating",shape:"island"}].some(u=>{let d=UB({slug:e.slug,detailPrefix:i,...s,headerShell:u});return typeof c=="string"?c===d:Buffer.from(c).equals(Buffer.from(d))})?a:null}function JB(e,t,n,r){let o=n.length,i=r.fields.map(E=>({...E}));(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(E=>E.kind==="source"&&E.status==="complete"&&E.path!==e.collection.list_entry_file).flatMap(E=>{let k=t.get(E.path);if(typeof k!="string")return[];let v=ws(E.path,k,e.collection.slug,"listStrict",t);return v?[v]:[]});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?qv(a,t,E=>E!==e.collection.detail_view_file):null;c?a&&!vl(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"?ws(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t):null,d=u?qv(u,t,E=>E===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."}):vl(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(E=>E.name)),g=a?zn(a.path,a.adapter_source,t):null,p=g?t.get(g):null,m=[...e.required_fields??i.filter(E=>E.required).map(E=>E.name)].sort(tm),y=[...e.force_multi_media??(typeof p=="string"?aI(p):[])].sort(tm);for(let E of[...m,...y])f.has(E)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${E}`,message:`Collection field ${E} is not present in the trusted schema.`});if(a&&y.length)for(let E of y)(typeof p!="string"||!qB(p,E))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:g??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${E}.`});let b=u?Il(u.ast,`/${e.collection.slug}`):null;b||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 S=u?ZB(u.ast):null;S||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 x=u?sI(u,t,b):null;return x==="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||!b?null:{source_slug:e.collection.slug,detail_prefix:b,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},...S?{title:S}:{},...x&&x!=="unproven"?{breadcrumb:x}:{},...m.length>0?{required_fields:m}:{},...y.length>0?{force_multi_media:y}:{}}}function ws(e,t,n,r,o,i=`/${n}`){let s;try{s=jr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=Eo(s,u=>M.isCallExpression(u)&&So(u.callee,r));if(!zB(s,e,o,r)||r==="listStrict"&&(a.length!==1||!M.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||Il(s,i)===null))return null;let l=s.program.body.flatMap(u=>M.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!M.isImportSpecifier(d))return[];let f=M.isIdentifier(d.imported)?d.imported.name:d.imported.value,g=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(f);return g?[{source:u.source.value,local_name:d.local.name,interface_name:g[1]}]:[]}):[]).filter(u=>Eo(s,d=>M.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!XB(s,e,o,l[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:l[0].source,interface_name:l[0].interface_name}}function XB(e,t,n,r,o,i){let s=!1;return nm(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!M.isJSXIdentifier(a.node.name)||a.node.attributes.some(y=>M.isJSXSpreadAttribute(y)))return;let l=a.parentPath;for(;l&&!l.isReturnStatement()&&!l.isFunction();){if(l.isVariableDeclarator()||l.isJSXAttribute()||l.isConditionalExpression()||l.isLogicalExpression()||l.isCallExpression()||l.isJSXElement()&&l.node!==a.parentPath.node&&(!M.isJSXIdentifier(l.node.openingElement.name)||!/^[a-z]/u.test(l.node.openingElement.name.name)))return;l=l.parentPath}if(!l?.isReturnStatement()||l.getFunctionParent()!==c||l.parentPath!==c.get("body"))return;let u=a.scope.getBinding(a.node.name.name),d=u?.path,f=d?.parentPath;if(!u?.constant||!f?.isImportDeclaration()||f.node.importKind==="type"||d?.isImportSpecifier()&&d.node.importKind==="type"||!(d?.isImportDefaultSpecifier()||d?.isImportSpecifier()))return;let g=zn(t,f.node.source.value,n);if(!g||!vl(n.get(g),r.source,r.interface_name))return;let p=a.get("attributes").filter(y=>y.isJSXAttribute()&&M.isJSXIdentifier(y.node.name,{name:o==="listStrict"?"records":"record"}));if(p.length!==1||!p[0].isJSXAttribute())return;let m=p[0].get("value");m.isJSXExpressionContainer()&&(o==="listStrict"?nI(m.get("expression"),c,r,i,new Set):rI(m.get("expression"),c,r,new Set))&&(s=!0)}}),s}function nI(e,t,n,r,o){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(o.add(e.node),e.isIdentifier()){let g=e.scope.getBinding(e.node.name);return!g?.constant||!g.path.isVariableDeclarator()||g.path.getFunctionParent()!==t||!g.path.parentPath.isVariableDeclaration({kind:"const"})||Os(g.referencePaths)?!1:nI(g.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!i.isMemberExpression()||i.node.computed||!M.isIdentifier(i.node.property,{name:"map"}))return!1;let s=e.get("arguments")[0];if(!s||!oI(s,n))return!1;let a=i.get("object");if(a.isConditionalExpression()){let g=a.get("consequent"),p=a.get("alternate"),m=y=>y.isArrayExpression()&&y.node.elements.length===0;if(m(g))a=p;else if(m(p))a=g;else return!1}if(!a.isMemberExpression()||a.node.computed||!M.isIdentifier(a.node.property,{name:"items"}))return!1;let c=a.get("object");if(!c.isMemberExpression()||c.node.computed||!M.isIdentifier(c.node.property,{name:"data"}))return!1;let l=c.get("object");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Os(u.referencePaths))return!1;let d=u.path.get("init");if(!d.isAwaitExpression())return!1;let f=d.get("argument");return f.isCallExpression()&&So(f.node.callee,"listStrict")&&M.isStringLiteral(f.node.arguments[0],{value:r})}function rI(e,t,n,r){if(!e.node||r.has(e.node)||r.size>=32)return!1;if(r.add(e.node),e.isIdentifier()){let u=e.scope.getBinding(e.node.name);return!u?.constant||!u.path.isVariableDeclarator()||u.path.getFunctionParent()!==t||!u.path.parentPath.isVariableDeclaration({kind:"const"})||Os(u.referencePaths)?!1:rI(u.path.get("init"),t,n,r)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let o=e.get("callee");if(!oI(o,n))return!1;let i=e.get("arguments")[0];if(!i?.isMemberExpression()||i.node.computed||!M.isIdentifier(i.node.property,{name:"data"}))return!1;let s=i.get("object");if(!s.isIdentifier())return!1;let a=s.scope.getBinding(s.node.name);if(!a?.constant||!a.path.isVariableDeclarator()||a.path.getFunctionParent()!==t||!a.path.parentPath.isVariableDeclaration({kind:"const"})||Os(a.referencePaths))return!1;let c=a.path.get("init");if(!c.isAwaitExpression())return!1;let l=c.get("argument");return l.isCallExpression()&&So(l.node.callee,"getByUrlStrict")}function oI(e,t){if(!e.isIdentifier({name:t.local_name}))return!1;let n=e.scope.getBinding(e.node.name),r=n?.path,o=r?.parentPath;return!(!n?.constant||!r?.isImportSpecifier()||r.node.importKind==="type"||!M.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function Os(e,t=new Set){return t.size>=32?!0:e.some(n=>{let r=n;for(;(r.parentPath?.isMemberExpression()||r.parentPath?.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(o?.isVariableDeclarator()&&o.node.init===r.node){if(!M.isIdentifier(o.node.id))return!0;let i=o.scope.getBinding(o.node.id.name);return i?.constant?t.has(i.identifier)?!1:(t.add(i.identifier),Os(i.referencePaths,t)):!0}return!!(o?.isAssignmentExpression()&&o.node.left===r.node||o?.isUpdateExpression()||o?.isUnaryExpression()&&o.node.operator==="delete")})}function zB(e,t,n,r){let o=0,i=Ar(e,"cms");for(let s of e.program.body){if(!M.isImportDeclaration(s)||s.importKind==="type")continue;let a=zn(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(M.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!M.isImportSpecifier(c))return!0;let l=M.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return nm(e,{CallExpression(s){if(!So(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),c=a?.path,l=c?.parentPath;if(!a?.constant||!c?.isImportSpecifier()||c.node.importKind==="type"||!M.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=zn(t,l.node.source.value,n);(!u||!/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(u)||a.referencePaths.some(d=>{let f=d.parentPath,g=f?.parentPath,p=g?.parentPath;return!(f?.isMemberExpression()&&f.node.object===d.node&&!f.node.computed&&M.isIdentifier(f.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===f.node&&!g.node.computed&&M.isIdentifier(g.node.property)&&p?.isCallExpression()&&p.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function HB(e,t){let n;try{n=jr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=Eo(n,o=>M.isCallExpression(o)&&So(o.callee,"listStrict")&&M.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(r[0])?r[0]:null}function WB(e,t,n){let r;try{r=jr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return Eo(r,o=>M.isCallExpression(o)&&So(o.callee,n)).length>0}function qv(e,t,n){let r=Fn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=zn(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!iI(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 iI(e,t){let n;try{n=jr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&M.isExportDefaultDeclaration(r))return!0;if(M.isExportNamedDeclaration(r)&&(r.declaration&&(M.isFunctionDeclaration(r.declaration)||M.isClassDeclaration(r.declaration)||M.isTSInterfaceDeclaration(r.declaration)||M.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||M.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>M.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>M.isExportSpecifier(o)?(M.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function vl(e,t,n){if(typeof e!="string")return!1;let r;try{r=jr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!M.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>M.isImportSpecifier(s)?(M.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>Eo(r,s=>M.isIdentifier(s,{name:i})).length>1)}function So(e,t){return M.isMemberExpression(e)&&!e.computed&&M.isIdentifier(e.property,{name:t})&&M.isMemberExpression(e.object)&&!e.object.computed&&M.isIdentifier(e.object.property,{name:"collections"})&&M.isIdentifier(e.object.object,{name:"cms"})}function Il(e,t){let n=[];return nm(e,{CallExpression(r){So(r.node.callee,"getByUrlStrict")&&n.push(GB(r.node.arguments[0],o=>YB(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function GB(e,t){return M.isBinaryExpression(e,{operator:"+"})&&M.isStringLiteral(e.left)&&M.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):M.isTemplateLiteral(e)&&e.expressions.length===1&&M.isIdentifier(e.expressions[0])&&t(e.expressions[0].name)&&e.quasis[1]?.value.cooked===""&&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 YB(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(M.isObjectPattern(r.id)&&M.isAwaitExpression(r.init)&&M.isIdentifier(r.init.argument))return r.id.properties.some(a=>M.isObjectProperty(a)&&!a.computed&&kl(a.key)==="slug"&&M.isIdentifier(a.value,{name:t}))&&Qv(n.path,r.init.argument.name);let o=r.init;if(!M.isIdentifier(r.id,{name:t})||!M.isCallExpression(o)||!M.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!M.isIdentifier(i.path.node.imported,{name:"decodeRouteSlug"})||!i.path.parentPath.isImportDeclaration()||i.path.parentPath.node.source.value!=="@/lib/cms")return!1;let s=o.arguments[0];return M.isMemberExpression(s)&&!s.computed&&M.isIdentifier(s.property,{name:"slug"})&&M.isAwaitExpression(s.object)&&M.isIdentifier(s.object.argument)&&Qv(n.path,s.object.argument.name)}function Qv(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>M.isObjectPattern(i)&&i.properties.some(s=>M.isObjectProperty(s)&&!s.computed&&kl(s.key)==="params"&&M.isIdentifier(s.value,{name:t})))}function ZB(e){for(let t of e.program.body)if(M.isVariableDeclaration(t))for(let n of t.declarations){if(!M.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=cI(n.init);if(!M.isObjectExpression(r))return null;let o=r.properties.find(i=>M.isObjectProperty(i)&&!i.computed&&kl(i.key)==="title");return o&&M.isStringLiteral(o.value)?o.value.value:null}return null}function sI(e,t,n){let o=Fn(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=zn(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=jr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of Eo(a,l=>M.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!M.isObjectExpression(f))return[];let g=new Map;for(let p of f.properties){if(!M.isObjectProperty(p)||p.computed)continue;let m=kl(p.key);m&&M.isStringLiteral(p.value)&&g.set(m,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 aI(e){let t;try{t=jr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(Eo(t,n=>{if(!M.isCallExpression(n))return!1;let r=n.callee;if(!M.isMemberExpression(r)||r.computed||!M.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return M.isMemberExpression(o)&&!o.computed&&M.isIdentifier(o.object,{name:"d"})&&M.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return M.isMemberExpression(r)&&!r.computed&&M.isIdentifier(r.property)?[r.property.name]:[]}))].sort(tm)}function qB(e,t){return aI(e).includes(t)}function Eo(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)eI(s)&&r(s);else eI(i)&&r(i)};return r(e),n}function eI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function cI(e){return e?M.isTSAsExpression(e)||M.isTSTypeAssertion(e)||M.isTSNonNullExpression(e)?cI(e.expression):e:null}function kl(e){return M.isIdentifier(e)?e.name:M.isStringLiteral(e)?e.value:null}function tm(e,t){return e.localeCompare(t)}function QB(e,t,n,r,o,i){let s=Fn(e,{filePath:t,exportName:"default"});for(let a of s.components){let c=zn(t,a.source,r);if(!c||i.has(c))continue;let l=n.find(d=>d.path===c),u=r.get(c);!l||l.kind==="external"||typeof u!="string"||oj(u)&&o.push({path:c,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function ej(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=Fn(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 Qp(e,t,n,r){typeof e.get(t)!="string"&&r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function tj(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 lI(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function uI(e){return lI(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function nj(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function rj(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=dI(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 oj(e){try{return jr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function zn(e,t,n){if(!Qe(t))return null;let r=t.startsWith("@/")?t.slice(2):ij(`${dI(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 dI(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function ij(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 fI(e){let t=e instanceof Map?e.entries():Object.entries(e);return new class extends Map{get(n){let r=super.get(n);if(r===void 0||!/\.[cm]?[jt]sx?$/iu.test(n))return r;let o=Ts(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function sj(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 em(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function aj(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function cj(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function lj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function uj(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var fj=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),pj=new Set(["data-vcp-block-id","data-vcp-edit-key"]),mj=new Set(["data-vcp-order","sourceOrder","source_order"]);function li(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(Fs)}),n;try{n=Pl(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=kj(n),o=Fn(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(Cl(n,new Set,(f,g)=>{if(!V.isJSXElement(f))return;let p=f.openingElement,m=p.start;if(typeof m!="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=xI(p.name);if(!y)return;let b=Cj(p.name,r);b&&(e.target.local_name&&e.target.local_name!==y||b.source!==e.target.source||b.export_name!==e.target.export_name||s.has(m)&&a.push({node:p,element:f,local:b,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=>hI(e,f.node,f.element,{kind:"import",component_source:f.local.source,export_name:f.local.export_name,local_name:f.local.local_name},f.context,f.ordinal)),u=yI(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:lm(d).sort(Fs)}}function gI(e){let t=a=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...a].sort(Fs)}),n;try{n=Pl(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}])}let r=[],o=0;if(Cl(n,new Set,(a,c)=>{if(!V.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||xI(l.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(l.loc?.start.line!==e.call_source_range.start_line||l.loc.start.column!==e.call_source_range.start_column)||r.push({node:l,element:a,context:c,ordinal:u})}),r.length===0)return t([{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected local component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let i=r.map(a=>hI(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=yI(i,e.target.original_block_id);return s?{complete:s.errors.length===0,entry_file:e.file_path,target:e.target,call:s.call,bindings:s.errors.length===0?s.bindings:[],original_block_id:s.original_block_id,original_order:s.original_order,semantic_props:s.semantic_props,errors:lm(s.errors).sort(Fs)}:t([{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected local component is rendered more than once and no unique original block identity was provided."}])}function gj(e){let t;try{t=Pl(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=xn({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=Fn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>li({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 hj(e){let t=li(e),n=Ej(e.files),r=Sj(e.file_path,e.target.source,n),o=r?Ts(n.get(r)):null,i=r&&typeof o=="string"?yj(o,r,e.collection.slug):null,s=om({files:e.files,source_closure:e.source_closure,collection:e.collection,list_route_required:i?.paginate??!1,trusted_schema:e.trusted_schema,...e.host_capabilities===void 0?{}:{host_capabilities:e.host_capabilities},...e.trusted_host_file_hashes===void 0?{}:{trusted_host_file_hashes:e.trusted_host_file_hashes},...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),a=[...t.errors],c=[];e.file_path!==e.collection.list_entry_file&&a.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation must belong to the proven collection caller."}),e.source_closure.complete||a.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 s.errors)a.push({code:xj(f.code),path:f.path,message:f.message});t.call&&c.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 l=s.collection_wiring;if(!r)a.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(!i)a.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:r,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{c.push({fact:"pagination",path:r,reason:i.paginate?`listStrict consumes route searchParams with literal pageSize ${i.limit}.`:`listStrict is embedded and uses literal top-N ${i.limit}.`});let f=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(i.paginate&&f.length!==1||!i.paginate&&f.length!==0)&&a.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:i.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})}l&&r!==l.list_container_file&&a.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(l&&i&&a.length===0){let f={source_slug:l.source_slug,list_mode:i.paginate?"page":"embedded",paginate:i.paginate,...i.paginate?{page_size:i.limit}:{top_n:i.limit},detail_prefix:l.detail_prefix,schema:l.schema.map(p=>({...p})),list_view:{...l.list_view},detail_view:{...l.detail_view},...l.title?{title:l.title}:{},...l.breadcrumb?{breadcrumb:{...l.breadcrumb}}:{},...l.required_fields?{required_fields:[...l.required_fields]}:{},...l.force_multi_media?{force_multi_media:[...l.force_multi_media]}:{},list_route_required:i.paginate},g=dj.safeParse(f);g.success?(u=g.data,c.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${l.detail_prefix}.`},{fact:"list-view",path:l.list_view.source_path,reason:`The list container renders ${l.list_view.export_name} with ${l.list_view.interface_name}.`},{fact:"detail-view",path:l.detail_view.source_path,reason:`The detail route renders ${l.detail_view.export_name} with ${l.detail_view.interface_name}.`},{fact:"schema",path:l.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):a.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${l.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=lm(a).sort(Fs);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:c.sort(Ij),related_entries:s}}function yj(e,t,n){let r;try{r=Pl(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=bj(r);if(!o)return null;let i=im(o,f=>{if(!V.isCallExpression(f))return!1;let g=f.callee;return V.isMemberExpression(g)&&!g.computed&&V.isIdentifier(g.property,{name:"listStrict"})&&V.isMemberExpression(g.object)&&!g.object.computed&&V.isIdentifier(g.object.property,{name:"collections"})&&V.isIdentifier(g.object.object,{name:"cms"})&&V.isStringLiteral(f.arguments[0],{value:n})});if(i.length!==1)return null;let s=i[0].arguments[1];if(!V.isObjectExpression(s)||s.properties.some(f=>V.isSpreadElement(f)))return null;let a=s.properties.find(f=>V.isObjectProperty(f)&&!f.computed&&Rl(f.key)==="pageSize");if(!a||!V.isNumericLiteral(a.value)||!Number.isSafeInteger(a.value.value)||a.value.value<=0||!s.properties.some(f=>V.isObjectProperty(f)&&!f.computed&&Rl(f.key)==="page"))return null;let l=s.properties.some(f=>V.isObjectProperty(f)&&!f.computed&&Rl(f.key)==="category"),u=im(o,f=>V.isAwaitExpression(f)&&V.isIdentifier(f.argument,{name:"searchParams"})).length;if(u>1)return null;let d=im(o,f=>{if(!V.isCallExpression(f))return!1;let g=f.callee;return V.isMemberExpression(g)&&!g.computed&&V.isIdentifier(g.property,{name:"categories"})&&V.isMemberExpression(g.object)&&!g.object.computed&&V.isIdentifier(g.object.property,{name:"collections"})&&V.isIdentifier(g.object.object,{name:"cms"})&&V.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 bj(e){let t=e.program.body.find(n=>V.isExportDefaultDeclaration(n));return V.isExportDefaultDeclaration(t)&&(V.isFunctionDeclaration(t.declaration)||V.isFunctionExpression(t.declaration)||V.isArrowFunctionExpression(t.declaration))?t.declaration:null}function im(e,t){let n=[],r=o=>{if(!(o!==e&&cm(o))){t(o)&&n.push(o);for(let i of Object.values(o))if(Array.isArray(i))for(let s of i)Nl(s)&&r(s);else Nl(i)&&r(i)}};return r(e),n}function xj(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_ROUTE_UNPROVEN"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function Ej(e){return e instanceof Map?e:new Map(Object.entries(e))}function Sj(e,t,n){if(!Qe(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):vj(`${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 vj(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function Ij(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function kj(e){let t=new Map;for(let n of e.program.body){if(!V.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(V.isIdentifier(o.local)){if(V.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(V.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(V.isImportSpecifier(o)){let i=V.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 hI(e,t,n,r,o,i){let s=Pj(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(m,y)=>{if(u.has(m)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${m}`,message:`Portable invocation contains duplicate prop ${m}.`,source_range:s});return}u.add(m),c.push({propName:m,value:y}),(m==="type"||m==="variant")&&y.kind==="json-literal"&&(l[m]=y.value)};for(let m of t.attributes){if(V.isJSXSpreadAttribute(m)){let E=$r(m.argument);if(!E.ok||!bI(E.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[k,v]of Object.entries(E.value)){if(!mI(k)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${k}`,message:`Portable invocation cannot encode prop ${k}.`,source_range:s});continue}g(k,sm(v))}continue}let y=Nj(m.name);if(!y)continue;let b=m.value,S=b&&V.isJSXExpressionContainer(b)?b.expression:null;if(pj.has(y)){let E=b?_l(b):{ok:!0,value:!0};!E.ok||typeof E.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=E.value;continue}if(mj.has(y)){let E=b?_l(b):{ok:!0,value:!0};!E.ok||typeof E.value!="number"||!Number.isSafeInteger(E.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):f=E.value;continue}if(!mI(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(fj.has(y)){let E=b?_l(b):{ok:!0,value:!0};E.ok&&typeof E.value=="string"?d=E.value:S&&pI(S,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(S&&pI(S,o)){g(y,{kind:"route-search-params"});continue}let x=b?_l(b):{ok:!0,value:!0};if(!x.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,sm(x.value))}let p=_j(n);return p.ok?p.value!==void 0&&g("children",sm(p.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:p.message,source_range:s}),{call:r.kind==="local"?{kind:"local",source_file:e.file_path,local_name:r.local_name,ordinal:i,source_range:s}:{source_file:e.file_path,component_source:r.component_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 yI(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 _l(e){return e===null?{ok:!0,value:!0}:V.isStringLiteral(e)?{ok:!0,value:e.value}:V.isJSXExpressionContainer(e)?$r(e.expression):{ok:!1}}function $r(e){if(!e)return{ok:!1};if(V.isStringLiteral(e))return{ok:!0,value:e.value};if(V.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(V.isBooleanLiteral(e))return{ok:!0,value:e.value};if(V.isNullLiteral(e))return{ok:!0,value:null};if(V.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(V.isTSAsExpression(e)||V.isTSTypeAssertion(e)||V.isTSNonNullExpression(e))return $r(e.expression);if(V.isUnaryExpression(e)){let t=$r(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(V.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=$r(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(V.isObjectExpression(e)){let t={};for(let n of e.properties){if(V.isSpreadElement(n)){let i=$r(n.argument);if(!i.ok||!bI(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!V.isObjectProperty(n)||n.computed)return{ok:!1};let r=Rl(n.key);if(!r)return{ok:!1};let o=$r(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function _j(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of V.react.buildChildren(e)){let r=$r(n);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value)}return t.length===0?{ok:!0,value:void 0}:{ok:!0,value:t.length===1?t[0]:t}}function Cl(e,t,n){let r=cm(e)?new Set([...t,...Rj(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)Nl(i)&&Cl(i,r,n);else Nl(o)&&Cl(o,r,n)}function Rj(e){if(!cm(e))return[];let t=[];for(let n of e.params)Ls(n,t);return t}function Ls(e,t){if(V.isIdentifier(e)){t.push(e.name);return}if(V.isAssignmentPattern(e)){Ls(e.left,t);return}if(V.isObjectPattern(e)){for(let n of e.properties)V.isRestElement(n)?Ls(n.argument,t):V.isObjectProperty(n)&&Ls(n.value,t);return}if(V.isArrayPattern(e))for(let n of e.elements)n&&Ls(n,t)}function pI(e,t){return V.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):V.isMemberExpression(e)&&!e.computed&&V.isIdentifier(e.property)&&e.property.name==="searchParams"&&V.isIdentifier(e.object)&&t.names.has(e.object.name)}function sm(e){return{kind:"json-literal",value:e}}function bI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mI(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function xI(e){if(V.isJSXIdentifier(e))return e.name;if(!V.isJSXMemberExpression(e))return null;let t=am(e.object);return t?`${t}.${e.property.name}`:null}function am(e){if(V.isJSXIdentifier(e))return e.name;if(!V.isJSXMemberExpression(e))return null;let t=am(e.object);return t?`${t}.${e.property.name}`:null}function Cj(e,t){if(V.isJSXIdentifier(e))return t.get(e.name)??null;if(!V.isJSXMemberExpression(e))return null;let n=am(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 Nj(e){return V.isJSXIdentifier(e)?e.name:V.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Rl(e){return V.isIdentifier(e)?e.name:V.isStringLiteral(e)||V.isNumericLiteral(e)?String(e.value):null}function cm(e){return V.isFunctionDeclaration(e)||V.isFunctionExpression(e)||V.isArrowFunctionExpression(e)}function Nl(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Pj(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 lm(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Fs(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var wj=typeof dm=="function"?dm:dm.default,fm=class extends Map{constructor(t){super(),this.files=t,this.failures=new Map}read(t){let n=super.get(t);if(n)return{ok:!0,module:n};let r=this.failures.get(t);if(r)return{ok:!1,missing:!1,message:r};let o=Al(this.files,t);if(o===null)return{ok:!1,missing:!0,message:"A re-exported source is missing or is not valid UTF-8 text."};let i=De(t,o);return i.ok?(super.set(t,i.module),{ok:!0,module:i.module}):(this.failures.set(t,i.diagnostic.message),{ok:!1,missing:!1,message:i.diagnostic.message})}get(t){let n=this.read(t);return n.ok?n.module:void 0}has(t){return super.has(t)||this.files.has(t)}};function ym(e){let{binding:t,files:n}=e;if(e.hostCapabilities!==null&&!Aj.safeParse(e.hostCapabilities).success)return ft("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!Ds(t.descriptor.source.file)||!Ds(t.ownerFile))return ft("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let r=Al(n,t.descriptor.source.file),o=Al(n,t.ownerFile);if(r===null||o===null)return ft("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(_e(r)!==t.descriptor.source.contentHash||_e(r)!==t.sourceHash||_e(o)!==t.ownerSourceHash)return ft("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let i=De(t.descriptor.source.file,r);if(!i.ok)return ft("INVOCATION_PARSE_FAILED",t.descriptor.source.file,i.diagnostic.message);let s=Tl(i.module.ast,t.rootLocator.sourceRange);if(s.length!==1)return ft("INVOCATION_TARGET_AMBIGUOUS",t.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let a=s[0],c=vI(a.node);if(!c)return ft("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The selected JSX element has no complete source range.");let l=[],u=t.root.callChain,d=new fm(n),f=Oj(e,c,d);if(f)return f;if(u.some(y=>(y.alternativeLocators?.length??0)>1))return ft("INVOCATION_TARGET_NOT_RENDERED",t.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[y,b]of u.entries()){let S=Al(n,b.sourceFile);if(S===null||!Ds(b.sourceFile))return ft("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let x=De(b.sourceFile,S);if(!x.ok)return ft("INVOCATION_PARSE_FAILED",b.sourceFile,x.diagnostic.message);let E=Tl(x.module.ast,b.callLocator.sourceRange);if(E.length!==1)return ft("INVOCATION_TARGET_AMBIGUOUS",b.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let k=u[y+1]?.sourceFile??t.descriptor.source.file,v=u[y+1]?.callLocator.sourceRange??t.rootLocator.sourceRange,I=yr({module:x.module,componentName:b.component,callSourceRange:b.callLocator.sourceRange});if(I.ok){if(I.sourceFile!==k)return ft("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(I.roots.filter(Ge=>ui(Ge.node,v)).length!==1)return ft("INVOCATION_TARGET_NOT_RENDERED",I.sourceFile,"The local component definition does not select exactly one proven JSX root.");let ee=gI({file_path:b.sourceFile,source:S,target:{kind:"local",local_name:b.component},call_source_range:{start_line:b.callLocator.sourceRange.startLine,start_column:b.callLocator.sourceRange.startColumn}});if(!ee.call||!ee.complete)return{complete:!1,errors:ee.errors.length>0?ee.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:b.sourceFile,message:"The selected local call did not produce a complete invocation binding."}]};l.push({kind:"local",call:ee.call,invocation:ee,definition:I,entryExport:null});continue}let N=pm(x.module.ast,E[0].node.openingElement.name,b.component,b.exportName);if(!N)return ft("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The statically proven component call no longer resolves through one exact import.");let A=mm(b.sourceFile,N.source,n);if(!A)return ft("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let w=d.read(A);if(!w.ok)return ft(w.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",A,w.message);let L=Xt({module:w.module,exportName:N.exportName,parsedModules:d});if(!L.ok)return ft("INVOCATION_TARGET_NOT_RENDERED",L.diagnostic.file,L.diagnostic.message);if(L.sourceFile!==k)return ft("INVOCATION_TARGET_NOT_RENDERED",b.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let B=L.roots.filter(W=>ui(W.node,v));if(B.length!==1)return ft("INVOCATION_TARGET_NOT_RENDERED",L.sourceFile,"The unique component export does not select exactly one proven JSX root.");let J=null;if(y===u.length-1&&u.length===1&&!kI(t.ownerFile)&&ui(B[0].node,t.rootLocator.sourceRange)){let W=d.read(L.sourceFile);if(!W.ok)return ft(W.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",L.sourceFile,W.message);if(J=SI(W.module,L.componentName,N.exportName),!J)return ft("INVOCATION_TARGET_AMBIGUOUS",L.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let $=li({file_path:b.sourceFile,source:S,target:{source:N.source,export_name:N.exportName,local_name:N.localName},call_source_range:{start_line:b.callLocator.sourceRange.startLine,start_column:b.callLocator.sourceRange.startColumn}});if(!$.call||!$.complete)return{complete:!1,errors:$.errors.length>0?$.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:b.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};l.push({kind:"import",call:$.call,invocation:$,definition:L,entryExport:J})}let g={kind:"page-block",composition:II(t.composition),blockKey:t.blockKey},p=Lj(t,a,l,n,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.error]};let m=l[0]?.invocation??null;return{complete:!0,selection:{target:g,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:y})=>y),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:m}}}function Oj(e,t,n){let{binding:r,files:o}=e,i=r.root.callChain;if(i.length!==2)return null;let[s,a]=i;if(!s||!a||(s.alternativeLocators?.length??0)>1)return null;let c=n.get(s.sourceFile);if(!c)return null;let l=Tl(c.ast,s.callLocator.sourceRange);if(l.length!==1)return null;let u=pm(c.ast,l[0].node.openingElement.name,s.component,s.exportName);if(!u)return null;let d=mm(s.sourceFile,u.source,o),f=d?n.get(d):void 0;if(!f)return null;let g=Xt({module:f,exportName:u.exportName,parsedModules:n});if(!g.ok||g.sourceFile!==a.sourceFile)return null;let p=n.get(g.sourceFile);if(!p||SI(p,g.componentName,"default")?.kind!=="default")return null;let m=rm({files:o,list_entry_file:s.sourceFile,selected_component_source:`@/${g.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`});if(!m.complete||!m.relation)return null;let y=a.alternativeLocators?.length?a.alternativeLocators:[a.callLocator],b=g.returnAlternatives?.length?g.returnAlternatives:g.roots;if(b.length!==y.length||!b.every(k=>y.filter(v=>ui(k.node,v.sourceRange)).length===1))return null;for(let k of y){let v=Tl(p.ast,k.sourceRange);if(v.length!==1)return null;let I=pm(p.ast,v[0].node.openingElement.name,a.component,a.exportName);if(!I)return null;let N=mm(g.sourceFile,I.source,o),A=N?n.get(N):void 0;if(!A)return null;let w=Xt({module:A,exportName:I.exportName,parsedModules:n});if(!w.ok||w.sourceFile!==r.descriptor.source.file||w.roots.length!==1||!ui(w.roots[0].node,r.rootLocator.sourceRange))return null}let S=li({file_path:s.sourceFile,source:c.source,target:{source:u.source,export_name:u.exportName,local_name:u.localName},call_source_range:{start_line:s.callLocator.sourceRange.startLine,start_column:s.callLocator.sourceRange.startColumn}});if(!S.complete||!S.call)return{complete:!1,errors:S.errors};let E=`components/site/portable/${EI("sha256").update(JSON.stringify(["collection-container",r.composition,r.blockKey,r.sourceHash,_e(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return o.has(E)?ft("INVOCATION_TARGET_AMBIGUOUS",E,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:II(r.composition),blockKey:r.blockKey},root_ref:r.root.rootRef,source_file:r.descriptor.source.file,structural_path:r.descriptor.source.structuralPath,content_hash:r.descriptor.source.contentHash,source_range:t,owner:r.descriptor.owner,call_chain:[S.call],strategy:"collection-container",collection_container_file:g.sourceFile,entry_file:E,entry_export:{kind:"default"},invocation:S}}}function Lj(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&ui(i.definition.roots[0].node,e.rootLocator.sourceRange),u=kI(e.ownerFile);if(n.length===1&&l&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&l&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!vI(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/${EI("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!Ds(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 SI(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(ze.isExportDefaultDeclaration(i)){let s=i.declaration;(ze.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||ze.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!ze.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=Fj(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ze.isExportSpecifier(s)&&s.exportKind!=="type"&&hm(s.local)===t&&r.add(hm(s.exported))}}if(r.size===0)return null;let o=r.has(n)?n:r.size===1?r.values().next().value:r.has("default")?"default":null;return o?o==="default"?{kind:"default"}:{kind:"named",name:o}:null}function Fj(e,t){return ze.isFunctionDeclaration(e)?e.id?.name===t?t:null:ze.isVariableDeclaration(e)&&e.declarations.some(n=>ze.isIdentifier(n.id)&&n.id.name===t)?t:null}function pm(e,t,n,r){let o=gm(t);if(!o||o!==n)return null;let i=ze.isJSXMemberExpression(t)?gm(t.object):ze.isJSXNamespacedName(t)?t.namespace.name:o,s=ze.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(ze.isImportDeclaration(a))for(let c of a.specifiers){if(ze.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(ze.isImportSpecifier(c)&&c.local.name===i){let l=hm(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(ze.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Tl(e,t){let n=[];return wj(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 vI(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 ui(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 Al(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 mm(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?um.posix.normalize(um.posix.join(um.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=>Ds(i)&&n.has(i))??null}function gm(e){if(ze.isJSXIdentifier(e))return e.name;if(ze.isJSXMemberExpression(e)){let t=gm(e.object);return t?`${t}.${e.property.name}`:null}return null}function hm(e){return ze.isIdentifier(e)?e.name:e.value}function II(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function Ds(e){return Tj.safeParse(e).success}function kI(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function ft(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import bm from"@babel/traverse";import*as Ce from"@babel/types";var NI=typeof bm=="function"?bm:bm.default,_I=256,RI=16;function PI(e){let t=[],n=new Map,r=new Map,o=new Set,i=new Set,s=0;class a extends Map{constructor(){super(...arguments),this.attempted=new Set}has(E){return e.files.has(E)}get(E){let k=super.get(E);if(k||this.attempted.has(E))return k;this.attempted.add(E);let v=e.files.get(E),I;try{if(typeof v=="string")I=v;else if(v instanceof Uint8Array)I=new TextDecoder("utf-8",{fatal:!0}).decode(v);else return}catch{return}let N=De(E,I);if(N.ok)return super.set(E,N.module),r.set(N.module.ast.program,N.module),N.module}}let c=new a;function l(x,E,k,v){let I=v?.loc?.start;t.push({code:x,source_path:E,message:k,...I?{call_site:{line:I.line,column:I.column}}:{}})}function u(x){if(!o.has(x.file)){if(o.size>=_I){l("CMS_MODULE_BUDGET_EXHAUSTED",x.file,"The module analysis budget was exhausted.");return}o.add(x.file);for(let E of x.ast.program.body){let k=null;if(Ce.isImportDeclaration(E)&&E.importKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Ce.isImportSpecifier(N)&&N.importKind==="type"))continue;k=E.source.value}else if(Ce.isExportNamedDeclaration(E)&&E.source&&E.exportKind!=="type"){if(E.specifiers.length&&E.specifiers.every(N=>Ce.isExportSpecifier(N)&&N.exportKind==="type"))continue;k=E.source.value}else Ce.isExportAllDeclaration(E)&&E.exportKind!=="type"&&(k=E.source.value);if(!k)continue;if(!Qe(k)){l("CMS_EXTERNAL_MODULE_UNRESOLVED",x.file,"An external module's initialization effects cannot be proven safe.",E);continue}let v=Br(x.file,k,e.files);if(!v){l("CMS_IMPORT_UNRESOLVED",x.file,`The local import ${k} is unavailable.`,E);continue}if(!/\.[cm]?[jt]sx?$/iu.test(v)||CI(v))continue;let I=c.get(v);I?u(I):l("CMS_SOURCE_UNAVAILABLE",v,"The imported source cannot be parsed.",E)}NI(x.ast,{Program(E){d(E,x,new Map),E.stop()}})}}function d(x,E,k){x.traverse({Function(v){(v.isObjectMethod()||v.isClassMethod()||v.isClassPrivateMethod())&&v.node.computed&&!Ur(v.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed method key may execute an unproven coercion.",v.node),v.skip()},BinaryExpression(v){(v.node.operator==="instanceof"||v.node.operator==="in"||v.node.operator!=="==="&&v.node.operator!=="!=="&&(!Ur(v.get("left"),k)||!Ur(v.get("right"),k)))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An operator may execute an unproven coercion or proxy trap.",v.node)},TemplateLiteral(v){v.get("expressions").some(I=>!Ur(I,k))&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Template interpolation may execute an unproven coercion.",v.node)},UnaryExpression(v){["+","-","~"].includes(v.node.operator)&&!Ur(v.get("argument"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A unary operator may execute an unproven coercion.",v.node)},UpdateExpression(v){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"An update may execute an unproven coercion or proxy trap.",v.node)},ObjectProperty(v){v.node.computed&&!Ur(v.get("key"),k)&&l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"A computed property key may execute an unproven coercion.",v.node)},ForInStatement(v){l("CMS_IMPLICIT_EXECUTION_UNRESOLVED",E.file,"Property enumeration may execute an unproven proxy trap.",v.node)},JSXOpeningElement(v){let I=v.node.name;if(Ce.isJSXIdentifier(I)&&/^[a-z]/u.test(I.name))return;if(Mj(v)){l("CMS_COMPONENT_REACHABILITY_UNPROVEN",E.file,"A component value is not proven to be rendered by the selected root.",v.node);return}if(!Ce.isJSXIdentifier(I)){l("CMS_COMPONENT_UNRESOLVED",E.file,"A dynamic or namespace component target is not proven.",v.node);return}let N=p(v.scope.getBinding(I.name),E);if(!N){l("CMS_COMPONENT_UNRESOLVED",E.file,"A rendered component target is not proven.",v.node);return}g(N,f(N,v,k))},JSXExpressionContainer(v){let I=v.get("expression");if(I.isFunctionExpression()||I.isArrowFunctionExpression())g(I,k);else if(I.isIdentifier()){let N=p(I.scope.getBinding(I.node.name),E);N?g(N,k):v.parentPath?.isJSXAttribute()&&Ce.isJSXIdentifier(v.parentPath.node.name)&&/^on[A-Z]/u.test(v.parentPath.node.name.name)&&l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An event handler target cannot be proven.",I.node)}},MemberExpression(v){let I=v.parentPath;I?.isMemberExpression()&&I.node.object===v.node||(I?.isCallExpression()||I?.isOptionalCallExpression())&&I.node.callee===v.node||I?.isVariableDeclarator()&&I.node.init===v.node&&m(v,E,new Set)||l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A property read may invoke an unproven getter or proxy.",v.node)},OptionalMemberExpression(v){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"An optional property read may invoke an unproven getter or proxy.",v.node)},VariableDeclarator(v){(Ce.isObjectPattern(v.node.id)||Ce.isArrayPattern(v.node.id))&&l("CMS_DESTRUCTURING_UNRESOLVED",E.file,"Destructuring can invoke an unproven getter or iterator.",v.node)},ForOfStatement(v){l("CMS_ITERATION_UNRESOLVED",E.file,"An iterable may invoke an unproven iterator.",v.node)},SpreadElement(v){l("CMS_ITERATION_UNRESOLVED",E.file,"A spread may invoke an unproven iterator or getter.",v.node)},JSXSpreadAttribute(v){l("CMS_PROPERTY_ACCESS_UNRESOLVED",E.file,"A JSX spread may invoke an unproven getter or proxy.",v.node)},CallExpression(v){if(Ce.isImport(v.node.callee)){l("CMS_DYNAMIC_IMPORT_UNRESOLVED",E.file,"A dynamic import cannot prove the selected call closure.",v.node);return}for(let A of v.get("arguments"))(A.isFunctionExpression()||A.isArrowFunctionExpression())&&g(A,new Map);let I=v.get("callee"),N=m(I,E,new Set);if(N){if(Ar(E.ast,N.originalName)){l("CMS_BINDING_MUTATED",E.file,"The trusted CMS binding or one of its aliases is modified.",v.node);return}let w=v.get("arguments")[0],L=w?tn(w,k,new Set):null;if(!L||L.length===0){l("CMS_IDENTITY_UNRESOLVED",E.file,"The CMS application identity is not statically bounded.",v.node);return}let B=Bj(N.name);for(let J of L){let $=Fc(Ce.callExpression(B,[Ce.stringLiteral(J)]),{file:E.file,imports:new Map([["__vcpCms",{source:N.source,importedName:N.importedName}]])}),ee=$?.operation==="getByUrl"||$?.operation==="getByUrlStrict"?/^\/([a-z0-9][a-z0-9_-]*)\/[a-z0-9][a-z0-9._~-]*$/iu.exec(J)?.[1]:$?.collection;if(!$||$.sourceKind!=="vcp-cms-collection"||!ee||!/^[a-z0-9][a-z0-9_-]*$/iu.test(ee)){l("CMS_OPERATION_UNRESOLVED",E.file,"The CMS operation or application identity cannot be proven.",v.node);continue}let Ge=v.node.loc?.start;if(!Ge){l("CMS_CALL_SITE_UNAVAILABLE",E.file,"The CMS call has no source location.",v.node);continue}let tt={source_path:E.file,operation:$.operation,binding:"trusted-cms",call_site:{line:Ge.line,column:Ge.column}},G=n.get(ee)??[];G.some(me=>JSON.stringify(me)===JSON.stringify(tt))||G.push(tt),n.set(ee,G)}return}if(I.isIdentifier()){let A=I.scope.getBinding(I.node.name),w=p(A,E);if(w){let L=new Map,B=w.get("params");for(let[J,$]of B.entries()){if(!$.isIdentifier())continue;let W=w.scope.getBinding($.node.name),ee=v.get("arguments")[J];W&&L.set(W.identifier,ee?tn(ee,k,new Set):null)}g(w,L);return}if(!A&&I.node.name==="Boolean"||!A&&["String","Number"].includes(I.node.name)&&v.get("arguments").every(L=>Ur(L,k)))return}jj(v,k,A=>!!m(A,E,new Set))||l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A reachable call target cannot be proven free of hidden CMS access.",v.node)},OptionalCallExpression(v){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"An optional call target cannot be proven.",v.node)},NewExpression(v){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A constructor's effects cannot be proven.",v.node)},TaggedTemplateExpression(v){l("CMS_CALL_TARGET_UNRESOLVED",E.file,"A tagged template's effects cannot be proven.",v.node)}})}function f(x,E,k){let v=new Map,I=x.get("params")[0];if(!I?.isObjectPattern())return v;let N=E.get("attributes"),A=N.some(w=>w.isJSXSpreadAttribute());for(let w of I.get("properties")){if(!w.isObjectProperty()||w.node.computed)continue;let L=w.node.key,B=Ce.isIdentifier(L)?L.name:Ce.isStringLiteral(L)?L.value:null,J=w.get("value"),$=J.isIdentifier()?J:J.isAssignmentPattern()&&J.get("left").isIdentifier()?J.get("left"):null;if(!B||!$?.isIdentifier())continue;let W=x.scope.getBinding($.node.name);if(!W)continue;let ee=N.filter(G=>G.isJSXAttribute()&&Ce.isJSXIdentifier(G.node.name,{name:B})),Ge=null,tt=ee[0];if(!A&&ee.length===1&&tt?.isJSXAttribute()){let G=tt.get("value");G.isStringLiteral()?Ge=[G.node.value]:G.isJSXExpressionContainer()&&(Ge=tn(G.get("expression"),k,new Set))}v.set(W.identifier,Ge)}return v}function g(x,E){let k=x.findParent(I=>I.isProgram()),v=k&&Ce.isProgram(k.node)?r.get(k.node):void 0;if(!v){l("CMS_FUNCTION_UNRESOLVED",e.entry_file,"A callable has no proven source module.",x.node);return}if(i.has(x.node)||s++>=_I){l("CMS_CALL_BUDGET_EXHAUSTED",v.file,"Recursive or excessive reachable calls are not proven.",x.node);return}i.add(x.node),d(x,v,E),i.delete(x.node)}function p(x,E){if(!x||x.constantViolations.length)return null;let k=x.path;if(k.isFunctionDeclaration())return k;if(k.isVariableDeclarator()){let B=k.get("init");return B.isFunctionExpression()||B.isArrowFunctionExpression()?B:null}let v=k.parentPath;if(!v?.isImportDeclaration()||v.node.importKind==="type")return null;let I=v.node.source.value;if(!Qe(I))return null;let N=Br(E.file,I,e.files),A=N&&c.get(N),w=k.isImportDefaultSpecifier()?"default":k.isImportSpecifier()&&Ce.isIdentifier(k.node.imported)?k.node.imported.name:null;if(!A||!w)return null;let L=Sr(A,w,c);return L&&(L.isFunctionDeclaration()||L.isFunctionExpression()||L.isArrowFunctionExpression())?L:null}function m(x,E,k){if(!x.node||k.has(x.node)||k.size>=32)return null;if(k.add(x.node),x.isMemberExpression()&&!x.node.optional){let L=!x.node.computed&&Ce.isIdentifier(x.node.property)?x.node.property.name:x.node.computed&&Ce.isStringLiteral(x.node.property)?x.node.property.value:null,B=m(x.get("object"),E,k);return B&&L?{...B,name:`${B.name}.${L}`}:null}if(!x.isIdentifier())return null;let v=x.scope.getBinding(x.node.name);if(!v||v.constantViolations.length)return null;if(v.path.isVariableDeclarator())return m(v.path.get("init"),E,k);let I=v.path.parentPath;if(!I?.isImportDeclaration()||!v.path.isImportSpecifier())return null;let N=v.path.node.imported,A=Ce.isIdentifier(N)?N.name:N.value,w=Br(E.file,I.node.source.value,e.files);return!w||!CI(w)||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(A)?null:{name:"__vcpCms",source:w,importedName:A,originalName:v.identifier.name}}let y=c.get(e.entry_file);if(!y)l("CMS_ENTRY_UNAVAILABLE",e.entry_file,"The selected entry is missing or invalid.");else{u(y);let x=Sr(y,e.entry_export.kind==="default"?"default":e.entry_export.name,c);!x||!(x.isFunctionDeclaration()||x.isFunctionExpression()||x.isArrowFunctionExpression())?l("CMS_ENTRY_UNRESOLVED",e.entry_file,"The selected entry export is not one proven function."):g(x,new Map)}let b=[...n.entries()].sort(([x],[E])=>x.localeCompare(E)).map(([x,E])=>({requirement_key:`cms-${x}`,slug:x,evidence:E.sort((k,v)=>k.source_path.localeCompare(v.source_path)||k.call_site.line-v.call_site.line||k.call_site.column-v.call_site.column)})),S=[...new Map(t.map(x=>[JSON.stringify(x),x])).values()];return{complete:S.length===0,dependencies:b,unresolved:S}}function AI(e,t){if(!e.complete||!e.dependencies.length||e.unresolved.length)return!1;let n=new Set(["list","listStrict","schema","categories"]),r=new Map;for(let o of e.dependencies){if(!o.evidence.length)return!1;for(let i of o.evidence){if(i.binding!=="trusted-cms"||!n.has(i.operation))return!1;let s=r.get(i.source_path);if(!s){let l=t.get(i.source_path),u;try{if(typeof l=="string")u=l;else if(l instanceof Uint8Array)u=new TextDecoder("utf-8",{fatal:!0}).decode(l);else return!1}catch{return!1}let d=De(i.source_path,u);if(!d.ok)return!1;s=new Map,NI(d.module.ast,{CallExpression(f){let g=f.node.loc?.start;if(!g)return;let p=`${g.line}:${g.column}`,m=s.get(p)??[];m.push(f),s.set(p,m)}}),r.set(i.source_path,s)}let a=`${i.call_site.line}:${i.call_site.column}`,c=s.get(a);if(c?.length!==1||!Dj(c[0],i.operation))return!1}}return!0}function Dj(e,t){let n=e.get("arguments");if(n.length<1||n.length>2||n[0].isSpreadElement())return!1;if(n.length===1)return!0;let r=n[1];if(!["list","listStrict"].includes(t)||!r.isObjectExpression())return!1;let o=new Set;for(let i of r.get("properties")){if(!i.isObjectProperty()||i.node.computed)return!1;let s=Ce.isIdentifier(i.node.key)?i.node.key.name:Ce.isStringLiteral(i.node.key)?i.node.key.value:null;if(!s||!["page","pageSize"].includes(s)||o.has(s))return!1;o.add(s);let a=xm(i.get("value"),new Set);if(a===null||!Number.isSafeInteger(a)||(s==="page"?a!==1:a<1||a>100))return!1}return!0}function xm(e,t){if(!e.node||t.has(e.node)||t.size>=32)return null;if(t.add(e.node),e.isNumericLiteral())return e.node.value;if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return xm(e.get("expression"),t);if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);return!n||n.constantViolations.length||!n.path.isVariableDeclarator()||!n.path.parentPath.isVariableDeclaration({kind:"const"})?null:xm(n.path.get("init"),t)}function CI(e){return/^(?:src\/)?lib\/cms(?:\/index|\/collections|\/client)?\.[cm]?[jt]s$/u.test(e)}function Mj(e){let t=e.parentPath?.parentPath;for(;t&&!t.isFunction()&&!t.isProgram();){if(t.isVariableDeclarator()||t.isJSXAttribute())return!0;if(t.isJSXElement()){let n=t.node.openingElement.name;if(!Ce.isJSXIdentifier(n)||!/^[a-z]/u.test(n.name))return!0}t=t.parentPath}return!1}function Bj(e){let[t,...n]=e.split(".");return n.reduce((r,o)=>Ce.memberExpression(r,Ce.identifier(o)),Ce.identifier(t))}function jj(e,t,n){let r=e.node.callee;if(!(Ce.isMemberExpression(r)&&!r.computed&&Ce.isIdentifier(r.object,{name:"Promise"})&&!e.scope.getBinding("Promise")&&Ce.isIdentifier(r.property,{name:"all"})))return!1;let o=e.get("arguments")[0];return o?.isArrayExpression()?o.get("elements").every(i=>!i.node||Ur(i,t)||i.isCallExpression()&&n(i.get("callee"))):!1}function Ur(e,t){return e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()||e.isNullLiteral()||tn(e,t,new Set)!==null}function tn(e,t,n){if(!e.node||n.has(e.node)||n.size>=32)return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return[e.node.value];if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!o||o.constantViolations.length?null:t.has(o.identifier)?t.get(o.identifier)??null:o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})?tn(o.path.get("init"),t,r):null}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return tn(e.get("expression"),t,r);if(e.isConditionalExpression()){let o=tn(e.get("consequent"),t,r),i=tn(e.get("alternate"),t,r);if(!o||!i)return null;let s=[...new Set([...o,...i])];return s.length<=RI?s:null}if(e.isBinaryExpression({operator:"+"})){let o=tn(e.get("left"),t,r),i=tn(e.get("right"),t,r);return!o||!i||o.length*i.length>RI?null:[...new Set(o.flatMap(s=>i.map(a=>s+a)))]}return null}import Em from"@babel/generator";import Sm from"@babel/traverse";import*as ie from"@babel/types";var TI=typeof Sm=="function"?Sm:Sm.default,$j=typeof Em=="function"?Em:Em.default;function OI(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=FI(t.get(o));if(i===null||!/\.[jt]sx?$/iu.test(o))continue;let s=De(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;TI(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),wI(l)&&(a=!0))}}}),TI(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=wI(c),l&&(a=!0),l&&c.scope.crawl();for(let d of c.get("body"))(d.isFunctionDeclaration()&&d.node.id&&!c.scope.getBinding(d.node.id.name)?.referenced||d.isVariableDeclaration({kind:"const"})&&d.node.declarations.every(f=>ie.isIdentifier(f.id)&&!c.scope.getBinding(f.id.name)?.referenced&&(!f.init||di(f.init))))&&(d.remove(),l=a=!0)}while(l);c.scope.crawl();let u=0;for(let d of c.node.body)ie.isExportDefaultDeclaration(d)?u+=1:ie.isExportAllDeclaration(d)&&d.exportKind!=="type"?u+=2:ie.isExportNamedDeclaration(d)&&d.exportKind!=="type"&&(d.declaration&&!ie.isTSInterfaceDeclaration(d.declaration)&&!ie.isTSTypeAliasDeclaration(d.declaration)&&(u+=Object.keys(ie.getOuterBindingIdentifiers(d.declaration)).length),u+=d.specifiers.filter(f=>!ie.isExportSpecifier(f)||f.exportKind!=="type").length);u>1&&r.push({code:"SOURCE_EXPORT_ISOLATION_UNPROVEN",path:o,message:"Multiple value exports cannot yet be isolated from unselected source."});for(let d of c.get("body")){if(!d.isImportDeclaration()||d.node.importKind==="type"||d.node.specifiers.length===0||!Qe(d.node.source.value))continue;let f=Br(o,d.node.source.value,t);if(!(!f||!n.has(f))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!LI(f,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:o,message:`The unused import ${d.node.source.value} may have initialization effects.`});continue}d.remove(),a=!0}}c.stop()}}),a&&t.set(o,$j(s.module.ast).code)}return{files:t,errors:r}}function wI(e){let t=new Map;for(let c of e.get("body")){let l=null,u=null;if(c.isFunctionDeclaration()&&c.node.id)l=c.node.id.name,u=c.node;else if(c.isVariableDeclaration({kind:"const"})&&c.node.declarations.length===1){let f=c.node.declarations[0];ie.isIdentifier(f.id)&&(ie.isFunctionExpression(f.init)||ie.isArrowFunctionExpression(f.init))&&(l=f.id.name,u=f.init)}let d=l?e.scope.getBinding(l):void 0;l&&u&&d&&d.constantViolations.length===0&&t.set(l,{definition:u,declaration:c,binding:d})}let n=new Map([...t].map(([c,l])=>[l.definition,c])),r=new Set,o=new Map;for(let[c,l]of t)for(let u of l.binding.referencePaths){let d=u.findParent(g=>n.has(g.node)),f=d?n.get(d.node):void 0;if(!f)r.add(c);else{let g=o.get(f)??new Set;g.add(c),o.set(f,g)}}let i=new Set,s=[...r];for(;s.length;){let c=s.pop();i.has(c)||(i.add(c),s.push(...o.get(c)??[]))}let a=!1;for(let[c,l]of t)i.has(c)||(l.declaration.remove(),a=!0);return a}function LI(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=FI(t.get(e));if(r===null)return!1;let o=De(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!Qe(a))return!1;let c=Br(e,a,t);return c!==null&&LI(c,t,i)};return o.module.ast.program.body.every(a=>ie.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(c=>ie.isImportSpecifier(c)&&c.importKind==="type")?!0:s(a.source.value):ie.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):ie.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?vm(a.declaration):!0:ie.isExportDefaultDeclaration(a)?vm(a.declaration):vm(a))}function vm(e){return ie.isFunctionDeclaration(e)||ie.isTSInterfaceDeclaration(e)||ie.isTSTypeAliasDeclaration(e)||ie.isTSDeclareFunction(e)||ie.isEmptyStatement(e)?!0:ie.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>ie.isIdentifier(t.id)&&(!t.init||di(t.init))):di(e)}function di(e){return ie.isStringLiteral(e)||ie.isNumericLiteral(e)||ie.isBooleanLiteral(e)||ie.isNullLiteral(e)||ie.isFunctionExpression(e)||ie.isArrowFunctionExpression(e)?!0:ie.isArrayExpression(e)?e.elements.every(t=>t===null||!ie.isSpreadElement(t)&&di(t)):ie.isObjectExpression(e)?e.properties.every(t=>ie.isObjectProperty(t)&&!t.computed&&!t.shorthand&&di(t.value)):ie.isTSAsExpression(e)||ie.isTSSatisfiesExpression(e)||ie.isTSNonNullExpression(e)||ie.isParenthesizedExpression(e)?di(e.expression):!1}function FI(e){if(typeof e=="string")return e;if(!(e instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}import Im from"@babel/traverse";import*as ct from"@babel/types";var Uj=typeof Im=="function"?Im:Im.default;function DI(e){let t=De(e.file_path,e.source),n=[],r=new Set,o=(s,a)=>{n.some(c=>c.code===s&&c.message===a)||n.push({code:s,path:e.file_path,message:a})};if(!t.ok)return o("ROUTE_SOURCE_UNAVAILABLE","The route source cannot be parsed."),{complete:!1,dependencies:[],errors:n};let i=s=>{if(!ct.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=Vj(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return Uj(t.module.ast,{JSXOpeningElement(s){let a=ct.isJSXIdentifier(s.node.name)?s.node.name.name:"";if((["form","iframe","embed","object","portal","script","base","meta","link"].includes(a.toLowerCase())||/^[a-z]/u.test(a)&&a.includes("-"))&&o("ROUTE_VALUE_UNRESOLVED","Embedded content or a form has unproven navigation effects."),a==="button"||a==="input"){let c=s.node.attributes.filter(d=>ct.isJSXAttribute(d)&&ct.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),l=c.length===1&&ct.isJSXAttribute(c[0])?c[0].value:null,u=ct.isStringLiteral(l)?l.value.toLowerCase():null;(a==="button"&&u!=="button"||a==="input"&&(c.length>1||c.length===1&&!u||u==="submit"||u==="image"))&&o("ROUTE_VALUE_UNRESOLVED","A form control may submit an unproven host form.")}},JSXAttribute(s){if(!ct.isJSXIdentifier(s.node.name)){o("ROUTE_VALUE_UNRESOLVED","A namespaced JSX attribute cannot prove navigation.");return}let a=s.node.name.name.toLowerCase();if(["dangerouslysetinnerhtml","srcdoc","action","formaction","form","download","xlinkhref"].includes(a)){o("ROUTE_VALUE_UNRESOLVED","Injected HTML or a form action has unproven navigation effects.");return}if(a!=="href")return;let c=s.node.value;i(ct.isJSXExpressionContainer(c)?c.expression:c)},JSXSpreadAttribute(){o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=Ms(s.node.key,s.node.computed);a===null&&s.node.computed?o("ROUTE_VALUE_UNRESOLVED","A computed property may contain an unproven navigation destination."):a==="href"&&i(s.node.value)},ObjectMethod(s){let a=Ms(s.node.key,s.node.computed);(a==="href"||a===null&&s.node.computed)&&o("ROUTE_VALUE_UNRESOLVED","A method or getter may provide an unproven navigation destination.")},SpreadElement(){o("ROUTE_VALUE_UNRESOLVED","A spread may contain an unproven navigation destination.")},MemberExpression(s){let a=Ms(s.node.property,s.node.computed);s.node.computed&&a===null&&o("ROUTE_VALUE_UNRESOLVED","A computed property may access an unproven navigation capability."),a&&["location","pushState","replaceState","navigate"].includes(a)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven."),a&&["setAttribute","setAttributeNS","insertAdjacentHTML","write","writeln"].includes(a)&&o("ROUTE_VALUE_UNRESOLVED","Imperative DOM modification is not proven."),a&&["push","replace","go","back","forward"].includes(a)&&ct.isIdentifier(s.node.object)&&/router|history|navigation/iu.test(s.node.object.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative router navigation is not proven."),a==="open"&&ct.isIdentifier(s.node.object)&&["window","globalThis"].includes(s.node.object.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},ReferencedIdentifier(s){s.node.name==="location"&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},AssignmentExpression(s){(ct.isIdentifier(s.node.left,{name:"location"})||ct.isMemberExpression(s.node.left)&&(Ms(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&Ms(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){ct.isIdentifier(s.node.callee)&&["redirect","navigate","open"].includes(s.node.callee.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")}}),{complete:n.length===0,dependencies:[...r].sort().map(s=>({kind:"host-route",href:s})),errors:n}}function Ms(e,t){return ct.isStringLiteral(e)?e.value:!t&&ct.isIdentifier(e)?e.name:t&&ct.isNumericLiteral(e)?String(e.value):null}function Vj(e){if(!e||e.length>2048||/[\s\u0000-\u0020\u007f-\u009f\\%]/u.test(e))return"unknown";if(e.startsWith("#")||/^(?:mailto|tel):.+/iu.test(e))return"external";if(!e.startsWith("/")||e.startsWith("//"))return"unknown";let t=e.split(/[?#]/u,1)[0];return t.includes("//")||t.split("/").some(n=>n==="."||n==="..")||/^\/(?:api|_next)(?:\/|$)/u.test(t)||/\.[a-z0-9]{1,12}$/iu.test(t)?"unknown":"host-route"}import{createHash as Kj}from"node:crypto";import Jj from"@babel/traverse";import*as Te from"@babel/types";var km=Jj,Xj=typeof km=="function"?km:km.default,zj=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),fi=new Set(["backgroundimage","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Hj=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,Wj=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function _m(e){let t=De(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=BI(c.node),u=n0(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:r0(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=BI(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})};Xj(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;Yj(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=jI(c.node.name),u=Wj.test(l);for(let d of c.node.attributes){if(Te.isJSXSpreadAttribute(d)){u&&i({node:d.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}let f=qj(d);if(f==="style"&&!Gj(d.value)){i({node:d.value??d,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!f||!Zj(f,u))continue;let g=Vr(d.value);i({node:d.value??d,kind:MI(f),source:"jsx-attribute",value:g.value,complete:g.complete})}},ObjectProperty(c){let l=Ll(c.node.key);if(!l||!fi.has(l)&&!(t0(c)&&$I(l))||fi.has(l)&&wl(c.node.value)&&Ol(c.node.value))return;let u=Vr(c.node.value);i({node:c.node.value,kind:MI(l),source:"object-property",value:u.value,complete:u.complete})},ArrayExpression(c){if(e0(c))for(let l of c.node.elements){if(!l||wl(l)&&Ol(l))continue;let u=Vr(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(!Te.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Te.isExpression(u)){s(c.node,null);return}let d=Vr(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!Qj(c.node.object))return;let l=c.node.computed?Vr(c.node.property):Te.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=o0(r).sort(i0);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function Gj(e){return!Te.isJSXExpressionContainer(e)||!Te.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!Te.isObjectProperty(t)||t.computed||!(Te.isIdentifier(t.key)||Te.isStringLiteral(t.key)))return!1;let n=Te.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:Te.isNumericLiteral(t.value)?Number.isFinite(t.value.value):Te.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function Yj(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&zj.has(n)}function Zj(e,t){return e!=="src"||t?fi.has(e):!1}function MI(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function qj(e){return Te.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Te.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function jI(e){return Te.isJSXIdentifier(e)?e.name:Te.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${jI(e.object)}.${e.property.name}`}function Ll(e){return Te.isIdentifier(e)?e.name.toLowerCase():Te.isStringLiteral(e)?e.value.toLowerCase():null}function Qj(e){return Te.isIdentifier(e,{name:"mediaAssets"})}function e0(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=Ll(t.node.key);return n!==null&&fi.has(n)}return t?.isVariableDeclarator()&&Te.isIdentifier(t.node.id)?Hj.test(t.node.id.name):!1}function t0(e){let n=e.parentPath?.parentPath;if(!n?.isObjectProperty())return!1;let r=Ll(n.node.key);return r!==null&&fi.has(r)}function $I(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function wl(e){return Te.isObjectExpression(e)||Te.isArrayExpression(e)}function Ol(e){if(Te.isArrayExpression(e))return e.elements.some(n=>n!==null&&(wl(n)?Ol(n):!0));let t=!1;for(let n of e.properties){if(!Te.isObjectProperty(n))return!1;let r=Ll(n.key);if(r!==null&&(fi.has(r)||$I(r))){t=!0;continue}wl(n.value)&&Ol(n.value)&&(t=!0)}return t}function Vr(e){return e?Te.isStringLiteral(e)?{value:e.value,complete:!0}:Te.isJSXExpressionContainer(e)?Vr(e.expression):Te.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Te.isTSAsExpression(e)||Te.isTSTypeAssertion(e)||Te.isParenthesizedExpression(e)?Vr(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function BI(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 n0(e,t){return e.slice(t.start_offset,t.end_offset)}function r0(e){return`sha256:${Kj("sha256").update(e).digest("hex")}`}function o0(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 i0(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)}var VI=512,u0=1024*1024,d0=8*1024*1024,KI=256,JI={"index.ts":"sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f","client.ts":"sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5"},f0=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]);function p0(e){return e.index===JI["index.ts"]&&e.client===JI["client.ts"]&&f0.has(e.collections)}function m0(e){let t=()=>({complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image could not be verified."}]});if(!e.exported.complete||e.snapshot_digest!==e.exported.snapshot_digest||zI(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%UI!==0)return t();let n=e.exported.media.filter(u=>u.file_path===e.file_path&&u.occurrence===e.occurrence);if(n.length!==1)return t();let r=n[0],o=r.value;if(!r.complete||!o||r.kind==="srcset"||!o.startsWith("/")||o.startsWith("//")||/[\\\0%?#]/u.test(o))return t();let i=o.slice(1).split("/");if(i.some(u=>!u||u.startsWith(".")||u==="node_modules"))return t();let s=`public/${i.join("/")}`,a=e.snapshot_files.get(s);if(!(a instanceof Uint8Array)||!a.byteLength||a.byteLength>c0||e.offset>=a.byteLength)return t();let c=g0(s,a);if(!c)return t();let l=Buffer.from(a);return{complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:s,mime_type:c,byte_size:l.byteLength,digest_sha256:Cm("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+UI).toString("base64")}}function g0(e,t){let n=e.toLowerCase(),r=o=>o.every((i,s)=>t[s]===i);return n.endsWith(".png")&&r([137,80,78,71,13,10,26,10])?"image/png":/\.jpe?g$/u.test(n)&&r([255,216,255])?"image/jpeg":n.endsWith(".gif")&&(r([71,73,70,56,55,97])||r([71,73,70,56,57,97]))?"image/gif":n.endsWith(".webp")&&r([82,73,70,70])&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function h0(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return nn("SNAPSHOT_MISMATCH","<snapshot>","The authoritative Snapshot does not match the requested site and version.");let t=e.site_id,n=e.base_snapshot_id,r=e.document_version,o=e.read_current_identity,i=new Map(e.trusted_host_file_hashes??[]),s=l0.safeParse(e.target),a=s0.safeParse(e.selection_ref);if(!s.success||!a.success)return nn("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let c=s.data,l=a.data,u=XI(o,t,n,r);if(u)return u;let d=a0.safeParse(e.host_capabilities);if(!d.success)return nn("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let f=new Map;for(let[G,me]of e.snapshot.files){if(typeof me!="string"&&!(me instanceof Uint8Array))return nn("SNAPSHOT_CONTENT_MISMATCH",G,"A Snapshot file has an unsupported content type.");f.set(G,typeof me=="string"?me:new Uint8Array(me))}if(!x0(e.snapshot.manifest,t,n,f))return nn("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let g=zI(f),p=await Bp({site_id:t,base_snapshot_id:n,composition:c.composition,document_version:r,target:c,selection_ref:l,files:f});if(!p.ok)return nn(`BLOCK_${p.code}`,c.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return nn("BLOCK_EXPORT_NOT_ALLOWED",c.blockKey,"The selected block is not exportable.");let m=ym({binding:p.binding,files:f,hostCapabilities:d.data});if(!m.complete)return Rm(m.errors.map(({code:G,path:me,message:qe})=>({code:G,path:me,message:qe})));let y=Gp({selection:m.selection,files:f});if(!y.complete)return Rm(y.errors.map(({code:G,path:me,message:qe})=>({code:G,path:me,message:qe})));let b=new Map(f);for(let G of y.source_files){let me=b.get(G.path);if(me!==void 0&&!y0(me,G.content))return nn("SOURCE_COLLISION",G.path,"An extracted entry conflicts with the pinned Snapshot.");b.set(G.path,G.content)}let S=Mr({entry_files:[y.entry_file],files:b,max_nodes:VI}),x=S.nodes.filter(G=>Fl(G.path)&&i.get(G.path)===Dl(b.get(G.path))).map(G=>G.path),E=hl({closure:S,host_capabilities:d.data,platform_managed_paths:x,platform_managed_packages:["server-only"]}),k=OI({files:b,private_paths:E.nodes.filter(G=>G.ownership==="private").map(G=>G.path)});b=new Map(k.files);let v=Mr({entry_files:[y.entry_file],files:b,max_nodes:VI}),I=hl({closure:v,host_capabilities:d.data,platform_managed_paths:x,platform_managed_packages:["server-only"]}),N=PI({entry_file:y.entry_file,entry_export:m.selection.entry_export,files:b}),A=[...k.errors.filter(G=>v.nodes.some(me=>me.path===G.path)),...I.errors.map(({code:G,path:me,message:qe})=>({code:G,path:me,message:qe})),...N.unresolved.map(({code:G,source_path:me,message:qe,call_site:fe})=>({code:G,path:me,message:qe,...fe?{call_site:fe}:{}}))],w=new Set(x);for(let G of v.nodes)Fl(G.path)&&!w.has(G.path)&&A.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:G.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let G of I.nodes)G.kind==="external"||G.ownership!=="host-public"||Fl(G.path)||i.get(G.path)!==Dl(f.get(G.path))&&A.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:G.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let L=new Map(I.nodes.map(G=>[G.path,G.ownership])),B=[];for(let G of v.nodes){if(L.get(G.path)!=="private")continue;let me=b.get(G.path),qe=null;try{typeof me=="string"?qe=me:me instanceof Uint8Array&&(qe=new TextDecoder("utf-8",{fatal:!0}).decode(me))}catch{}qe===null?A.push({code:"SOURCE_TEXT_UNSUPPORTED",path:G.path,message:"A private source dependency is not valid UTF-8 text."}):B.push({path:G.path,content:qe})}for(let G of B)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(G.path)||G.path==="lib/generated/product-search-config.json")&&A.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:G.path,message:"A managed capability requires a proven requirement before exporting the block."});B.some(G=>G.path===y.entry_file)||A.push({code:"ENTRY_NOT_PRIVATE",path:y.entry_file,message:"The selected entry is not site-owned source."});let J=0,$=[];for(let G of B){let me=Buffer.byteLength(G.content,"utf8");if(J+=me,(me>u0||J>d0)&&A.push({code:"SOURCE_BUDGET_EXCEEDED",path:G.path,message:"The selected source exceeds its export byte budget."}),/\.[jt]sx?$/iu.test(G.path)){let qe=_m({file_path:G.path,source:G.content});$.push(...qe.references),A.push(...qe.errors.map(({code:fe,file_path:nt,message:Me})=>({code:fe,path:nt,message:Me})))}}let W=new Map,ee=!0;if(N.complete){let G=new Map(B.map(me=>[me.path,me.content]));for(let me of I.nodes){if(me.kind!=="source"||me.ownership!=="host-public")continue;let qe=b.get(me.path);try{if(typeof qe=="string")G.set(me.path,qe);else if(qe instanceof Uint8Array)G.set(me.path,new TextDecoder("utf-8",{fatal:!0}).decode(qe));else throw new Error("missing source")}catch{ee=!1,N.dependencies.length===0&&A.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:me.path,message:"A host source cannot be inspected for navigation."})}}for(let[me,qe]of G){if(!/\.[cm]?[jt]sx?$/iu.test(me))continue;let fe=DI({file_path:me,source:qe});fe.complete||(ee=!1),N.dependencies.length===0&&A.push(...fe.errors);for(let nt of fe.dependencies)W.set(nt.href,nt)}W.size>256&&N.dependencies.length===0&&A.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let Ge=N.dependencies.length>0&&ee&&W.size===0&&b0(v,b,i)&&AI(N,b);if(A.length>0||!v.complete||!I.complete||!N.complete)return Rm(A);let tt=XI(o,t,n,r);return tt||{complete:!0,site_id:t,base_snapshot_id:n,snapshot_digest:g,document_version:r,target:m.selection.target,selection_ref:y.selected_root_ref,entry:{file:y.entry_file,export:m.selection.entry_export},files:B.map(({path:G,content:me})=>({path:G,content:me})),source_closure:v,dependency_audit:I,cms:N,media:$,invocation_bindings:y.invocation_bindings,host_contract_digest:d.data.host_contract_digest,...N.dependencies.length===0?{route_dependencies:[...W.values()].sort((G,me)=>G.href.localeCompare(me.href))}:{},...Ge?{cms_sample_proof:{kind:"first-page-no-host-routes"}}:{}}}function XI(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return nn("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?nn("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?nn("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return nn("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function zI(e){let t=Cm("sha256");for(let[n,r]of[...e.entries()].sort(([o],[i])=>o.localeCompare(i))){let o=typeof r=="string"?Buffer.from(r,"utf8"):r;t.update(`${n.length}:${n}:${o.byteLength}:`),t.update(o)}return`sha256:${t.digest("hex")}`}function y0(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function Fl(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function b0(e,t,n){let r=e.nodes.filter(s=>Fl(s.path)),o=r[0]?.path.startsWith("src/")?"src/lib/cms/":"lib/cms/";if(!r.length||r.some(s=>!s.path.startsWith(o)))return!1;let i=new Map;for(let s of["index.ts","collections.ts","client.ts"]){let a=`${o}${s}`,c=n.get(a);if(!c||!r.some(l=>l.path===a&&l.status==="complete")||Dl(t.get(a))!==c)return!1;i.set(s,c)}return p0({index:i.get("index.ts"),collections:i.get("collections.ts"),client:i.get("client.ts")})}function Dl(e){return e===void 0?null:`sha256:${Cm("sha256").update(e).digest("hex")}`}function x0(e,t,n,r){if(!e||e.version!==1||e.site_id!==t||e.snapshot_id!==n||!Array.isArray(e.files)||e.files.length!==r.size)return!1;let o=new Set;for(let i of e.files){if(!i||typeof i.path!="string"||!i.path||i.path.startsWith("/")||i.path.includes("\\")||i.path.includes("\0")||i.path.split("/").some(a=>!a||a==="."||a==="..")||o.has(i.path)||!/^sha256:[a-f0-9]{64}$/u.test(i.hash)||!Number.isSafeInteger(i.size_bytes)||i.size_bytes<0)return!1;o.add(i.path);let s=r.get(i.path);if(s===void 0||Dl(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function nn(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function Rm(e){return e.length?e.length<=KI?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,KI-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:nn("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import Nm from"@babel/generator";import{parse as E0}from"@babel/parser";import S0 from"@babel/traverse";import*as bt from"@babel/types";var Pm=S0,v0=typeof Pm=="function"?Pm:Pm.default,I0=typeof Nm=="function"?Nm:Nm.default,qI="components/site/generated/{{$INSTANCE}}/",QI=new Set([".tsx",".ts",".jsx",".js"]),HI=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),k0=new Set(["data-site-block-order","data-vcp-order"]);function _0(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 x of e.source_files){let E=or(x.path);if(!E||n.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:x.path,message:"Portable source files must have unique safe paths."});continue}n.set(E,{...x,path:E})}for(let x of e.ownership){let E=or(x.path);if(!E||r.has(E)){t.push({code:"SOURCE_INPUT_INVALID",path:x.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(E,{...x,path:E})}let o=or(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 x of n.keys())r.has(x)||t.push({code:"SOURCE_OWNERSHIP_MISSING",path:x,message:"Every source closure file requires an ownership decision."});let s=[...n.keys()].filter(x=>r.get(x)?.ownership==="private").sort((x,E)=>x.localeCompare(E)),a=s.map(x=>({source_path:x,path_template:O0(x)})),c=new Map(a.map(x=>[x.source_path,x.path_template])),l=R0(e.source_mapping??[],c,t),u=C0(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let x of s){let E=n.get(x);if(!E)continue;let k=P0(x,E.content,r,c,d,f,t);k!==null&&g.push({path_template:c.get(x),content:k,...E.role?{role:E.role}:{}})}let p=YI(t).sort(ZI);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 m=g.map(x=>{let E=a.find(v=>v.path_template===x.path_template)?.source_path,k=n.get(E)?.content??"";return{source_path:E,path_template:x.path_template,original_byte_size:WI(k),output_byte_size:WI(x.content),original_line_count:GI(k),output_line_count:GI(x.content)}}),y=[...f.values()].map(x=>({...x,normalized:!0})).sort((x,E)=>x.source_path.localeCompare(E.source_path)),b=c.get(o)??null;if(e.thin_entry_plan){let x=N0(e.thin_entry_plan,c,t);x&&(g.push(x),b=x.path_template)}let S=YI(t).sort(ZI);return S.length>0?{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:S}:{complete:!0,entry_path_template:b,files:g.sort((x,E)=>x.path_template.localeCompare(E.path_template)),source_path_mappings:m.sort((x,E)=>x.path_template.localeCompare(E.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(B0),block_metadata:y,errors:[]}}function R0(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=or(s.generated_path),c=or(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 C0(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=or(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 N0(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(or(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=`${qI}__managed-root-entry.tsx`,i=ek(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}
41
+ `;return eu({entryFile:r,entryContent:c,files:n,selection:t,sourceMapping:{generated_path:t.source_file,source_file:t.source_file,structural_path:t.structural_path}})}return n.has(r)?Xt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):Xj(t,o,n)}function Xj(e,t,n){let r;try{r=$j(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(R){return Xt("SOURCE_PARSE_FAILED",e.source_file,R instanceof Error?R.message:String(R))}let o=zj(r,e);if(o.length!==1)return Xt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(R=>R.isFunction());if(!s||!ek(s.node))return Xt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=u0(a);if(!c.ok)return Xt("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=new Set;for(let R of r.program.body){if(!B.isImportDeclaration(R)||R.specifiers.length||R.importKind==="type")continue;let F=R.source.value,$=F.startsWith(".")||F.startsWith("@/")?ou(e.source_file,F,n):null;if(!$?.endsWith(".css"))return Xt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has($)||l.imports.add(R),u.add($)}let d=Hj(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(Wj(i,i.node,a,d.value,e,c.translationBinding??null,l,n),l.errors.length>0)return{complete:!1,errors:l.errors};if(c.translationBinding&&![...l.functionDeclarations].some(R=>B.isVariableDeclaration(R)&&R.declarations.some(F=>B.isIdentifier(F.id,{name:c.translationBinding}))))return Xt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let p=m0(r,"__vcpPortableProps"),g=B.cloneNode(i.node,!0),m=[];for(let R of[...l.imports].sort(Dm)){let F=c0(R,e.source_file,e.entry_file,n);if(!F.ok)return{complete:!1,errors:[F.error]};m.push(F.node)}let f=[...l.moduleDeclarations].sort(Dm).map(R=>B.cloneNode(R,!0)),y=[...l.functionDeclarations].sort(Dm).map(R=>B.cloneNode(R,!0)),x=B.returnStatement(g),E=[...l.props].filter(([R])=>!R.startsWith("@")).map(([R,F])=>B.variableDeclaration("const",[B.variableDeclarator(B.identifier(R),B.memberExpression(B.identifier(p),B.identifier(F)))]));l.propsObjectName&&E.push(B.variableDeclaration("const",[B.variableDeclarator(B.identifier(l.propsObjectName),B.identifier(p))]));let b=B.blockStatement([...E,...y,x]),S=l.props.size?[a0(p)]:[],I=B.functionDeclaration(B.identifier("PortableBlockEntry"),S,b),w=B.program([...m,...f,I,B.exportDefaultDeclaration(B.identifier("PortableBlockEntry"))]);w.directives=r.program.directives.map(R=>B.cloneNode(R,!0));let C=Jj(B.file(w),{jsescOption:{minimal:!0}}).code,N={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return eu({entryFile:e.entry_file,entryContent:C,files:n,selection:e,sourceMapping:N,invocationBindings:p0(e,l.props)})}function zj(e,t){let n=[];return $m(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function Hj(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:Ct("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(B.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!B.isObjectPattern(o))return{ok:!1,error:Ct("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!B.isObjectProperty(i)||i.computed||!(B.isIdentifier(i.key)||B.isStringLiteral(i.key))||!(B.isIdentifier(i.value)||B.isAssignmentPattern(i.value)&&B.isIdentifier(i.value.left)))return{ok:!1,error:Ct("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=B.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=B.isIdentifier(a)?a.name:B.isAssignmentPattern(a)&&B.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function Wj(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=m=>{let f=l.get(m);if(f!==void 0)return f;let y=Yj(n,r,m,o,a);return l.set(m,y),y||s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${m} is mutated or escapes its proven invocation value.`)),y},d=m=>{let f=m.node.name,y=m.scope.getBinding(f);if(!y){$v.has(f)||s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${f}.`));return}if(!nu(y.path.node,t)){if(r.bindingByLocalName.has(f)&&y.scope===n.scope){let x=r.bindingByLocalName.get(f);Vv(o,x)?u(x)&&s.props.set(f,x):s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,`The selected root prop ${x} has no proven invocation binding.`));return}if(r.propsParameter&&y.path.node===r.propsParameter&&m.parentPath?.isMemberExpression()&&m.parentPath.node.object===m.node){let x=m.parentPath.node,E=!x.computed&&B.isIdentifier(x.property)?x.property.name:x.computed&&B.isStringLiteral(x.property)?x.property.value:null;E&&Vv(o,E)?u(E)&&(s.propsObjectName=f,s.props.set(`@${f}.${E}`,E)):s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${f}.`));return}c.has(y)||(c.add(y),Uv(y,n,o,s,d,p,a))}},p=(m,f)=>{let y=Qv(m);if(!y||/^[a-z]/u.test(y.name))return;let x=f.scope.getBinding(y.name);if(!x){$v.has(y.name)||s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||nu(x.path.node,t)||(c.add(x),Uv(x,n,o,s,d,p,a))};(m=>{m.isIdentifier()&&m.isReferencedIdentifier()&&d(m),m.isJSXElement()&&p(m.node.openingElement.name,m),m.traverse({ReferencedIdentifier(f){d(f)},JSXOpeningElement(f){p(f.node.name,f)},CallExpression(f){qv(f,i)||s.errors.push(Ct("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(Ct("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),f.stop()},UpdateExpression(f){s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),f.stop()},NewExpression(f){s.errors.push(Ct("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),f.stop()}})})(e)}function Uv(e,t,n,r,o,i,s){let a=e.path;if(f0(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`The selected root captures unsupported component-local binding ${e.identifier.name}.`));return}if(e.constantViolations.length>0){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(e0(e)){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new tu(s),l=new Map,u=a.parentPath,d=u?.isImportDeclaration(),p=!1;if(d&&(u.node.source.value.startsWith(".")||u.node.source.value.startsWith("@/"))){let y=ou(n.source_file,u.node.source.value,s),x=y?c.get(y):void 0,E=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?yn(a.node.imported,!1):null,b=x&&E&&u.node.importKind!=="type"?Kn(x,E,c):null,S=b?hn(b):null;if(!S?.length){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,S),p=S.every(I=>I.isFunctionDeclaration()||I.isFunctionExpression()||I.isArrowFunctionExpression())}else d&&(p=e.referencePaths.every(y=>y.parentPath?.isJSXOpeningElement()||y.parentPath?.isJSXClosingElement()||y.parentPath?.isCallExpression()&&y.parentPath.node.callee===y.node));if((d&&!p||Gj(e))&&!la(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is mutated or escapes its static object shape.`));return}let g=a.isImportDeclaration()?a:a.findParent(y=>y.isImportDeclaration());if(g?.isImportDeclaration()){r.imports.add(g.node);return}let m=a.isVariableDeclarator()?a:a.findParent(y=>y.isVariableDeclarator());if(m?.isVariableDeclarator()){let y=m.parentPath,x=m.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!x.node||!Nr(m.node.id)||!Nr(x.node)&&!d0(x)){r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let b=y.findParent(I=>I.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=B.variableDeclaration("const",[B.cloneNode(m.node,!0)]);Jv(b,S,m.node),m.traverse({ReferencedIdentifier(I){I.isIdentifier()&&o(I)},JSXOpeningElement(I){i(I.node.name,I)}});return}let f=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(f?.isFunctionDeclaration()&&Dc(f.node)){let x=f.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;Jv(x,B.cloneNode(f.node,!0),f.node),f.traverse({ReferencedIdentifier(E){E.isIdentifier()&&o(E)},JSXOpeningElement(E){i(E.node.name,E)}});return}r.errors.push(Ct("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function Gj(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=s0(n.node);return B.isFunctionExpression(r)||B.isArrowFunctionExpression(r)||B.isCallExpression(r)&&Mc(r)?!1:!Mf(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Bf(i,new Map))}var tu=class extends Map{constructor(t){super(),this.files=t,this.attempted=new Set}has(t){return this.files.has(t)}get(t){let n=super.get(t);if(n||this.attempted.has(t)||this.attempted.size>=64)return n;this.attempted.add(t);let r=ru(this.files,t);if(r===null)return;let o=Fe(t,r);if(o.ok)return super.set(t,o.module),o.module}};function Yj(e,t,n,r,o){let i=r.invocation?.bindings.find(l=>l.propName===n);if(!i)return!1;let s=[];if(i.value.kind==="json-literal"){let l=B.file(B.program([B.expressionStatement(B.valueToNode(i.value.value))]));$m(l,{ExpressionStatement(u){s.push(u.get("expression")),u.stop()}})}let a=new Map,c={bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:a,files:o,modules:new tu(o)};if(t.propsParameter)return Mm(e,n,s,c);for(let[l,u]of t.bindingByLocalName){if(u!==n)continue;let d=e.scope.getBinding(l);if(!d||(a.set(d.identifier,s),!la(d,c,!0)))return!1}return!0}function Zj(e,t){if(Bf(e,t.inputs))return!0;let n=e.parentPath;if(!n)return!1;let r=n.isJSXExpressionContainer()?n.parentPath:n;if(!r)return!1;let o=r.isJSXAttribute()||r.isJSXSpreadAttribute()?r.parentPath:r.isJSXElement()?r.get("openingElement"):null;if(r.isJSXFragment())return!0;if(!o?.isJSXOpeningElement())return!1;let i=o.node.name;if(B.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!B.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=qj(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=hn(e,t.inputs);if(!c)return!1;if(r.isJSXSpreadAttribute()){let u=new Set;for(let d of c){if(!d.isObjectExpression())return!1;for(let p of d.node.properties){if(!B.isObjectProperty(p)||p.computed)return!1;let g=yn(p.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let p=Bc(c,d,t.inputs);return p!==null&&Mm(s,d,p,a)})}let l=r.isJSXAttribute()&&B.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return Mm(s,l,c,a)}function qj(e,t){let n=e.node.name;if(!B.isJSXIdentifier(n))return null;let r=e.scope.getBinding(n.name);if(!r||r.constantViolations.length)return null;if(r.path.isFunctionDeclaration())return r.path;if(r.path.isVariableDeclarator()){let d=r.path.get("init");return d.isFunctionExpression()||d.isArrowFunctionExpression()?d:null}let o=r.path.parentPath;if(!o?.isImportDeclaration())return null;let i=o.node.source.value,s=o.node.loc?.filename;if(!s||!(i.startsWith(".")||i.startsWith("@/")))return null;let a=ou(s,i,t.files);if(!a)return null;let c=t.modules.get(a);if(!c)return null;let l=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()?yn(r.path.node.imported,!1):null;if(!l)return null;let u=Yt({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function Mm(e,t,n,r){let o=e.get("params")[0];if(!o)return!0;let i=new Map(r.inputs);if(o.isObjectPattern()){let a=!0;for(let c of o.get("properties")){if(!c.isObjectProperty()||c.node.computed){if(Object.keys(c.getBindingIdentifiers()).some(p=>c.scope.getBinding(p)?.referencePaths.length))return!1;continue}if(yn(c.node.key,!1)!==t)continue;let l=c.get("value");if(!l.isIdentifier())return!1;let u=l.scope.getBinding(l.node.name);if(!u)return!1;i.set(u.identifier,n),a=la(u,{...r,inputs:i},!0)&&a}return a}if(!o.isIdentifier())return!1;let s=o.scope.getBinding(o.node.name);return!s||s.constantViolations.length?!1:s.referencePaths.every(a=>{let c=a.parentPath;if(!(c?.isMemberExpression()||c?.isOptionalMemberExpression())||c.node.object!==a.node)return!1;let l=yn(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),Gv(c,{...r,inputs:i},!0))})}function la(e,t,n){if(t.bindings.has(e))return!0;if(t.activeBindings.has(e)||t.bindings.size+t.activeBindings.size>=128||e.constantViolations.length>0)return!1;let r={...t,activeBindings:new Set(t.activeBindings).add(e)},o=e.referencePaths.every(i=>Gv(i,r,n));return o&&t.bindings.add(e),o}function Vm(e,t,n){let r=e.node.id;if(B.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?la(o,t,n):!1}if(B.isObjectPattern(r)||B.isArrayPattern(r)){let o=[];return ji(r,o)?Qj(o,e,t):!1}return!1}function ji(e,t){if(B.isRestElement(e))return ji(e.argument,t);if(B.isIdentifier(e))return t.push(e.name),!0;if(B.isAssignmentPattern(e))return ji(e.left,t);if(B.isObjectPattern(e)){for(let n of e.properties){if(B.isRestElement(n)){if(!ji(n.argument,t))return!1;continue}if(!B.isObjectProperty(n)||n.computed||!(B.isIdentifier(n.key)||B.isStringLiteral(n.key)||B.isNumericLiteral(n.key))||!ji(n.value,t))return!1}return!0}if(B.isArrayPattern(e)){for(let n of e.elements)if(n&&!ji(n,t))return!1;return!0}return!1}function Qj(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?la(o,n,!0):!1})}function e0(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=Wv(t);if(!r)return!1;let o=n.parentPath;return!!(Hv(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function Hv(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?nu(e.node,t.node.left):!1}function Wv(e){let t=Bm(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=Bm(t.parentPath);return{current:t,memberAccess:n}}function Gv(e,t,n){if(!r0(e,t))return!1;let{current:r,memberAccess:o}=Wv(e),i=r.parentPath;if(!i)return!1;if(i.isVariableDeclarator()&&i.node.init===r.node){let s=i.parentPath;return!s?.isVariableDeclaration()||s.node.kind!=="const"?!1:Vm(i,t,o||n)}return Hv(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:t0(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?Zj(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?n0(r,o,n,t):i.isJSXAttribute()||i.isJSXSpreadAttribute()||i.isObjectMethod()||i.isReturnStatement()||i.isArrowFunctionExpression()?o||n:i.isTemplateLiteral()&&i.parentPath?.isTaggedTemplateExpression()?!1:(o||n)&&(i.isBinaryExpression()||i.isUnaryExpression()||i.isTemplateLiteral())}function t0(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(B.isIdentifier(r)){if(zv.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!gi(i)?!1:ca(e,n,new Set)}if(!B.isMemberExpression(r)&&!B.isOptionalMemberExpression(r)||!B.isIdentifier(r.property))return!1;let o=Jm(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:ca(e,n,new Set):Xv.get(o.name)?.has(r.property.name)??!1?Zv(e)?ca(e,n,new Set):!0:!1}function n0(e,t,n,r){let o=Yv(e);return o.kind==="declarator"?Vm(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function Yv(e){let t=Bm(e),n=!0,r=!1;for(;;){let o=t.parentPath;if(!o)return r?{kind:"escape"}:{kind:"read"};if(o.isTSAsExpression()||o.isTSTypeAssertion()||o.isTSNonNullExpression()||o.isTSSatisfiesExpression()||o.isParenthesizedExpression()){t=o;continue}if((o.isMemberExpression()||o.isOptionalMemberExpression())&&o.node.object===t.node){t=o;continue}if(o.isConditionalExpression()){if(o.node.test===t.node)return{kind:"read"};t=o;continue}if(o.isLogicalExpression()||o.isAwaitExpression()){t=o;continue}if(o.isSequenceExpression()){let i=o.node.expressions;if(i[i.length-1]!==t.node)return{kind:"read"};t=o;continue}if(o.isVariableDeclarator()&&o.node.init===t.node)return{kind:"declarator",declarator:o,directValue:n};if(o.isObjectProperty()&&o.node.value===t.node){r=!0,n=!1,t=o;continue}if(o.isObjectExpression()||o.isArrayExpression()){r=!0,n=!1,t=o;continue}if(o.isSpreadElement()){r=!0,n=!1,t=o;continue}return o.isCallExpression()||o.isOptionalCallExpression()?o.node.callee===t.node?{kind:"escape"}:{kind:"call",call:o}:o.isNewExpression()?{kind:"escape"}:o.isJSXExpressionContainer()||o.isJSXAttribute()||o.isJSXSpreadAttribute()||o.isReturnStatement()||o.isArrowFunctionExpression()?r?{kind:"escape"}:{kind:"read"}:r?{kind:"escape"}:{kind:"read"}}}function ca(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=Yv(e);return r.kind==="declarator"?Vm(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:Zv(r.call)?ca(r.call,t,n):i0(r.call):!0}function r0(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!ek(n.node))return!0;let r=o0(n);return!r||!gi(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:ca(i,t,new Set)})}function o0(e){let t=e.node,n=null;if(B.isFunctionDeclaration(t)?n=t.id?.name??null:(B.isArrowFunctionExpression(t)||B.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&B.isIdentifier(e.parentPath.node.id)&&(n=e.parentPath.node.id.name),!n)return null;let r=[e.scope.getBinding(n),e.scope.parent?.getBinding(n),e.parentPath?.scope.getBinding(n)];for(let o of r)if(o&&(o.path.node===t||o.path.node===e.parentPath?.node))return o;return null}function Zv(e){let t=e.node.callee;if(B.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&gi(r))}if(!B.isMemberExpression(t)&&!B.isOptionalMemberExpression(t)||!B.isIdentifier(t.property))return!1;let n=Jm(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&Kj.has(t.property.name)}function i0(e){let t=e.node.callee;if(B.isIdentifier(t))return zv.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!B.isMemberExpression(t)&&!B.isOptionalMemberExpression(t)||!B.isIdentifier(t.property))return!1;let n=Jm(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:Xv.get(n.name)?.has(t.property.name)??!1}function Bm(e){let t=e;for(;t.parentPath&&(t.parentPath.isTSAsExpression()||t.parentPath.isTSTypeAssertion()||t.parentPath.isTSNonNullExpression()||t.parentPath.isTSSatisfiesExpression()||t.parentPath.isParenthesizedExpression());)t=t.parentPath;return t}function s0(e){let t=e;for(;t&&(B.isTSAsExpression(t)||B.isTSTypeAssertion(t)||B.isTSNonNullExpression(t)||B.isTSSatisfiesExpression(t)||B.isParenthesizedExpression(t));)t=t.expression;return t&&B.isExpression(t)?t:null}function Jm(e){return!e.computed&&B.isIdentifier(e.object)?e.object:null}function a0(e){let t=B.identifier(e);return t.typeAnnotation=B.tsTypeAnnotation(B.tsTypeReference(B.identifier("Record"),B.tsTypeParameterInstantiation([B.tsStringKeyword(),B.tsAnyKeyword()]))),t}function eu(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=uo({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>Ct(g0(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=ru(t,i.path);if(s===null)return Xt("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 c0(e,t,n,r){let o=B.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=ou(t,i,r);if(!s)return{ok:!1,error:Ct("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=l0(n,s)}return{ok:!0,node:o}}function ou(e,t,n){let r=t.startsWith("@/")?t.slice(2):aa.posix.normalize(aa.posix.join(aa.posix.dirname(e),t));if(!jm(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 l0(e,t){let n=aa.posix.relative(aa.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function u0(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!B.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!B.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"||!B.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!B.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 qv(e,t){let n=e.node.callee;if(B.isImport(n))return!1;if(t&&B.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>B.isStringLiteral(o))){let o=e.scope.getBinding(t);if(o&&o.constantViolations.length>0)return!1;let i=o?.path.isVariableDeclarator()?o.path:o?.path.findParent(a=>a.isVariableDeclarator()),s=i?.isVariableDeclarator()?i.node.init:null;return!!(B.isCallExpression(s)&&Mc(s))}if(!B.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?gi(r):!1}function d0(e){return e.isCallExpression()&&qv(e,null)&&B.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>B.isExpression(t)&&Nr(t))}function Qv(e){return B.isJSXIdentifier(e)?B.isValidIdentifier(e.name)?B.identifier(e.name):null:B.isJSXMemberExpression(e)?Qv(e.object):null}function f0(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>B.isObjectPattern(n)&&n.properties.some(r=>B.isObjectProperty(r)&&B.isIdentifier(r.value,{name:e.node.name}))))}function nu(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 ek(e){return B.isFunction(e)}function Vv(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function p0(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function m0(e,t){let n=new Set;$m(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function Jv(e,t,n){if(typeof n.start=="number"){if([...e].some(r=>r.start===n.start))return;t.start=n.start}e.add(t)}function Dm(e,t){return(e.start??0)-(t.start??0)}function ru(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 Kv(e,t){let n=jj("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function jm(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function g0(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 Xt(e,t,n){return{complete:!1,errors:[Ct(e,t,n)]}}function Ct(e,t,n){return{code:e,path:t,message:n}}import{createHash as sk}from"node:crypto";import Hm from"@babel/generator";import Wm from"@babel/traverse";import*as Ze from"@babel/types";function Tt(e){try{let t=typeof e=="string"?e:e instanceof Uint8Array?new TextDecoder("utf-8",{fatal:!0}).decode(e):null;return t!==null&&!t.includes("\0")?t:null}catch{return null}}import*as ok from"@babel/types";import{createHash as Km}from"node:crypto";var h0="sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f",y0="sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5",x0=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]),b0=new Set(["sha256:64f26e7284e844de65cfeaf268974aeb4a612ae796638fe219587f1d3e46b429"]),E0=new Map([["sha256:3b952ddc14778008dac157346c997cdea06844d890f1e5280ea08d38fbf03776","sha256:061e4143d12a22f4256157df2824144ac8fb86744f456afa50ff963278ddb263"],["sha256:92f7425b0f1eb031ef47470adb2b777fe863234c268504287323ff06cd4f91cc","sha256:4b5aa33d4bbf4e895e0186ee7049a7f9606b5d85ee6e045b8eed084cee458646"]]);function tk(e,t,n){if(!/^(?:src\/)?lib\/cms\/jsonld\.tsx$/u.test(n))return!1;let r=i=>{let s=e.get(i),a=s===void 0?"":`sha256:${Km("sha256").update(s).digest("hex")}`;return a&&t.get(i)===a?a:""},o=r(n);return!!o&&E0.get(o)===r(n.replace("jsonld.tsx","metadata-fields.ts"))}function iu(e){return e.index===h0&&e.client===y0&&x0.has(e.collections)}function fo(e,t){let n=e.has("lib/cms/index.ts")?"lib/cms/":"src/lib/cms/",r=o=>{let i=e.get(`${n}${o}.ts`),s=i===void 0?"":`sha256:${Km("sha256").update(i).digest("hex")}`;return t.get(`${n}${o}.ts`)===s?s:""};return iu({index:r("index"),collections:r("collections"),client:r("client")})&&b0.has(r("field"))}function nk(e,t){let n=e.has("lib/cms/index.ts")?"lib/cms/build-sample.ts":"src/lib/cms/build-sample.ts",r=e.get(n);if(r===void 0)return!1;let o=`sha256:${Km("sha256").update(r).digest("hex")}`;return o==="sha256:6e1c0d0af2938dc4e74d4a35b185bec0ad1fd6d16fd2323ee0cd72eaa05c836f"&&t.get(n)===o&&fo(e,t)}import*as un from"@babel/types";var Qe={kind:"primitive"},yr={kind:"json"},Xm=new Set(["__proto__","prototype","constructor","then","toString","valueOf","toLocaleString"]),po=e=>({kind:"object",properties:new Map(Object.entries(e))}),xr=e=>({kind:"array",item:e});function au(e){let t=new Map;for(let n of e.split("/")){let r=/^\[(\[)?(\.\.\.)?([^\[\]/]+)\]\]?$/u.exec(n);r&&t.set(r[3],r[2]?xr(Qe):Qe)}return{kind:"object",properties:t}}function yt(e){return!!e&&e.kind!=="promise"&&e.kind!=="jsx"}function cu(e,t){let n=po({id:Qe,url:Qe,seo:yr,fields:t?{kind:"json",origin:{slug:t,field_path:""}}:yr}),r=["list","listStrict"].includes(e)?po({items:xr(n),total:Qe,page:Qe,pageSize:Qe}):["get","getStrict","getByUrl","getByUrlStrict"].includes(e)?n:e==="categories"?xr(po({id:Qe,label:Qe,children:yr})):e==="schema"?yr:null;return r?{kind:"promise",value:e.endsWith("Strict")?po({kind:Qe,data:r,error:yr}):r}:null}function zm(e){if(["text","selected","num","bool","url","phone"].includes(e))return Qe;if(e==="richtext")return po({__html:Qe});if(["image","images"].includes(e)){let t=po({url:Qe,name:Qe});return e==="images"?xr(t):t}return e==="category"?xr(po({id:Qe,label:Qe})):e==="list"?xr(Qe):e==="dateRange"?po({start:Qe,end:Qe}):null}function rk(e,t,n=new Map){let r=new Map(n),o=(i,s)=>{if(s)if(i.isIdentifier()){let a=i.scope.getBinding(i.node.name);a?.constant&&r.set(a.identifier,s)}else if(i.isObjectPattern()&&s.kind==="object")for(let a of i.get("properties")){if(!a.isObjectProperty()||a.node.computed)continue;let c=a.node.key,l=un.isIdentifier(c)?c.name:un.isStringLiteral(c)?c.value:null;l&&!Xm.has(l)&&o(a.get("value"),s.properties.get(l)??null)}else i.isAssignmentPattern()&&o(i.get("left"),s)};return e.get("params").forEach((i,s)=>o(i,t[s]??null)),r}function lu(e){let t=(o,i,s,a)=>{if(a.has(o.node)||a.size>=48)return null;let c=new Set(a).add(o.node),l=rk(o,i,s),u=o.get("body"),d=[];u.isBlockStatement()?u.traverse({Function(g){g.skip()},ReturnStatement(g){d.push(g.node.argument?n(g.get("argument"),l,c):Qe)}}):d.push(n(u,l,c));let p=ua(d);return p&&o.node.async?{kind:"promise",value:p}:p},n=(o,i=new Map,s=new Set)=>{if(!o.node||s.has(o.node)||s.size>=48)return null;let a=new Set(s).add(o.node),c=g=>n(g,i,a);if(o.isStringLiteral()||o.isNumericLiteral()||o.isBooleanLiteral()||o.isNullLiteral())return Qe;if(o.isJSXElement()||o.isJSXFragment())return{kind:"jsx"};if(o.isJSXExpressionContainer()||o.isTSAsExpression()||o.isTSSatisfiesExpression()||o.isTSNonNullExpression()||o.isParenthesizedExpression())return c(o.get("expression"));if(o.isIdentifier()){let g=o.scope.getBinding(o.node.name);if(!g)return["undefined","NaN","Infinity"].includes(o.node.name)?Qe:null;if(!g.constant||g.constantViolations.length)return null;let m=i.get(g.identifier);if(m)return m;let f=e.resolve_value?.(o);return f?c(f):g.path.isVariableDeclarator()&&g.path.parentPath.isVariableDeclaration({kind:"const"})?c(g.path.get("init")):null}if(o.isAwaitExpression()){let g=c(o.get("argument"));return g?.kind==="promise"?g.value:yt(g)?g:null}if(o.isObjectExpression()){let g=new Map;for(let m of o.get("properties")){if(!m.isObjectProperty()||m.node.computed)return null;let f=m.node.key,y=un.isIdentifier(f)?f.name:un.isStringLiteral(f)?f.value:null,x=n(m.get("value"),i,a);if(!y||Xm.has(y)||g.has(y)||!yt(x))return null;g.set(y,x)}return{kind:"object",properties:g}}if(o.isArrayExpression()){if(!o.node.elements.length)return{kind:"array",item:yr,empty:!0};let g=ua(o.get("elements").map(m=>c(m)));return yt(g)?xr(g):null}if(o.isMemberExpression()||o.isOptionalMemberExpression()){let g=S0(o);if(!g||Xm.has(g))return null;let m=c(o.get("object"));return m?.kind==="object"?su(m.properties.get(g)??null,m.origin):m?.kind==="json"?m.origin?{kind:"json",origin:{slug:m.origin.slug,field_path:m.origin.field_path||g}}:yr:m?.kind==="array"?g==="length"?Qe:/^\d+$/u.test(g)?su(m.item,m.origin):null:m?.kind==="primitive"&&g==="length"?Qe:null}if(o.isConditionalExpression())return ua([c(o.get("consequent")),c(o.get("alternate"))]);if(o.isLogicalExpression())return ua([c(o.get("left")),c(o.get("right"))]);if(o.isUnaryExpression())return["typeof","!","void"].includes(o.node.operator)||yt(c(o.get("argument")))?Qe:null;if(o.isBinaryExpression())return["in","instanceof"].includes(o.node.operator)?null:["===","!=="].includes(o.node.operator)||yt(c(o.get("left")))&&yt(c(o.get("right")))?Qe:null;if(o.isTemplateLiteral())return o.get("expressions").every(g=>yt(c(g)))?Qe:null;if(!o.isCallExpression())return null;let l=e.cms_value(o,i,a);if(l)return l;let u=o.get("callee");if(u.isIdentifier()&&!u.scope.getBinding(u.node.name)&&["String","Number","Boolean","encodeURIComponent","decodeURIComponent"].includes(u.node.name))return o.get("arguments").every(g=>yt(c(g)))?Qe:null;let d=r(o,i,a);if(d)return d.result;if(u.isMemberExpression()&&!u.node.computed){if(un.isIdentifier(u.node.object,{name:"Object"})&&!u.scope.getBinding("Object")&&un.isIdentifier(u.node.property,{name:"keys"})&&o.node.arguments.length===1&&yt(c(o.get("arguments")[0])))return xr(Qe);let g=c(u.get("object")),m=un.isIdentifier(u.node.property)?u.node.property.name:"";if(g?.kind==="array"&&m==="slice"&&o.node.arguments.length<=2&&o.get("arguments").every(f=>c(f)?.kind==="primitive"))return g;if(g?.kind==="primitive"&&["includes","startsWith","endsWith","trim","toLowerCase","toUpperCase","replace","split"].includes(m)&&o.get("arguments").every(f=>yt(c(f))))return m==="split"?xr(Qe):Qe}let p=e.resolve_function(u);return p?t(p,o.get("arguments").map(g=>c(g)),i,a):null};function r(o,i,s=new Set){let a=o.get("callee");if(!a.isMemberExpression()||a.node.computed||!un.isIdentifier(a.node.property))return null;let c=a.node.property.name;if(!["map","filter","some","every","find"].includes(c)||o.node.arguments.length!==1)return null;let l=n(a.get("object"),i,s);if(l?.kind!=="array")return null;let u=o.get("arguments")[0],d=u.isFunctionExpression()||u.isArrowFunctionExpression()?u:e.resolve_function(u);if(!d||d.node.async||d.node.generator)return null;let p=[su(l.item,l.origin),Qe,l];if(l.empty)return{target:d,args:p,result:["map","filter"].includes(c)?l:Qe,empty:!0};let g=t(d,p,i,s);return g?{target:d,args:p,result:c==="map"?xr(g):c==="filter"?l:c==="find"?l.item:Qe}:null}return{value:n,arrayCall:r,bind:rk}}function S0(e){let t=e.node.property;return!e.node.computed&&un.isIdentifier(t)?t.name:un.isStringLiteral(t)?t.value:un.isNumericLiteral(t)?String(t.value):null}function ua(e){if(!e.length||e.some(n=>!n))return null;let t=e[0];if(e.length===1)return t;if(e.every(n=>n?.kind==="array")){let n=e.filter(r=>r?.kind==="array"&&!r.empty);return n.length?{kind:"array",item:ua(n.map(r=>r?.kind==="array"?r.item:null))??yr}:{kind:"array",item:yr,empty:!0}}return e.every(n=>n?.kind==="primitive")?e.every(n=>JSON.stringify(n?.origin)===JSON.stringify(t.origin))?su(Qe,t.origin):Qe:e.every(n=>n?.kind==="jsx")?t:e.every(yt)?yr:null}function su(e,t){return e&&t?{...e,origin:e.origin??t}:e}function ik(e){if(!fo(e.files,e.trusted_host_file_hashes))return()=>!1;let t=new Map([[e.module.ast.program,e.module]]);class n extends Map{has(d){return e.files.has(d)}get(d){let p=super.get(d);if(p)return p;let g=Tt(e.files.get(d)),m=g===null?null:Fe(d,g);if(m?.ok)return super.set(d,m.module),t.set(m.module.ast.program,m.module),m.module}}let r=new n([[e.module.file,e.module]]),o=u=>{let d=u.findParent(p=>p.isProgram());return d?.isProgram()?t.get(d.node):void 0},i=u=>{let d=u.scope.getBinding(u.node.name),p=d?.path.parentPath,g=o(u);if(!g||!d?.constant||!d.path.isImportSpecifier()||d.path.node.importKind==="type"||!p?.isImportDeclaration()||p.node.importKind==="type")return null;let m=Kt(g.file,p.node.source.value,e.files);if(!m)return null;let f=d.path.node.imported;return{module:g,file:m,name:ok.isIdentifier(f)?f.name:f.value,local:d.identifier.name}},s=u=>{let d=i(u),p=d?r.get(d.file):void 0;return p&&d?Kn(p,d.name,r):null},a=u=>{let d=u.get("callee");if(!d.isIdentifier())return!1;let p=i(d);if(!p||!["pickJsonLd","pickCustomMeta"].includes(p.name))return!1;let g=s(d),m=g&&o(g);return!!(g?.isFunctionDeclaration()&&g.node.id?.name===p.name&&m&&tk(e.files,e.trusted_host_file_hashes,m.file))},c=lu({resolve_function(u){if(!u.isIdentifier())return null;let d=u.scope.getBinding(u.node.name);if(!d?.constant)return null;let p=s(u)??(d.path.isVariableDeclarator()?d.path.get("init"):d.path);return p.isFunctionDeclaration()||p.isFunctionExpression()||p.isArrowFunctionExpression()?p:null},resolve_value:s,cms_value(u,d,p){if(a(u))return u.get("arguments").every(y=>yt(c.value(y,d,p)))?{kind:"json"}:null;let g=u.get("callee");for(;g.isMemberExpression()&&!g.node.computed;)g=g.get("object");if(!g.isIdentifier())return null;let m=i(g);if(!m||m.name!=="cms"||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(m.file)||In(m.module.ast,m.local))return null;let f=dr(u.node,{file:m.module.file,imports:new Map([[m.local,{source:m.file,importedName:m.name}]])})?.operation;return f?cu(f):null}}),l=c.bind(e.owner,[{kind:"object",properties:new Map([["params",{kind:"promise",value:au(e.route_id)}],["searchParams",{kind:"promise",value:{kind:"json"}}]])}]);return u=>{if(!u.node||!yt(c.value(u,l)))return!1;let d=!0,p=g=>{if(!d){g.skip();return}if(g.isCallExpression()){let m=g.get("callee"),f=m.isIdentifier()&&!m.scope.getBinding(m.node.name)&&["String","Number","Boolean","encodeURIComponent","decodeURIComponent"].includes(m.node.name);(!(a(g)||f)||!yt(c.value(g,l)))&&(d=!1)}else g.isMemberExpression()||g.isOptionalMemberExpression()?yt(c.value(g,l))||(d=!1):!Nr(g.node)&&!g.isObjectExpression()&&!g.isObjectProperty()&&!g.isArrayExpression()&&!g.isLogicalExpression()&&!g.isConditionalExpression()&&!g.isBinaryExpression()&&!g.isTSAsExpression()&&!g.isTSSatisfiesExpression()&&!g.isParenthesizedExpression()&&(d=!1)};return p(u),u.traverse({enter:p}),d}}var I0=typeof Wm=="function"?Wm:Wm.default,v0=typeof Hm=="function"?Hm:Hm.default;function ak(e){let{binding:t,files:n}=e,r=t.root.callChain;if(r.length!==1||(r[0].alternativeLocators?.length??0)>1||r[0].sourceFile!==t.ownerFile)return{complete:!1};let o=r[0],i=Tt(n.get(o.sourceFile));if(i===null||`sha256:${sk("sha256").update(i).digest("hex")}`!==t.ownerSourceHash)return{complete:!1};let s=Fe(o.sourceFile,i);if(!s.ok)return{complete:!1};let a=null;I0(s.module.ast,{JSXElement(Y){let he=o.callLocator.sourceRange;Y.node.loc?.start.line===he.startLine&&Y.node.loc.start.column===he.startColumn&&Y.node.loc.end.line===he.endLine&&Y.node.loc.end.column===he.endColumn&&(a=Y)}});let c=a,l=c?.getFunctionParent();if(!c||!l?.isFunctionDeclaration()||!l.parentPath.isExportDefaultDeclaration()||!l.get("body").isBlockStatement())return{complete:!1};let u=c.findParent(Y=>Y.isReturnStatement());if(!u?.isReturnStatement()||u.parentPath!==l.get("body"))return{complete:!1};let d=new Set,p=new Map,g=new Set,m=new Set,f=new Set,y=!1,x=Y=>{if(!Y||d.has(Y))return;if(d.add(Y),!Y.constant||Y.constantViolations.length){y=!0;return}let he=Y.path;if(he.isImportSpecifier()||he.isImportDefaultSpecifier()||he.isImportNamespaceSpecifier()){let Me=he.parentPath;if(!Me.isImportDeclaration()){y=!0;return}let Ye=p.get(Me.node)??new Set;Ye.add(he.node),p.set(Me.node,Ye);return}if(Y.kind==="param"){let Me=l.node.params[0];if(!Ze.isObjectPattern(Me)){y=!0;return}let Ye=Me.properties.filter(D=>Ze.isObjectProperty(D)&&!D.computed&&Ze.isIdentifier(D.value,{name:Y.identifier.name})),pt=Ye[0];if(Ye.length!==1||!Ze.isObjectProperty(pt)){y=!0;return}let O=Ze.isIdentifier(pt.key)?pt.key.name:Ze.isStringLiteral(pt.key)?pt.key.value:"";if(!["params","searchParams"].includes(O)){y=!0;return}f.add(O);return}let le=he.getStatementParent();if(!le||le.node===l.node){y=!0;return}if(he.isVariableDeclarator()){if(!le.isVariableDeclaration({kind:"const"})||le.node.declarations.length!==1){y=!0;return}}else if(!he.isFunctionDeclaration()&&!he.isTSTypeAliasDeclaration()&&!he.isTSInterfaceDeclaration()){y=!0;return}if(le.parentPath===l.get("body"))m.add(le.node);else if(le.parentPath.isProgram())g.add(le.node);else if(le.parentPath.isExportNamedDeclaration()&&le.parentPath.parentPath.isProgram())g.add(le.node);else{y=!0;return}E(le)},E=Y=>{let he=le=>x(le.scope.getBinding(le.node.name));Y.isReferencedIdentifier()&&he(Y),Y.traverse({ReferencedIdentifier(le){he(le)},JSXOpeningElement(le){Ze.isJSXIdentifier(le.node.name)&&!/^[a-z]/u.test(le.node.name.name)&&x(le.scope.getBinding(le.node.name.name))}})};E(c);let b=l.get("body").get("body").filter(Y=>(Y.node.start??1/0)<(u.node.start??-1)),S=ik({module:s.module,owner:l,files:n,trusted_host_file_hashes:e.trusted_host_file_hashes,route_id:e.target.composition.routeId}),I=new Set,w=(Y,he)=>{let le=he.path.parentPath;if(!he.path.isImportSpecifier()||!Ze.isIdentifier(he.path.node.imported,{name:"cms"})||!le?.isImportDeclaration())return!1;let Me=Kt(o.sourceFile,le.node.source.value,n);if(!Me||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(Me))return!1;let Ye=Y;for(;Ye.parentPath?.isMemberExpression()&&Ye.parentPath.node.object===Ye.node&&!Ye.parentPath.node.computed;)Ye=Ye.parentPath;let pt=Ye.parentPath;return!!(pt?.isCallExpression()&&pt.node.callee===Ye.node&&dr(pt.node,{file:o.sourceFile,imports:new Map([[he.identifier.name,{source:Me,importedName:"cms"}]])}))},C=!0;for(;C&&!y;){C=!1;for(let Y of b){if(m.has(Y.node))continue;let he=!1;if(Y.traverse({ReferencedIdentifier(Me){let Ye=Me.scope.getBinding(Me.node.name);Ye&&(d.has(Ye)||I.has(Ye))&&!w(Me,Ye)&&(he=!0)}}),!he)continue;if(Y.isVariableDeclaration({kind:"const"})&&Y.node.declarations.length===1){let Me=Y.get("declarations")[0];if(Me.get("id").isIdentifier()&&S(Me.get("init"))){let Ye=Me.node.id.name,pt=Y.scope.getBinding(Ye);pt&&!I.has(pt)&&(I.add(pt),C=!0);continue}}let le=!1;if(Y.traverse({Function(Me){Me.skip()},ReturnStatement(Me){Me.node.argument&&(le=!0)}}),le){y=!0;break}m.add(Y.node),E(Y);for(let Me of Object.keys(Ze.getBindingIdentifiers(Y.node)))x(Y.scope.getBinding(Me));C=!0}}if(y||!d.size)return{complete:!1};let N=sk("sha256").update(JSON.stringify([t.sourceHash,t.ownerSourceHash,o.callLocator.sourceRange])).digest("hex"),R=`components/site/portable/${N.slice(0,24)}/page.tsx`;if(n.has(R))return{complete:!1};let F=[];for(let[Y,he]of p){let le=Ze.cloneNode(Y,!0);if(le.specifiers=Y.specifiers.filter(Me=>he.has(Me)||Ze.isImportSpecifier(Me)&&Me.importKind==="type").map(Me=>Ze.cloneNode(Me,!0)),le.source.value.startsWith(".")){let Me=Kt(o.sourceFile,le.source.value,n);if(!Me)return{complete:!1};le.source=Ze.stringLiteral(`@/${Me.replace(/\.[cm]?[jt]sx?$/u,"")}`)}F.push(le)}let $=Ze.functionDeclaration(Ze.identifier(`PortableCmsDataEntry_${N.slice(0,8)}`),l.node.params.map(Y=>Ze.cloneNode(Y,!0)),Ze.blockStatement([...[...m].sort(Gm).map(Y=>Ze.cloneNode(Y,!0)),Ze.returnStatement(Ze.cloneNode(c.node,!0))]));$.async=l.node.async;let V=Ze.program([...F.sort(Gm),...[...g].sort(Gm).map(Y=>Ze.cloneNode(Y,!0)),Ze.exportDefaultDeclaration($)]),U=v0(Ze.file(V)).code,J=c.node.loc;if(!J||c.node.start==null||c.node.end==null)return{complete:!1};let te=[...f].sort().map(Y=>({propName:Y,value:{kind:Y==="params"?"route-params":"route-search-params"}}));return{complete:!0,selection:{target:e.target,root_ref:t.root.rootRef,source_file:o.sourceFile,structural_path:t.descriptor.source.structuralPath,content_hash:t.ownerSourceHash,source_range:{start_offset:c.node.start,end_offset:c.node.end,start_line:J.start.line,start_column:J.start.column,end_line:J.end.line,end_column:J.end.column},owner:t.descriptor.owner,call_chain:[],strategy:"extract-jsx",entry_file:R,entry_export:{kind:"default"},invocation:null},extracted:{complete:!0,entry_file:R,source_files:[{path:R,content:U}],source_mapping:[],invocation_bindings:te,selected_root_ref:t.root.rootRef}}}function Gm(e,t){return(e.start??0)-(t.start??0)}import{createHash as o_}from"node:crypto";import Eg from"node:path";import Sg from"@babel/traverse";import*as ct from"@babel/types";import{GeneratedSiteCapabilitiesSchema as G$,SiteEditSourcePathSchema as Y$}from"@vcp-dev/contracts";import{parse as yg}from"@babel/parser";import*as ie from"@babel/types";import{PortableCollectionRecipeFactsSchema as T$}from"@vcp-dev/contracts";import{parse as xo}from"@babel/parser";import sg from"@babel/traverse";import*as M from"@babel/types";import{createHash as W0}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as G0,generateDetailBreadcrumb as Y0,ResolvedFieldSchema as Z0}from"@vcp-dev/contracts";import qm from"@babel/traverse";import*as W from"@babel/types";import{PORTABLE_AUDITED_SAFE_IMAGE as pk}from"@vcp-dev/contracts";import{createHash as Qm}from"node:crypto";import{createHash as k0}from"node:crypto";import _0 from"@babel/traverse";import*as Ge from"@babel/types";var Ym=_0,C0=typeof Ym=="function"?Ym:Ym.default,R0=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),go=new Set(["backgroundimage","fallbacksrc","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),dk=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,P0=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function $i(e){let t=Fe(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=uk(c.node),u=F0(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:D0(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=uk(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})};C0(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;A0(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=fk(c.node.name),u=P0.test(l);for(let d of c.get("attributes")){if(d.isJSXSpreadAttribute()){u&&i({node:d.node.argument,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!d.isJSXAttribute())continue;let p=d.node,g=w0(p);if(g==="style"&&!N0(p.value)){i({node:p.value??p,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!g||!T0(g,u))continue;let m=da(d.get("value"));i({node:p.value??p,kind:ck(g),source:"jsx-attribute",value:m.value,complete:m.complete})}},ObjectProperty(c){let l=fa(c);if(!l.known){i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1});return}let u=l.name;if(!u||!go.has(u)&&!(lk(c)&&Zm(u)))return;let d=c.get("value");if(go.has(u)&&(d.isObjectExpression()||d.isArrayExpression())&&uu(d))return;let p=mo(c.node.value);i({node:c.node.value,kind:ck(u),source:"object-property",value:p.value,complete:p.complete})},ObjectMethod(c){let l=fa(c);(!l.known||c.node.kind!=="method"&&l.name&&(go.has(l.name)||lk(c)&&Zm(l.name)))&&i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1})},ArrayExpression(c){if(L0(c))for(let l of c.get("elements")){if(!l.node||(l.isObjectExpression()||l.isArrayExpression())&&uu(l))continue;let u=mo(l.node);(u.value!==null||!u.complete)&&i({node:l.node,kind:"array-item",source:"array-item",value:u.value,complete:u.complete})}},CallExpression(c){let l=c.node.callee;if(!Ge.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Ge.isExpression(u)){s(c.node,null);return}let d=mo(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!O0(c.node.object))return;let l=c.node.computed?mo(c.node.property):Ge.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=M0(r).sort(B0);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function N0(e){return!Ge.isJSXExpressionContainer(e)||!Ge.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!Ge.isObjectProperty(t)||t.computed||!(Ge.isIdentifier(t.key)||Ge.isStringLiteral(t.key)))return!1;let n=Ge.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:Ge.isNumericLiteral(t.value)?Number.isFinite(t.value.value):Ge.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function A0(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&R0.has(n)}function T0(e,t){return e!=="src"||t?go.has(e):!1}function ck(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function w0(e){return Ge.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Ge.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function fk(e){return Ge.isJSXIdentifier(e)?e.name:Ge.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${fk(e.object)}.${e.property.name}`}function fa(e){if(!e.node.computed){let n=e.node.key;return Ge.isIdentifier(n)?{known:!0,name:n.name.toLowerCase()}:Ge.isStringLiteral(n)?{known:!0,name:n.value.toLowerCase()}:{known:!0,name:null}}let t=da(e.get("key"));if(t.complete&&t.value!==null)return{known:!0,name:t.value.toLowerCase()};if(Ge.isTemplateLiteral(e.node.key)){let n=e.node.key.quasis[0]?.value.cooked?.toLowerCase(),r=e.node.key.quasis.at(-1)?.value.cooked?.toLowerCase(),o=[...go,"url","thumbnail_url"];if(n!==void 0&&r!==void 0&&!o.some(i=>i.startsWith(n)&&i.endsWith(r)))return{known:!0,name:null}}return{known:!1,name:null}}function O0(e){return Ge.isIdentifier(e,{name:"mediaAssets"})}function L0(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=fa(t).name;return n!==null&&go.has(n)}return t?.isVariableDeclarator()&&Ge.isIdentifier(t.node.id)?dk.test(t.node.id.name):!1}function lk(e){let t=e.parentPath;for(let n=0;t&&n<32;n++){let r=t.parentPath;if(r?.isArrayExpression()){t=r;continue}if(r?.isObjectProperty()&&r.node.value===t.node){let o=fa(r).name;if(o&&go.has(o))return!0;t=r.parentPath;continue}return!!(r?.isVariableDeclarator()&&r.node.init===t.node&&Ge.isIdentifier(r.node.id)&&dk.test(r.node.id.name))}return t!==null}function Zm(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function uu(e,t=0){if(t>=32)return!1;if(e.isArrayExpression())return e.get("elements").some(r=>r.node!==null&&(r.isObjectExpression()||r.isArrayExpression()?uu(r,t+1):!0));let n=!1;for(let r of e.get("properties")){if(!r.isObjectProperty()&&!r.isObjectMethod())return!1;let o=fa(r);if(!o.known)return!0;let i=o.name;if(r.isObjectMethod()&&r.node.kind==="method")continue;if(i!==null&&(go.has(i)||Zm(i))){n=!0;continue}if(r.isObjectMethod())continue;let s=r.get("value");(s.isObjectExpression()||s.isArrayExpression())&&uu(s,t+1)&&(n=!0)}return n}function mo(e){return e?Ge.isStringLiteral(e)?{value:e.value,complete:!0}:Ge.isJSXExpressionContainer(e)?mo(e.expression):Ge.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Ge.isTSAsExpression(e)||Ge.isTSTypeAssertion(e)||Ge.isParenthesizedExpression(e)?mo(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function da(e,t=new Set){if(!e.node||t.has(e.node)||t.size>=32)return{value:null,complete:!1};let n=new Set(t).add(e.node);if(e.isJSXExpressionContainer()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return da(e.get("expression"),n);if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r?.constant||r.kind!=="const"||!r.path.isVariableDeclarator()||!Ge.isIdentifier(r.path.node.id,{name:e.node.name})||!r.path.parentPath.isVariableDeclaration({kind:"const"})||r.path.node.start==null||e.node.start==null||r.path.node.start>=e.node.start?{value:null,complete:!1}:da(r.path.get("init"),n)}return mo(e.node)}function uk(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 F0(e,t){return e.slice(t.start_offset,t.end_offset)}function D0(e){return`sha256:${k0("sha256").update(e).digest("hex")}`}function M0(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 B0(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)}var Ek=typeof qm=="function"?qm:qm.default,du=256,eg=16,j0=new Set(["article","b","br","code","dd","div","dl","dt","em","h1","h2","h3","h4","h5","h6","i","li","ol","p","pre","section","small","span","strong","time","ul","wbr"]);function Sk(e){let t=[],n=new Map,r=new Set,o=new Map,i=new Set,s=new Set,a=0;class c extends Map{constructor(){super(...arguments),this.attempted=new Set}has(D){return e.files.has(D)}get(D){let H=super.get(D);if(H||this.attempted.has(D))return H;this.attempted.add(D);let j=e.files.get(D),z;try{if(typeof j=="string")z=j;else if(j instanceof Uint8Array)z=new TextDecoder("utf-8",{fatal:!0}).decode(j);else return}catch{return}let L=Fe(D,z);if(L.ok)return super.set(D,L.module),o.set(L.module.ast.program,L.module),L.module}}let l=new c,u=fo(e.files,e.trusted_host_file_hashes??new Map),d=nk(e.files,e.trusted_host_file_hashes??new Map),p=(O,D)=>{if(!d||!e.on_build_only_value||O.node.arguments.length!==2)return;let H=O.get("arguments")[1];if(!H?.isObjectExpression())return;let j=H.get("properties").filter(L=>L.isObjectProperty()&&!L.node.computed&&(W.isIdentifier(L.node.key,{name:"buildSample"})||W.isStringLiteral(L.node.key,{value:"buildSample"})));if(j.length!==1||!j[0].isObjectProperty())return;let z=j[0].get("value");if(z.isIdentifier()){let L=z.scope.getBinding(z.node.name);if(!L?.constant||!L.path.isVariableDeclarator()||L.referencePaths.length!==1||L.referencePaths[0].node!==z.node)return;z=L.path.get("init")}for(;z.isTSAsExpression()||z.isTSSatisfiesExpression()||z.isParenthesizedExpression();){let L=z.get("expression");if(Array.isArray(L))return;z=L}!z.isObjectExpression()||z.node.start==null||z.node.end==null||e.on_build_only_value({file_path:D.file,start:z.node.start,end:z.node.end,source_hash:`sha256:${Qm("sha256").update(D.source).digest("hex")}`})},g=new Set(["next/link","next/navigation","lucide-react"]),m=O=>{let D=O.findParent(H=>H.isProgram());return D&&W.isProgram(D.node)?o.get(D.node):void 0},f=u?lu({resolve_function(O){let D=m(O);return D&&O.isIdentifier()?he(O.scope.getBinding(O.node.name),D):null},resolve_value(O){let D=O.scope.getBinding(O.node.name),H=D?.path.parentPath,j=m(O);if(!j||!D?.constant||!D.path.isImportSpecifier()||D.path.node.importKind==="type"||!H?.isImportDeclaration()||H.node.importKind==="type")return null;let z=Kt(j.file,H.node.source.value,e.files),L=z?l.get(z):void 0,G=D.path.node.imported;return L?Kn(L,W.isIdentifier(G)?G.name:G.value,l):null},cms_value(O,D,H){let j=m(O);if(!j)return null;let z=le(O.get("callee"),j,new Set);if(!z||In(j.ast,z.originalName))return null;if(z.importedName==="cms"&&z.name.startsWith("__vcpCms.field.")){let q=zm(z.name.slice(15)),ce=O.get("arguments")[0],_e=ce&&f?.value(ce,D,H)?.origin;return q&&_e?{...q,origin:_e}:q}let L=dr(W.callExpression(xk(z.name),[]),{file:j.file,imports:new Map([["__vcpCms",{source:z.source,importedName:z.importedName}]])})?.operation,G=O.get("arguments")[0],A=G?L==="getByUrl"||L==="getByUrlStrict"?fu(G,new Map):Ht(G,new Map,new Set)?.[0]:void 0;return L?cu(L,A??void 0):null}}):null,y=new Map;function x(O,D,H){if(!e.on_cms_media_value||!f||O.node.start==null||O.node.end==null)return;let j=y.get(D.file);if(j||(j=new Set($i({file_path:D.file,source:D.source}).references.filter(z=>!z.complete).map(z=>`${z.source_range.start_offset}:${z.source_range.end_offset}`)),y.set(D.file,j)),j.has(`${O.node.start}:${O.node.end}`)){let z=f.value(O,H)?.origin;e.on_cms_media_value({file_path:D.file,start:O.node.start,end:O.node.end,...z?{origin:z}:{}})}}function E(O){return u&&/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(O.file)&&e.trusted_host_file_hashes?.get(O.file)===`sha256:${pk.digest_sha256}`&&Qm("sha256").update(O.source).digest("hex")===pk.digest_sha256}function b(O){let D=O?.path.parentPath;return!!(u&&O?.constant&&D?.isImportDeclaration()&&g.has(D.node.source.value))}function S(O){if(!u||!W.isJSXIdentifier(O.node.name))return!1;let D=O.scope.getBinding(O.node.name.name),H=D?.path.parentPath;return!!(D?.constant&&D.path.isImportDefaultSpecifier()&&H?.isImportDeclaration()&&H.node.source.value==="next/link")}function I(O,D,H,j){let z=j?.loc?.start;t.push({code:O,source_path:D,message:H,...z?{call_site:{line:z.line,column:z.column}}:{}})}function w(O,D,H,j){let z=j.loc?.start;if(!z){I("CMS_CALL_SITE_UNAVAILABLE",H.file,"The CMS call has no source location.",j);return}let L={source_path:H.file,operation:D,binding:"trusted-cms",call_site:{line:z.line,column:z.column}},G=n.get(O)??[];G.some(A=>JSON.stringify(A)===JSON.stringify(L))||G.push(L),n.set(O,G)}function C(O){if(!i.has(O.file)){if(i.size>=du){I("CMS_MODULE_BUDGET_EXHAUSTED",O.file,"The module analysis budget was exhausted.");return}if(i.add(O.file),!E(O)){for(let D of O.ast.program.body){let H=null;if(W.isImportDeclaration(D)&&D.importKind!=="type"){if(D.specifiers.length&&D.specifiers.every(L=>W.isImportSpecifier(L)&&L.importKind==="type"))continue;H=D.source.value}else if(W.isExportNamedDeclaration(D)&&D.source&&D.exportKind!=="type"){if(D.specifiers.length&&D.specifiers.every(L=>W.isExportSpecifier(L)&&L.exportKind==="type"))continue;H=D.source.value}else W.isExportAllDeclaration(D)&&D.exportKind!=="type"&&(H=D.source.value);if(!H)continue;if(!mt(H)){if(u&&g.has(H))continue;I("CMS_EXTERNAL_MODULE_UNRESOLVED",O.file,"An external module's initialization effects cannot be proven safe.",D);continue}let j=Kt(O.file,H,e.files);if(!j){I("CMS_IMPORT_UNRESOLVED",O.file,`The local import ${H} is unavailable.`,D);continue}if(!/\.[cm]?[jt]sx?$/iu.test(j)||hk(j))continue;let z=l.get(j);z?C(z):I("CMS_SOURCE_UNAVAILABLE",j,"The imported source cannot be parsed.",D)}Ek(O.ast,{Program(D){N(D,O,new Map,new Map),D.stop()}})}}}function N(O,D,H,j,z=new Map){let L=A=>Rk(A,H,j,V)||yt(f?.value(A,z)??null),G=A=>{let q=A.parentPath;return!(q?.isAssignmentExpression()&&q.node.left===A.node||q?.isUpdateExpression()||q?.isUnaryExpression({operator:"delete"}))&&yt(f?.value(A,z)??null)};O.traverse({enter(A){x(A,D,z)},Function(A){(A.isObjectMethod()||A.isClassMethod()||A.isClassPrivateMethod())&&A.node.computed&&!L(A.get("key"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"A computed method key may execute an unproven coercion.",A.node),A.skip()},BinaryExpression(A){(A.node.operator==="instanceof"||A.node.operator==="in"||A.node.operator!=="==="&&A.node.operator!=="!=="&&(!L(A.get("left"))||!L(A.get("right"))))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"An operator may execute an unproven coercion or proxy trap.",A.node)},TemplateLiteral(A){A.get("expressions").some(q=>!L(q))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"Template interpolation may execute an unproven coercion.",A.node)},UnaryExpression(A){["+","-","~"].includes(A.node.operator)&&!L(A.get("argument"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"A unary operator may execute an unproven coercion.",A.node)},UpdateExpression(A){I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"An update may execute an unproven coercion or proxy trap.",A.node)},ObjectProperty(A){A.node.computed&&!L(A.get("key"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"A computed property key may execute an unproven coercion.",A.node)},ForInStatement(A){I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",D.file,"Property enumeration may execute an unproven proxy trap.",A.node)},JSXOpeningElement(A){let q=A.node.name;if(W.isJSXIdentifier(q)&&/^[a-z]/u.test(q.name)){(q.name.includes("-")||A.node.attributes.some(Ke=>W.isJSXAttribute(Ke)&&W.isJSXIdentifier(Ke.name,{name:"is"})))&&I("CMS_COMPONENT_UNRESOLVED",D.file,"A custom element may execute an unproven implementation.",A.node);return}if(yk(A,S)){I("CMS_COMPONENT_REACHABILITY_UNPROVEN",D.file,"A component value is not proven to be rendered by the selected root.",A.node);return}if(!W.isJSXIdentifier(q)){I("CMS_COMPONENT_UNRESOLVED",D.file,"A dynamic or namespace component target is not proven.",A.node);return}let ce=he(A.scope.getBinding(q.name),D);if(!ce){if(b(A.scope.getBinding(q.name))){for(let Ke of A.get("attributes")){if(!Ke.isJSXAttribute()||!W.isJSXIdentifier(Ke.node.name)){I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"A runtime component spread is not a proven data argument.",Ke.node);continue}let rt=Ke.get("value");rt.isJSXExpressionContainer()&&!/^(?:on[A-Za-z]|ref$)/u.test(Ke.node.name.name)&&!yt(f?.value(rt.get("expression"),z)??null)&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"A runtime component argument is not proven plain data.",Ke.node)}return}I("CMS_COMPONENT_UNRESOLVED",D.file,"A rendered component target is not proven.",A.node);return}let _e=A.node.attributes.every(Ke=>W.isJSXAttribute(Ke)&&W.isJSXIdentifier(Ke.name)&&Ke.name.name!=="__proto__"),qe=m(ce);_e&&qe&&E(qe)&&A.node.start!=null&&A.node.end!=null&&e.on_audited_ui_call?.({file_path:D.file,host_file:qe.file,start:A.node.start,end:A.node.end,source_hash:`sha256:${Qm("sha256").update(D.source).digest("hex")}`}),te(ce,$(ce,A,H),_e?"jsx-props":"unknown",_e?J(ce,A,D,H,j):new Map,f?f.bind(ce,[R(A,z)],z):z)},JSXExpressionContainer(A){let q=A.get("expression"),ce=A.parentPath;if(ce?.isJSXAttribute()&&W.isJSXIdentifier(ce.node.name)&&(ce.node.name.name==="ref"||/^on[A-Za-z]/u.test(ce.node.name.name))){F(q,D,H,j);return}if(q.isFunctionExpression()||q.isArrowFunctionExpression())te(q,H,"unknown",j);else if(q.isIdentifier()){gk(q,j)&&!V(q)&&!yt(f?.value(q,z)??null)&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"A local data object escapes through an unproven JSX value.",q.node);let _e=he(q.scope.getBinding(q.node.name),D);_e&&te(_e,H,"unknown",j)}},MemberExpression(A){let q=A.parentPath;q?.isMemberExpression()&&q.node.object===A.node||(q?.isCallExpression()||q?.isOptionalCallExpression())&&q.node.callee===A.node||q?.isVariableDeclarator()&&q.node.init===A.node&&le(A,D,new Set)||G(A)||tg(A,H,j,V)||I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"A property read may invoke an unproven getter or proxy.",A.node)},OptionalMemberExpression(A){G(A)||tg(A,H,j,V)||I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"An optional property read may invoke an unproven getter or proxy.",A.node)},VariableDeclarator(A){(W.isObjectPattern(A.node.id)&&!yt(f?.value(A.get("init"),z)??null)&&!U0(A,H,j,V)||W.isArrayPattern(A.node.id))&&I("CMS_DESTRUCTURING_UNRESOLVED",D.file,"Destructuring can invoke an unproven getter or iterator.",A.node)},CatchClause(A){A.node.param&&!W.isIdentifier(A.node.param)&&I("CMS_DESTRUCTURING_UNRESOLVED",D.file,"A caught value may invoke an unproven getter or iterator.",A.node.param)},AssignmentExpression(A){let q=A.get("left");q.isIdentifier()&&["Boolean","Number","String","Promise","Object","encodeURIComponent"].includes(q.node.name)&&!q.scope.getBinding(q.node.name)&&I("CMS_GLOBAL_BUILTIN_MUTATED",D.file,"A relied-upon global builtin is reassigned by reachable source.",A.node),(W.isObjectPattern(A.node.left)||W.isArrayPattern(A.node.left))&&I("CMS_DESTRUCTURING_UNRESOLVED",D.file,"A destructuring assignment may invoke an unproven getter or iterator.",A.node)},ForOfStatement(A){I("CMS_ITERATION_UNRESOLVED",D.file,"An iterable may invoke an unproven iterator.",A.node)},SpreadElement(A){I("CMS_ITERATION_UNRESOLVED",D.file,"A spread may invoke an unproven iterator or getter.",A.node)},JSXSpreadAttribute(A){I("CMS_PROPERTY_ACCESS_UNRESOLVED",D.file,"A JSX spread may invoke an unproven getter or proxy.",A.node)},AwaitExpression(A){let q=f?.value(A.get("argument"),z);q?.kind!=="promise"&&!yt(q??null)&&!Y(A.get("argument"),D,H)&&I("CMS_AWAIT_TARGET_UNRESOLVED",D.file,"Awaiting an unproven value may execute a hidden thenable.",A.node)},ReturnStatement(A){let q=A.getFunctionParent(),ce=A.get("argument");q?.node.async&&ce.node&&!Y(ce,D,H)&&!yt(f?.value(ce,z)??null)&&I("CMS_ASYNC_RETURN_UNRESOLVED",D.file,"An async return may execute an unproven thenable.",A.node)},CallExpression(A){if(W.isImport(A.node.callee)){I("CMS_DYNAMIC_IMPORT_UNRESOLVED",D.file,"A dynamic import cannot prove the selected call closure.",A.node);return}let q=$0(A),ce=f?.arrayCall(A,z);if(ce){ce.empty||te(ce.target,new Map,"unknown",j,f.bind(ce.target,ce.args,z));return}for(let Ke of A.get("arguments"))if(Ke.isFunctionExpression()||Ke.isArrowFunctionExpression()){let rt=q?.callback===Ke.node?new Map(j).set(q.parameter,q.properties):j;te(Ke,new Map,"unknown",rt,z)}if(q)return;let _e=A.get("callee"),qe=le(_e,D,new Set);if(qe){if(In(D.ast,qe.originalName)){I("CMS_BINDING_MUTATED",D.file,"The trusted CMS binding or one of its aliases is modified.",A.node);return}let rt=A.get("arguments")[0],vt=xk(qe.name),pn={file:D.file,imports:new Map([["__vcpCms",{source:qe.source,importedName:qe.importedName}]])},Pt=dr(W.callExpression(vt,[]),pn)?.operation;if(u&&Pt&&!A.get("arguments").every(Mt=>yt(f?.value(Mt,z)??null))){I("CMS_REQUEST_ARGUMENT_UNPROVEN",D.file,"The audited CMS reader requires data-only request arguments.",A.node);return}if(u&&qe.importedName==="cms"&&qe.name.startsWith("__vcpCms.field.")&&zm(qe.name.slice(15))){A.get("arguments").every(Mt=>yt(f?.value(Mt,z)??null))||I("CMS_FIELD_VALUE_UNPROVEN",D.file,"The audited field helper requires proven plain data arguments.",A.node);return}if(Pt==="getByUrl"||Pt==="getByUrlStrict"){let Mt=rt&&fu(rt,H);if(Mt&&r.add(Mt),u&&Mt&&e.trusted_cms_schemas?.some(Lr=>Lr.source_slug===Mt)){w(Mt,Pt,D,A.node),Pt==="getByUrlStrict"&&p(A,D);return}I("CMS_URL_COLLECTION_UNPROVEN",D.file,"A site-wide CMS URL lookup does not prove which application owns the returned record.",A.node);return}let Or=["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(qe.importedName),br=rt?Or?H0(rt,H):Ht(rt,H,new Set):null;if(!br||br.length===0){I("CMS_IDENTITY_UNRESOLVED",D.file,"The CMS application identity is not statically bounded.",A.node);return}for(let Mt of br){if(Or&&Mt==="/content/by-url"){I("CMS_URL_COLLECTION_UNPROVEN",D.file,"A site-wide CMS URL lookup does not prove which application owns the returned record.",A.node);continue}if(Or&&!/^\/collections\/[a-z0-9][a-z0-9_-]{0,79}\/(?:records(?:\/[a-z0-9_-]+)?|schema|categories)$/iu.test(Mt)){I("CMS_OPERATION_UNRESOLVED",D.file,"The CMS transport path does not prove a collection-scoped read.",A.node);continue}let Lr=dr(W.callExpression(vt,[W.stringLiteral(Mt)]),pn),zi=Lr?.collection;if(!Lr||Lr.sourceKind!=="vcp-cms-collection"||!zi||!/^[a-z0-9][a-z0-9_-]*$/iu.test(zi)){I("CMS_OPERATION_UNRESOLVED",D.file,"The CMS operation or application identity cannot be proven.",A.node);continue}w(zi,Lr.operation,D,A.node)}return}if(_e.isIdentifier()){let Ke=_e.scope.getBinding(_e.node.name),rt=he(Ke,D);if(rt){let vt=new Map,pn=rt.get("params");for(let[Pt,Or]of pn.entries()){if(!Or.isIdentifier())continue;let br=rt.scope.getBinding(Or.node.name),Mt=A.get("arguments")[Pt];br&&vt.set(br.identifier,Mt?Ht(Mt,H,new Set):null)}te(rt,vt,"unknown",j,f?f.bind(rt,A.get("arguments").map(Pt=>f.value(Pt,z)),z):z);return}if(!Ke&&_e.node.name==="Boolean"||!Ke&&["String","Number","encodeURIComponent"].includes(_e.node.name)&&A.get("arguments").every(vt=>L(vt)))return}bk(A,H,Ke=>!!le(Ke,D,new Set))||b(_e.isIdentifier()?_e.scope.getBinding(_e.node.name):void 0)&&A.get("arguments").every(Ke=>L(Ke))||f?.value(A,z)||I("CMS_CALL_TARGET_UNRESOLVED",D.file,"A reachable call target cannot be proven free of hidden CMS access.",A.node)},OptionalCallExpression(A){I("CMS_CALL_TARGET_UNRESOLVED",D.file,"An optional call target cannot be proven.",A.node)},NewExpression(A){u&&W.isIdentifier(A.node.callee,{name:"Error"})&&!A.scope.getBinding("Error")&&A.get("arguments").every(q=>L(q))||I("CMS_CALL_TARGET_UNRESOLVED",D.file,"A constructor's effects cannot be proven.",A.node)},TaggedTemplateExpression(A){I("CMS_CALL_TARGET_UNRESOLVED",D.file,"A tagged template's effects cannot be proven.",A.node)}})}function R(O,D){let H=new Map;for(let j of O.get("attributes")){if(!j.isJSXAttribute()||!W.isJSXIdentifier(j.node.name)||H.has(j.node.name.name))return null;let z=j.get("value"),L=!z.node||z.isStringLiteral()?{kind:"primitive"}:z.isJSXExpressionContainer()?f?.value(z.get("expression"),D):null;L&&H.set(j.node.name.name,L)}return{kind:"object",properties:H}}function F(O,D,H,j,z=0){if(!O.node||z>=32){I("CMS_CALL_TARGET_UNRESOLVED",D.file,"An event handler target cannot be proven.",O.node??void 0);return}let L=A=>F(A,D,H,j,z+1);if(O.isTSAsExpression()||O.isTSSatisfiesExpression()||O.isTSNonNullExpression()||O.isParenthesizedExpression()){L(O.get("expression"));return}if(O.isConditionalExpression()){L(O.get("consequent")),L(O.get("alternate"));return}if(O.isLogicalExpression()){L(O.get("left")),L(O.get("right"));return}if(ho(O,H)||O.isUnaryExpression({operator:"void"})||O.isIdentifier({name:"undefined"})&&!O.scope.getBinding("undefined"))return;let G=O.isFunctionExpression()||O.isArrowFunctionExpression()?O:O.isIdentifier()?he(O.scope.getBinding(O.node.name),D):null;G?te(G,H,"unknown",j):I("CMS_CALL_TARGET_UNRESOLVED",D.file,"An event handler target cannot be proven.",O.node)}function $(O,D,H){let j=new Map,z=O.get("params")[0];if(!z?.isObjectPattern())return j;let L=D.get("attributes"),G=L.some(A=>A.isJSXSpreadAttribute());for(let A of z.get("properties")){if(!A.isObjectProperty()||A.node.computed)continue;let q=A.node.key,ce=W.isIdentifier(q)?q.name:W.isStringLiteral(q)?q.value:null,_e=A.get("value"),qe=_e.isIdentifier()?_e:_e.isAssignmentPattern()&&_e.get("left").isIdentifier()?_e.get("left"):null;if(!ce||!qe?.isIdentifier())continue;let Ke=O.scope.getBinding(qe.node.name);if(!Ke)continue;let rt=L.filter(Pt=>Pt.isJSXAttribute()&&W.isJSXIdentifier(Pt.node.name,{name:ce})),vt=null,pn=rt[0];if(!G&&rt.length===1&&pn?.isJSXAttribute()){let Pt=pn.get("value");Pt.isStringLiteral()?vt=[Pt.node.value]:Pt.isJSXExpressionContainer()&&(vt=Ht(Pt.get("expression"),H,new Set))}j.set(Ke.identifier,vt)}return j}function V(O){let D=O.parentPath,H=D?.parentPath,j=H?.parentPath;if(!D?.isJSXExpressionContainer()||D.node.expression!==O.node||!H?.isJSXAttribute()||!W.isJSXIdentifier(H.node.name)||!j?.isJSXOpeningElement()||!W.isJSXIdentifier(j.node.name)||/^[a-z]/u.test(j.node.name.name)||yk(j,S)||j.node.attributes.some(q=>!W.isJSXAttribute(q)||!W.isJSXIdentifier(q.name)||q.name.name==="__proto__"))return!1;let z=H.node.name.name;if(j.node.attributes.filter(q=>W.isJSXAttribute(q)&&W.isJSXIdentifier(q.name,{name:z})).length!==1)return!1;let L=j.findParent(q=>q.isProgram()),G=L&&W.isProgram(L.node)?o.get(L.node):void 0;if(!G)return!1;let A=he(j.scope.getBinding(j.node.name.name),G);return A?U(A,z)!==null:!1}function U(O,D){let H=O.get("params")[0];if(!H?.isObjectPattern())return null;let j=H.get("properties").filter(G=>!G.isObjectProperty()||G.node.computed?!1:Ui(G.node.key,!1)===D&&G.get("value").isIdentifier());if(j.length!==1)return null;let z=j[0];if(!z.isObjectProperty())return null;let L=z.get("value");return L.isIdentifier()?O.scope.getBinding(L.node.name)??null:null}function J(O,D,H,j,z){let L=new Map;for(let G of D.get("attributes")){if(!G.isJSXAttribute()||!W.isJSXIdentifier(G.node.name))continue;let A=G.node.name.name;if(D.node.attributes.filter(Ke=>W.isJSXAttribute(Ke)&&W.isJSXIdentifier(Ke.name,{name:A})).length!==1)continue;let q=G.get("value");if(!q.isJSXExpressionContainer())continue;let ce=q.get("expression");if(ce.isIdentifier()&&!V(ce))continue;let _e=U(O,A);if(!_e)continue;let qe=rg(ce,j,z,V);if(!qe&&(ce.isObjectExpression()||ce.isIdentifier()&&gk(ce,z))&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",H.file,"A JSX data argument is not a proven unescaped primitive-valued object.",G.node),qe){if(!og(_e,qe,V)){I("CMS_PROPERTY_ACCESS_UNRESOLVED",H.file,"A transferred data object has an unproven use or escape.",G.node);continue}L.set(_e.identifier,qe)}}return L}function te(O,D,H="unknown",j=new Map,z=new Map){let L=O.findParent(q=>q.isProgram()),G=L&&W.isProgram(L.node)?o.get(L.node):void 0;if(!G){I("CMS_FUNCTION_UNRESOLVED",e.entry_file,"A callable has no proven source module.",O.node);return}if(E(G))return;if(s.has(O.node)||a++>=du){I("CMS_CALL_BUDGET_EXHAUSTED",G.file,"Recursive or excessive reachable calls are not proven.",O.node);return}s.add(O.node),O.node.async&&O.node.generator&&I("CMS_ASYNC_RETURN_UNRESOLVED",G.file,"An async generator's promise and iteration effects are not proven.",O.node);for(let[q,ce]of O.node.params.entries())V0(ce,H==="jsx-props"&&q===0)&&I("CMS_DESTRUCTURING_UNRESOLVED",G.file,"A parameter pattern can invoke an unproven getter or iterator.",ce);let A=O.get("body");O.node.async&&!A.isBlockStatement()&&!Y(A,G,D)&&I("CMS_ASYNC_RETURN_UNRESOLVED",G.file,"An async return may execute an unproven thenable.",A.node),N(O,G,D,j,z),s.delete(O.node)}function Y(O,D,H,j=new Set){if(!O.node||j.has(O.node)||j.size>=32)return!1;let z=new Set(j).add(O.node);if(O.isJSXElement()||O.isJSXFragment()||zt(O,H))return!0;if(O.isIdentifier({name:"undefined"}))return!O.scope.getBinding("undefined");if(O.isTSAsExpression()||O.isTSSatisfiesExpression()||O.isTSNonNullExpression()||O.isParenthesizedExpression()||O.isAwaitExpression())return Y(O.get(O.isAwaitExpression()?"argument":"expression"),D,H,z);if(O.isConditionalExpression())return Y(O.get("consequent"),D,H,z)&&Y(O.get("alternate"),D,H,z);if(!O.isCallExpression())return!1;let L=le(O.get("callee"),D,new Set);if(L&&!In(D.ast,L.originalName)||bk(O,H,Ke=>{let rt=le(Ke,D,new Set);return!!(rt&&!In(D.ast,rt.originalName))}))return!0;let G=O.get("callee");if(!G.isIdentifier())return!1;let A=he(G.scope.getBinding(G.node.name),D);if(!A?.node.async||j.has(A.node))return!1;let q=A.findParent(Ke=>Ke.isProgram()),ce=q&&W.isProgram(q.node)?o.get(q.node):void 0;if(!ce)return!1;let _e=A.get("body");if(!_e.isBlockStatement())return Y(_e,ce,new Map,z);let qe=_e.get("body");return qe.length!==1||!qe[0].isReturnStatement()?!1:Y(qe[0].get("argument"),ce,new Map,new Set(z).add(A.node))}function he(O,D){if(!O||O.constantViolations.length)return null;let H=O.path;if(H.isFunctionDeclaration())return H;if(H.isVariableDeclarator()){let ce=H.get("init");return ce.isFunctionExpression()||ce.isArrowFunctionExpression()?ce:null}let j=H.parentPath;if(!j?.isImportDeclaration()||j.node.importKind==="type")return null;let z=j.node.source.value;if(!mt(z))return null;let L=Kt(D.file,z,e.files),G=L&&l.get(L),A=H.isImportDefaultSpecifier()?"default":H.isImportSpecifier()&&W.isIdentifier(H.node.imported)?H.node.imported.name:null;if(!G||!A)return null;let q=Kn(G,A,l);return q&&(q.isFunctionDeclaration()||q.isFunctionExpression()||q.isArrowFunctionExpression())?q:null}function le(O,D,H){if(!O.node||H.has(O.node)||H.size>=32)return null;if(H.add(O.node),O.isMemberExpression()&&!O.node.optional){let q=!O.node.computed&&W.isIdentifier(O.node.property)?O.node.property.name:O.node.computed&&W.isStringLiteral(O.node.property)?O.node.property.value:null,ce=le(O.get("object"),D,H);return ce&&q?{...ce,name:`${ce.name}.${q}`}:null}if(!O.isIdentifier())return null;let j=O.scope.getBinding(O.node.name);if(!j||j.constantViolations.length)return null;if(j.path.isVariableDeclarator())return le(j.path.get("init"),D,H);let z=j.path.parentPath;if(!z?.isImportDeclaration()||!j.path.isImportSpecifier())return null;let L=j.path.node.imported,G=W.isIdentifier(L)?L.name:L.value,A=Kt(D.file,z.node.source.value,e.files);return!A||!hk(A)||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(G)?null:{name:"__vcpCms",source:A,importedName:G,originalName:j.identifier.name}}let Me=l.get(e.entry_file);if(!Me)I("CMS_ENTRY_UNAVAILABLE",e.entry_file,"The selected entry is missing or invalid.");else{C(Me);let O=Kn(Me,e.entry_export.kind==="default"?"default":e.entry_export.name,l);!O||!(O.isFunctionDeclaration()||O.isFunctionExpression()||O.isArrowFunctionExpression())?I("CMS_ENTRY_UNRESOLVED",e.entry_file,"The selected entry export is not one proven function."):te(O,new Map,e.entry_argument_origin==="jsx-props"?"jsx-props":"unknown",new Map,f?f.bind(O,[{kind:"object",properties:new Map((e.entry_invocation_bindings??[]).flatMap(D=>D.value.kind==="route-search-params"||D.value.kind==="route-params"?[[D.propName,{kind:"promise",value:D.value.kind==="route-params"&&e.entry_route_id?au(e.entry_route_id):{kind:"json"}}]]:[]))}]):new Map)}let Ye=[...n.entries()].sort(([O],[D])=>O.localeCompare(D)).map(([O,D])=>({requirement_key:`cms-${O}`,slug:O,evidence:D.sort((H,j)=>H.source_path.localeCompare(j.source_path)||H.call_site.line-j.call_site.line||H.call_site.column-j.call_site.column)})),pt=[...new Map(t.map(O=>[JSON.stringify(O),O])).values()];return{complete:pt.length===0,dependencies:Ye,unresolved:pt,...r.size&&pt.length?{candidates:[...r].sort()}:{}}}function $0(e){let t=e.get("callee"),n=e.get("arguments");if(!t.isMemberExpression()||t.node.computed||!W.isIdentifier(t.node.property,{name:"map"})||n.length!==1)return null;let r=t.get("object"),o=n[0];if(!r.isIdentifier()||!o||!o.isFunctionExpression()&&!o.isArrowFunctionExpression()||o.node.async||o.node.generator||o.node.params.length!==1)return null;let i=r.scope.getBinding(r.node.name);if(!i?.constant||!i.path.isVariableDeclarator()||!W.isIdentifier(i.path.node.id)||!i.path.parentPath.isVariableDeclaration({kind:"const"})||i.path.parentPath.parentPath.isExportNamedDeclaration()||i.referencePaths.length!==1||i.referencePaths[0]?.node!==r.node)return null;let s=i.path.get("init");if(!s.isArrayExpression()||s.node.elements.length===0||s.node.elements.length>du)return null;let a=null;for(let p of s.get("elements")){if(!p.isObjectExpression())return null;let g=new Set;for(let m of p.get("properties")){if(!m.isObjectProperty()||m.node.computed)return null;let f=Ui(m.node.key,!1),y=m.node.value;if(!f||["__proto__","prototype","constructor"].includes(f)||g.has(f)||!(W.isStringLiteral(y)||W.isNumericLiteral(y)||W.isBooleanLiteral(y)||W.isNullLiteral(y)))return null;g.add(f)}if(a===null)a=g;else{let m=new Set;for(let f of a)g.has(f)&&m.add(f);a=m}}let l=o.get("params")[0];if(!a||!l?.isIdentifier())return null;let u=o.scope.getBinding(l.node.name);if(!u||!og(u,a,()=>!1))return null;let d=!1;return o.traverse({Function(p){d=!0,p.skip()},CallExpression(){d=!0},OptionalCallExpression(){d=!0},NewExpression(){d=!0},TaggedTemplateExpression(){d=!0},ThisExpression(){d=!0},Super(){d=!0},ReferencedIdentifier(p){p.scope.getBinding(p.node.name)!==u&&!(p.node.name==="undefined"&&!p.scope.getBinding("undefined"))&&(d=!0)},JSXOpeningElement(p){(!W.isJSXIdentifier(p.node.name)||!j0.has(p.node.name.name))&&(d=!0)},JSXAttribute(p){(!W.isJSXIdentifier(p.node.name)||/^(?:ref|is|dangerouslysetinnerhtml|on)/iu.test(p.node.name.name))&&(d=!0)},JSXSpreadAttribute(){d=!0}}),d?null:{callback:o.node,parameter:u.identifier,properties:a}}function mk(e,t){if(!e.isObjectExpression())return null;let n=new Set;for(let r of e.get("properties")){if(!r.isObjectProperty()||!ho(r.get("value"),t))return null;let o=Ui(r.node.key,r.node.computed);if(!o||["__proto__","prototype","constructor"].includes(o)||n.has(o))return null;n.add(o)}return n}function ho(e,t,n=new Set){if(!e.node||n.has(e.node)||n.size>=32)return!1;if(zt(e,t))return!0;let r=new Set(n).add(e.node);if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!!(o?.constant&&o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})&&ho(o.path.get("init"),t,r))}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return ho(e.get("expression"),t,r);if(e.isConditionalExpression())return ho(e.get("consequent"),t,r)&&ho(e.get("alternate"),t,r);if(e.isLogicalExpression())return ho(e.get("left"),t,r)&&ho(e.get("right"),t,r);if(e.isBinaryExpression())return["<","<=",">",">=","==","!=","===","!=="].includes(e.node.operator);if(e.isCallExpression()){let o=e.get("callee");return o.isIdentifier()&&["Number","String","Boolean","encodeURIComponent"].includes(o.node.name)&&!o.scope.getBinding(o.node.name)}return!1}function Ui(e,t){return!t&&W.isIdentifier(e)?e.name:W.isStringLiteral(e)?e.value:null}function Ik(e,t){return W.isObjectPattern(e)&&e.properties.every(n=>{if(!W.isObjectProperty(n)||!W.isIdentifier(n.value))return!1;let r=Ui(n.key,n.computed);return r!==null&&t.has(r)})}function vk(e,t){let n=Ui(e.node.property,e.node.computed);if(n===null||!t.has(n))return!1;let r=e,o=r.parentPath;for(;o&&(o.isTSAsExpression()||o.isTSSatisfiesExpression()||o.isTSNonNullExpression()||o.isParenthesizedExpression());)r=o,o=r.parentPath;return!(o?.isAssignmentExpression()&&o.node.left===r.node||o?.isObjectProperty()&&o.parentPath?.isObjectPattern()||o?.isArrayPattern()||o?.isAssignmentPattern()||o?.isRestElement()||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"})||(o?.isForInStatement()||o?.isForOfStatement())&&o.node.left===r.node||(o?.isCallExpression()||o?.isOptionalCallExpression())&&o.node.callee===r.node)}function rg(e,t,n,r){if(e.isObjectExpression())return mk(e,t);if(!e.isIdentifier())return null;let o=e.scope.getBinding(e.node.name);if(!o||o.constantViolations.length)return null;let i=n.get(o.identifier)??null;if(!i){if(!o.scope.getFunctionParent()||!o.path.isVariableDeclarator()||!o.path.parentPath.isVariableDeclaration({kind:"const"})||!W.isIdentifier(o.path.node.id))return null;i=mk(o.path.get("init"),t)}return i&&og(o,i,r)?i:null}function og(e,t,n){if(e.constantViolations.length||e.referencePaths.length>du)return!1;for(let r of e.referencePaths){let o=r.parentPath;if(!((o?.isMemberExpression()||o?.isOptionalMemberExpression())&&o.node.object===r.node&&vk(o,t))&&!(o?.isVariableDeclarator()&&o.node.init===r.node&&Ik(o.node.id,t))&&!(r.isIdentifier()&&n(r)))return!1}return!0}function tg(e,t,n,r){let o=rg(e.get("object"),t,n,r);return o!==null&&vk(e,o)}function U0(e,t,n,r){let o=rg(e.get("init"),t,n,r);return o!==null&&Ik(e.node.id,o)}function gk(e,t){let n=e.scope.getBinding(e.node.name);return n?t.has(n.identifier)||!!n.scope.getFunctionParent()&&n.path.isVariableDeclarator()&&W.isObjectExpression(n.path.node.init):!1}function V0(e,t){let n=W.isAssignmentPattern(e)?e.left:e;return W.isIdentifier(n)?!1:W.isRestElement(n)?!W.isIdentifier(n.argument):!W.isObjectPattern(n)||!t?!0:n.properties.some(r=>{if(!W.isObjectProperty(r)||r.computed)return!0;let o=W.isIdentifier(r.key)?r.key.name:W.isStringLiteral(r.key)?r.key.value:null;if(!o||["__proto__","prototype","constructor"].includes(o))return!0;let i=r.value;return!(W.isIdentifier(i)||W.isAssignmentPattern(i)&&W.isIdentifier(i.left))})}function kk(e,t){if(!e.complete||!e.dependencies.length||e.unresolved.length)return!1;let n=new Set(["list","listStrict","schema","categories"]),r=new Map;for(let o of e.dependencies){if(!o.evidence.length)return!1;for(let i of o.evidence){if(i.binding!=="trusted-cms"||!n.has(i.operation))return!1;let s=r.get(i.source_path);if(!s){let l=t.get(i.source_path),u;try{if(typeof l=="string")u=l;else if(l instanceof Uint8Array)u=new TextDecoder("utf-8",{fatal:!0}).decode(l);else return!1}catch{return!1}let d=Fe(i.source_path,u);if(!d.ok)return!1;s=new Map,Ek(d.module.ast,{CallExpression(p){let g=p.node.loc?.start;if(!g)return;let m=`${g.line}:${g.column}`,f=s.get(m)??[];f.push(p),s.set(m,f)}}),r.set(i.source_path,s)}let a=`${i.call_site.line}:${i.call_site.column}`,c=s.get(a);if(c?.length!==1||!J0(c[0],i.operation))return!1}}return!0}function J0(e,t){let n=e.get("arguments");if(n.length<1||n.length>2||n[0].isSpreadElement())return!1;if(n.length===1)return!0;let r=n[1];if(!["list","listStrict"].includes(t)||!r.isObjectExpression())return!1;let o=new Set;for(let i of r.get("properties")){if(!i.isObjectProperty()||i.node.computed)return!1;let s=W.isIdentifier(i.node.key)?i.node.key.name:W.isStringLiteral(i.node.key)?i.node.key.value:null;if(!s||!["page","pageSize"].includes(s)||o.has(s))return!1;o.add(s);let a=ng(i.get("value"),new Set);if(a===null||!Number.isSafeInteger(a)||(s==="page"?a!==1:a<1||a>100))return!1}return!0}function ng(e,t){if(!e.node||t.has(e.node)||t.size>=32)return null;if(t.add(e.node),e.isNumericLiteral())return e.node.value;if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return ng(e.get("expression"),t);if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);return!n||n.constantViolations.length||!n.path.isVariableDeclarator()||!n.path.parentPath.isVariableDeclaration({kind:"const"})?null:ng(n.path.get("init"),t)}function hk(e){return/^(?:src\/)?lib\/cms(?:\/index|\/collections|\/client)?\.[cm]?[jt]s$/u.test(e)}function yk(e,t=()=>!1){let n=e.parentPath,r=n?.parentPath;for(;r&&!r.isFunction()&&!r.isProgram();){if(r.isVariableDeclarator())return!K0(r);if(r.isJSXAttribute()||r.isCallExpression()||r.isOptionalCallExpression()||r.isNewExpression()||r.isArrayExpression()||r.isObjectExpression()||r.isObjectProperty()||r.isSpreadElement()||r.isConditionalExpression()&&r.node.test===n?.node||r.isConditionalExpression()&&!_k(r,n?.node)||r.isLogicalExpression()&&r.node.left===n?.node||r.isLogicalExpression()&&!Ck(r))return!0;if(r.isJSXElement()){let o=r.node.openingElement.name;if((!W.isJSXIdentifier(o)||!/^[a-z]/u.test(o.name))&&!ig(r.get("openingElement"))&&!t(r.get("openingElement")))return!0}n=r,r=r.parentPath}return!1}function ig(e){if(!W.isJSXIdentifier(e.node.name)||e.node.attributes.length)return!1;let t=e.scope.getBinding(e.node.name.name);if(!t?.constant||t.constantViolations.length)return!1;let n=t.path,r=n.isFunctionDeclaration()?n:n.isVariableDeclarator()&&n.parentPath.isVariableDeclaration({kind:"const"})?n.get("init"):null;if(!r||!(r.isFunctionDeclaration()||r.isFunctionExpression()||r.isArrowFunctionExpression())||r.node.async||r.node.generator||r.node.params.length!==1)return!1;let o=r.node.params[0];if(!W.isObjectPattern(o)||o.properties.length!==1||!W.isObjectProperty(o.properties[0])||o.properties[0].computed||!W.isIdentifier(o.properties[0].key,{name:"children"})||!W.isIdentifier(o.properties[0].value))return!1;let i=r.scope.getBinding(o.properties[0].value.name);if(!i?.constant||i.constantViolations.length||i.referencePaths.length!==1)return!1;let s=r.node.body,a=W.isBlockStatement(s)?s.body.length===1&&W.isReturnStatement(s.body[0])?s.body[0].argument:null:s,c=new Set(["article","aside","div","footer","header","li","main","nav","ol","p","section","span","ul"]),l=(u,d)=>{if(!u||d>32)return!1;if(W.isJSXExpressionContainer(u))return u.expression===i.referencePaths[0].node;if(!W.isJSXElement(u)&&!W.isJSXFragment(u)||W.isJSXElement(u)&&(!W.isJSXIdentifier(u.openingElement.name)||!c.has(u.openingElement.name.name)||u.openingElement.attributes.length>0))return!1;let p=u.children.filter(g=>!W.isJSXText(g)||g.value.trim()!=="");return p.length===1&&l(p[0],d+1)};return l(a,0)}function K0(e){if(!W.isIdentifier(e.node.id)||!e.parentPath.isVariableDeclaration({kind:"const"}))return!1;let t=e.getFunctionParent(),n=e.scope.getBinding(e.node.id.name);if(!t||!n?.constant||n.path.node!==e.node||!n.referencePaths.length||n.referencePaths.length>256)return!1;let r=!1;for(let o of n.referencePaths){if(o.getFunctionParent()!==t)return!1;let i=X0(o,t);if(i===null)return!1;i==="direct"&&(r=!0)}return r}function X0(e,t){let n=new Set(["article","aside","div","li","main","nav","ol","section","span","ul"]),r=e,o=!1,i=!1;for(let s=0;s<64;s++){let a=r.parentPath;if(!a)return null;if(a.isTSAsExpression()||a.isTSSatisfiesExpression()||a.isTSNonNullExpression()||a.isParenthesizedExpression()){r=a;continue}if(a.isConditionalExpression()&&a.node.test!==r.node){if(!_k(a,r.node))return null;r=a;continue}if(a.isLogicalExpression()&&a.node.right===r.node){if(!Ck(a))return null;r=a;continue}if(a.isJSXExpressionContainer()){if(a.node.expression!==r.node||!(a.parentPath.isJSXElement()||a.parentPath.isJSXFragment()))return null;o=!0,r=a;continue}if(a.isJSXElement()){if(!a.node.children.includes(r.node))return null;let c=a.node.openingElement,l=c.name;(!W.isJSXIdentifier(l)||!n.has(l.name)||c.attributes.some(u=>W.isJSXSpreadAttribute(u)||W.isJSXAttribute(u)&&W.isJSXIdentifier(u.name,{name:"is"})))&&(i=!0),r=a;continue}if(a.isJSXFragment()){if(!a.node.children.includes(r.node))return null;r=a;continue}return(a.isReturnStatement()&&a.node.argument===r.node&&a.getFunctionParent()===t||a===t&&t.isArrowFunctionExpression()&&t.node.body===r.node)&&o?i?"wrapped":"direct":null}return null}function _k(e,t){let n=Zn(e.get("test"),new Set);return n.known?n.value?t===e.node.consequent:t===e.node.alternate:!0}function Ck(e){let t=Zn(e.get("left"),new Set);return t.known?e.node.operator==="&&"?!!t.value:e.node.operator==="||"?!t.value:t.value===null||t.value===void 0:!0}function Zn(e,t){if(!e.node||t.has(e.node)||t.size>=32)return{known:!1};let n=new Set(t).add(e.node);if(e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral())return{known:!0,value:e.node.value};if(e.isNullLiteral())return{known:!0,value:null};if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r&&e.node.name==="undefined"?{known:!0,value:void 0}:!r?.constant||!r.path.isVariableDeclarator()||!r.path.parentPath.isVariableDeclaration({kind:"const"})?{known:!1}:Zn(r.path.get("init"),n)}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Zn(e.get("expression"),n);if(e.isUnaryExpression({operator:"!"})){let r=Zn(e.get("argument"),n);return r.known?{known:!0,value:!r.value}:{known:!1}}if(e.isBinaryExpression()&&["===","!=="].includes(e.node.operator)){let r=Zn(e.get("left"),n),o=Zn(e.get("right"),n);if(!r.known||!o.known)return{known:!1};let i=r.value===o.value;return{known:!0,value:e.node.operator==="==="?i:!i}}if(e.isLogicalExpression()){let r=Zn(e.get("left"),n);return r.known?e.node.operator==="&&"&&!r.value||e.node.operator==="||"&&r.value||e.node.operator==="??"&&r.value!==null&&r.value!==void 0?r:Zn(e.get("right"),n):{known:!1}}if(e.isConditionalExpression()){let r=Zn(e.get("test"),n);return r.known?Zn(r.value?e.get("consequent"):e.get("alternate"),n):{known:!1}}return{known:!1}}function xk(e){let[t,...n]=e.split(".");return n.reduce((r,o)=>W.memberExpression(r,W.identifier(o)),W.identifier(t))}function bk(e,t,n){let r=e.node.callee;if(!(W.isMemberExpression(r)&&!r.computed&&W.isIdentifier(r.object,{name:"Promise"})&&!e.scope.getBinding("Promise")&&W.isIdentifier(r.property,{name:"all"})))return!1;let o=e.get("arguments")[0];return o?.isArrayExpression()?o.get("elements").every(i=>!i.node||zt(i,t)||i.isCallExpression()&&n(i.get("callee"))):!1}function zt(e,t,n=new Set){if(!e.node||n.has(e.node)||n.size>=32)return!1;let r=new Set(n).add(e.node);if(e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()||e.isNullLiteral())return!0;if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!o&&e.node.name==="undefined"?!0:!o||o.constantViolations.length?!1:t.has(o.identifier)?t.get(o.identifier)!=null:o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})&&zt(o.path.get("init"),t,r)}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return zt(e.get("expression"),t,r);if(e.isUnaryExpression()&&["typeof","!","void"].includes(e.node.operator))return!0;if(e.isLogicalExpression())return zt(e.get("left"),t,r)&&zt(e.get("right"),t,r);if(e.isCallExpression()){let o=e.get("callee");return!o.isIdentifier()||o.scope.getBinding(o.node.name)?!1:o.node.name==="Boolean"?!0:["String","Number","encodeURIComponent"].includes(o.node.name)?e.get("arguments").every(i=>zt(i,t,r)):!1}return e.isConditionalExpression()?z0(e,t,r)||zt(e.get("consequent"),t,r)&&zt(e.get("alternate"),t,r):e.isBinaryExpression()?["===","!=="].includes(e.node.operator)||e.node.operator!=="in"&&e.node.operator!=="instanceof"&&zt(e.get("left"),t,r)&&zt(e.get("right"),t,r):!1}function z0(e,t,n){let r=e.get("test"),o=r.isLogicalExpression({operator:"&&"})?r:null,i=o?o.get("left"):r;if(!i.isBinaryExpression()||!["===","!=="].includes(i.node.operator))return!1;let s=i.get("left"),a=i.get("right"),c=s.isUnaryExpression({operator:"typeof"})?s:a,l=c===s?a:s;if(!c.isUnaryExpression({operator:"typeof"})||!l.isStringLiteral({value:"string"}))return!1;let u=c.get("argument");if(!u.isIdentifier())return!1;let d=u.scope.getBinding(u.node.name);if(!d?.constant||!["param","const"].includes(d.kind))return!1;if(o){let m=o.get("right");if(i.node.operator!=="==="||!m.isBinaryExpression()||!["===","!=="].includes(m.node.operator))return!1;let f=m.get("left"),y=m.get("right"),x=f.isIdentifier()?f:y,E=x===f?y:f;if(!x.isIdentifier()||x.scope.getBinding(x.node.name)!==d||!E.isStringLiteral())return!1}let p=e.get(i.node.operator==="==="?"consequent":"alternate"),g=e.get(i.node.operator==="==="?"alternate":"consequent");return p.isIdentifier()&&p.scope.getBinding(p.node.name)===d&&zt(g,t,n)}function Rk(e,t,n,r,o=new Set){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(zt(e,t))return!0;let i=new Set(o).add(e.node),s=a=>Rk(a,t,n,r,i);if(e.isMemberExpression()||e.isOptionalMemberExpression())return tg(e,t,n,r);if(e.isIdentifier()){let a=e.scope.getBinding(e.node.name);return!!(a?.constant&&a.path.isVariableDeclarator()&&a.path.parentPath.isVariableDeclaration({kind:"const"})&&s(a.path.get("init")))}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return s(e.get("expression"));if(e.isUnaryExpression()&&["+","-","~"].includes(e.node.operator))return s(e.get("argument"));if(e.isLogicalExpression())return s(e.get("left"))&&s(e.get("right"));if(e.isTemplateLiteral())return e.get("expressions").every(a=>s(a));if(e.isConditionalExpression())return s(e.get("consequent"))&&s(e.get("alternate"));if(e.isBinaryExpression())return e.node.operator!=="in"&&e.node.operator!=="instanceof"&&s(e.get("left"))&&s(e.get("right"));if(e.isCallExpression()){let a=e.get("callee");return a.isIdentifier()&&["Number","String","encodeURIComponent"].includes(a.node.name)&&!a.scope.getBinding(a.node.name)&&e.get("arguments").every(c=>s(c))}return!1}function Ht(e,t,n){if(!e.node||n.has(e.node)||n.size>=32)return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return[e.node.value];if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);return!o||o.constantViolations.length?null:t.has(o.identifier)?t.get(o.identifier)??null:o.path.isVariableDeclarator()&&o.path.parentPath.isVariableDeclaration({kind:"const"})?Ht(o.path.get("init"),t,r):null}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Ht(e.get("expression"),t,r);if(e.isTemplateLiteral()){let o=[e.node.quasis[0]?.value.cooked];if(o[0]==null)return null;for(let[i,s]of e.get("expressions").entries()){let a=Ht(s,t,r),c=e.node.quasis[i+1]?.value.cooked;if(!a||c==null||o.length*a.length>eg)return null;o=o.flatMap(l=>a.map(u=>`${l}${u}${c}`))}return[...new Set(o)]}if(e.isConditionalExpression()){let o=Ht(e.get("consequent"),t,r),i=Ht(e.get("alternate"),t,r);if(!o||!i)return null;let s=[...new Set([...o,...i])];return s.length<=eg?s:null}if(e.isBinaryExpression({operator:"+"})){let o=Ht(e.get("left"),t,r),i=Ht(e.get("right"),t,r);return!o||!i||o.length*i.length>eg?null:[...new Set(o.flatMap(s=>i.map(a=>s+a)))]}return null}function H0(e,t){if(!e.isObjectExpression())return null;let n=new Set,r=null;for(let o of e.get("properties")){if(!o.isObjectProperty()||o.node.computed)return null;let i=Ui(o.node.key,!1);if(!i||!["path","method"].includes(i)||n.has(i))return null;if(n.add(i),i==="path"&&(r=Ht(o.get("value"),t,new Set)),i==="method"){let s=Ht(o.get("value"),t,new Set);if(!s||s.length!==1||s[0]!=="GET")return null}}return r}function fu(e,t,n=new Set){if(!e.node||n.has(e.node)||n.size>=32)return null;let r=new Set(n).add(e.node);if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return fu(e.get("expression"),t,r);if(e.isIdentifier()){let a=e.scope.getBinding(e.node.name);return!a?.constant||a.constantViolations.length||!a.path.isVariableDeclarator()||!a.path.parentPath.isVariableDeclaration({kind:"const"})?null:fu(a.path.get("init"),t,r)}let o=null,i=null;if(e.isBinaryExpression({operator:"+"})){let a=Ht(e.get("left"),t,new Set);a?.length===1&&(o=a[0]),i=e.get("right")}else e.isTemplateLiteral()&&e.node.expressions.length===1&&e.node.quasis[1]?.value.cooked===""&&(o=e.node.quasis[0]?.value.cooked??null,i=e.get("expressions")[0]??null);if(!o||!i?.isIdentifier())return null;let s=i.scope.getBinding(i.node.name);return!s?.constant||s.constantViolations.length?null:xl(`${o}:record`)}var ma=typeof sg=="function"?sg:sg.default;function ug(e){return Tk(e,!1)}function q0(e){if(e.list_container_file.length===0||e.list_container_file.length>1024||/[\\%?#:\s\u0000-\u001f\u007f]/u.test(e.list_container_file)||e.list_container_file.split("/").some(o=>!o||o.startsWith(".")||o==="node_modules"))return{complete:!1,relation:null,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:"<list-container>",message:"The existing list container path is unsafe."}]};let t=Tk({files:e.files,list_entry_file:e.list_container_file,selected_component_source:`@/${e.list_container_file}`,detail_prefix:e.detail_prefix},!0);if(!t.relation)return{...t,relation:null};let{list_entry_file:n,...r}=t.relation;return{...t,relation:r}}function Tk(e,t){let n=pg(e.files),r=(g,m,f)=>({complete:!1,relation:null,errors:[{code:g,path:m,message:f}]}),o=Ok(e,n,t);if(!o.complete)return{complete:!1,relation:null,errors:o.errors};if(!o.consumer)return{complete:!0,relation:null,errors:[]};let{slug:i,consumer:s}=o,a=[...n.keys()].filter(Uk),c=a.find(g=>typeof n.get(g)!="string");if(c)return r("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",c,"A candidate detail route is not valid UTF-8 source, so uniqueness cannot be proven.");let l=a.flatMap(g=>{let m=n.get(g);if(typeof m!="string")return[];let f=Go(g,m,i,"getByUrlStrict",n,e.detail_prefix??`/${i}`);return f&&hu(f.ast,e.detail_prefix??`/${i}`)!==null?[f]:[]});if(l.length!==1)return r("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",e.list_entry_file,"Exactly one dynamic detail route must consume the selected collection.");let u=l[0];if(!y$(u.path,e.detail_prefix??`/${i}`))return r("RELATED_DETAIL_ROUTE_UNPROVEN",u.path,"The detail page path does not match the proven CMS lookup prefix.");if(u.adapter_source!==s.adapter_source||u.interface_name!==s.interface_name)return r("RELATED_COLLECTION_ADAPTER_UNPROVEN",u.path,"The list and detail routes do not share the selected collection adapter and view interface.");let d=Mn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let m=dn(u.path,g.source,n),f=m?n.get(m):void 0;return!m||typeof f!="string"||!Dk(f,g.export_name)||!mu(f,u.adapter_source,u.interface_name)?[]:[{path:m,export_name:g.export_name}]});if(d.length!==1)return r("RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",u.path,"The collection detail route does not prove one private detail view.");let p=d[0];return{complete:!0,relation:{slug:i,requirement_key:`cms-${i}`,list_entry_file:e.list_entry_file,detail_entry_file:u.path,detail_view_file:p.path,detail_view_export:p.export_name},errors:[]}}function wk(e){let t=Ok(e,pg(e.files));return t.complete&&t.consumer!==null}function Ok(e,t,n=!1){let r=(c,l)=>({complete:!1,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:c,message:l}]}),o=dn(e.list_entry_file,e.selected_component_source,t),i=o?t.get(o):void 0;if(!o||typeof i!="string")return r(e.list_entry_file,"The selected Page Unit does not resolve to one Snapshot list container.");if(!l$(i,o,"listStrict"))return{complete:!0,slug:null,consumer:null};if(!n&&!gu(e.list_entry_file,o,t))return r(e.list_entry_file,"The selected list must be reached by one proven rendered component call.");let s=c$(i,o),a=s?Go(o,i,s,"listStrict",t):null;return!s||!a?r(o,"The selected list container does not prove one literal CMS collection."):{complete:!0,slug:s,consumer:a}}function gu(e,t,n,r=!1,o="default"){let i=Tt(n.get(e));if(i===null)return!1;let s=Fe(e,i);if(!s.ok)return!1;let a=Yt({module:s.module,exportName:o,allowNonRenderingGuards:r});if(!a.ok||a.metadataOnly)return!1;let c=Mn(i,{filePath:e,exportName:o}),l=new Set(c.rendered_component_openings.filter(d=>!d.static_render_blockers?.length).map(d=>d.start_offset)),u=d=>{let p=0,g=m=>{if(m.isJSXElement()){let f=m.get("openingElement"),y=f.node.name;if(!M.isJSXIdentifier(y))return;if(!/^[a-z]/u.test(y.name)){let x=f.scope.getBinding(y.name),E=x?.path.parentPath;if(x?.constant&&E?.isImportDeclaration()&&E.node.importKind!=="type"&&(x.path.isImportDefaultSpecifier()||x.path.isImportSpecifier()&&x.path.node.importKind!=="type"&&M.isIdentifier(x.path.node.imported,{name:"default"}))&&typeof f.node.start=="number"&&l.has(f.node.start)&&dn(e,E.node.source.value,n)===t){p++;return}if(!ig(f))return}if(Q0(f.node))return}for(let f of m.get("children"))if(f.isJSXElement()||f.isJSXFragment())g(f);else if(f.isJSXExpressionContainer()){let y=f.get("expression");(y.isJSXElement()||y.isJSXFragment())&&g(y)}};for(let m of d)g(m);return p};return a.returnAlternatives?a.returnAlternatives.every(d=>u([d])===1):u(a.roots)===1}function Q0(e){if(!M.isJSXIdentifier(e.name)||["template","noscript","script","style","head","dialog","details"].includes(e.name.name))return!0;for(let t of e.attributes){if(M.isJSXSpreadAttribute(t)||!M.isJSXIdentifier(t.name))return!0;let n=t.name.name;if(["style","dangerouslySetInnerHTML"].includes(n)||n==="className"&&!M.isStringLiteral(t.value)&&(!M.isJSXExpressionContainer(t.value)||!M.isStringLiteral(t.value.expression)))return!0;if(["hidden","inert","aria-hidden"].includes(n)){let r=t.value;if(n==="aria-hidden"&&M.isStringLiteral(r,{value:"false"})||M.isJSXExpressionContainer(r)&&M.isBooleanLiteral(r.expression,{value:!1}))continue;return!0}}return!1}function dg(e){let t=pg(e.files),n=[],r=[],o=[],i=e.host_capabilities!==void 0||e.trusted_host_file_hashes!==void 0,s=new Map(e.files instanceof Map?e.files.entries():Object.entries(e.files)),a=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."});for(let b of e.source_closure.nodes)b.kind==="source"&&typeof t.get(b.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:b.path,message:"A selected source is missing or is not valid UTF-8 text."});ag(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),ag(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),ag(t,e.collection.detail_view_file,"RELATED_DETAIL_VIEW_MISSING",n),i&&e.list_route_required===void 0&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"A trusted collection analysis must prove whether the caller is a list route."});let c=e.list_route_required??!i,l=c&&$k(e.collection.list_entry_file);c&&!l&&n.push({code:"RELATED_LIST_ROUTE_UNPROVEN",path:e.collection.list_entry_file,message:"The collection caller is not a Next App Router page."}),l&&cg(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),Uk(e.collection.detail_entry_file)?cg(o,{path:e.collection.detail_entry_file,kind:"route",requirementKey:e.collection.requirement_key}):n.push({code:"RELATED_DETAIL_ROUTE_UNPROVEN",path:e.collection.detail_entry_file,message:"The collection detail must be an App Router slug page."});let u=uo({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!G0.safeParse(e.host_capabilities).success)n.push({code:"RELATED_HOST_CAPABILITIES_INVALID",path:"<host-capabilities>",message:"Related-entry ownership requires a valid trusted host contract."});else for(let b of u.nodes){if(b.kind==="external"||Di({node:b,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!x$(b.path))continue;d.add(b.path);let I=s.get(b.path),w=I===void 0?null:`sha256:${W0("sha256").update(I).digest("hex")}`;(!w||e.trusted_host_file_hashes?.get(b.path)!==w)&&n.push({code:"RELATED_HOST_IMPLEMENTATION_UNPROVEN",path:b.path,message:"A related host source requires trusted matching Snapshot provenance."})}for(let b of u.nodes)b.kind==="source"&&typeof t.get(b.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:b.path,message:"A detail source is missing or is not valid UTF-8 text."});u.complete||n.push(...u.errors.map(b=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:b.path,message:b.message})));let p=u.nodes.find(b=>b.path===e.collection.detail_view_file);!p||p.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."}):d.has(e.collection.detail_view_file)?n.push({code:"RELATED_DETAIL_VIEW_NOT_PRIVATE",path:e.collection.detail_view_file,message:"A collection detail entry must be site-owned source."}):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"});let g=i?t$(e.collection,t,s):null,m=e.trusted_schema===void 0?null:n$(e,t,n,e.trusted_schema),f=i&&m&&e.trusted_schema?e$(e.collection,m,e.trusted_schema,t,s):null;for(let b of u.nodes)if(b.kind!=="external"&&b.path!==e.collection.detail_entry_file&&b.path!==e.collection.detail_view_file&&!d.has(b.path)&&!(!l&&b.path===e.collection.list_entry_file)){if(h$(b.path,e.collection)){if(i&&b.path!==g&&b.path!==f){n.push({code:"RELATED_MANAGED_SOURCE_UNPROVEN",path:b.path,message:"A related generated source cannot be omitted based on its pathname alone."});continue}cg(o,{path:b.path,kind:b.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}b$(b.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:b.path,export:{kind:"default"},purpose:"i18n-companion"})}let y=t.get(e.collection.detail_view_file);typeof y=="string"&&m$(y,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=g$(e.page_template,t,n));let x=I$(r).map((b,S)=>({key:k$(b,S),pathTemplate:b.path,export:b.export,purpose:b.purpose,requirementKey:e.collection.requirement_key})),E=_$(n).sort(C$);return{complete:E.length===0,entries:x.sort((b,S)=>b.pathTemplate.localeCompare(S.pathTemplate)||b.purpose.localeCompare(S.purpose)||b.key.localeCompare(S.key)),managed_requirements:o.sort(v$),thin_entry_plan:a,collection_wiring:m,errors:E}}function e$(e,t,n,r,o){let i=Z0.strict().array().min(1).max(200).safeParse(n.fields);if(n.source_slug!==e.slug||t.source_slug!==e.slug||!n.evidence_path.trim()||!/^[a-z0-9][a-z0-9_-]*$/u.test(e.slug)||!i.success)return null;let s=i.data,a=new Set,c=new Set(["id","url","seo"]);for(let E of s){if(!/^[A-Za-z_$][A-Za-z0-9_$]{0,99}$/u.test(E.name)||["__proto__","prototype","constructor"].includes(E.name)||a.has(E.name))return null;if(a.add(E.name),E.front_display==="forbidden")continue;let b=["id","url","seo"].includes(E.name)?`${E.name}_field`:E.name;if(c.has(b))return null;c.add(b)}let l=new Set(t.force_multi_media??[]);for(let E of l){let b=s.find(S=>S.name===E);if(!b||b.front_display==="forbidden"||b.value_shape!=="media_list"&&!["Image","Avatar","Video","File","Audio"].includes(b.cms_type))return null}let u=Tt(r.get(t.list_container_file)),d=Tt(r.get(e.detail_entry_file)),p=fg(e.detail_entry_file);if(u===null||d===null||!p)return null;let g=Go(t.list_container_file,u,e.slug,"listStrict",r),m=Go(e.detail_entry_file,d,e.slug,"getByUrlStrict",r,p),f=`lib/cms/generated/${e.slug}.ts`;if(!g||!m||g.adapter_source!==m.adapter_source||dn(g.path,g.adapter_source,r)!==f||dn(m.path,m.adapter_source,r)!==f)return null;let y=o.get(f);if(y===void 0)return null;let x=Pm(e.slug,s,{forceMultiMedia:l});return typeof y=="string"?y===x?f:null:Buffer.from(y).equals(Buffer.from(x))?f:null}function t$(e,t,n){let r=t.get(e.detail_entry_file),o=fg(e.detail_entry_file);if(typeof r!="string"||!o)return null;let i=Go(e.detail_entry_file,r,e.slug,"getByUrlStrict",t,o);if(!i)return null;let s=hu(i.ast,o),a=Mk(i,t,s);if(!s||!a||a==="unproven")return null;let c=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!gu(i.path,c,t,!0))return null;let l=n.get(c);return l===void 0?null:[void 0,{variant:"floating",shape:"bar"},{variant:"floating",shape:"island"}].some(d=>{let p=Y0({slug:e.slug,detailPrefix:s,...a,headerShell:d});return typeof l=="string"?l===p:Buffer.from(l).equals(Buffer.from(p))})?c:null}function n$(e,t,n,r){let o=n.length,i=r.fields.map(I=>({...I}));(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(I=>I.kind==="source"&&I.status==="complete"&&I.path!==e.collection.list_entry_file).flatMap(I=>{let w=t.get(I.path);if(typeof w!="string")return[];let C=Go(I.path,w,e.collection.slug,"listStrict",t);return C?[C]:[]});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?Pk(a,t,I=>I!==e.collection.detail_view_file):null;c?a&&!mu(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=fg(e.collection.detail_entry_file),d=typeof l=="string"&&u?Go(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t,u):null,p=d?Pk(d,t,I=>I===e.collection.detail_view_file):null;!d||!p||p.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."}):mu(t.get(p.source_path),d.adapter_source,d.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:p.source_path,message:"The rendered detail view does not consume the generated collection interface."}),a&&d&&(a.adapter_source!==d.adapter_source||a.interface_name!==d.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 g=new Set(i.map(I=>I.name)),m=a?dn(a.path,a.adapter_source,t):null,f=m?t.get(m):null,y=[...e.required_fields??i.filter(I=>I.required).map(I=>I.name)].sort(lg),x=[...e.force_multi_media??(typeof f=="string"?Bk(f):[])].sort(lg);for(let I of[...y,...x])g.has(I)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${I}`,message:`Collection field ${I} is not present in the trusted schema.`});if(a&&x.length)for(let I of x)(typeof f!="string"||!p$(f,I))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:m??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${I}.`});let E=d&&u?hu(d.ast,u):null;E||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 b=d?f$(d.ast):null;b||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 S=d?Mk(d,t,E):null;return S==="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||!d||!p||!E?null:{source_slug:e.collection.slug,detail_prefix:E,schema:i,schema_evidence_path:r.evidence_path,list_container_file:a.path,list_view:{...c,interface_name:a.interface_name},detail_view:{...p,interface_name:d.interface_name},...b?{title:b}:{},...S&&S!=="unproven"?{breadcrumb:S}:{},...y.length>0?{required_fields:y}:{},...x.length>0?{force_multi_media:x}:{}}}function Go(e,t,n,r,o,i=`/${n}`){let s;try{s=xo(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=yo(s,u=>M.isCallExpression(u)&&Yo(u.callee,r));if(!a$(s,e,o,r)||r==="listStrict"&&(a.length!==1||!M.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||hu(s,i)===null))return null;let l=s.program.body.flatMap(u=>M.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!M.isImportSpecifier(d))return[];let p=M.isIdentifier(d.imported)?d.imported.name:d.imported.value,g=/^to([A-Za-z_$][A-Za-z0-9_$]*View)$/u.exec(p);return g?[{source:u.source.value,local_name:d.local.name,interface_name:g[1]}]:[]}):[]).filter(u=>yo(s,d=>M.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!r$(s,e,o,l[0],r,n)?null:{path:e,source:t,ast:s,adapter_source:l[0].source,interface_name:l[0].interface_name}}function r$(e,t,n,r,o,i){let s=!1;return ma(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!M.isJSXIdentifier(a.node.name)||a.node.attributes.some(x=>M.isJSXSpreadAttribute(x)))return;let l=a.parentPath;for(;l&&!l.isReturnStatement()&&!l.isFunction();){if(l.isVariableDeclarator()||l.isJSXAttribute()||l.isConditionalExpression()||l.isLogicalExpression()||l.isCallExpression()||l.isJSXElement()&&l.node!==a.parentPath.node&&(!M.isJSXIdentifier(l.node.openingElement.name)||!/^[a-z]/u.test(l.node.openingElement.name.name)))return;l=l.parentPath}if(!l?.isReturnStatement()||l.getFunctionParent()!==c||l.parentPath!==c.get("body"))return;let u=a.scope.getBinding(a.node.name.name),d=u?.path,p=d?.parentPath;if(!u?.constant||!p?.isImportDeclaration()||p.node.importKind==="type"||d?.isImportSpecifier()&&d.node.importKind==="type"||!(d?.isImportDefaultSpecifier()||d?.isImportSpecifier()))return;let g=dn(t,p.node.source.value,n);if(!g||!mu(n.get(g),r.source,r.interface_name))return;let m=a.get("attributes").filter(x=>x.isJSXAttribute()&&M.isJSXIdentifier(x.node.name,{name:o==="listStrict"?"records":"record"}));if(m.length!==1||!m[0].isJSXAttribute())return;let f=m[0].get("value");if(!f.isJSXExpressionContainer())return;let y={opening:a,attribute:o==="listStrict"?"records":"record",file:t,files:n};(o==="listStrict"?Lk(f.get("expression"),c,r,i,y,new Set):Fk(f.get("expression"),c,r,y,new Set))&&(s=!0)}}),s}function Lk(e,t,n,r,o,i){if(!e.node||i.has(e.node)||i.size>=32)return!1;if(i.add(e.node),e.isIdentifier()){let m=e.scope.getBinding(e.node.name);return!m?.constant||!m.path.isVariableDeclarator()||m.path.getFunctionParent()!==t||!m.path.parentPath.isVariableDeclaration({kind:"const"})||pa(m.referencePaths,n,o)?!1:Lk(m.path.get("init"),t,n,r,o,i)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let s=e.get("callee");if(!s.isMemberExpression()||s.node.computed||!M.isIdentifier(s.node.property,{name:"map"}))return!1;let a=e.get("arguments")[0];if(!a||!pu(a,n))return!1;let c=s.get("object");if(c.isConditionalExpression()){let m=c.get("consequent"),f=c.get("alternate"),y=x=>x.isArrayExpression()&&x.node.elements.length===0;if(y(m))c=f;else if(y(f))c=m;else return!1}if(!c.isMemberExpression()||c.node.computed||!M.isIdentifier(c.node.property,{name:"items"}))return!1;let l=c.get("object");if(!l.isMemberExpression()||l.node.computed||!M.isIdentifier(l.node.property,{name:"data"}))return!1;let u=l.get("object");if(!u.isIdentifier())return!1;let d=u.scope.getBinding(u.node.name);if(!d?.constant||!d.path.isVariableDeclarator()||d.path.getFunctionParent()!==t||!d.path.parentPath.isVariableDeclaration({kind:"const"})||pa(d.referencePaths,n,null))return!1;let p=d.path.get("init");if(!p.isAwaitExpression())return!1;let g=p.get("argument");return g.isCallExpression()&&Yo(g.node.callee,"listStrict")&&M.isStringLiteral(g.node.arguments[0],{value:r})}function Fk(e,t,n,r,o){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(o.add(e.node),e.isIdentifier()){let d=e.scope.getBinding(e.node.name);return!d?.constant||!d.path.isVariableDeclarator()||d.path.getFunctionParent()!==t||!d.path.parentPath.isVariableDeclaration({kind:"const"})||pa(d.referencePaths,n,r)?!1:Fk(d.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!pu(i,n))return!1;let s=e.get("arguments")[0];if(!s?.isMemberExpression()||s.node.computed||!M.isIdentifier(s.node.property,{name:"data"}))return!1;let a=s.get("object");if(!a.isIdentifier())return!1;let c=a.scope.getBinding(a.node.name);if(!c?.constant||!c.path.isVariableDeclarator()||c.path.getFunctionParent()!==t||!c.path.parentPath.isVariableDeclaration({kind:"const"})||pa(c.referencePaths,n,null))return!1;let l=c.path.get("init");if(!l.isAwaitExpression())return!1;let u=l.get("argument");return u.isCallExpression()&&Yo(u.node.callee,"getByUrlStrict")}function pu(e,t){if(!e.isIdentifier({name:t.local_name}))return!1;let n=e.scope.getBinding(e.node.name),r=n?.path,o=r?.parentPath;return!(!n?.constant||!r?.isImportSpecifier()||r.node.importKind==="type"||!M.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function pa(e,t,n,r=new Set){return r.size>=32||e.length>256?!0:e.some(o=>{let i=o;for(;i.parentPath;){let a=i.parentPath;if((a.isMemberExpression()||a.isOptionalMemberExpression())&&a.node.object===i.node||a.isConditionalExpression()&&a.node.test!==i.node||a.isLogicalExpression()||a.isTSAsExpression()||a.isTSSatisfiesExpression()||a.isTSNonNullExpression()||a.isParenthesizedExpression()){i=a;continue}break}let s=i.parentPath;if(s?.isVariableDeclarator()&&s.node.init===i.node){if(!M.isIdentifier(s.node.id))return!0;let a=s.scope.getBinding(s.node.id.name);return a?.constant?r.has(a.identifier)?!1:(r.add(a.identifier),pa(a.referencePaths,t,n,r)):!0}if(s?.isCallExpression()||s?.isOptionalCallExpression()){if(!s.isCallExpression()||s.node.arguments.length!==1)return!0;if(s.node.callee===i.node){let c=s.get("callee"),l=s.get("arguments")[0];return!(c.isMemberExpression()&&!c.node.computed&&M.isIdentifier(c.node.property,{name:"map"})&&l&&pu(l,t))}let a=s.get("callee");return!(i.isMemberExpression()&&!i.node.computed&&M.isIdentifier(i.node.property,{name:"data"})&&pu(a,t))}if(s?.isJSXExpressionContainer()){let a=s.parentPath;return n?.attribute==="record"&&i.isMemberExpression()&&i.node.object===o.node&&!i.node.computed&&M.isIdentifier(i.node.property)&&a?.isJSXAttribute()&&o$(a,i.node.property.name,t,n)?!1:!(n&&a?.isJSXAttribute()&&a.parentPath===n.opening&&M.isJSXIdentifier(a.node.name,{name:n.attribute})&&i===o)}return!!(s?.isAssignmentExpression()||s?.isReturnStatement()||s?.isArrowFunctionExpression()||s?.isYieldExpression()||s?.isSpreadElement()||s?.isObjectProperty()&&s.parentPath?.isObjectPattern()||s?.isArrayPattern()||s?.isAssignmentPattern()||s?.isRestElement()||s?.isArrayExpression()||s?.isObjectProperty()&&s.parentPath?.isObjectExpression()||s?.isUpdateExpression()||s?.isUnaryExpression()&&s.node.operator==="delete")})}function o$(e,t,n,r){if(["__proto__","prototype","constructor"].includes(t)||!M.isJSXIdentifier(e.node.name)||["key","ref"].includes(e.node.name.name))return!1;let o=e.parentPath;if(!o?.isJSXOpeningElement()||!M.isJSXIdentifier(o.node.name)||/^[a-z]/u.test(o.node.name.name)||o.node.attributes.some(d=>M.isJSXSpreadAttribute(d)))return!1;let i=o.scope.getBinding(o.node.name.name);if(!i?.constant||!i.path.isImportDefaultSpecifier())return!1;let s=i.path.parentPath;if(!s.isImportDeclaration()||s.node.importKind==="type")return!1;let a=dn(r.file,s.node.source.value,r.files),c=dn(r.file,n.source,r.files),l=a?r.files.get(a):void 0,u=c?r.files.get(c):void 0;return typeof l!="string"||typeof u!="string"?!1:i$(l,a)&&s$(u,c,`to${n.interface_name}`,t)}function i$(e,t){let n=Fe(t,e);if(!n.ok||n.module.ast.program.body.length!==1)return!1;let r=n.module.ast.program.body[0];if(!M.isExportDefaultDeclaration(r)||!M.isFunctionDeclaration(r.declaration)||r.declaration.params.length!==0||r.declaration.async||r.declaration.generator)return!1;let o=!1;return ma(n.module.ast,{Function(i){i.node!==r.declaration&&(o=!0)},ReferencedIdentifier(i){let s=i.node.name,a=i.scope.getBinding(s);(["arguments","eval","undefined"].includes(s)||!a?.constant||!a.path.isVariableDeclarator()||!a.path.parentPath.isVariableDeclaration({kind:"const"}))&&(o=!0)},MemberExpression(i){let s=i.get("object"),a=s.isIdentifier()?s.scope.getBinding(s.node.name):null;(i.node.computed||!M.isIdentifier(i.node.property,{name:"length"})||!a?.constant||!a.path.isVariableDeclarator()||!M.isArrayExpression(a.path.node.init))&&(o=!0)},OptionalMemberExpression(){o=!0},ObjectProperty(i){i.node.computed&&(o=!0)},VariableDeclarator(i){M.isIdentifier(i.node.id)||(o=!0)},SpreadElement(){o=!0},BinaryExpression(i){["===","!=="].includes(i.node.operator)||(o=!0)},TemplateLiteral(i){i.node.expressions.length>0&&(o=!0)},UnaryExpression(i){["!","typeof","void"].includes(i.node.operator)||(o=!0)},ForInStatement(){o=!0},ForOfStatement(){o=!0},ForStatement(){o=!0},WhileStatement(){o=!0},DoWhileStatement(){o=!0},CallExpression(){o=!0},OptionalCallExpression(){o=!0},NewExpression(){o=!0},TaggedTemplateExpression(){o=!0},AssignmentExpression(){o=!0},UpdateExpression(){o=!0},AwaitExpression(){o=!0},YieldExpression(){o=!0},ThrowStatement(){o=!0},ThisExpression(){o=!0},Super(){o=!0},JSXSpreadAttribute(){o=!0},JSXExpressionContainer(i){let s=i.node.expression;!M.isStringLiteral(s)&&!M.isNumericLiteral(s)&&!M.isBooleanLiteral(s)&&!M.isNullLiteral(s)&&!M.isJSXEmptyExpression(s)&&!(M.isMemberExpression(s)&&M.isJSXElement(i.parentPath.node))&&(o=!0)},JSXOpeningElement(i){(!M.isJSXIdentifier(i.node.name)||!["nav","div","section","span","p","h1","h2","h3","ol","ul","li","strong","em"].includes(i.node.name.name)||i.node.attributes.some(s=>!M.isJSXAttribute(s)||!M.isJSXIdentifier(s.name)||!["className","id","role","title","aria-label"].includes(s.name.name)))&&(o=!0)}}),!o}function s$(e,t,n,r){let o=Fe(t,e);if(!o.ok)return!1;let i=o.module.ast.program.body.filter(d=>M.isExportNamedDeclaration(d)&&M.isFunctionDeclaration(d.declaration)&&d.declaration.id?.name===n);if(i.length!==1)return!1;let s=i[0].declaration;if(!M.isFunctionDeclaration(s)||s.async||s.generator)return!1;let a=!1;if(ma(o.module.ast,{Program(d){let p=d.scope.getBinding(n);a=!!(p?.constant&&p.path.node===s),d.stop()}}),!a)return!1;let c=yo(s.body,d=>M.isReturnStatement(d)),l=s.body.body.at(-1);if(c.length!==1||!M.isReturnStatement(l)||l!==c[0]||!M.isObjectExpression(l.argument))return!1;let u=new Set;for(let d of l.argument.properties){if(!M.isObjectProperty(d)||d.computed||!(M.isIdentifier(d.key)||M.isStringLiteral(d.key)))return!1;let p=M.isIdentifier(d.key)?d.key.name:d.key.value;if(["__proto__","prototype","constructor"].includes(p)||u.has(p))return!1;u.add(p)}return u.has(r)}function a$(e,t,n,r){let o=0,i=In(e,"cms");for(let s of e.program.body){if(!M.isImportDeclaration(s)||s.importKind==="type")continue;let a=dn(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(M.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!M.isImportSpecifier(c))return!0;let l=M.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return ma(e,{CallExpression(s){if(!Yo(s.node.callee,r))return;o+=1;let a=s.scope.getBinding("cms"),c=a?.path,l=c?.parentPath;if(!a?.constant||!c?.isImportSpecifier()||c.node.importKind==="type"||!M.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=dn(t,l.node.source.value,n);(!u||!/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(u)||a.referencePaths.some(d=>{let p=d.parentPath,g=p?.parentPath,m=g?.parentPath;return!(p?.isMemberExpression()&&p.node.object===d.node&&!p.node.computed&&M.isIdentifier(p.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===p.node&&!g.node.computed&&M.isIdentifier(g.node.property)&&m?.isCallExpression()&&m.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function c$(e,t){let n;try{n=xo(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=yo(n,o=>M.isCallExpression(o)&&Yo(o.callee,"listStrict")&&M.isStringLiteral(o.arguments[0])).map(o=>o.arguments[0].value);return r.length===1&&/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(r[0])?r[0]:null}function l$(e,t,n){let r;try{r=xo(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return yo(r,o=>M.isCallExpression(o)&&Yo(o.callee,n)).length>0}function Pk(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=dn(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!Dk(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 Dk(e,t){let n;try{n=xo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&M.isExportDefaultDeclaration(r))return!0;if(M.isExportNamedDeclaration(r)&&(r.declaration&&(M.isFunctionDeclaration(r.declaration)||M.isClassDeclaration(r.declaration)||M.isTSInterfaceDeclaration(r.declaration)||M.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||M.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>M.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>M.isExportSpecifier(o)?(M.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function mu(e,t,n){if(typeof e!="string")return!1;let r;try{r=xo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!M.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>M.isImportSpecifier(s)?(M.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>yo(r,s=>M.isIdentifier(s,{name:i})).length>1)}function Yo(e,t){return M.isMemberExpression(e)&&!e.computed&&M.isIdentifier(e.property,{name:t})&&M.isMemberExpression(e.object)&&!e.object.computed&&M.isIdentifier(e.object.property,{name:"collections"})&&M.isIdentifier(e.object.object,{name:"cms"})}function hu(e,t){let n=[];return ma(e,{CallExpression(r){Yo(r.node.callee,"getByUrlStrict")&&n.push(u$(r.node.arguments[0],o=>d$(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function u$(e,t){return M.isBinaryExpression(e,{operator:"+"})&&M.isStringLiteral(e.left)&&M.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):M.isTemplateLiteral(e)&&e.expressions.length===1&&M.isIdentifier(e.expressions[0])&&t(e.expressions[0].name)&&e.quasis[1]?.value.cooked===""&&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 d$(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(M.isObjectPattern(r.id)&&M.isAwaitExpression(r.init)&&M.isIdentifier(r.init.argument))return r.id.properties.some(a=>M.isObjectProperty(a)&&!a.computed&&yu(a.key)==="slug"&&M.isIdentifier(a.value,{name:t}))&&Nk(n.path,r.init.argument.name);let o=r.init;if(!M.isIdentifier(r.id,{name:t})||!M.isCallExpression(o)||!M.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!M.isIdentifier(i.path.node.imported,{name:"decodeRouteSlug"})||!i.path.parentPath.isImportDeclaration()||i.path.parentPath.node.source.value!=="@/lib/cms")return!1;let s=o.arguments[0];return M.isMemberExpression(s)&&!s.computed&&M.isIdentifier(s.property,{name:"slug"})&&M.isAwaitExpression(s.object)&&M.isIdentifier(s.object.argument)&&Nk(n.path,s.object.argument.name)}function Nk(e,t){let n=e.scope.getBinding(t);if(!n?.constant||n.kind!=="param")return!1;let r=n.path.getFunctionParent();if(!r||!r.isFunctionDeclaration())return!1;let o=r.parentPath;return!o.isExportDefaultDeclaration()&&!(o.isExportNamedDeclaration()&&r.node.id?.name==="generateMetadata")?!1:r.node.params.some(i=>M.isObjectPattern(i)&&i.properties.some(s=>M.isObjectProperty(s)&&!s.computed&&yu(s.key)==="params"&&M.isIdentifier(s.value,{name:t})))}function f$(e){for(let t of e.program.body)if(M.isVariableDeclaration(t))for(let n of t.declarations){if(!M.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=jk(n.init);if(!M.isObjectExpression(r))return null;let o=r.properties.find(i=>M.isObjectProperty(i)&&!i.computed&&yu(i.key)==="title");return o&&M.isStringLiteral(o.value)?o.value.value:null}return null}function Mk(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=dn(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=xo(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of yo(a,l=>M.isArrayExpression(l))){let l=c.elements.flatMap(p=>{if(!M.isObjectExpression(p))return[];let g=new Map;for(let m of p.properties){if(!M.isObjectProperty(m)||m.computed)continue;let f=yu(m.key);f&&M.isStringLiteral(m.value)&&g.set(f,m.value.value)}return g.has("name")&&g.has("href")?[g]:[]}),u=l.find(p=>p.get("href")==="/"),d=l.find(p=>p.get("href")===n);if(u&&d)return{homeLabel:u.get("name"),collectionLabel:d.get("name")}}return"unproven"}function Bk(e){let t;try{t=xo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(yo(t,n=>{if(!M.isCallExpression(n))return!1;let r=n.callee;if(!M.isMemberExpression(r)||r.computed||!M.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return M.isMemberExpression(o)&&!o.computed&&M.isIdentifier(o.object,{name:"d"})&&M.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return M.isMemberExpression(r)&&!r.computed&&M.isIdentifier(r.property)?[r.property.name]:[]}))].sort(lg)}function p$(e,t){return Bk(e).includes(t)}function yo(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)Ak(s)&&r(s);else Ak(i)&&r(i)};return r(e),n}function Ak(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function jk(e){return e?M.isTSAsExpression(e)||M.isTSTypeAssertion(e)||M.isTSNonNullExpression(e)?jk(e.expression):e:null}function yu(e){return M.isIdentifier(e)?e.name:M.isStringLiteral(e)?e.value:null}function lg(e,t){return e.localeCompare(t)}function m$(e,t,n,r,o,i){let s=Mn(e,{filePath:t,exportName:"default"});for(let a of s.components){let c=dn(t,a.source,r);if(!c||i.has(c))continue;let l=n.find(d=>d.path===c),u=r.get(c);!l||l.kind==="external"||typeof u!="string"||E$(u)&&o.push({path:c,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function g$(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 ag(e,t,n,r){typeof e.get(t)!="string"&&r.push({code:n,path:t,message:`Portable related-entry analysis could not read ${t}.`})}function h$(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 $k(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function Uk(e){return $k(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function y$(e,t){return/^\/[A-Za-z0-9_-]+$/u.test(t)?[`app${t}/[slug]/page`,`src/app${t}/[slug]/page`].some(n=>e.startsWith(n)&&/^\.[cm]?[jt]sx?$/u.test(e.slice(n.length))):!1}function fg(e){let t=/^(?:src\/)?app\/([A-Za-z0-9_-]+)\/\[slug\]\/page\.[cm]?[jt]sx?$/u.exec(e);return t?`/${t[1]}`:null}function x$(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function b$(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=Vk(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 E$(e){try{return xo(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function dn(e,t,n){if(!mt(t))return null;let r=t.startsWith("@/")?t.slice(2):S$(`${Vk(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 Vk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function S$(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 pg(e){let t=e instanceof Map?e.entries():Object.entries(e);return new class extends Map{get(n){let r=super.get(n);if(r===void 0||!/\.[cm]?[jt]sx?$/iu.test(n))return r;let o=Tt(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function I$(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 cg(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function v$(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function k$(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function _$(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function C$(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import{parse as Hk}from"@babel/parser";import mg from"@babel/traverse";import*as we from"@babel/types";var R$=typeof mg=="function"?mg:mg.default,P$=Hk(`
42
+ async function list({ searchParams }) {
43
+ const sp = (await searchParams) ?? {};
44
+ const pageValue = typeof sp.page === "string" ? sp.page : undefined;
45
+ const page = Number(pageValue ?? 1) || 1;
46
+ const category = typeof sp.category === "string" && sp.category !== "" ? sp.category : undefined;
47
+ }
48
+ `).program.body[0],Jk=P$.body.body;function Wk(e,t,n){let r;try{r=Hk(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=[];R$(r,{ExportDefaultDeclaration(f){let y=f.get("declaration");(y.isFunctionDeclaration()||y.isFunctionExpression()||y.isArrowFunctionExpression())&&o.push(y)}});let i=o.length===1?o[0]:void 0;if(!i||!we.isBlockStatement(i.node.body))return null;let s=i.node.body.body,a=zk(i.node,f=>we.isCallExpression(f)&&Kk(f,"listStrict",n));if(a.length!==1||a[0].arguments.length!==2)return null;let c=a[0],l=s.findIndex(f=>Xk(f,c));if(l<0)return null;let u=c.arguments[1];if(!we.isObjectExpression(u))return null;let d=new Map;for(let f of u.properties){if(!we.isObjectProperty(f)||f.computed)return null;let y=we.isIdentifier(f.key)?f.key.name:we.isStringLiteral(f.key)?f.key.value:null;if(!y||!["page","pageSize","category"].includes(y)||d.has(y)||!we.isExpression(f.value))return null;d.set(y,f.value)}let p=d.get("page"),g=d.get("pageSize");if(!p||!we.isNumericLiteral(g)||!Number.isSafeInteger(g.value)||g.value<1||g.value>100)return null;let m=zk(i.node,f=>we.isCallExpression(f)&&Kk(f,"categories",n));return d.has("category")?!we.isIdentifier(p,{name:"page"})||!we.isIdentifier(d.get("category"),{name:"category"})||m.length!==1||m[0].arguments.length!==1||!Xk(s[l+1],m[0])||!A$(i,s.slice(0,l))?null:{paginate:!0,limit:g.value}:m.length||!N$(p,s.slice(0,l),i)?null:{paginate:!1,limit:g.value}}function Kk(e,t,n){let r=e.callee;return we.isMemberExpression(r)&&!r.computed&&we.isIdentifier(r.property,{name:t})&&we.isMemberExpression(r.object)&&!r.object.computed&&we.isIdentifier(r.object.property,{name:"collections"})&&we.isIdentifier(r.object.object,{name:"cms"})&&we.isStringLiteral(e.arguments[0],{value:n})}function Xk(e,t){return!!(we.isVariableDeclaration(e,{kind:"const"})&&e.declarations.length===1&&we.isIdentifier(e.declarations[0].id)&&we.isAwaitExpression(e.declarations[0].init)&&e.declarations[0].init.argument===t)}function N$(e,t,n){if(n.scope.getBinding("searchParams")?.referencePaths.length)return!1;if(we.isNumericLiteral(e,{value:1}))return t.length===0;if(!we.isIdentifier(e)||t.length!==1)return!1;let o=t[0];if(!we.isVariableDeclaration(o,{kind:"const"})||o.declarations.length!==1)return!1;let i=o.declarations[0],s=n.scope.getBinding(e.name);return!!(we.isIdentifier(i.id,{name:e.name})&&we.isNumericLiteral(i.init,{value:1})&&s?.identifier===i.id&&s.constant)}function A$(e,t){if(t.length!==Jk.length||!t.every((u,d)=>we.isNodesEquivalent(u,Jk[d]))||e.scope.getBinding("Number")||e.scope.getBinding("undefined"))return!1;let n=e.node.params[0];if(!we.isObjectPattern(n)||n.properties.length!==1||!we.isObjectProperty(n.properties[0])||n.properties[0].computed||!we.isIdentifier(n.properties[0].key,{name:"searchParams"})||!we.isIdentifier(n.properties[0].value,{name:"searchParams"}))return!1;let r=t.map(u=>we.isVariableDeclaration(u)?u.declarations[0]:void 0),[o,i,s,a]=r;if(!o?.init||!i?.init||!s?.init||!a?.init)return!1;let c=["sp","pageValue","page","category"].map(u=>e.scope.getBinding(u));if(c.some((u,d)=>!u?.constant||u.identifier!==r[d]?.id))return!1;let l=e.scope.getBinding("searchParams");return!(!l?.constant||l.identifier!==n.properties[0].value||!gg(l.referencePaths,[o.init])||!gg(c[0].referencePaths,[i.init,a.init])||!gg(c[1].referencePaths,[s.init]))}function gg(e,t){return e.every(n=>!!n.findParent(r=>t.includes(r.node)))}function zk(e,t){let n=[],r=o=>{if(!(o!==e&&we.isFunction(o))){t(o)&&n.push(o);for(let i of we.VISITOR_KEYS[o.type]??[]){let s=o[i];if(Array.isArray(s))for(let a of s)we.isNode(a)&&r(a);else we.isNode(s)&&r(s)}}};return r(e),n}var w$=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),O$=new Set(["data-vcp-block-id","data-vcp-edit-key"]),L$=new Set(["data-vcp-order","sourceOrder","source_order"]);function Vi(e){let t=p=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...p].sort(ha)}),n;try{n=yg(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(p){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:p instanceof Error?p.message:String(p)}])}let r=V$(n),o=Mn(e.source,{filePath:e.file_path,exportName:e.export_name??"default"}),i=o.diagnostics.map(p=>({code:"INVOCATION_RENDER_GRAPH_INCOMPLETE",path:p.file_path||e.file_path,message:p.message})),s=new Set(o.rendered_component_openings.filter(p=>p.source===e.target.source&&p.export_name===e.target.export_name).map(p=>p.start_offset)),a=[],c=0;if(bu(n,new Set,(p,g)=>{if(!ie.isJSXElement(p))return;let m=p.openingElement,f=m.start;if(typeof f!="number"||e.call_source_range&&(m.loc?.start.line!==e.call_source_range.start_line||m.loc.start.column!==e.call_source_range.start_column))return;let y=n_(m.name);if(!y)return;let x=X$(m.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(f)&&a.push({node:m,element:p,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(p=>Qk(e,p.node,p.element,{kind:"import",component_source:p.local.source,export_name:p.local.export_name,local_name:p.local.local_name},p.context,p.ordinal)),u=e_(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:bg(d).sort(ha)}}function qk(e){let t=a=>({complete:!1,entry_file:e.file_path,target:e.target,call:null,bindings:[],original_block_id:null,original_order:null,semantic_props:{},errors:[...a].sort(ha)}),n;try{n=yg(e.source,{sourceType:"module",sourceFilename:e.file_path,plugins:["jsx","typescript"]})}catch(a){return t([{code:"INVOCATION_PARSE_FAILED",path:e.file_path,message:a instanceof Error?a.message:String(a)}])}let r=[],o=0;if(bu(n,new Set,(a,c)=>{if(!ie.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||n_(l.name)!==e.target.local_name)return;let u=o++;e.call_source_range&&(l.loc?.start.line!==e.call_source_range.start_line||l.loc.start.column!==e.call_source_range.start_column)||r.push({node:l,element:a,context:c,ordinal:u})}),r.length===0)return t([{code:"INVOCATION_TARGET_NOT_RENDERED",path:e.file_path,message:`The selected local component call is not a statically rendered Page Unit in ${e.file_path}.`}]);let i=r.map(a=>Qk(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=e_(i,e.target.original_block_id);return s?{complete:s.errors.length===0,entry_file:e.file_path,target:e.target,call:s.call,bindings:s.errors.length===0?s.bindings:[],original_block_id:s.original_block_id,original_order:s.original_order,semantic_props:s.semantic_props,errors:bg(s.errors).sort(ha)}:t([{code:"INVOCATION_TARGET_AMBIGUOUS",path:e.file_path,message:"The selected local component is rendered more than once and no unique original block identity was provided."}])}function F$(e){let t;try{t=yg(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=Vn({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=>Vi({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 D$(e){let t=Vi(e),n=B$(e.files),r=j$(e.file_path,e.target.source,n),o=r?Tt(n.get(r)):null,i=r&&typeof o=="string"?Wk(o,r,e.collection.slug):null,s=dg({files:e.files,source_closure:e.source_closure,collection:e.collection,list_route_required:i?.paginate??!1,trusted_schema:e.trusted_schema,...e.host_capabilities===void 0?{}:{host_capabilities:e.host_capabilities},...e.trusted_host_file_hashes===void 0?{}:{trusted_host_file_hashes:e.trusted_host_file_hashes},...e.required_fields?{required_fields:e.required_fields}:{},...e.force_multi_media?{force_multi_media:e.force_multi_media}:{}}),a=[...t.errors],c=[];e.file_path!==e.collection.list_entry_file&&a.push({code:"COLLECTION_LIST_CONTAINER_UNPROVEN",path:e.file_path,message:"The selected invocation must belong to the proven collection caller."}),e.source_closure.complete||a.push({code:"COLLECTION_SOURCE_CLOSURE_INCOMPLETE",path:e.collection.list_entry_file,message:"Collection recipe analysis requires a complete selected source closure."});for(let p of s.errors)a.push({code:M$(p.code),path:p.path,message:p.message});t.call&&c.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 l=s.collection_wiring;if(!r)a.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(!i)a.push({code:"COLLECTION_PAGINATION_UNPROVEN",path:r,message:"The collection list container must expose one literal pageSize with statically provable searchParams behavior."});else{c.push({fact:"pagination",path:r,reason:i.paginate?`listStrict consumes route searchParams with literal pageSize ${i.limit}.`:`listStrict is embedded and uses literal top-N ${i.limit}.`});let p=t.bindings.filter(g=>g.propName==="searchParams"&&g.value.kind==="route-search-params");(i.paginate&&p.length!==1||!i.paginate&&p.length!==0)&&a.push({code:"COLLECTION_SEARCH_PARAMS_MISMATCH",path:`${e.file_path}:searchParams`,message:i.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})}l&&r!==l.list_container_file&&a.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(l&&i&&a.length===0){let p={source_slug:l.source_slug,list_mode:i.paginate?"page":"embedded",paginate:i.paginate,...i.paginate?{page_size:i.limit}:{top_n:i.limit},detail_prefix:l.detail_prefix,schema:l.schema.map(m=>({...m})),list_view:{...l.list_view},detail_view:{...l.detail_view},...l.title?{title:l.title}:{},...l.breadcrumb?{breadcrumb:{...l.breadcrumb}}:{},...l.required_fields?{required_fields:[...l.required_fields]}:{},...l.force_multi_media?{force_multi_media:[...l.force_multi_media]}:{},list_route_required:i.paginate},g=T$.safeParse(p);g.success?(u=g.data,c.push({fact:"detail-route",path:e.collection.detail_entry_file,reason:`The rendered detail consumer proves literal prefix ${l.detail_prefix}.`},{fact:"list-view",path:l.list_view.source_path,reason:`The list container renders ${l.list_view.export_name} with ${l.list_view.interface_name}.`},{fact:"detail-view",path:l.detail_view.source_path,reason:`The detail route renders ${l.detail_view.export_name} with ${l.detail_view.interface_name}.`},{fact:"schema",path:l.schema_evidence_path,reason:"The complete CMS schema is supplied by the trusted application projection."})):a.push({code:"COLLECTION_RECIPE_INVALID",path:`collection-recipe:${l.source_slug}`,message:g.error.issues[0]?.message??"Observed collection facts do not satisfy the portable recipe contract."})}let d=bg(a).sort(ha);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:c.sort(U$),related_entries:s}}function M$(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_ROUTE_UNPROVEN"||e==="RELATED_DETAIL_VIEW_MISSING"||e==="RELATED_DETAIL_VIEW_NOT_REACHED"||e==="RELATED_DETAIL_SOURCE_INCOMPLETE"?"COLLECTION_DETAIL_CONSUMER_UNPROVEN":"COLLECTION_VIEW_UNPROVEN"}function B$(e){return e instanceof Map?e:new Map(Object.entries(e))}function j$(e,t,n){if(!mt(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):$$(`${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 $$(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function U$(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function V$(e){let t=new Map;for(let n of e.program.body){if(!ie.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(ie.isIdentifier(o.local)){if(ie.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(ie.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(ie.isImportSpecifier(o)){let i=ie.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 Qk(e,t,n,r,o,i){let s=W$(t),a=[],c=[],l={},u=new Set,d=null,p=null,g=(f,y)=>{if(u.has(f)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${f}`,message:`Portable invocation contains duplicate prop ${f}.`,source_range:s});return}u.add(f),c.push({propName:f,value:y}),(f==="type"||f==="variant")&&y.kind==="json-literal"&&(l[f]=y.value)};for(let f of t.attributes){if(ie.isJSXSpreadAttribute(f)){let S=bo(f.argument);if(!S.ok||!t_(S.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[I,w]of Object.entries(S.value)){if(!Yk(I)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${I}`,message:`Portable invocation cannot encode prop ${I}.`,source_range:s});continue}g(I,hg(w))}continue}let y=z$(f.name);if(!y)continue;let x=f.value,E=x&&ie.isJSXExpressionContainer(x)?x.expression:null;if(O$.has(y)){let S=x?xu(x):{ok:!0,value:!0};!S.ok||typeof S.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=S.value;continue}if(L$.has(y)){let S=x?xu(x):{ok:!0,value:!0};!S.ok||typeof S.value!="number"||!Number.isSafeInteger(S.value)?a.push({code:"INVOCATION_ORDER_UNRESOLVED",path:`${e.file_path}:${y}`,message:"Portable invocation requires a literal original order.",source_range:s}):p=S.value;continue}if(!Yk(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if(w$.has(y)){let S=x?xu(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&Gk(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&&Gk(E,o)){g(y,{kind:"route-search-params"});continue}let b=x?xu(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,hg(b.value))}let m=J$(n);return m.ok?m.value!==void 0&&g("children",hg(m.value)):a.push({code:"INVOCATION_CHILDREN_UNRESOLVED",path:`${e.file_path}:children`,message:m.message,source_range:s}),{call:r.kind==="local"?{kind:"local",source_file:e.file_path,local_name:r.local_name,ordinal:i,source_range:s}:{source_file:e.file_path,component_source:r.component_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:p,semantic_props:l,errors:a}}function e_(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 xu(e){return e===null?{ok:!0,value:!0}:ie.isStringLiteral(e)?{ok:!0,value:e.value}:ie.isJSXExpressionContainer(e)?bo(e.expression):{ok:!1}}function bo(e){if(!e)return{ok:!1};if(ie.isStringLiteral(e))return{ok:!0,value:e.value};if(ie.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(ie.isBooleanLiteral(e))return{ok:!0,value:e.value};if(ie.isNullLiteral(e))return{ok:!0,value:null};if(ie.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(ie.isTSAsExpression(e)||ie.isTSTypeAssertion(e)||ie.isTSNonNullExpression(e))return bo(e.expression);if(ie.isUnaryExpression(e)){let t=bo(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(ie.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=bo(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(ie.isObjectExpression(e)){let t={};for(let n of e.properties){if(ie.isSpreadElement(n)){let i=bo(n.argument);if(!i.ok||!t_(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!ie.isObjectProperty(n)||n.computed)return{ok:!1};let r=H$(n.key);if(!r)return{ok:!1};let o=bo(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function J$(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of ie.react.buildChildren(e)){let r=bo(n);if(!r.ok)return{ok:!1,message:"Portable invocation cannot preserve dynamic JSX children."};t.push(r.value)}return t.length===0?{ok:!0,value:void 0}:{ok:!0,value:t.length===1?t[0]:t}}function bu(e,t,n){let r=r_(e)?new Set([...t,...K$(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)Zk(i)&&bu(i,r,n);else Zk(o)&&bu(o,r,n)}function K$(e){if(!r_(e))return[];let t=[];for(let n of e.params)ga(n,t);return t}function ga(e,t){if(ie.isIdentifier(e)){t.push(e.name);return}if(ie.isAssignmentPattern(e)){ga(e.left,t);return}if(ie.isObjectPattern(e)){for(let n of e.properties)ie.isRestElement(n)?ga(n.argument,t):ie.isObjectProperty(n)&&ga(n.value,t);return}if(ie.isArrayPattern(e))for(let n of e.elements)n&&ga(n,t)}function Gk(e,t){return ie.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):ie.isMemberExpression(e)&&!e.computed&&ie.isIdentifier(e.property)&&e.property.name==="searchParams"&&ie.isIdentifier(e.object)&&t.names.has(e.object.name)}function hg(e){return{kind:"json-literal",value:e}}function t_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yk(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function n_(e){if(ie.isJSXIdentifier(e))return e.name;if(!ie.isJSXMemberExpression(e))return null;let t=xg(e.object);return t?`${t}.${e.property.name}`:null}function xg(e){if(ie.isJSXIdentifier(e))return e.name;if(!ie.isJSXMemberExpression(e))return null;let t=xg(e.object);return t?`${t}.${e.property.name}`:null}function X$(e,t){if(ie.isJSXIdentifier(e))return t.get(e.name)??null;if(!ie.isJSXMemberExpression(e))return null;let n=xg(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 z$(e){return ie.isJSXIdentifier(e)?e.name:ie.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function H$(e){return ie.isIdentifier(e)?e.name:ie.isStringLiteral(e)||ie.isNumericLiteral(e)?String(e.value):null}function r_(e){return ie.isFunctionDeclaration(e)||ie.isFunctionExpression(e)||ie.isArrowFunctionExpression(e)}function Zk(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function W$(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 bg(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function ha(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var Z$=typeof Sg=="function"?Sg:Sg.default,Ig=class extends Map{constructor(t){super(),this.files=t,this.failures=new Map}read(t){let n=super.get(t);if(n)return{ok:!0,module:n};let r=this.failures.get(t);if(r)return{ok:!1,missing:!1,message:r};let o=Eu(this.files,t);if(o===null)return{ok:!1,missing:!0,message:"A re-exported source is missing or is not valid UTF-8 text."};let i=Fe(t,o);return i.ok?(super.set(t,i.module),{ok:!0,module:i.module}):(this.failures.set(t,i.diagnostic.message),{ok:!1,missing:!1,message:i.diagnostic.message})}get(t){let n=this.read(t);return n.ok?n.module:void 0}has(t){return super.has(t)||this.files.has(t)}};function q$(e){return s_(e,!1)}function i_(e){return s_(e,!0)}function s_(e,t){let{binding:n,files:r}=e;if(e.hostCapabilities!==null&&!G$.safeParse(e.hostCapabilities).success)return Rt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!ya(n.descriptor.source.file)||!ya(n.ownerFile))return Rt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let o=Eu(r,n.descriptor.source.file),i=Eu(r,n.ownerFile);if(o===null||i===null)return Rt("INVOCATION_TARGET_NOT_RENDERED",o===null?n.descriptor.source.file:n.ownerFile,"The resolved block or owner source is missing or is not valid UTF-8 text.");if(je(o)!==n.descriptor.source.contentHash||je(o)!==n.sourceHash||je(i)!==n.ownerSourceHash)return Rt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let s=Fe(n.descriptor.source.file,o);if(!s.ok)return Rt("INVOCATION_PARSE_FAILED",n.descriptor.source.file,s.diagnostic.message);let a=Su(s.module.ast,n.rootLocator.sourceRange);if(a.length!==1)return Rt("INVOCATION_TARGET_AMBIGUOUS",n.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let c=a[0],l=c_(c.node);if(!l)return Rt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The selected JSX element has no complete source range.");let u=[],d=n.root.callChain,p=new Ig(r),g=Q$(e,l,p,t);if(g)return g;if(d.some(x=>(x.alternativeLocators?.length??0)>1))return Rt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[x,E]of d.entries()){let b=Eu(r,E.sourceFile);if(b===null||!ya(E.sourceFile))return Rt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let S=Fe(E.sourceFile,b);if(!S.ok)return Rt("INVOCATION_PARSE_FAILED",E.sourceFile,S.diagnostic.message);let I=Su(S.module.ast,E.callLocator.sourceRange);if(I.length!==1)return Rt("INVOCATION_TARGET_AMBIGUOUS",E.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let w=d[x+1]?.sourceFile??n.descriptor.source.file,C=d[x+1]?.callLocator.sourceRange??n.rootLocator.sourceRange,N=Ln({module:S.module,componentName:E.component,callSourceRange:E.callLocator.sourceRange});if(N.ok){if(N.sourceFile!==w)return Rt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(N.roots.filter(le=>Ji(le.node,C)).length!==1)return Rt("INVOCATION_TARGET_NOT_RENDERED",N.sourceFile,"The local component definition does not select exactly one proven JSX root.");let he=qk({file_path:E.sourceFile,source:b,target:{kind:"local",local_name:E.component},call_source_range:{start_line:E.callLocator.sourceRange.startLine,start_column:E.callLocator.sourceRange.startColumn}});if(!he.call||!he.complete)return{complete:!1,errors:he.errors.length>0?he.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:E.sourceFile,message:"The selected local call did not produce a complete invocation binding."}]};u.push({kind:"local",call:he.call,invocation:he,definition:N,entryExport:null});continue}let R=vg(S.module.ast,I[0].node.openingElement.name,E.component,E.exportName);if(!R)return Rt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The statically proven component call no longer resolves through one exact import.");let F=kg(E.sourceFile,R.source,r);if(!F)return Rt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let $=p.read(F);if(!$.ok)return Rt($.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",F,$.message);let V=Yt({module:$.module,exportName:R.exportName,parsedModules:p});if(!V.ok)return Rt("INVOCATION_TARGET_NOT_RENDERED",V.diagnostic.file,V.diagnostic.message);if(V.sourceFile!==w)return Rt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let U=V.roots.filter(Y=>Ji(Y.node,C));if(U.length!==1)return Rt("INVOCATION_TARGET_NOT_RENDERED",V.sourceFile,"The unique component export does not select exactly one proven JSX root.");let J=null;if(x===d.length-1&&d.length===1&&!u_(n.ownerFile)&&Ji(U[0].node,n.rootLocator.sourceRange)){let Y=p.read(V.sourceFile);if(!Y.ok)return Rt(Y.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",V.sourceFile,Y.message);if(J=a_(Y.module,V.componentName,R.exportName),!J)return Rt("INVOCATION_TARGET_AMBIGUOUS",V.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let te=Vi({file_path:E.sourceFile,source:b,target:{source:R.source,export_name:R.exportName,local_name:R.localName},call_source_range:{start_line:E.callLocator.sourceRange.startLine,start_column:E.callLocator.sourceRange.startColumn}});if(!te.call||!te.complete)return{complete:!1,errors:te.errors.length>0?te.errors:[{code:"INVOCATION_TARGET_NOT_RENDERED",path:E.sourceFile,message:"The selected call did not produce a complete invocation binding."}]};u.push({kind:"import",call:te.call,invocation:te,definition:V,entryExport:J})}let m={kind:"page-block",composition:l_(n.composition),blockKey:n.blockKey},f=eU(n,c,u,r,e.hostCapabilities);if(!f.ok)return{complete:!1,errors:[f.error]};let y=u[0]?.invocation??null;return{complete:!0,selection:{target:m,root_ref:n.root.rootRef,source_file:n.descriptor.source.file,structural_path:n.descriptor.source.structuralPath,content_hash:n.descriptor.source.contentHash,source_range:l,owner:n.descriptor.owner,call_chain:u.map(({call:x})=>x),strategy:f.strategy,entry_file:f.entryFile,entry_export:f.entryExport,invocation:y}}}function Q$(e,t,n,r){let{binding:o,files:i}=e,s=o.root.callChain;if(s.length!==2)return null;let[a,c]=s;if(!a||!c||(a.alternativeLocators?.length??0)>1)return null;let l=n.get(a.sourceFile);if(!l)return null;let u=Su(l.ast,a.callLocator.sourceRange);if(u.length!==1)return null;let d=vg(l.ast,u[0].node.openingElement.name,a.component,a.exportName);if(!d)return null;let p=kg(a.sourceFile,d.source,i),g=p?n.get(p):void 0;if(!g)return null;let m=Yt({module:g,exportName:d.exportName,parsedModules:n});if(!m.ok||m.sourceFile!==c.sourceFile)return null;let f=n.get(m.sourceFile);if(!f||a_(f,m.componentName,"default")?.kind!=="default")return null;let y={files:i,list_entry_file:a.sourceFile,selected_component_source:`@/${m.sourceFile.replace(/\.[cm]?[jt]sx?$/u,"")}`};if(r){if(!wk(y))return null}else{let w=ug(y);if(!w.complete||!w.relation)return null}let x=c.alternativeLocators?.length?c.alternativeLocators:[c.callLocator],E=m.returnAlternatives?.length?m.returnAlternatives:m.roots;if(E.length!==x.length||!E.every(w=>x.filter(C=>Ji(w.node,C.sourceRange)).length===1))return null;for(let w of x){let C=Su(f.ast,w.sourceRange);if(C.length!==1)return null;let N=vg(f.ast,C[0].node.openingElement.name,c.component,c.exportName);if(!N)return null;let R=kg(m.sourceFile,N.source,i),F=R?n.get(R):void 0;if(!F)return null;let $=Yt({module:F,exportName:N.exportName,parsedModules:n});if(!$.ok||$.sourceFile!==o.descriptor.source.file||$.roots.length!==1||!Ji($.roots[0].node,o.rootLocator.sourceRange))return null}let b=Vi({file_path:a.sourceFile,source:l.source,target:{source:d.source,export_name:d.exportName,local_name:d.localName},call_source_range:{start_line:a.callLocator.sourceRange.startLine,start_column:a.callLocator.sourceRange.startColumn}});if(!b.complete||!b.call)return{complete:!1,errors:b.errors};let I=`components/site/portable/${o_("sha256").update(JSON.stringify(["collection-container",o.composition,o.blockKey,o.sourceHash,je(f.source)])).digest("hex").slice(0,24)}/page.tsx`;return i.has(I)?Rt("INVOCATION_TARGET_AMBIGUOUS",I,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:l_(o.composition),blockKey:o.blockKey},root_ref:o.root.rootRef,source_file:o.descriptor.source.file,structural_path:o.descriptor.source.structuralPath,content_hash:o.descriptor.source.contentHash,source_range:t,owner:o.descriptor.owner,call_chain:[b.call],strategy:"collection-container",collection_container_file:m.sourceFile,entry_file:I,entry_export:{kind:"default"},invocation:b}}}function eU(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&Ji(i.definition.roots[0].node,e.rootLocator.sourceRange),u=u_(e.ownerFile);if(n.length===1&&l&&u)return{ok:!0,strategy:"managed-thin-entry",entryFile:e.ownerFile,entryExport:{kind:"default"}};if(n.length===1&&l&&i.entryExport)return{ok:!0,strategy:"reuse-entry",entryFile:i.definition.sourceFile,entryExport:i.entryExport}}if(!c_(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/${o_("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!ya(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 a_(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(ct.isExportDefaultDeclaration(i)){let s=i.declaration;(ct.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||ct.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!ct.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=tU(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ct.isExportSpecifier(s)&&s.exportKind!=="type"&&Cg(s.local)===t&&r.add(Cg(s.exported))}}if(r.size===0)return null;let o=r.has(n)?n:r.size===1?r.values().next().value:r.has("default")?"default":null;return o?o==="default"?{kind:"default"}:{kind:"named",name:o}:null}function tU(e,t){return ct.isFunctionDeclaration(e)?e.id?.name===t?t:null:ct.isVariableDeclaration(e)&&e.declarations.some(n=>ct.isIdentifier(n.id)&&n.id.name===t)?t:null}function vg(e,t,n,r){let o=_g(t);if(!o||o!==n)return null;let i=ct.isJSXMemberExpression(t)?_g(t.object):ct.isJSXNamespacedName(t)?t.namespace.name:o,s=ct.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(ct.isImportDeclaration(a))for(let c of a.specifiers){if(ct.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(ct.isImportSpecifier(c)&&c.local.name===i){let l=Cg(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(ct.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Su(e,t){let n=[];return Z$(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 c_(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 Ji(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 Eu(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 kg(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Eg.posix.normalize(Eg.posix.join(Eg.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=>ya(i)&&n.has(i))??null}function _g(e){if(ct.isJSXIdentifier(e))return e.name;if(ct.isJSXMemberExpression(e)){let t=_g(e.object);return t?`${t}.${e.property.name}`:null}return null}function Cg(e){return ct.isIdentifier(e)?e.name:e.value}function l_(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function ya(e){return Y$.safeParse(e).success}function u_(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function Rt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import Rg from"@babel/generator";import Pg from"@babel/traverse";import*as ye from"@babel/types";var d_=typeof Pg=="function"?Pg:Pg.default,nU=typeof Rg=="function"?Rg:Rg.default;function p_(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=g_(t.get(o));if(i===null||!/\.[cm]?[jt]sx?$/iu.test(o))continue;let s=Fe(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;d_(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),f_(l)&&(a=!0))}}}),d_(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=f_(c),l&&(a=!0),l&&c.scope.crawl();for(let d of c.get("body"))(d.isFunctionDeclaration()&&d.node.id&&!c.scope.getBinding(d.node.id.name)?.referenced||d.isVariableDeclaration({kind:"const"})&&d.node.declarations.every(p=>ye.isIdentifier(p.id)&&!c.scope.getBinding(p.id.name)?.referenced&&(!p.init||Ki(p.init))))&&(d.remove(),l=a=!0)}while(l);c.scope.crawl();let u=0;for(let d of c.node.body)ye.isExportDefaultDeclaration(d)?u+=1:ye.isExportAllDeclaration(d)&&d.exportKind!=="type"?u+=2:ye.isExportNamedDeclaration(d)&&d.exportKind!=="type"&&(d.declaration&&!ye.isTSInterfaceDeclaration(d.declaration)&&!ye.isTSTypeAliasDeclaration(d.declaration)&&(u+=Object.keys(ye.getOuterBindingIdentifiers(d.declaration)).length),u+=d.specifiers.filter(p=>!ye.isExportSpecifier(p)||p.exportKind!=="type").length);u>1&&r.push({code:"SOURCE_EXPORT_ISOLATION_UNPROVEN",path:o,message:"Multiple value exports cannot yet be isolated from unselected source."});for(let d of c.get("body")){if(!d.isImportDeclaration()||d.node.importKind==="type"||d.node.specifiers.length===0||!mt(d.node.source.value))continue;let p=Kt(o,d.node.source.value,t);if(!(!p||!n.has(p))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!m_(p,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:o,message:`The unused import ${d.node.source.value} may have initialization effects.`});continue}d.remove(),a=!0}}c.stop()}}),a&&t.set(o,nU(s.module.ast).code)}return{files:t,errors:r}}function f_(e){let t=new Map;for(let c of e.get("body")){let l=null,u=null;if(c.isFunctionDeclaration()&&c.node.id)l=c.node.id.name,u=c.node;else if(c.isVariableDeclaration({kind:"const"})&&c.node.declarations.length===1){let p=c.node.declarations[0];ye.isIdentifier(p.id)&&(ye.isFunctionExpression(p.init)||ye.isArrowFunctionExpression(p.init))&&(l=p.id.name,u=p.init)}let d=l?e.scope.getBinding(l):void 0;l&&u&&d&&d.constantViolations.length===0&&t.set(l,{definition:u,declaration:c,binding:d})}let n=new Map([...t].map(([c,l])=>[l.definition,c])),r=new Set,o=new Map;for(let[c,l]of t)for(let u of l.binding.referencePaths){let d=u.findParent(g=>n.has(g.node)),p=d?n.get(d.node):void 0;if(!p)r.add(c);else{let g=o.get(p)??new Set;g.add(c),o.set(p,g)}}let i=new Set,s=[...r];for(;s.length;){let c=s.pop();i.has(c)||(i.add(c),s.push(...o.get(c)??[]))}let a=!1;for(let[c,l]of t)i.has(c)||(l.declaration.remove(),a=!0);return a}function m_(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=g_(t.get(e));if(r===null)return!1;let o=Fe(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!mt(a))return!1;let c=Kt(e,a,t);return c!==null&&m_(c,t,i)};return o.module.ast.program.body.every(a=>ye.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(c=>ye.isImportSpecifier(c)&&c.importKind==="type")?!0:s(a.source.value):ye.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):ye.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?Ng(a.declaration):!0:ye.isExportDefaultDeclaration(a)?Ng(a.declaration):Ng(a))}function Ng(e){return ye.isFunctionDeclaration(e)||ye.isTSInterfaceDeclaration(e)||ye.isTSTypeAliasDeclaration(e)||ye.isTSDeclareFunction(e)||ye.isEmptyStatement(e)?!0:ye.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>ye.isIdentifier(t.id)&&(!t.init||Ki(t.init))):Ki(e)}function Ki(e){return ye.isStringLiteral(e)||ye.isNumericLiteral(e)||ye.isBooleanLiteral(e)||ye.isNullLiteral(e)||ye.isFunctionExpression(e)||ye.isArrowFunctionExpression(e)?!0:ye.isArrayExpression(e)?e.elements.every(t=>t===null||!ye.isSpreadElement(t)&&Ki(t)):ye.isObjectExpression(e)?e.properties.every(t=>ye.isObjectProperty(t)&&!t.computed&&!t.shorthand&&Ki(t.value)):ye.isTSAsExpression(e)||ye.isTSSatisfiesExpression(e)||ye.isTSNonNullExpression(e)||ye.isParenthesizedExpression(e)?Ki(e.expression):!1}function g_(e){if(typeof e=="string")return e;if(!(e instanceof Uint8Array))return null;try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return null}}import{createHash as xa}from"node:crypto";import Ag from"@babel/traverse";import*as Oe from"@babel/types";import{PORTABLE_AUDITED_PLACEHOLDER_SVG as Tg,PORTABLE_AUDITED_SAFE_IMAGE as rU}from"@vcp-dev/contracts";var Og=typeof Ag=="function"?Ag:Ag.default,Iu=rU.digest_sha256;function y_(e){let t=()=>({complete:!1});if(!/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(e.host_file)||!e.closure.complete||e.trusted_host_file_hashes.get(e.host_file)!==`sha256:${Iu}`)return t();let n=new Map([[e.entry_file,"default"]]),r=new Set([e.entry_file]),o=new Map;for(let u of e.related_entries??[]){if(u.file===e.entry_file||!["collection-detail-view","client-importer","i18n-companion"].includes(u.purpose)||u.export.kind==="named"&&(!/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(u.export.name)||u.export.name==="default"))return t();let d=JSON.stringify([u.purpose,u.export.kind,u.export.kind==="named"?u.export.name:""]),p=o.get(u.file);if(p!==void 0){if(p!==d)return t();continue}o.set(u.file,d),r.add(u.file),u.purpose==="collection-detail-view"&&n.set(u.file,u.export.kind==="default"?"default":u.export.name)}if(r.size>512||r.size!==e.closure.entry_files.length||new Set(e.closure.entry_files).size!==r.size||e.closure.entry_files.some(u=>!r.has(u)))return t();let i=e.files.get(e.host_file),s=e.files.get(Tg.path);if(i===void 0||xa("sha256").update(i).digest("hex")!==Iu||!(s instanceof Uint8Array)||s.byteLength!==Tg.byte_size||xa("sha256").update(s).digest("hex")!==Tg.digest_sha256)return t();let a=e.closure.edges.filter(u=>u.target===e.host_file&&u.kind!=="type");if(a.length===0||a.length>256||a.some(u=>u.kind!=="import"||u.resolution!=="resolved")||new Set(a.map(u=>u.from)).size!==a.length)return t();let c=[],l=oU(e,n);for(let u of a){let d=u.from,p=(e.selected_host_calls??[]).filter(R=>R.file_path===d&&R.host_file===e.host_file);if(!p.length&&!l(d))return t();let g=Tt(e.files.get(d));if(g===null)return t();let m=Fe(d,g);if(!m.ok)return t();let f=Yt({module:m.module,exportName:n.get(d)??"default"});if(!p.length&&(!f.ok||f.metadataOnly||f.returnAlternatives))return t();let y=null,x=!1;if(Og(m.module.ast,{ImportDeclaration(R){if(Kt(d,R.node.source.value,e.files)!==e.host_file||R.node.importKind==="type")return;let F=R.get("specifiers"),$=F[0];if(y||F.length!==1||!$?.isImportSpecifier()||$.node.importKind==="type"||!Oe.isIdentifier($.node.imported,{name:"SafeImage"})){x=!0;return}y=$}}),x||!y)return t();let E=y,b=E.scope.getBinding(E.node.local.name);if(!b?.constant||b.path.node!==E.node)return t();if(p.length){let R=`sha256:${xa("sha256").update(g).digest("hex")}`;if(p.length>256||p.some(U=>U.source_hash!==R))return t();let F=new Set(p.map(U=>`${U.start}:${U.end}`)),$=new Map,V=!1;if(Og(m.module.ast,{JSXOpeningElement(U){if(!(!Oe.isJSXIdentifier(U.node.name)||U.scope.getBinding(U.node.name.name)!==b)){if(!F.has(`${U.node.start}:${U.node.end}`)||!h_(U.node)){V=!0;return}$.set(U.node,U)}}}),V||$.size!==F.size||!wg(b.referencePaths,new Set($.keys())))return t();for(let U of $.values()){let J=U.node;if(J.start==null||J.end==null||!J.loc)return t();let te=g.slice(J.start,J.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:te,asset_key:null,source_range:{start_offset:J.start,end_offset:J.end,start_line:J.loc.start.line,start_column:J.loc.start.column,end_line:J.loc.end.line,end_column:J.loc.end.column},content_digest:`sha256:${xa("sha256").update(te).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:Iu}})}continue}if(!f.ok||f.metadataOnly||f.returnAlternatives)return t();let S=new Map,I=new Map,w=!1,C=0,N=(R,F=0,$=!1)=>{if(++C>2048||F>128){w=!0;return}if(R.isJSXElement()){let V=R.get("openingElement");if(!Oe.isJSXIdentifier(V.node.name)){w=!0;return}if(V.scope.getBinding(V.node.name.name)===b){h_(V.node)||(w=!0),S.set(V.node,V);return}if(!/^[a-z]/u.test(V.node.name.name)){if($)return;let U=V.scope.getBinding(V.node.name.name);if(!U?.constant)return;let J=U.path;if(!(J.isFunctionDeclaration()&&!J.parentPath.isExportNamedDeclaration()&&!J.parentPath.isExportDefaultDeclaration()||J.isVariableDeclarator()&&J.parentPath.isVariableDeclaration({kind:"const"})&&!J.parentPath.parentPath.isExportNamedDeclaration()&&(Oe.isFunctionExpression(J.node.init)||Oe.isArrowFunctionExpression(J.node.init)))||!R.node.loc)return;let Y=I.get(U.identifier);if(Y){Y.openings.add(V.node),Y.active&&(w=!0);return}if(I.size>=32){w=!0;return}let he={references:U.referencePaths,openings:new Set([V.node]),active:!0};I.set(U.identifier,he);let le=Ln({module:m.module,componentName:V.node.name.name,callSourceRange:{startLine:R.node.loc.start.line,startColumn:R.node.loc.start.column,endLine:R.node.loc.end.line,endColumn:R.node.loc.end.column}});if(!le.ok||le.metadataOnly||le.returnAlternatives||le.sourceFile!==d){w=!0;return}for(let Me of le.roots)N(Me,F+1,$);he.active=!1;return}if(["template","script","style","noscript"].includes(V.node.name.name)||V.node.attributes.some(U=>!Oe.isJSXAttribute(U)||!Oe.isJSXIdentifier(U.name)||/^(?:on|ref$|style$|dangerouslySetInnerHTML$)/iu.test(U.name.name))){w=!0;return}}for(let V of R.get("children"))if(V.isJSXElement()||V.isJSXFragment())N(V,F+1,$);else if(V.isJSXExpressionContainer()){let U=V.get("expression");if(U.isJSXElement()||U.isJSXFragment())N(U,F+1,$);else if(U.isLogicalExpression({operator:"&&"})&&vu(U.node.left)&&sU(U.get("left"))){let J=U.get("right");(J.isJSXElement()||J.isJSXFragment())&&N(J,F+1,!0)}}};for(let R of f.roots)N(R);if(w||S.size===0||!wg(b.referencePaths,new Set(S.keys())))return t();for(let R of I.values())if(!wg(R.references,R.openings))return t();for(let R of S.values()){let F=R.node;if(F.start==null||F.end==null||!F.loc)return t();let $=g.slice(F.start,F.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:$,asset_key:null,source_range:{start_offset:F.start,end_offset:F.end,start_line:F.loc.start.line,start_column:F.loc.start.column,end_line:F.loc.end.line,end_column:F.loc.end.column},content_digest:`sha256:${xa("sha256").update($).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:Iu}})}}return{complete:!0,references:c}}function wg(e,t){return e.length>256?!1:e.every(n=>{let r=n.parentPath;return r?.isJSXOpeningElement()&&r.node.name===n.node?t.has(r.node):r?.isJSXClosingElement()&&r.node.name===n.node&&r.parentPath?.isJSXElement()?t.has(r.parentPath.node.openingElement):!1})}function oU(e,t){let n=new Map;for(let a of e.closure.edges){if(!a.target||a.kind==="type")continue;let c=n.get(a.target)??[];c.push(a),n.set(a.target,c)}let r=new Map,o=new Set,i=new Map,s=a=>{if(t.has(a))return!0;let c=r.get(a);if(c!==void 0)return c;if(o.has(a)||o.size>=32||r.size>=512)return!1;o.add(a);let l=n.get(a)??[],u=l.length>0&&l.length<=256;for(let d of l){if(!u||d.kind!=="import"||d.resolution!=="resolved"){u=!1;break}let p=JSON.stringify([d.from,a]),g=i.get(p);if(g===void 0){if(i.size>=2048){u=!1;break}g=iU(d.from,a,e.files,t.get(d.from)??"default")&&gu(d.from,a,e.files,!1,t.get(d.from)??"default"),i.set(p,g)}if(!g||!s(d.from)){u=!1;break}}return o.delete(a),r.set(a,u),u};return s}function iU(e,t,n,r){let o=Tt(n.get(e));if(o===null)return!1;let i=Fe(e,o);if(!i.ok)return!1;let s=null,a=!1;if(Og(i.module.ast,{ImportDeclaration(f){if(f.node.importKind==="type"||Kt(e,f.node.source.value,n)!==t)return;let y=f.get("specifiers"),x=y[0];if(s||y.length!==1||!x||!(x.isImportDefaultSpecifier()||x.isImportSpecifier()&&x.node.importKind!=="type"&&Oe.isIdentifier(x.node.imported,{name:"default"}))){a=!0;return}s=x}}),a||!s)return!1;let c=s,l=c.scope.getBinding(c.node.local.name);if(!l?.constant||l.path.node!==c.node)return!1;let u=[],d=[];for(let f of l.referencePaths){let y=f.parentPath;if(y?.isJSXOpeningElement()&&y.node.name===f.node)u.push(y);else if(y?.isJSXClosingElement()&&y.node.name===f.node)d.push(y);else return!1}let p=Mn(o,{filePath:e,exportName:r}),g=new Set(p.rendered_component_openings.filter(f=>!f.static_render_blockers?.length).map(f=>f.start_offset)),m=new Set(u.map(f=>f.node));if(u.length>1){let f=Yt({module:i.module,exportName:r});if(!f.ok||f.metadataOnly||!f.returnAlternatives||f.returnAlternatives.length!==u.length||!f.returnAlternatives.every(y=>y.isJSXElement()&&m.has(y.node.openingElement))||new Set(f.returnAlternatives.map(y=>y.node)).size!==u.length)return!1}return u.length>0&&u.length<=256&&u.every(f=>typeof f.node.start=="number"&&g.has(f.node.start))&&d.every(f=>f.parentPath?.isJSXElement()&&m.has(f.parentPath.node.openingElement))}function h_(e){let t=new Set;for(let n of e.attributes){if(!Oe.isJSXAttribute(n)||!Oe.isJSXIdentifier(n.name))return!1;let r=n.name.name;if(t.has(r)||!["src","alt","className","width","height","loading","decoding","fill","priority"].includes(r))return!1;if(t.add(r),r==="src")continue;let o=n.value;if(!(r==="alt"&&Oe.isJSXExpressionContainer(o)&&Zo(o.expression))&&o!==null&&!Oe.isStringLiteral(o)&&!(Oe.isJSXExpressionContainer(o)&&(Oe.isStringLiteral(o.expression)||Oe.isNumericLiteral(o.expression)||Oe.isBooleanLiteral(o.expression))))return!1}return t.has("src")}function sU(e){try{let t=e.evaluate();return!t.confident||!!t.value}catch{return!1}}function vu(e,t=0){return t>32?!1:Oe.isIdentifier(e)?!["undefined","NaN","Infinity"].includes(e.name):Oe.isMemberExpression(e)||Oe.isOptionalMemberExpression(e)?Zo(e):Oe.isUnaryExpression(e,{operator:"!"})?vu(e.argument,t+1):Oe.isBinaryExpression(e)?vu(e.left,t+1)&&Zo(e.right)||Zo(e.left)&&vu(e.right,t+1):!1}function Zo(e,t=0){if(t>32)return!1;if(Oe.isStringLiteral(e)||Oe.isNumericLiteral(e)||Oe.isBooleanLiteral(e)||Oe.isNullLiteral(e)||Oe.isIdentifier(e))return!0;if(Oe.isMemberExpression(e)||Oe.isOptionalMemberExpression(e)){let n=e.property;return!e.computed&&!Oe.isIdentifier(n)||e.computed&&!(Oe.isStringLiteral(n)||Oe.isNumericLiteral(n))||(Oe.isIdentifier(n)||Oe.isStringLiteral(n))&&["__proto__","prototype","constructor"].includes(Oe.isIdentifier(n)?n.name:n.value)?!1:Zo(e.object,t+1)}return Oe.isLogicalExpression(e)?Zo(e.left,t+1)&&Zo(e.right,t+1):!1}async function b_(e){let{binding:t,files:n}=e,r=t.root.callChain;if(r.length!==1)return[];let o=r[0];if((o.alternativeLocators?.length??0)>1)return[];let i=Tt(n.get(t.ownerFile)),s=Tt(n.get(t.descriptor.source.file));if(i===null||s===null)return[];let a=async c=>{let l=Tt(n.get(c));if(l===null)throw new Error("Snapshot source unavailable");return l};try{let c=await ai(t.ownerFile,i,a,async f=>n.has(f));if(!c.entryModule||c.diagnostics.length)return[];let l=[...c.graph.elements.values()].filter(f=>f.importedFrom===t.descriptor.source.file);if(l.length!==1||l[0].sourceFile!==o.sourceFile||l[0].exportName!==o.exportName||!aU(l[0].sourceRange,o.callLocator.sourceRange))return[];let u=[...c.graph.elements.values()].filter(f=>f.sourceFile===t.descriptor.source.file&&x_(t.rootLocator.sourceRange,f.sourceRange));if(!u.length||u.length>256)return[];let d=new Set(u.map(f=>f.identity.key));for(let f of u){if(f.boundaryKind!=="component-boundary"||f.isPublicUiComponent)continue;let y=c.parsedModules.get(f.sourceFile);if(!y)continue;let x=Ln({module:y,componentName:f.tag,callSourceRange:f.sourceRange,...f.importedFrom?{imported:{file:f.importedFrom,module:c.parsedModules.get(f.importedFrom),exportName:f.exportName??f.tag,parsedModules:c.parsedModules}}:{}});if(!x.ok||x.metadataOnly)continue;let E=[...x.roots,...x.returnAlternatives??[]];for(let b of c.graph.fileIndex.get(x.sourceFile)??[]){let S=c.graph.elements.get(b);if(!(!S||d.has(b)||!E.some(I=>{let w=I.node.loc;return w&&x_({startLine:w.start.line,startColumn:w.start.column,endLine:w.end.line,endColumn:w.end.column},S.sourceRange)}))&&(d.add(b),u.push(S),u.length>256))return[]}}d.add(l[0].identity.key);let p={...c.graph,elements:new Map([...c.graph.elements].filter(([f])=>d.has(f))),regions:c.graph.regions.filter(f=>d.has(f.ownerKey))},g=new Set,m=new Map;for(let f of u){let y=await Pl({element:f,graph:p,file:f.sourceFile,source:await a(f.sourceFile),readFile:a,exists:async x=>n.has(x),fileCache:m});for(let x of y.bindings)x.sourceKind==="vcp-cms-collection"&&x.collection&&/^[a-z0-9][a-z0-9_-]{0,79}$/u.test(x.collection)&&((x.operation==="getByUrl"||x.operation==="getByUrlStrict")&&x.endpointPattern==="/content/by-url"&&x.evidence.some(E=>E.reason==="CMS collection namespace from the actual content request path")||["list","listStrict","get","schema","categories"].includes(x.operation??"")&&(x.endpointPattern===`/collections/${x.collection}`||x.endpointPattern?.startsWith(`/collections/${x.collection}/`))&&x.evidence.some(E=>E.reason==="VCP CMS fetch helper"))&&g.add(x.collection);if(g.size>16)return[]}return[...g].sort()}catch{return[]}}function aU(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function x_(e,t){return(t.startLine>e.startLine||t.startLine===e.startLine&&t.startColumn>=e.startColumn)&&(t.endLine<e.endLine||t.endLine===e.endLine&&t.endColumn<=e.endColumn)}import Lg from"@babel/traverse";import*as xt from"@babel/types";var cU=typeof Lg=="function"?Lg:Lg.default;function E_(e){let t=Fe(e.file_path,e.source),n=[],r=new Set,o=(s,a)=>{n.some(c=>c.code===s&&c.message===a)||n.push({code:s,path:e.file_path,message:a})};if(!t.ok)return o("ROUTE_SOURCE_UNAVAILABLE","The route source cannot be parsed."),{complete:!1,dependencies:[],errors:n};let i=s=>{if(e.document_base_proven===!0&&lU(s,e.current_route)){r.add(e.current_route);return}if(!xt.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=S_(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return cU(t.module.ast,{JSXOpeningElement(s){let a=xt.isJSXIdentifier(s.node.name)?s.node.name.name:"";if((["form","iframe","embed","object","portal","script","base","meta","link"].includes(a.toLowerCase())||/^[a-z]/u.test(a)&&a.includes("-"))&&o("ROUTE_VALUE_UNRESOLVED","Embedded content or a form has unproven navigation effects."),a==="button"||a==="input"){let c=s.node.attributes.filter(d=>xt.isJSXAttribute(d)&&xt.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),l=c.length===1&&xt.isJSXAttribute(c[0])?c[0].value:null,u=xt.isStringLiteral(l)?l.value.toLowerCase():null;(a==="button"&&u!=="button"||a==="input"&&(c.length>1||c.length===1&&!u||u==="submit"||u==="image"))&&o("ROUTE_VALUE_UNRESOLVED","A form control may submit an unproven host form.")}},JSXAttribute(s){if(!xt.isJSXIdentifier(s.node.name)){o("ROUTE_VALUE_UNRESOLVED","A namespaced JSX attribute cannot prove navigation.");return}let a=s.node.name.name.toLowerCase();if(["dangerouslysetinnerhtml","srcdoc","action","formaction","form","download","xlinkhref"].includes(a)){o("ROUTE_VALUE_UNRESOLVED","Injected HTML or a form action has unproven navigation effects.");return}if(a!=="href")return;let c=s.node.value;i(xt.isJSXExpressionContainer(c)?c.expression:c)},JSXSpreadAttribute(){o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=ba(s.node.key,s.node.computed);a===null&&s.node.computed?o("ROUTE_VALUE_UNRESOLVED","A computed property may contain an unproven navigation destination."):a==="href"&&i(s.node.value)},ObjectMethod(s){let a=ba(s.node.key,s.node.computed);(a==="href"||a===null&&s.node.computed)&&o("ROUTE_VALUE_UNRESOLVED","A method or getter may provide an unproven navigation destination.")},SpreadElement(){o("ROUTE_VALUE_UNRESOLVED","A spread may contain an unproven navigation destination.")},MemberExpression(s){let a=ba(s.node.property,s.node.computed);s.node.computed&&a===null&&o("ROUTE_VALUE_UNRESOLVED","A computed property may access an unproven navigation capability."),a&&["location","pushState","replaceState","navigate"].includes(a)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven."),a&&["setAttribute","setAttributeNS","insertAdjacentHTML","write","writeln"].includes(a)&&o("ROUTE_VALUE_UNRESOLVED","Imperative DOM modification is not proven."),a&&["push","replace","go","back","forward"].includes(a)&&xt.isIdentifier(s.node.object)&&/router|history|navigation/iu.test(s.node.object.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative router navigation is not proven."),a==="open"&&xt.isIdentifier(s.node.object)&&["window","globalThis"].includes(s.node.object.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},ReferencedIdentifier(s){s.node.name==="location"&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},AssignmentExpression(s){(xt.isIdentifier(s.node.left,{name:"location"})||xt.isMemberExpression(s.node.left)&&(ba(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&ba(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){xt.isIdentifier(s.node.callee)&&["redirect","navigate","open"].includes(s.node.callee.name)&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")}}),{complete:n.length===0,dependencies:[...r].sort().map(s=>({kind:"host-route",href:s})),errors:n}}function lU(e,t){if(!t||t.includes("?")||t.includes("#")||S_(t)!=="host-route")return!1;let n=xt.isStringLiteral(e)?[e.value]:xt.isTemplateLiteral(e)?e.quasis.map(r=>r.value.cooked):[];return n.length>0&&typeof n[0]=="string"&&n[0].startsWith("?")&&n.every(r=>typeof r=="string"&&r.length<=2048&&!/[\s\u0000-\u0020\u007f-\u009f\\]/u.test(r))}function ba(e,t){return xt.isStringLiteral(e)?e.value:!t&&xt.isIdentifier(e)?e.name:t&&xt.isNumericLiteral(e)?String(e.value):null}function S_(e){if(!e||e.length>2048||/[\s\u0000-\u0020\u007f-\u009f\\%]/u.test(e))return"unknown";if(e.startsWith("#")||/^(?:mailto|tel):.+/iu.test(e))return"external";if(!e.startsWith("/")||e.startsWith("//"))return"unknown";let t=e.split(/[?#]/u,1)[0];return t.includes("//")||t.split("/").some(n=>n==="."||n==="..")||/^\/(?:api|_next)(?:\/|$)/u.test(t)||/\.[a-z0-9]{1,12}$/iu.test(t)?"unknown":"host-route"}var v_=512,gU=1024*1024,hU=8*1024*1024,k_=256;function yU(e){let t=()=>({complete:!1,unresolved:[{code:"PORTABLE_LOCAL_ASSET_UNAVAILABLE",path:"<asset>",message:"The selected local image could not be verified."}]});if(!e.exported.complete||e.snapshot_digest!==e.exported.snapshot_digest||__(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%I_!==0)return t();let n=e.exported.media.filter(u=>u.file_path===e.file_path&&u.occurrence===e.occurrence);if(n.length!==1)return t();let r=n[0],o=r.value;if(!r.complete||!o||r.kind==="srcset"||!o.startsWith("/")||o.startsWith("//")||/[\\\0%?#]/u.test(o))return t();let i=o.slice(1).split("/");if(i.some(u=>!u||u.startsWith(".")||u==="node_modules"))return t();let s=`public/${i.join("/")}`,a=e.snapshot_files.get(s);if(!(a instanceof Uint8Array)||!a.byteLength||a.byteLength>fU||e.offset>=a.byteLength)return t();let c=xU(s,a);if(!c)return t();let l=Buffer.from(a);return{complete:!0,snapshot_digest:e.snapshot_digest,file_path:e.file_path,occurrence:e.occurrence,path:s,mime_type:c,byte_size:l.byteLength,digest_sha256:Ru("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+I_).toString("base64")}}function xU(e,t){let n=e.toLowerCase(),r=o=>o.every((i,s)=>t[s]===i);return n.endsWith(".png")&&r([137,80,78,71,13,10,26,10])?"image/png":/\.jpe?g$/u.test(n)&&r([255,216,255])?"image/jpeg":n.endsWith(".gif")&&(r([71,73,70,56,55,97])||r([71,73,70,56,57,97]))?"image/gif":n.endsWith(".webp")&&r([82,73,70,70])&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":e===Fg.path&&t.byteLength===Fg.byte_size&&Ru("sha256").update(t).digest("hex")===Fg.digest_sha256?"image/svg+xml":null}async function bU(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return fn("SNAPSHOT_MISMATCH","<snapshot>","The authoritative Snapshot does not match the requested site and version.");let t=e.site_id,n=e.base_snapshot_id,r=e.document_version,o=e.read_current_identity,i=new Map(e.trusted_host_file_hashes??[]),s=structuredClone(e.trusted_cms_schemas??[]),a=pU.safeParse(e.target),c=uU.safeParse(e.selection_ref);if(!a.success||!c.success)return fn("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let l=a.data,u=c.data,d=ku(o,t,n,r);if(d)return d;let p=dU.safeParse(e.host_capabilities);if(!p.success)return fn("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let g=new Map;for(let[L,G]of e.snapshot.files){if(typeof G!="string"&&!(G instanceof Uint8Array))return fn("SNAPSHOT_CONTENT_MISMATCH",L,"A Snapshot file has an unsupported content type.");g.set(L,typeof G=="string"?G:new Uint8Array(G))}if(!IU(e.snapshot.manifest,t,n,g))return fn("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let m=__(g),f=await Am({site_id:t,base_snapshot_id:n,composition:l.composition,document_version:r,target:l,selection_ref:u,files:g});if(!f.ok)return fn(`BLOCK_${f.code}`,l.blockKey,f.message);if(!f.binding.descriptor.capabilities.save)return fn("BLOCK_EXPORT_NOT_ALLOWED",l.blockKey,"The selected block is not exportable.");let y=i_({binding:f.binding,files:g,hostCapabilities:p.data}),x;if(!y.complete){let L=_u(y.errors.map(({code:_e,path:qe,message:Ke})=>({code:_e,path:qe,message:Ke})));if(!y.errors.some(_e=>_e.code==="INVOCATION_VALUE_UNRESOLVED"))return L;let G=await b_({binding:f.binding,files:g}),A=ku(o,t,n,r);if(A)return A;let ce=G.length>0&&s.length===G.length&&new Set(s.map(_e=>_e.source_slug)).size===G.length&&G.every(_e=>s.some(qe=>qe.source_slug===_e))&&fo(g,i)?ak({binding:f.binding,target:l,files:g,trusted_host_file_hashes:i}):null;if(!ce?.complete)return G.length?{...L,cms_candidates:{kind:"partial-unproven",slugs:G}}:L;y={complete:!0,selection:ce.selection},x=ce.extracted}let E=x??Um({selection:y.selection,files:g});if(!E.complete)return _u(E.errors.map(({code:L,path:G,message:A})=>({code:L,path:G,message:A})));let b=new Map(g);for(let L of E.source_files){let G=b.get(L.path);if(G!==void 0&&!EU(G,L.content))return fn("SOURCE_COLLISION",L.path,"An extracted entry conflicts with the pinned Snapshot.");b.set(L.path,L.content)}let S=uo({entry_files:[E.entry_file],files:b,max_nodes:v_}),I=S.nodes.filter(L=>Cu(L.path)&&i.get(L.path)===Ea(b.get(L.path))).map(L=>L.path),w=Ql({closure:S,host_capabilities:p.data,platform_managed_paths:I,platform_managed_packages:["server-only"]}),C=p_({files:b,private_paths:w.nodes.filter(L=>L.ownership==="private").map(L=>L.path)});b=new Map(C.files);let N=uo({entry_files:[E.entry_file],files:b,max_nodes:v_}),R=Ql({closure:N,host_capabilities:p.data,platform_managed_paths:I,platform_managed_packages:["server-only"]}),F=new Map,$=[],V=[],U=Sk({entry_file:E.entry_file,entry_export:y.selection.entry_export,files:b,trusted_host_file_hashes:i,trusted_cms_schemas:s,entry_invocation_bindings:E.invocation_bindings,entry_route_id:l.composition.routeId,on_cms_media_value(L){let G=`${L.file_path}:${L.start}:${L.end}`,A=F.get(G)??{invalid:!1,sources:new Map};!L.origin||!L.origin.field_path?A.invalid=!0:A.sources.set(`${L.origin.slug}:${L.origin.field_path}`,L.origin),F.set(G,A)},on_audited_ui_call(L){V.push(L)},on_build_only_value(L){$.push(L)},...x||y.selection.strategy==="collection-container"?{entry_argument_origin:"jsx-props"}:{}}),J=[...C.errors.filter(L=>N.nodes.some(G=>G.path===L.path)),...R.errors.map(({code:L,path:G,message:A})=>({code:L,path:G,message:A})),...U.unresolved.map(({code:L,source_path:G,message:A,call_site:q})=>({code:L,path:G,message:A,...q?{call_site:q}:{}}))];if(U.complete){let L=new Set(U.dependencies.map(A=>A.slug)),G=new Set;for(let A of s){if(G.has(A.source_slug)||!L.has(A.source_slug)){J.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"The schema proof does not identify a unique CMS dependency used by the selected block."});break}G.add(A.source_slug)}}let te=new Set(I);for(let L of N.nodes)Cu(L.path)&&!te.has(L.path)&&J.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:L.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let L of R.nodes)L.kind==="external"||L.ownership!=="host-public"||Cu(L.path)||i.get(L.path)!==Ea(g.get(L.path))&&J.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:L.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let Y=[];for(let L of R.nodes){if(L.kind!=="source"||!["host-public","platform-managed"].includes(L.ownership))continue;let G=Tt(b.get(L.path)),A=G===null?null:$i({file_path:L.path,source:G});if(!A||A.references.length>0||A.errors.length>0){let q=L.ownership==="host-public"&&y.selection.entry_export.kind==="default"?y_({entry_file:E.entry_file,host_file:L.path,files:b,closure:N,trusted_host_file_hashes:i,...U.complete?{selected_host_calls:V}:{}}):{complete:!1};if(q.complete){Y.push(...q.references);continue}J.push({code:"HOST_MEDIA_DEPENDENCY_UNPROVEN",path:L.path,message:"The omitted host source has media that cannot yet be bound to this archive."})}}let he=new Map(R.nodes.map(L=>[L.path,L.ownership])),le=[];for(let L of N.nodes){if(he.get(L.path)!=="private")continue;let G=b.get(L.path),A=null;try{typeof G=="string"?A=G:G instanceof Uint8Array&&(A=new TextDecoder("utf-8",{fatal:!0}).decode(G))}catch{}A===null?J.push({code:"SOURCE_TEXT_UNSUPPORTED",path:L.path,message:"A private source dependency is not valid UTF-8 text."}):le.push({path:L.path,content:A})}for(let L of le)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(L.path)||L.path==="lib/generated/product-search-config.json")&&J.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:L.path,message:"A managed capability requires a proven requirement before exporting the block."});le.some(L=>L.path===E.entry_file)||J.push({code:"ENTRY_NOT_PRIVATE",path:E.entry_file,message:"The selected entry is not site-owned source."});let Me=0,Ye=[];for(let L of le){let G=Buffer.byteLength(L.content,"utf8");if(Me+=G,(G>gU||Me>hU)&&J.push({code:"SOURCE_BUDGET_EXCEEDED",path:L.path,message:"The selected source exceeds its export byte budget."}),/\.[cm]?[jt]sx?$/iu.test(L.path)){let A=$i({file_path:L.path,source:L.content}),q=new Set;Ye.push(...A.references.filter(ce=>!U.complete||!$.some(_e=>_e.file_path===L.path&&_e.source_hash===Ea(L.content)&&_e.start<=ce.source_range.start_offset&&_e.end>=ce.source_range.end_offset)).map(ce=>{if(ce.complete||!U.complete)return ce;let _e=ce.source_range,qe=F.get(`${L.path}:${_e.start_offset}:${_e.end_offset}`);if(!qe||qe.invalid||!qe.sources.size)return ce;let Ke=[...qe.sources.values()].sort((rt,vt)=>`${rt.slug}:${rt.field_path}`.localeCompare(`${vt.slug}:${vt.field_path}`));return Ke.every(rt=>U.dependencies.some(vt=>vt.slug===rt.slug)&&s.some(vt=>vt.source_slug===rt.slug&&vt.fields.some(pn=>pn.name===rt.field_path&&["Image","Images","MultiImage","RichText","Richtext"].includes(pn.cms_type))))?(q.add(`${_e.start_offset}:${_e.end_offset}`),{...ce,complete:!0,cms_field:{sources:Ke}}):ce})),J.push(...A.errors.filter(ce=>!ce.source_range||!q.has(`${ce.source_range.start_offset}:${ce.source_range.end_offset}`)).map(({code:ce,file_path:_e,message:qe})=>({code:ce,path:_e,message:qe})))}}for(let L of Y){let A=Ye.filter(q=>q.file_path===L.file_path).reduce((q,ce)=>Math.max(q,ce.occurrence+1),0);Ye.push({...L,occurrence:A})}let pt=new Map,O=!0;if(U.complete){let L=new Map(le.map(G=>[G.path,G.content]));for(let G of R.nodes){if(G.kind!=="source"||!["host-public","platform-managed"].includes(G.ownership))continue;let A=b.get(G.path);try{if(typeof A=="string")L.set(G.path,A);else if(A instanceof Uint8Array)L.set(G.path,new TextDecoder("utf-8",{fatal:!0}).decode(A));else throw new Error("missing source")}catch{O=!1,U.dependencies.length===0&&J.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:G.path,message:"A host source cannot be inspected for navigation."})}}for(let[G,A]of L){if(!/\.[cm]?[jt]sx?$/iu.test(G))continue;let q=E_({file_path:G,source:A,current_route:l.composition.routeId});q.complete||(O=!1),U.dependencies.length===0&&J.push(...q.errors);for(let ce of q.dependencies)pt.set(ce.href,ce)}pt.size>256&&U.dependencies.length===0&&J.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let D=U.dependencies.length>0&&y.selection.strategy!=="collection-container"&&O&&pt.size===0&&SU(N,b,i)&&kk(U,b),H=U.complete&&U.dependencies.length>0&&s.length===U.dependencies.length&&new Set(s.map(L=>L.source_slug)).size===s.length&&U.dependencies.every(L=>s.some(G=>G.source_slug===L.slug)&&L.evidence.every(G=>["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"].includes(G.operation)))&&fo(b,i);if(J.length>0||!N.complete||!R.complete||!U.complete){let L=[...new Set([...U.dependencies.map(q=>q.slug),...U.candidates??[]])].sort();if(!(L.length>0&&L.length<=16&&new Set(L).size===L.length&&L.every(q=>/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(q))))return _u(J);let A=ku(o,t,n,r);return A||{..._u(J),cms_candidates:{kind:"partial-unproven",slugs:L}}}let j=ku(o,t,n,r);if(j)return j;let z={complete:!0,site_id:t,base_snapshot_id:n,snapshot_digest:m,document_version:r,target:y.selection.target,selection_ref:E.selected_root_ref,entry:{file:E.entry_file,export:y.selection.entry_export},files:le.map(({path:L,content:G})=>({path:L,content:G})),source_closure:N,dependency_audit:R,cms:U,media:Ye,invocation_bindings:E.invocation_bindings,host_contract_digest:p.data.host_contract_digest,...U.dependencies.length===0?{route_dependencies:[...pt.values()].sort((L,G)=>L.href.localeCompare(G.href))}:{},...H?{cms_sample_proof:{kind:"application-first-page-example"}}:D?{cms_sample_proof:{kind:"first-page-no-host-routes"}}:{}};return mU.safeParse(z).success?z:fn("PORTABLE_EXPORT_RESULT_INVALID","<export>","The selected source result failed its bounded export contract.")}function ku(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return fn("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?fn("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?fn("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return fn("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function __(e){let t=Ru("sha256");for(let[n,r]of[...e.entries()].sort(([o],[i])=>o.localeCompare(i))){let o=typeof r=="string"?Buffer.from(r,"utf8"):r;t.update(`${n.length}:${n}:${o.byteLength}:`),t.update(o)}return`sha256:${t.digest("hex")}`}function EU(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function Cu(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function SU(e,t,n){let r=e.nodes.filter(s=>Cu(s.path)),o=r[0]?.path.startsWith("src/")?"src/lib/cms/":"lib/cms/";if(!r.length||r.some(s=>!s.path.startsWith(o)))return!1;let i=new Map;for(let s of["index.ts","collections.ts","client.ts"]){let a=`${o}${s}`,c=n.get(a);if(!c||!r.some(l=>l.path===a&&l.status==="complete")||Ea(t.get(a))!==c)return!1;i.set(s,c)}return iu({index:i.get("index.ts"),collections:i.get("collections.ts"),client:i.get("client.ts")})}function Ea(e){return e===void 0?null:`sha256:${Ru("sha256").update(e).digest("hex")}`}function IU(e,t,n,r){if(!e||e.version!==1||e.site_id!==t||e.snapshot_id!==n||!Array.isArray(e.files)||e.files.length!==r.size)return!1;let o=new Set;for(let i of e.files){if(!i||typeof i.path!="string"||!i.path||i.path.startsWith("/")||i.path.includes("\\")||i.path.includes("\0")||i.path.split("/").some(a=>!a||a==="."||a==="..")||o.has(i.path)||!/^sha256:[a-f0-9]{64}$/u.test(i.hash)||!Number.isSafeInteger(i.size_bytes)||i.size_bytes<0)return!1;o.add(i.path);let s=r.get(i.path);if(s===void 0||Ea(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function fn(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function _u(e){return e.length?e.length<=k_?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,k_-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:fn("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import Dg from"@babel/generator";import{parse as vU}from"@babel/parser";import kU from"@babel/traverse";import*as Ft from"@babel/types";var Mg=kU,_U=typeof Mg=="function"?Mg:Mg.default,CU=typeof Dg=="function"?Dg:Dg.default,T_="components/site/generated/{{$INSTANCE}}/",w_=new Set([".tsx",".ts",".jsx",".js"]),C_=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),RU=new Set(["data-site-block-order","data-vcp-order"]);function PU(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 S=wr(b.path);if(!S||n.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source files must have unique safe paths."});continue}n.set(S,{...b,path:S})}for(let b of e.ownership){let S=wr(b.path);if(!S||r.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:b.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(S,{...b,path:S})}let o=wr(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,S)=>b.localeCompare(S)),a=s.map(b=>({source_path:b,path_template:DU(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=NU(e.source_mapping??[],c,t),u=AU(e.required_source_paths??[],c,t),d=[],p=new Map,g=[];for(let b of s){let S=n.get(b);if(!S)continue;let I=wU(b,S.content,r,c,d,p,t);I!==null&&g.push({path_template:c.get(b),content:I,...S.role?{role:S.role}:{}})}let m=N_(t).sort(A_);if(m.length>0)return{complete:!1,entry_path_template:null,files:[],source_path_mappings:[],required_path_mappings:[],source_mapping:[],managed_rebindings:[],block_metadata:[],errors:m};let f=g.map(b=>{let S=a.find(w=>w.path_template===b.path_template)?.source_path,I=n.get(S)?.content??"";return{source_path:S,path_template:b.path_template,original_byte_size:R_(I),output_byte_size:R_(b.content),original_line_count:P_(I),output_line_count:P_(b.content)}}),y=[...p.values()].map(b=>({...b,normalized:!0})).sort((b,S)=>b.source_path.localeCompare(S.source_path)),x=c.get(o)??null;if(e.thin_entry_plan){let b=TU(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let E=N_(t).sort(A_);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,S)=>b.path_template.localeCompare(S.path_template)),source_path_mappings:f.sort((b,S)=>b.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(UU),block_metadata:y,errors:[]}}function NU(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=wr(s.generated_path),c=wr(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 AU(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=wr(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 TU(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(wr(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=`${T_}__managed-root-entry.tsx`,i=O_(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}
17
49
  export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
18
50
  return <Root {...props} />;
19
51
  }
20
- `}}function P0(e,t,n,r,o,i,s){if(!M0(e))return t;let a;try{a=E0(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=A0(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 m=r.get(d.path);if(!m){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=ek(r.get(e),m,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=T0(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 v0(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];(bt.isImport(u)||bt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&bt.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=L0(l.node.name);if(!u||!HI.has(u)&&!k0.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};HI.has(u)?(p.original_block_attribute=u,p.original_block_id=F0(l.node.value)):p.original_order=D0(l.node.value),i.set(g,p),l.remove()}}),I0(a,{jsescOption:{minimal:!0}}).code}function A0(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):or(`${rk(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 ek(e,t,n){let r=rk(e),o=w0(r,t),i=o.startsWith(".")?o:`./${o}`;return tk(n)?i:nk(i)}function T0(e,t){let n=`@/${e}`;return tk(t)?n:nk(n)}function w0(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 O0(e){let t=or(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${qI}${r}`}function L0(e){return bt.isJSXIdentifier(e)?e.name:bt.isJSXNamespacedName(e)&&bt.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function F0(e){return e?bt.isStringLiteral(e)?e.value:bt.isJSXExpressionContainer(e)&&bt.isStringLiteral(e.expression)?e.expression.value:null:null}function D0(e){if(!e)return null;if(bt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return bt.isJSXExpressionContainer(e)&&bt.isNumericLiteral(e.expression)?e.expression.value:null}function M0(e){return[...QI].some(t=>e.endsWith(t))}function tk(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function nk(e){for(let t of QI)if(e.endsWith(t))return e.slice(0,-t.length);return e}function or(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 rk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function WI(e){return new TextEncoder().encode(e).byteLength}function GI(e){return e.length===0?0:e.split(`
21
- `).length}function YI(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function ZI(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function B0(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 j0 from"node:path";import{GeneratedSiteCapabilitiesSchema as $0,FormDefinitionIdSchema as U0,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as V0,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as K0,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as J0,SiteEditMaterializationExportSchema as X0,SiteEditMaterializationSchema as z0,SiteEditSourcePathSchema as H0}from"@vcp-dev/contracts";var Ml="components/site/generated",W0=/^[a-z][a-z0-9._-]{0,127}$/,jl=/^[a-z][a-z0-9._-]{0,127}$/,G0=new Set(["collection-detail-view","i18n-companion","client-importer"]);function Y0(e){if(!pi(e))return Je("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!W0.test(e.instanceId))return Je("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=$0.safeParse(e.trustedHostPolicy);if(!t.success)return Je("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return Je("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!e$(e.existingSources))return Je("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 m=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(p)?.[1];return!U0.safeParse(m).success||!Bl(e.existingSources,`${p.slice(2)}.tsx`)})))return Je("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=Z0(e.resolved);if(!n.ok)return n;let r=z0.safeParse(n.materialization);if(!r.success)return Je("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=q0(n.relatedEntries,r.data);if(!o.ok)return o;let i=Q0(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=j0.posix.join(Ml,e.instanceId),a=[],c=new Set;for(let p of r.data.files){let m=Bi({pathTemplate:p.pathTemplate,generatedRoot:Ml,instanceName:e.instanceId,instanceRoot:s});if(!m.ok)return Am(m.error);if(c.has(m.data))return Je("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${m.data}`,m.data);c.add(m.data),a.push({kind:"create-only",path:m.data,content:p.content,...p.role?{role:p.role}:{},sourcePathTemplate:p.pathTemplate})}if(a.length>K0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let p of a){let m=Buffer.byteLength(p.content,"utf8");if(m>V0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",p.path);l+=m}if(l>J0)return Je("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=ok(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 m=ok(p.pathTemplate,p.export,c,e.instanceId,s);if(!m.ok)return m;d.push({...p,path:m.data.path}),f.push(m.data)}if(Bl(e.existingSources,s)||a.some(p=>Bl(e.existingSources,p.path)))return Je("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=hd({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((p,m)=>p.path.localeCompare(m.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:Ml,instanceRoot:s,entry:u.data,relatedEntries:d.sort((p,m)=>p.path.localeCompare(m.path)),entryConsumers:i.data,files:a}}):Am(g.error)}function Z0(e){if(!pi(e))return Je("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 Je("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!pi(n))return Je("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return Je("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?Je("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function q0(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(!pi(c))return Je("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=X0.safeParse(c.export);if(typeof l!="string"||!jl.test(l)||typeof u!="string"||!jl.test(u)||typeof d!="string"||typeof f!="string"||!G0.has(f)||!g.success)return Je("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 Je("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return Je("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return Je("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return Je("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 Q0(e,t,n,r){let o=new Map(t.map(l=>[l.key,l])),i=new Set((n.dataRequirements??[]).map(l=>l.key)),s=new Set,a=[];for(let[l,u]of e.entries()){if(!pi(u))return Je("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,f=u.requirement_key,g=u.kind,p=u.consumer_path;if(typeof d!="string"||!jl.test(d)||typeof f!="string"||!jl.test(f)||typeof p!="string"||!p.trim()||g!=="route"&&g!=="capability"&&g!=="preserved-route")return Je("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let m=o.get(d);if(!m)return Je("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(g==="preserved-route"&&(m.purpose!=="collection-detail-view"||!H0.safeParse(p).success||!/^app\/.*\/page\.tsx$/u.test(p)||!Bl(r,p)))return Je("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return Je("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(m.requirementKey!==f)return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(f))return Je("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",f);s.add(d),a.push({entry_key:d,requirement_key:f,kind:g,consumer_path:p})}let c=t.find(l=>!s.has(l.key));return c?Je("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",c.key):{ok:!0,data:a.sort((l,u)=>l.entry_key.localeCompare(u.entry_key)||l.consumer_path.localeCompare(u.consumer_path))}}function ok(e,t,n,r,o){let i=Bi({pathTemplate:e,generatedRoot:Ml,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:Je("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):Am(i.error)}function Bl(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function e$(e){return Array.isArray(e)||e instanceof Map||pi(e)}function pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Am(e){return{ok:!1,error:e}}function Je(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import ik from"node:path";import{SiteEditSourcePathSchema as Tm}from"@vcp-dev/contracts";function t$(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||!Tm.safeParse(e.entryFile).success||!Tm.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(_e(n)!==t.sourceHash)return St("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=i$(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):n$(e,n):o$(e,n))}function n$(e,t){let n=De(e.entryFile,t);if(!n.ok)return St("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=xn({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=r$(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=Od({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||!Om(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 r$(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Om(o.anchorSourceRange,t)?[]:sk(o.members).filter(i=>i.sourceRange!==null&&Om(i.sourceRange,t)));return r.length===1?r[0].label:null}function sk(e){return e.flatMap(t=>[t,...sk(t.children)])}function o$(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=xr({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=s$(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=cn({source:t,locator:wm(r),anchorLocator:wm(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=ln({source:s.source,moduleSpecifier:a$(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 i$(e){return!Tm.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 s$(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=De(t,e);if(!o.ok)return St("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Ie(o.module.ast,wm(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 wm(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 a$(e,t){let n=ik.posix.relative(ik.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Om(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{parse as c$}from"@babel/parser";import Lm from"@babel/traverse";import*as gt from"@babel/types";var l$=typeof Lm=="function"?Lm:Lm.default,u$=new Set(["slice","map","trim","toString"]);function d$(e){let t=new Set;try{let n=c$(e,{sourceType:"module",plugins:["jsx","typescript"]});l$(n,{JSXExpressionContainer(r){let o=r.get("expression");Bs(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Bs(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Bs(e.get("object"),t),c=e.node;return!c.computed&&gt.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&gt.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&gt.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!gt.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>gt.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:Bs(a.get("object"),t)==="array"?"array":null}if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);if(!n?.constant||t.has(n)||!Fm(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&gt.isIdentifier(n.path.node.id))return Bs(n.path.get("init"),r);if(n.kind!=="param")return null;let o=n.path.getFunctionParent();if(!o)return null;if(e.node.name==="record"&&o.node.params.some(a=>gt.isObjectPattern(a)&&a.properties.some(c=>gt.isObjectProperty(c)&&!c.computed&&gt.isIdentifier(c.key,{name:"record"})&&gt.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!gt.isIdentifier(o.node.params[0],{name:e.node.name})||!o.parentPath.isCallExpression())return null;let i=o.parentPath,s=i.get("callee");return i.node.arguments[0]!==o.node||!s.isMemberExpression()||s.node.computed||!gt.isIdentifier(s.node.property,{name:"map"})?null:Bs(s.get("object"),r)==="array"?"item":null}function Fm(e,t){return t.has(e)?!0:(t.add(e),e.constant?e.referencePaths.every(n=>{let r=n;for(;r.parentPath&&(r.parentPath.isMemberExpression()||r.parentPath.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(!o||o.isAssignmentExpression()||o.isUpdateExpression()||o.isUnaryExpression()&&o.node.operator==="delete"||o.isSpreadElement()||o.isObjectProperty()||o.isReturnStatement())return!1;if(o.isVariableDeclarator()){if(!gt.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Fm(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&gt.isIdentifier(r.node.property)&&u$.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&gt.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!gt.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Fm(a,t))return!1}return!0}return r!==n}):!1)}export{Ee as FileHistoryStoreError,Zi as PageTemplateManagedSourceError,gl as PreviewFileSystemSiteEditEngineRuntime,py as SITE_EDIT_RAW_COLOR_LITERAL_RE,pl as SnapshotSiteEditEngineRuntime,hj as analyzePortableCollectionInvocation,li as analyzePortableInvocation,om as analyzePortableRelatedEntries,fd as auditGeneratedCode,hl as auditPortableDependencies,Gi as buildPageBlockIndex,xr as buildPortableInvocation,Y0 as buildPortableMaterializationPlan,Mr as buildPortableSourceClosure,hi as checkComponentI18nHostCompatibility,ii as classifyPortableDependencyOwnership,Fb as computeManagedPageTemplatePaths,OM as createPreviewSiteEditEngineRuntime,PM as createSiteEditEngineRuntime,wb as decodePageTemplateKey,rm as discoverPortableCollectionSourceRelation,nf as encodePageTemplateId,h0 as exportPortableBlockFromSnapshot,Gp as extractPortableBlockEntry,Wk as instrumentSiteEditRuntimeAttributes,Db as isManagedPageTemplateSourcePath,FA as normalizePortableBlockMetadata,_0 as normalizePortableSource,Oh as openFileHistoryStore,wk as parseSourceModule,t$ as planPortableBlockPatch,Od as planPortableRouteCompositionPatch,Vi as planRouteCompositionRewrite,d$ as provenRecordThumbnailRanges,m0 as readPortableBlockLocalAssetChunk,Ok as resolveImportBase,vw as resolveManagedPageTemplateComposition,ac as resolvePageBlockBoundary,Bp as resolvePageBlockFromSnapshot,$o as resolvePageBlockTarget,xn as resolvePageCompositionProjection,ym as resolvePortableBlockSelection,FM as resolvePortableDependencyOwnership,Br as resolvePortableSourcePath,dc as scanManagedPageTemplateCandidates,_m as scanPortableMediaReferences,fc as scanSiteEditCompositionsFromFiles,ld as scanSiteEditThemeStyleViolations,gj as selectPortablePageUnitInvocation};
52
+ `}}function wU(e,t,n,r,o,i,s){if(!$U(e))return t;let a;try{a=vU(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=OU(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 p=n.get(d.path);if(!p){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The local import target ${d.path} has no ownership decision.`});return}if(p.ownership==="private"){let f=r.get(d.path);if(!f){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=O_(r.get(e),f,u);return}if(p.ownership!=="platform-managed"&&p.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=LU(d.path,u);l.value=g;let m=p.requirement_key??"host-public";if(!/^[a-z][a-z0-9._-]{0,127}$/u.test(m)){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:m})};return _U(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];(Ft.isImport(u)||Ft.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&Ft.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=MU(l.node.name);if(!u||!C_.has(u)&&!RU.has(u))return;let d=l.parentPath.parentPath?.node,p=typeof d?.start=="number"?d.start:l.node.start??0,g=`${e}:${p}`,m=i.get(g)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};C_.has(u)?(m.original_block_attribute=u,m.original_block_id=BU(l.node.value)):m.original_order=jU(l.node.value),i.set(g,m),l.remove()}}),CU(a,{jsescOption:{minimal:!0}}).code}function OU(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):wr(`${D_(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 O_(e,t,n){let r=D_(e),o=FU(r,t),i=o.startsWith(".")?o:`./${o}`;return L_(n)?i:F_(i)}function LU(e,t){let n=`@/${e}`;return L_(t)?n:F_(n)}function FU(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 DU(e){let t=wr(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${T_}${r}`}function MU(e){return Ft.isJSXIdentifier(e)?e.name:Ft.isJSXNamespacedName(e)&&Ft.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function BU(e){return e?Ft.isStringLiteral(e)?e.value:Ft.isJSXExpressionContainer(e)&&Ft.isStringLiteral(e.expression)?e.expression.value:null:null}function jU(e){if(!e)return null;if(Ft.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return Ft.isJSXExpressionContainer(e)&&Ft.isNumericLiteral(e.expression)?e.expression.value:null}function $U(e){return[...w_].some(t=>e.endsWith(t))}function L_(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function F_(e){for(let t of w_)if(e.endsWith(t))return e.slice(0,-t.length);return e}function wr(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 D_(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function R_(e){return new TextEncoder().encode(e).byteLength}function P_(e){return e.length===0?0:e.split(`
53
+ `).length}function N_(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function A_(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function UU(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 VU from"node:path";import{GeneratedSiteCapabilitiesSchema as JU,FormDefinitionIdSchema as KU,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as XU,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as zU,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as HU,SiteEditMaterializationExportSchema as WU,SiteEditMaterializationSchema as GU,SiteEditSourcePathSchema as YU}from"@vcp-dev/contracts";var Pu="components/site/generated",ZU=/^[a-z][a-z0-9._-]{0,127}$/,Au=/^[a-z][a-z0-9._-]{0,127}$/,qU=new Set(["collection-detail-view","i18n-companion","client-importer"]);function QU(e){if(!Xi(e))return st("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!ZU.test(e.instanceId))return st("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=JU.safeParse(e.trustedHostPolicy);if(!t.success)return st("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return st("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!rV(e.existingSources))return st("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(m=>{if(typeof m!="string")return!0;let f=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(m)?.[1];return!KU.safeParse(f).success||!Nu(e.existingSources,`${m.slice(2)}.tsx`)})))return st("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=eV(e.resolved);if(!n.ok)return n;let r=GU.safeParse(n.materialization);if(!r.success)return st("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=tV(n.relatedEntries,r.data);if(!o.ok)return o;let i=nV(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=VU.posix.join(Pu,e.instanceId),a=[],c=new Set;for(let m of r.data.files){let f=ys({pathTemplate:m.pathTemplate,generatedRoot:Pu,instanceName:e.instanceId,instanceRoot:s});if(!f.ok)return Bg(f.error);if(c.has(f.data))return st("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${f.data}`,f.data);c.add(f.data),a.push({kind:"create-only",path:f.data,content:m.content,...m.role?{role:m.role}:{},sourcePathTemplate:m.pathTemplate})}if(a.length>zU)return st("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let m of a){let f=Buffer.byteLength(m.content,"utf8");if(f>XU)return st("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",m.path);l+=f}if(l>HU)return st("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=M_(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],p=[u.data];for(let m of o.data){let f=M_(m.pathTemplate,m.export,c,e.instanceId,s);if(!f.ok)return f;d.push({...m,path:f.data.path}),p.push(f.data)}if(Nu(e.existingSources,s)||a.some(m=>Nu(e.existingSources,m.path)))return st("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=af({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:p,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((m,f)=>m.path.localeCompare(f.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:Pu,instanceRoot:s,entry:u.data,relatedEntries:d.sort((m,f)=>m.path.localeCompare(f.path)),entryConsumers:i.data,files:a}}):Bg(g.error)}function eV(e){if(!Xi(e))return st("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 st("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!Xi(n))return st("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return st("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?st("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function tV(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(!Xi(c))return st("PORTABLE_INPUT_INVALID","Every related entry must be an object.",`resolved.relatedEntries[${a}]`);let l=c.key,u=c.requirementKey,d=c.pathTemplate,p=c.purpose,g=WU.safeParse(c.export);if(typeof l!="string"||!Au.test(l)||typeof u!="string"||!Au.test(u)||typeof d!="string"||typeof p!="string"||!qU.has(p)||!g.success)return st("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 st("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return st("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return st("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return st("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:p,requirementKey:u})}return{ok:!0,data:s}}function nV(e,t,n,r){let o=new Map(t.map(l=>[l.key,l])),i=new Set((n.dataRequirements??[]).map(l=>l.key)),s=new Set,a=[];for(let[l,u]of e.entries()){if(!Xi(u))return st("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,p=u.requirement_key,g=u.kind,m=u.consumer_path;if(typeof d!="string"||!Au.test(d)||typeof p!="string"||!Au.test(p)||typeof m!="string"||!m.trim()||g!=="route"&&g!=="capability"&&g!=="preserved-route")return st("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let f=o.get(d);if(!f)return st("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(g==="preserved-route"&&(f.purpose!=="collection-detail-view"||!YU.safeParse(m).success||!/^app\/.*\/page\.tsx$/u.test(m)||!Nu(r,m)))return st("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return st("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(f.requirementKey!==p)return st("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(p))return st("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must reference a resolved managed requirement.",p);s.add(d),a.push({entry_key:d,requirement_key:p,kind:g,consumer_path:m})}let c=t.find(l=>!s.has(l.key));return c?st("PORTABLE_ENTRY_UNCONSUMED","Every related entry must be consumed by its managed route or capability.",c.key):{ok:!0,data:a.sort((l,u)=>l.entry_key.localeCompare(u.entry_key)||l.consumer_path.localeCompare(u.consumer_path))}}function M_(e,t,n,r,o){let i=ys({pathTemplate:e,generatedRoot:Pu,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:st("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):Bg(i.error)}function Nu(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function rV(e){return Array.isArray(e)||e instanceof Map||Xi(e)}function Xi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bg(e){return{ok:!1,error:e}}function st(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import B_ from"node:path";import{SiteEditSourcePathSchema as jg}from"@vcp-dev/contracts";function oV(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||!jg.safeParse(e.entryFile).success||!jg.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 Dt("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 Dt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(je(n)!==t.sourceHash)return Dt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=cV(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?Dt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):iV(e,n):aV(e,n))}function iV(e,t){let n=Fe(e.entryFile,t);if(!n.ok)return Dt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=Vn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return Dt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=sV(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return Dt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=vf({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 Dt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return Dt("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||!Ug(a,e.resolvedBoundary.anchorLocator.sourceRange))?Dt("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 sV(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!Ug(o.anchorSourceRange,t)?[]:j_(o.members).filter(i=>i.sourceRange!==null&&Ug(i.sourceRange,t)));return r.length===1?r[0].label:null}function j_(e){return e.flatMap(t=>[t,...j_(t.children)])}function aV(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return Dt("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 Dt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=Wr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return Dt(o.error.code,o.error.message,n.ownerFile);if(o.plan.requiresRouteParams)return Dt("UNSUPPORTED_ROUTE_PARAMS","A captured native detail parameter cannot be injected into an unproven shared owner.",n.ownerFile);let i=lV(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=An({source:t,locator:$g(r),anchorLocator:$g(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return Dt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=Tn({source:s.source,moduleSpecifier:uV(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}]}:Dt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function cV(e){return!jg.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)?Dt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function lV(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=Fe(t,e);if(!o.ok)return Dt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=De(o.module.ast,$g(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?Dt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function $g(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 uV(e,t){let n=B_.posix.relative(B_.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function Ug(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Dt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as dV}from"@babel/parser";import Vg from"@babel/traverse";import*as wt from"@babel/types";var fV=typeof Vg=="function"?Vg:Vg.default,pV=new Set(["slice","map","trim","toString"]);function mV(e){let t=new Set;try{let n=dV(e,{sourceType:"module",plugins:["jsx","typescript"]});fV(n,{JSXExpressionContainer(r){let o=r.get("expression");Sa(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function Sa(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=Sa(e.get("object"),t),c=e.node;return!c.computed&&wt.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&wt.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&wt.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!wt.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>wt.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:Sa(a.get("object"),t)==="array"?"array":null}if(!e.isIdentifier())return null;let n=e.scope.getBinding(e.node.name);if(!n?.constant||t.has(n)||!Jg(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&wt.isIdentifier(n.path.node.id))return Sa(n.path.get("init"),r);if(n.kind!=="param")return null;let o=n.path.getFunctionParent();if(!o)return null;if(e.node.name==="record"&&o.node.params.some(a=>wt.isObjectPattern(a)&&a.properties.some(c=>wt.isObjectProperty(c)&&!c.computed&&wt.isIdentifier(c.key,{name:"record"})&&wt.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!wt.isIdentifier(o.node.params[0],{name:e.node.name})||!o.parentPath.isCallExpression())return null;let i=o.parentPath,s=i.get("callee");return i.node.arguments[0]!==o.node||!s.isMemberExpression()||s.node.computed||!wt.isIdentifier(s.node.property,{name:"map"})?null:Sa(s.get("object"),r)==="array"?"item":null}function Jg(e,t){return t.has(e)?!0:(t.add(e),e.constant?e.referencePaths.every(n=>{let r=n;for(;r.parentPath&&(r.parentPath.isMemberExpression()||r.parentPath.isOptionalMemberExpression())&&r.parentPath.node.object===r.node;)r=r.parentPath;let o=r.parentPath;if(!o||o.isAssignmentExpression()||o.isUpdateExpression()||o.isUnaryExpression()&&o.node.operator==="delete"||o.isSpreadElement()||o.isObjectProperty()||o.isReturnStatement())return!1;if(o.isVariableDeclarator()){if(!wt.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Jg(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&wt.isIdentifier(r.node.property)&&pV.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&wt.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!wt.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Jg(a,t))return!1}return!0}return r!==n}):!1)}export{Ae as FileHistoryStoreError,As as PageTemplateManagedSourceError,ql as PreviewFileSystemSiteEditEngineRuntime,mx as SITE_EDIT_RAW_COLOR_LITERAL_RE,Yl as SnapshotSiteEditEngineRuntime,D$ as analyzePortableCollectionInvocation,Vi as analyzePortableInvocation,dg as analyzePortableRelatedEntries,nf as auditGeneratedCode,Ql as auditPortableDependencies,Ps as buildPageBlockIndex,Wr as buildPortableInvocation,QU as buildPortableMaterializationPlan,uo as buildPortableSourceClosure,Gi as checkComponentI18nHostCompatibility,Di as classifyPortableDependencyOwnership,Rm as cmsFieldAccessor,Db as computeManagedPageTemplatePaths,aj as createPreviewSiteEditEngineRuntime,rj as createSiteEditEngineRuntime,Ob as decodePageTemplateKey,ug as discoverPortableCollectionSourceRelation,q0 as discoverPortableExistingCollectionRelation,zf as encodePageTemplateId,bU as exportPortableBlockFromSnapshot,Um as extractPortableBlockEntry,Pm as generateCollectionAdapter,IC as instrumentSiteEditRuntimeAttributes,Mb as isManagedPageTemplateSourcePath,lw as normalizePortableBlockMetadata,PU as normalizePortableSource,Ly as openFileHistoryStore,sC as parseSourceModule,oV as planPortableBlockPatch,vf as planPortableRouteCompositionPatch,Ss as planRouteCompositionRewrite,mV as provenRecordThumbnailRanges,yU as readPortableBlockLocalAssetChunk,aC as resolveImportBase,YO as resolveManagedPageTemplateComposition,Jc as resolvePageBlockBoundary,Am as resolvePageBlockFromSnapshot,yi as resolvePageBlockTarget,Vn as resolvePageCompositionProjection,q$ as resolvePortableBlockSelection,lj as resolvePortableDependencyOwnership,Kt as resolvePortableSourcePath,Hc as scanManagedPageTemplateCandidates,$i as scanPortableMediaReferences,Wc as scanSiteEditCompositionsFromFiles,Qd as scanSiteEditThemeStyleViolations,F$ as selectPortablePageUnitInvocation};