@vcp-dev/site-edit-engine 0.11.29 → 0.11.30

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,17 +1,17 @@
1
- import*as aC from"@babel/parser";import*as Yt from"@babel/types";import*as $r from"node:path";var Vu=[".tsx",".ts",".jsx",".js"],cC=Vu.map(e=>`/index${e}`),lC=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 ih(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&lC.has(n[1].toLowerCase())}function sh(e){let t=[];for(let n of e.program.body)Yt.isImportDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),Yt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value),Yt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&mt(n.source.value)&&t.push(n.source.value);return Yt.traverseFast(e.program,n=>{let r=Yt.isImportExpression(n)?n.source:Yt.isCallExpression(n)&&Yt.isImport(n.callee)?n.arguments[0]:null;Yt.isStringLiteral(r)&&mt(r.value)&&t.push(r.value)}),t}function mt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function nr(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=$r.dirname(e);return $r.join(n,t).replace(/\\/g,"/")}async function uC(e,t){for(let n of ah(e))if(await t(n))return n;return null}function ah(e){return[...Vu.some(t=>e.endsWith(t))?[e]:[],...Vu.map(t=>`${e}${t}`),...cC.map(t=>`${e}${t}`)]}function Ur(e,t,n){let r=nr(e,t);if(!mt(t)||!ch(e,t,r))return null;for(let o of ah(r))if(n.has(o))return o;return null}async function vo(e,t,n){let r=await Na(e,t,n);return r.ok?r.path:null}async function Na(e,t,n){let r=nr(e,t);try{if(!ch(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 uC(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 ch(e,t,n){if(!mt(t)||t.includes("\0")||t.includes("\\")||$r.posix.isAbsolute(n))return!1;let r=$r.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!$r.posix.isAbsolute(e)}import{createHash as fC}from"node:crypto";import*as lh from"@babel/parser";function _o(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function de(e,t,n,r,o){return{ok:!1,source:e,diagnostic:_o(t,n,r,o)}}function Ju(e,t,n,r,o){return{ok:!1,source:e,diagnostic:_o(t,n,r,o)}}var dC={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function rr(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:lh.parse(t,{sourceType:"module",plugins:dC[n]})}}catch(r){return{ok:!1,source:t,diagnostic:_o("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function Ku(e,t){return rr({source:e,profile:uh(t.kind)})}function Zi(e,t){return rr({source:e,profile:uh(t)})}function uh(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 we=(e,t)=>{let n=rr({source:t,profile:ko({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${fC("sha256").update(t).digest("hex")}`,ast:n.ast,imports:sh(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function pC(e,t){return we(e,t)}function mC(e,t){return nr(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as gC,parseComponentI18nResourcesJson as hC,resolveSiteTextDirection as yC,SiteLocaleSchema as xC}from"@vcp-dev/contracts";var bC=["i18next","react-i18next"],EC="components/ui/site-locale-provider.tsx",SC="components/ui/component-i18n-provider.tsx",dh="app/layout.tsx";async function qi(e){let t=e.files.filter(p=>p.path.endsWith(gC));if(t.length===0)return{ok:!0};for(let p of["package.json",dh,EC,SC])if(!await e.exists(p))return Vr(`Target snapshot is missing required i18n host file: ${p}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return Vr("Target snapshot package.json is invalid.")}let r=fh(n)&&fh(n.dependencies)?n.dependencies:{},o=bC.filter(p=>typeof r[p]!="string"||r[p].trim().length===0);if(o.length>0)return Vr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile(dh),s=Xu(i,"html","lang"),a=Xu(i,"html","dir"),c=Xu(i,"SiteLocaleProvider","locale"),l=xC.safeParse(s);if(!l.success||!a||!c||s!==c||a!==yC(l.data))return Vr("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 Vr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return Vr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let p of t){let g=hC(p.content);if(!g.success)return Vr(`Component i18n resource is invalid: ${p.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return Vr(`Component i18n resource ${p.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function Xu(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 fh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vr(e){return{ok:!1,message:e}}import Hu from"@babel/generator";import*as xh from"@babel/parser";import Wu from"@babel/traverse";import*as lt from"@babel/types";import{computeSiteEditSourceIdentityKey as vC}from"@vcp-dev/contracts";var ph="data-vcp-ui-component",Aa="components/ui";function vr(e){if(!e)return!1;let t=zu(e);return t===Aa||t.startsWith(`${Aa}/`)||t.includes(`/${Aa}/`)||t.endsWith(`/${Aa}`)}function Co(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?vr(e.slice(2)):e.startsWith("./")||e.startsWith("../")?vr(zu(`${IC(t)}/${e}`)):vr(e):!1}function zu(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 IC(e){let t=zu(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as jV}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as UV,isSiteEditRuntimeTextTag as VV}from"@vcp-dev/contracts/site-edit-runtime-capability";var mh={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 _C=typeof Hu=="function"?Hu:Hu.default,kC=typeof Wu=="function"?Wu:Wu.default,CC=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),RC="suppressHydrationWarning",PC=new Set(["SiteEditBootstrap"]);function NC(e){let t=wC(e.file,e.projectRoot);if(!TC(e.source)||vr(t))return{code:e.source,elements:[]};let n=e.attributes??mh,r=xh.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=LC(r,t);return kC(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!DC(c)||bh(a,n.key))return;let l=BC(s)??"default",u=$C(s),d=vC(t,l,u),p=wa(c)??"unknown",g=OC(c)?"jsx":"component-call";if(g==="component-call"&&!jC(s.node.children)&&PC.has(p))return;let m=g==="component-call"&&FC(p,i);MC(a,n.key,d),m&&gh(a,ph),AC(s)&&gh(a,RC),o.push({key:d,tag:p,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:_C(r,{jsescOption:{minimal:!0}}).code,elements:o}}function AC(e){return!e.findParent(t=>t.isJSXElement())}function TC(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function wC(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 OC(e){return lt.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function wa(e){return lt.isJSXIdentifier(e)?e.name:lt.isJSXMemberExpression(e)?Sh(e):null}function LC(e,t){let n=new Set;for(let r of e.program.body)if(!(!lt.isImportDeclaration(r)||!Co(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function FC(e,t){let n=e.split(".")[0]??e;return t.has(n)}function DC(e){let t=wa(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!CC.has(t)}function bh(e,t){return e.attributes.some(n=>lt.isJSXAttribute(n)&&lt.isJSXIdentifier(n.name,{name:t}))}function MC(e,t,n){Eh(e,lt.jsxAttribute(lt.jsxIdentifier(t),lt.stringLiteral(n)))}function gh(e,t){bh(e,t)||Eh(e,lt.jsxAttribute(lt.jsxIdentifier(t),null))}function Eh(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 Sh(e){return`${lt.isJSXIdentifier(e.object)?e.object.name:Sh(e.object)}.${e.property.name}`}function BC(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 jC(e){return e.some(t=>lt.isJSXElement(t)||lt.isJSXFragment(t))}var hh=new WeakMap,Ta=new WeakMap,Gu=new WeakMap;function $C(e){let t=hh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=UC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return hh.set(e.node,o),o}function UC(e){let t=wa(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${yh(e,t)}`:`${t}#${yh(e,t)}`}function yh(e,t){let n=Ih(e)??e.getFunctionParent();if(!n)return 0;let r=Gu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Gu.get(n.node);o||(o=new Map,Gu.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()?Oa(n):VC(n);for(let c of a)if(wa(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 VC(e){let t=Ta.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Ih(r)&&n.push(r)}}),Ta.set(e.node,n),n}function Ih(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 Oa(e){let t=Ta.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(...Oa(o));continue}o.isJSXExpressionContainer()&&n.push(...Ro(o.get("expression")))}return Ta.set(e.node,n),n}function Ro(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return Oa(e);if(e.isParenthesizedExpression())return Ro(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return Ro(e.get("right"));if(e.isConditionalExpression())return[...Ro(e.get("consequent")),...Ro(e.get("alternate"))];if(e.isCallExpression()&&KC(e.node)){let t=e.get("arguments")[0];return JC(t)}return[]}function JC(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return Oa(t);if(t.isParenthesizedExpression())return Ro(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?Ro(r):[]}return[]}function KC(e){return lt.isMemberExpression(e.callee)&&lt.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as aj,SiteEditPatchPlanSchema as cj}from"@vcp-dev/contracts";function Po(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 La(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 Fa(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 Da(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:XC(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 Ma(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:Po(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 XC(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 xB,computeSiteEditCompositionKey as bB,getSiteEditSourceDeleteProtectionReason as EB,isSiteEditTextSourcePath as SB,parseSiteEditRepeatInstanceKey as IB,SITE_EDIT_SOURCE_DELETE_CAPABILITY as vB,stripSiteEditRepeatInstanceKeys as fn}from"@vcp-dev/contracts";import Wl from"node:path";import{parse as _B}from"yaml";import ed from"node:path";import{TextDecoder as HC}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as _h,SITE_EDIT_SOURCE_ALLOWED_DIRS as kh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as Ch,SiteEditCompositionContextSchema as WC,SiteEditSourceFileResponseSchema as Yu,SiteEditSourceLocationSchema as GC,SiteEditSourcePathSchema as Ba,SiteEditSourceTreeResponseSchema as YC,isSiteEditTextSourcePath as ZC}from"@vcp-dev/contracts";import{createHash as zC}from"node:crypto";var Qi=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 Ue(e){return`sha256:${zC("sha256").update(e).digest("hex")}`}var qC=[...Ch,..._h,...kh];function td(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return WC.parse(e.composition)}var Zu=2e3,qu=12,Qu=24*1024*1024,vh=512*1024,QC=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),eR={".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"},tR={".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"},nR=new HC("utf-8",{fatal:!0});async function ja(e,t={}){let n=td(t),{files:r,truncated:o}=await lR(e,t),i=fR(r.map(s=>s.metadata));return YC.parse({composition:n,nodes:i,defaultPath:pR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function $a(e,t,n={}){let r=td(n),o=Ba.parse(t.path),i=await oR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(rd(o)){let a=Nh(o),c=await sR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return Yu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await nd(e,o);return s.ok?Yu.parse({composition:r,path:o,kind:"text",language:Ah(o),sizeBytes:s.sizeBytes,contentHash:Ue(s.content),readonly:!1,content:s.content}):Yu.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function nd(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=rR(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 rR(e){if(e.includes(0))return null;try{return nR.decode(e)}catch{return null}}async function oR(e,t,n){if(!aR(t,n))return null;let r=await iR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function iR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=Rh(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(rd(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function sR(e,t){if(!QC.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>vh)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>vh?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function aR(e,t){return Ch.some(n=>n===e)||_h.some(n=>n===e)||kh.some(n=>e===n||e.startsWith(`${n}/`))?!0:!e.startsWith("app/")&&!e.startsWith("src/app/")?!1:(t.routeEntryFiles??[]).some(n=>{let r=Ba.safeParse(n);return r.success&&r.data===e})}function Ua(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return GC.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 Rh(e){return Array.isArray(e)?{files:e}:e}function cR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function lR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=Rh(await e.listFiles({roots:uR(t),maxFiles:Zu+1,maxDepth:qu,maxTotalBytes:Qu+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=Ba.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>qu){o.add("max-depth");continue}if(r.size>=Zu){o.add("max-files");break}if(i+a.sizeBytes>Qu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:dR(l,a.sizeBytes,td(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:cR([...o]),maxFiles:Zu,maxDepth:qu,maxTotalBytes:Qu}}:{}}}function uR(e){let t=new Set(qC);for(let n of e.routeEntryFiles??[]){let r=Ba.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function dR(e,t,n){return rd(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:Nh(e),readonly:!0}:{composition:n,path:e,kind:"text",language:Ah(e),sizeBytes:t,readonly:!1}}function fR(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 Ph(t)}function Ph(e){return e.map(t=>t.kind==="directory"?{...t,children:Ph(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function pR(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 rd(e){return!ZC(e)}function Nh(e){let t=ed.posix.extname(e).toLowerCase();return!t&&ed.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":eR[t]??"application/octet-stream"}function Ah(e){let t=ed.posix.extname(e).toLowerCase();return tR[t]??"plaintext"}import*as Ao from"@babel/types";import od from"@babel/traverse";import*as or from"@babel/types";function ft(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(or.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(or.isIdentifier(s)&&s.name==="Fragment"||or.isStringLiteral(s)&&s.value==="Fragment")&&Th(i.parentPath)}if(!or.isJSXMemberExpression(t)||!or.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!or.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())&&Th(r.parentPath)}function Th(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var Jr=typeof od=="function"?od:od.default,Va=new WeakMap,Ja=new WeakMap;function ir(e,t){let n=Ku(e,t);if(!n.ok)return Ju(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Be(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 Be(e,t){return t.kind==="jsx-node"?Fh(e,t):t.kind==="jsx-attribute"?bR(e,t):t.kind==="value"?ER(e,t):t.kind==="expression"?SR(e,t):t.kind==="directive"?IR(e,t):t.kind==="export"?vR(e,t):{ok:!1,diagnostic:_o("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function Fh(e,t){return t.strategy==="source-range"?mR(e,t):gR(e,t)}function mR(e,t){let n=null;if(Jr(e,{JSXElement(o){if(!No(o.node,t.sourceRange))return;let i=Ct("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!No(o.node,t.sourceRange))return;let i=Ct("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!No(o.node,t.sourceRange))return;let i=Ct("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!No(o.node,t.sourceRange))return;let i=Ct("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return At("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!FR(r.path,t.expectedIdentity)?At("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function gR(e,t){if(t.structuralPath===""){let r=yR(e,t.component);if(r){let o=xR(r);if(o)return o}}let n=null;return Jr(e,{JSXElement(r){if(ts(r)!==t.component||sd(r)!==t.structuralPath)return;let i=Ct("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(ts(r)!==t.component||sd(r)!==t.structuralPath)return;let i=Ct("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=hR(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:At("jsx-node","locator-miss","JSX node not found for structural-path locator")}function hR(e,t,n){let r=null;return Jr(e,{JSXElement(o){if(ts(o)!==t||!No(o.node,n))return;let i=Ct("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(ts(o)!==t||!No(o.node,n))return;let i=Ct("jsx-node",o);i&&(r=i,o.stop())}}),r}function yR(e,t){let n=null;return Jr(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 xR(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 At("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?At("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 At("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function bR(e,t){let n=Fh(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>DR(c,t.name));if(!s||!s.isJSXAttribute())return At("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=Ct("jsx-attribute",s);return a?{ok:!0,match:a}:At("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function ER(e,t){let n=_R(e,t);if(!n.ok)return n;let r=kR(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!kr(r.match.path.node.loc,t.expectedRange)?At("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function SR(e,t){let n=null;return Jr(e,{Identifier(r){if(!TR(r))return;let o=Oh(r);if(!o||!Lh(o,t))return;let i=Ct("expression",r);i&&(t.expectedRange&&!kr(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=Oh(r);if(!o||!Lh(o,t))return;let i=Ct("expression",r);i&&(t.expectedRange&&!kr(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:At("expression","locator-miss","Expression not found")}function IR(e,t){let n=null;return Jr(e,{Program(r){let i=r.get("directives").find(a=>a.node.value.value===t.value);if(!i||t.expectedRange&&!kr(i.node.loc,t.expectedRange))return;let s=Ct("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:At("directive","locator-miss",`Directive '${t.value}' not found`)}function vR(e,t){let n=null;return Jr(e,{ExportNamedDeclaration(r){if(t.exportKind==="generate-metadata"){let c=r.get("declaration");if(c.isFunctionDeclaration()&&c.node.id?.name==="generateMetadata"){let p=Ct("export",c);if(!p||t.expectedRange&&!kr(c.node.loc,t.expectedRange))return;n=p,r.stop();return}if(!c.isVariableDeclaration())return;let l=ad(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=Ct("export",u);if(!d||t.expectedRange&&!kr(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=ad(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!kr(s.node.loc,t.expectedRange))return;let a=Ct("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=Ct("export",o);i&&(t.expectedRange&&!kr(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:At("export","export-not-found",`Export '${LR(t)}' not found`)}function _R(e,t){let n=null;return Jr(e,{Expression(r){if(n||t.root.kind!=="expression"||!No(r.node,t.root.sourceRange))return;let o=Ct("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=Ct("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=Ct("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=ad(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=Ct("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=Ct("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:At("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 kR(e,t){let n=id(e);for(let o of t){if(n=id(n),o.kind==="property"){if(!n.isObjectExpression())return At("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return At("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>MR(l,o.name));if(!c||!c.isObjectProperty())return At("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return At("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return At("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return At("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=id(n);let r=Ct("value",n);return r?{ok:!0,match:r}:At("value","locator-miss","Resolved value has no source range")}function id(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function Ct(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 No(e,t){return kr(e.loc,t)}function kr(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 sd(e){let t=[],n=e,r=e.node;for(;n;){if(n.isJSXElement()){if(!ft(n)){let o=Mh(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${wh(n,o)}`):t.unshift(`${o}#${wh(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||NR(n.parentPath)&&!AR(n.parentPath))break;n=n.parentPath}return t.join("/")}function wh(e,t){let n=Dh(e)??e.getFunctionParent();if(!n)return 0;let r=Va.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Va.get(n.node)?.get(t);if(!i){let a=Va.get(n.node);a||(a=new Map,Va.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?es(n):CR(n);for(let a of s)if(Mh(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function CR(e){let t=Ja.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Dh(r)&&n.push(r)}}),Ja.set(e.node,n),n}function Dh(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 es(e){let t=Ja.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(...es(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...es(o));continue}o.isJSXExpressionContainer()&&n.push(..._r(o.get("expression")))}return Ja.set(e.node,n),n}function _r(e){if(e.isJSXElement())return ft(e)?es(e):[e];if(e.isJSXFragment())return es(e);if(e.isParenthesizedExpression())return _r(e.get("expression"));if(e.isLogicalExpression()&&RR(e.node.operator))return _r(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(..._r(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(..._r(a));break}}return i}else if(o.node&&o.isExpression())return _r(o)}}}}return e.isConditionalExpression()?[..._r(e.get("consequent")),..._r(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:_r(t)):[]}function RR(e){return e==="&&"||e==="||"||e==="??"}function Mh(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?PR(e.name):null}function PR(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 ts(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 NR(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function AR(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 TR(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function Oh(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 Lh(e,t){return e.base===t.base&&wR(e.path,t.path??[])}function wR(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 OR(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function LR(e){return e.exportKind==="named"?e.name:e.exportKind}function At(e,t,n,r){return{ok:!1,diagnostic:_o(t,n,e,r)}}function FR(e,t){return ts(e)!==t.component?!1:sd(e)===t.structuralPath}function DR(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function ad(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function MR(e,t){return e.isObjectProperty()?OR(e.node)===t:!1}import*as jh from"@babel/parser";import{arrayExpression as VR,booleanLiteral as JR,identifier as KR,jsxAttribute as XR,jsxExpressionContainer as zR,jsxIdentifier as HR,nullLiteral as WR,numericLiteral as GR,objectExpression as YR,objectProperty as ZR,stringLiteral as ld}from"@babel/types";import cd from"@babel/generator";var BR=typeof cd=="function"?cd:cd.default;function jR(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 $R(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 UR(e,t){return e.split(`
3
- `).map(r=>$R(r,t)).join(`
4
- `)}function Ka(e){let{ast:t,source:n}=e;try{let r=jR(n),i=BR(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=UR(i,r)),{ok:!0,source:i}}catch(r){return de(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function Bh(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 ns(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:Bh(e),afterSourceHash:Bh(t),inverse:n.inverse}}}function et(e,t,n){let r=Ka({ast:e,source:t});return r.ok?ns(t,r.source,n):r}function ut(e,t){let n=Zi(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function Xa(e,t){return Ka({ast:e,source:t})}function qR(e,t,n){let r=Be(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function ti(e,t,n){let r=qR(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:de(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Kr(e){return typeof e=="string"?ld(e):typeof e=="number"?GR(e):typeof e=="boolean"?JR(e):e===null?WR():Array.isArray(e)?VR(e.map(t=>Kr(t))):YR(Object.entries(e).map(([t,n])=>{let r=ZR(ud(t),Kr(n));return t==="__proto__"&&(r.computed=!0),r}))}function QR(e){return typeof e=="string"?ld(e):zR(Kr(e))}function rs(e,t){return XR(HR(e),QR(t))}function za(e,t){try{let r=jh.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:de(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:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function ud(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?KR(e):ld(e)}function Ha(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=ut(t,"jsx-node");if(!i.ok)return i.result;let s=Be(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=eP(s.match.path)[r];if(!c)return de(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?[Ao.jsxText(d)]:[],Ao.jsxExpressionContainer(Ao.stringLiteral("")),...p?[Ao.jsxText(p)]:[]]);break}let u=tP(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 eP(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=nP(r.get("expression"));o.length>0&&t.push(...o)}}return t}function tP(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function nP(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 dd}from"@babel/types";function To(e){let{source:t,locator:n}=e,r=ut(t,"jsx-node");if(!r.ok)return r.result;let o=Be(r.ast,n);return o.ok?(rP(o.match.path),et(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function rP(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{cloneNode as oP}from"@babel/types";function ni(e){let t=ut(e.source,"jsx-node");if(!t.ok)return t.result;let n=Be(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=za(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(oP(r.node,!0)),et(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as gP}from"@babel/types";import fd from"@babel/traverse";import*as Ce from"@babel/types";function os(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 iP=typeof fd=="function"?fd:fd.default;function An(e,t,n,r){if(!e.ok)return e;let o=Nn(n,t);if(!o)return e;let i=sP(t,o,r);return i?{...e,selectionRef:i}:e}function sP(e,t,n){let r=aP(e,t);if(!r)return;let o=n.sourceLocator?$h(n.sourceLocator):void 0,i=n.targetParentLocator?$h(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??lP(r)??i?.component??o?.component;if(!(!s||!a))return{key:os(s,a,uP(r))}}function $h(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function aP(e,t){let n=zh(e,t);return!n||n.node.type!=="JSXElement"?null:n}function zh(e,t){let n=null;return iP(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function Nn(e,t){if(!e)return null;if(Ce.isJSXElement(e))return mP(t,e)?Uh(e.children,t):e;if(Ce.isJSXFragment(e))return Uh(e.children,t);if(Ce.isJSXExpressionContainer(e)||Ce.isParenthesizedExpression(e)||Ce.isTSAsExpression(e)||Ce.isTSSatisfiesExpression(e)||Ce.isTSTypeAssertion(e)||Ce.isTSNonNullExpression(e))return Nn(e.expression,t);if(Ce.isLogicalExpression(e))return Nn(e.right,t);if(Ce.isConditionalExpression(e))return Nn(e.consequent,t)??Nn(e.alternate,t);if(Ce.isCallExpression(e)||Ce.isOptionalCallExpression(e))return Hh(e)?cP(e.arguments[0],t):null;if(Ce.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=Nn(n,t);if(r)return r}return null}function Uh(e,t){for(let n of e){let r=Nn(n,t);if(r)return r}return null}function cP(e,t){return!e||!Ce.isArrowFunctionExpression(e)&&!Ce.isFunctionExpression(e)?null:Ce.isBlockStatement(e.body)?is(e.body.body,t):Nn(e.body,t)}function is(e,t){for(let n of e){if(Ce.isReturnStatement(n)){let r=Nn(n.argument,t);if(r)return r;continue}if(Ce.isBlockStatement(n)){let r=is(n.body,t);if(r)return r;continue}if(Ce.isIfStatement(n)){let r=Vh(n.consequent,t);if(r)return r;let o=n.alternate?Vh(n.alternate,t):null;if(o)return o;continue}if(Ce.isSwitchStatement(n))for(let r of n.cases){let o=is(r.consequent,t);if(o)return o}}return null}function Vh(e,t){return Ce.isBlockStatement(e)?is(e.body,t):is([e],t)}function lP(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 Jh=new WeakMap,Kh=new WeakMap,pd=new WeakMap;function uP(e){let t=Jh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=dP(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Jh.set(e.node,o),o}function dP(e){let t=Wh(e.node.openingElement.name);return!t||ft(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Xh(e,t)}`:`${t}#${Xh(e,t)}`}function Xh(e,t){let n=fP(e);if(!n)return 0;let r=pd.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=pd.get(n.node);o||(o=new Map,pd.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of wo(n))if(Wh(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 fP(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 wo(e){let t=Kh.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(...wo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...wo(o));continue}o.isJSXExpressionContainer()&&n.push(...sr(o.get("expression")))}return Kh.set(e.node,n),n}function sr(e){if(e.isJSXElement())return ft(e)?wo(e):[e];if(e.isJSXFragment())return wo(e);if(e.isParenthesizedExpression())return sr(e.get("expression"));if(e.isLogicalExpression())return sr(e.get("right"));if(e.isConditionalExpression())return[...sr(e.get("consequent")),...sr(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:sr(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&Hh(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?pP(n):[]}return[]}function pP(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return ft(t)?wo(t):[t];if(t.isJSXFragment())return wo(t);if(t.isParenthesizedExpression())return sr(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return sr(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(...sr(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...sr(o)),n}return n}function Hh(e){let t=e.callee;return(Ce.isMemberExpression(t)||Ce.isOptionalMemberExpression(t))&&Ce.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function mP(e,t){let n=zh(e,t);return n?ft(n):!1}function Wh(e){return Ce.isJSXIdentifier(e)?e.name:Ce.isJSXMemberExpression(e)?Gh(e):Ce.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function Gh(e){return`${Ce.isJSXIdentifier(e.object)?e.object.name:Gh(e.object)}.${e.property.name}`}function Xr(e,t){if(t.parentPath===e&&t.listKey==="children"&&md(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!md(n))return null;let r=n;for(;r&&r!==e;){if(!md(r)||!ft(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function md(e){return e.isJSXElement()||e.isJSXFragment()}function Tn(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=Be(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return de(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 de(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=za(t,r.jsx);if(!u.ok)return u.result;let d=gP(u.node,!0),p=l.node.children,g={...s,targetParentLocator:n},m=b=>s?An(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 de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=Be(a.ast,i);if(!f.ok)return{ok:!1,source:t,diagnostic:f.diagnostic};let y=Xr(c.match.path,f.match.path);if(!y)return de(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?de(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 Yh from"@babel/parser";import{cloneNode as hP}from"@babel/types";function Wa(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=yP(t,r);if(!c.ok)return c.result;let l=Be(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return de(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 de(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let x=Be(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let E=Xr(l.match.path,x.match.path);if(!E)return de(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 de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=hP(c.node,!0),g=u.node.children,m={...s,targetParentLocator:n},f=x=>s?An(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?de(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 yP(e,t){try{let r=Yh.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:de(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as xP,nullLiteral as gd}from"@babel/types";import*as zr from"@babel/types";import*as Zh from"@babel/types";function ss(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 Oo(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=Be(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Be(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return de(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 de(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let b=Be(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=b.match.path.isJSXElement()?ss(b.match.path,l.match.path):b.match.path,I=Xr(l.match.path,S);if(!I)return de(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 de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=d&&typeof d.key=="number"?d.key:-1;if(d&&p===-1)return de(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?ss(c.match.path,l.match.path):c.match.path,m=xP(g.node,!0);if(!zr.isJSXElement(m)&&!zr.isJSXExpressionContainer(m)&&!zr.isJSXFragment(m)&&!zr.isJSXText(m))return de(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 de(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");bP(g);let y=u.node.children,x={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(m),An(Xa(a.ast,t),a.ast,m,x);if(o==="prepend")return y.unshift(m),An(Xa(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),An(Xa(a.ast,t),a.ast,m,x)}function bP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(gd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(gd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(gd());return}e.remove()}import*as qh from"@babel/parser";import{cloneNode as EP,nullLiteral as hd}from"@babel/types";function Ga(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=SP(t,s);if(!l.ok)return l.result;let u=Be(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Be(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return de(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 de(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=Be(c.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let S=Xr(d.match.path,b.match.path);if(!S)return de(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 de(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return de(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let m=p.node,f=EP(l.node,!0);IP(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},x=m.children;if(o==="append")return x.push(f),An(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),An(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?de(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(x.splice(o==="before"?E:E+1,0,f),An(et(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,f,y))}function SP(e,t){try{let r=qh.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:de(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:de(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function IP(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(hd());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(hd());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(hd());return}e.remove()}import{SiteEditSetPropsParamsSchema as vP,classifySiteEditPropertyName as _P}from"@vcp-dev/contracts";import*as ri from"@babel/types";function Ya(e){let t=vP.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return de(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=ti(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=_P(a.name);if(c.owner!=="generic")return de(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(ri.isJSXAttribute),s=new Map;for(let a of i){let c=kP(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 de(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=rs(a.name,a.value).value;c?c.value=l:o.attributes.push(rs(a.name,a.value))}return et(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function kP(e){return ri.isJSXIdentifier(e.name)?e.name.name:ri.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as CP}from"@vcp-dev/contracts";import*as ge from"@babel/types";var Qh=["prefetch","replace","scroll","locale","onNavigate"],RP=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function PP(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>ge.isJSXAttribute(n)&&ge.isJSXIdentifier(n.name)&&RP.test(n.name.name)))return!0;t=t.parentPath}return!1}function Za(e){let t=ut(e.source,"jsx-node");if(!t.ok)return t.result;let n=ti(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=CP.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return Cr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=FP(s.name);if(!a)return Cr(e.source,"Unsupported JSX link tag");if(s.attributes.some(ge.isJSXSpreadAttribute))return Cr(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=xd(m);if(!f)return Cr(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 Cr(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!LP(l))return Cr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:TP(o,s.name);if(!u&&!d)return Cr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&PP(o))return Cr(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=wP(t.ast,o);if(!m.ok)return Cr(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")),OP(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"),Qh.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&Qh.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!ge.isJSXAttribute(m))return!0;let f=xd(m);return!f||!g.has(f)}),e.link.kind!=="none"&&s.attributes.push(ge.jsxAttribute(ge.jsxIdentifier("href"),ge.stringLiteral(e.link.href))),NP(s,e.changes),et(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function NP(e,t){for(let n of t){let r=e.attributes.find(s=>ge.isJSXAttribute(s)&&xd(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(yd(n.value)),i=ge.jsxAttribute(ge.jsxIdentifier(n.name),o);r&&ge.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function yd(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=>yd(t))):typeof e=="object"?ge.objectExpression(Object.entries(e).map(([t,n])=>ge.objectProperty(ge.isValidIdentifier(t)?ge.identifier(t):ge.stringLiteral(t),yd(n)))):ge.nullLiteral()}function AP(e){return ge.isImportDefaultSpecifier(e)||ge.isImportSpecifier(e)&&e.importKind!=="type"&&(ge.isIdentifier(e.imported,{name:"default"})||ge.isStringLiteral(e.imported,{value:"default"}))}function ey(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 TP(e,t){if(!ge.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!ey(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function wP(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(AP);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 OP(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!ey(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 LP(e){return!e.value||ge.isStringLiteral(e.value)}function FP(e){return ge.isJSXIdentifier(e)?e.name:null}function xd(e){return ge.isJSXIdentifier(e.name)?e.name.name:null}function Cr(e,t){return de(e,"unsupported-syntax",t,"jsx-node")}import*as jt from"@babel/types";import{classifySiteEditPropertyName as ty}from"@vcp-dev/contracts";function qa(e){let t=ty(e.name),n=ty(e.property);if(t.owner!=="generic"||n.owner!=="generic")return de(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!ny(e.object))return de(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return de(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=ti(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>jt.isJSXAttribute(l)&&MP(l)===e.name);if(s.length>1)return de(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=DP(e.object,e.property),c=s[0];if(c)c.value=jt.jsxExpressionContainer(a);else{let l=rs(e.name,"");l.value=jt.jsxExpressionContainer(a),i.attributes.push(l)}return et(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function DP(e,t){return ny(t)?jt.memberExpression(jt.identifier(e),jt.identifier(t)):jt.memberExpression(jt.identifier(e),jt.stringLiteral(t),!0)}function ny(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function MP(e){return jt.isJSXIdentifier(e.name)?e.name.name:jt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as jP,identifier as as,importDeclaration as $P,importDefaultSpecifier as UP,importNamespaceSpecifier as VP,importSpecifier as JP,isImportDefaultSpecifier as ry,isImportNamespaceSpecifier as oy,isImportSpecifier as iy,stringLiteral as KP}from"@babel/types";function wn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!QP(y));if(o!==-1){let y=r[o],x=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return de(t,"unsupported-syntax",`Unsupported import spec kind: ${String(x)}`)}let i=YP(r);if(!i.ok)return de(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=eN(y,x);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has(dy(y)));if(d.length===0)return ns(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let p=ZP(c.body),g=d.find(y=>p.has(bd(y)));if(g)return de(t,"unsupported-syntax",`Import local binding already exists: ${bd(g)}`);let m=GP(d);if(m.reduce((y,x)=>y+x.length,0)!==d.length)return de(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of m){if(!ly(ay(y)))return de(t,"unsupported-syntax","Unsupported import specifier combination");let x=l.find(E=>XP(E,y));if(x)zP(x,y);else{let E=$P(sy(y),KP(n));qP(c.body,E),l.push(E)}}return et(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function XP(e,t){return e.importKind==="type"?!1:ly(WP(HP(e),ay(t)))}function zP(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Ed(o)));for(let o of sy(t)){let i=Ed(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return uy(e.specifiers),{changed:n}}function sy(e){let t=e.map(n=>{switch(n.kind){case"named":return JP(n.local?as(n.local):as(n.imported),as(n.imported));case"default":return UP(as(n.local));case"namespace":return VP(as(n.local));default:return n}});return uy(t),t}function ay(e){let t=cy();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 HP(e){let t=cy();for(let n of e.specifiers)ry(n)?t.defaultLocals.add(n.local.name):oy(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function cy(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function WP(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function ly(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function uy(e){let t=[...e.filter(n=>ry(n)),...e.filter(n=>oy(n)),...e.filter(n=>iy(n))];e.splice(0,e.length,...t)}function GP(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 YP(e){let t=new Map,n=new Map;for(let r of e){let o=dy(r);if(t.has(o))continue;let i=bd(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 ZP(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(jP(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 qP(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 QP(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 dy(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 bd(e){return e.kind==="named"?e.local??e.imported:e.local}function eN(e,t){return e.importKind==="type"||iy(t)&&t.importKind==="type"?null:Ed(t)}function Ed(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 oi(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!nN(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return de(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 ns(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=>tN(u,d))),l.specifiers.length===0&&a.body.splice(c,1),et(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function tN(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 nN(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 cs(e){let{source:t,locator:n,next:r}=e,o=nc(t,n);return o.ok?(o.path.replaceWith(Kr(r)),et(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function Qa(e){let{source:t,locator:n,index:r,value:o}=e,i=nc(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?de(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?de(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Kr(o)),et(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):de(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function ec(e){let{source:t,locator:n,index:r}=e,o=nc(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?de(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?de(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"})):de(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function tc(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=nc(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return de(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return de(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 de(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 nc(e,t){let n=ut(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Be(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 Kt from"@babel/types";function rc(e){let t=ut(e.source,"value");if(!t.ok)return t.result;let n=Be(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return de(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Kt.isSpreadElement(a)||Kt.isObjectProperty(a)&&a.computed))return de(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Kt.isObjectProperty(a)&&rN(a.key)===e.name);if(o.length>1)return de(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Kt.unaryExpression("void",Kt.numericLiteral(0)):Kr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Kt.objectProperty(ud(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 rN(e){return Kt.isIdentifier(e)?e.name:Kt.isStringLiteral(e)?e.value:Kt.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as oN,isSiteEditRuntimeVoidElementTag as iN}from"@vcp-dev/contracts/site-edit-runtime-capability";function ii(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function sN(e,t,n){let r=ii(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&&iN(u),g=d||oN(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 oc(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,sN(r,e,t));return n}function Sd(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:Ue(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=aN(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:Ue(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:py(r),version:{documentVersion:e.route.graph.version,contentHash:Ue(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()?cN(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:fy(e.route.source,o),valueRaw:s?fy(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:py(o),diagnostics:[]}}function my(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 aN(e,t){let n=rr({source:e,profile:ko({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Be(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:lN(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function cN(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 gy(e){let t=rr({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 fy(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function py(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 lN(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function hy(){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 uN}from"node:crypto";import ic from"node:fs/promises";import Id from"node:path";import{setTimeout as dN}from"node:timers/promises";var fN={async mkdir(e,t){await ic.mkdir(e,t)},async writeFile(e,t,n){await ic.writeFile(e,t,n)},async rename(e,t){await ic.rename(e,t)},async rm(e,t){await ic.rm(e,t)}},pN=new Set(["EACCES","EBUSY","EPERM"]),mN=[10,20,40,80,160];async function gN(e,t,n){for(let r of mN)try{await e.rename(t,n);return}catch(o){if(!hN(o))throw o;await dN(r)}await e.rename(t,n)}function hN(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&pN.has(e.code)}async function sc(e,t,n=fN){let r=Id.dirname(e),o=Id.basename(e),i=Id.join(r,`.${o}.${process.pid}.${uN()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await gN(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import vd from"@babel/traverse";import*as N from"@babel/types";import*as Ge from"@babel/types";function ar(e,t={}){if(Ge.isTSAsExpression(e)||Ge.isTSSatisfiesExpression(e)||Ge.isTSNonNullExpression(e)||Ge.isTypeCastExpression(e)||Ge.isParenthesizedExpression(e))return ar(e.expression,t);if(Ge.isStringLiteral(e))return{status:"resolved",value:e.value};if(Ge.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Ge.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Ge.isNullLiteral(e))return{status:"resolved",value:null};if(Ge.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(Ge.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Ge.isUnaryExpression(e)&&e.operator==="void"&&Ge.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Ge.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Ge.isSpreadElement(r))return{status:"unresolved"};let o=ar(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Ge.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Ge.isObjectProperty(r)||r.computed||!Ge.isExpression(r.value))return{status:"unresolved"};let o=yN(r.key);if(o===null)return{status:"unresolved"};let i=ar(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 Ge.isMemberExpression(e)||Ge.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function yN(e){return Ge.isIdentifier(e)?e.name:Ge.isStringLiteral(e)?e.value:Ge.isNumericLiteral(e)?String(e.value):null}var xN=typeof vd=="function"?vd:vd.default;function Zt(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 bN(e){return/^[A-Z]/.test(e)}function Pd(e){let t=e.openingElement;return N.isJSXIdentifier(t.name)?t.name.name==="Fragment":N.isJSXMemberExpression(t.name)?t.name.property.name==="Fragment":!1}function ai(e){return N.isJSXFragment(e)}function xy(e){return N.isJSXIdentifier(e.name)?e.name.name:N.isJSXMemberExpression(e.name)?by(e.name):N.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function by(e){return N.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:N.isJSXMemberExpression(e.object)?`${by(e.object)}.${e.property.name}`:e.property.name}function EN(e){return e.split(".")[0]??e}function SN(e){let t=e;for(;t;){let n=t.node;if(N.isFunctionDeclaration(n)&&n.id||N.isVariableDeclarator(n)&&N.isIdentifier(n.id))return n.id.name;if(N.isExportDefaultDeclaration(n)){let r=n.declaration;if(N.isFunctionDeclaration(r)&&r.id)return r.id.name;if(N.isFunctionDeclaration(r)&&!r.id)return"default"}t=t.parentPath}return null}function IN(){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 vN(e){let t=new Map;for(let n of e.program.body){if(!N.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(N.isImportDefaultSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"default"});else if(N.isImportNamespaceSpecifier(o))t.set(o.local.name,{specifier:r,exportName:"*"});else if(N.isImportSpecifier(o)){let i=N.isIdentifier(o.imported)?o.imported.name:o.imported.value;t.set(o.local.name,{specifier:r,exportName:i})}}return t}function Rr(e,t=[]){if(N.isIdentifier(e))return t.push(e.name),t;if(N.isObjectPattern(e)){for(let n of e.properties)N.isObjectProperty(n)?Rr(n.value,t):N.isRestElement(n)&&Rr(n.argument,t);return t}if(N.isArrayPattern(e)){for(let n of e.elements)n&&(N.isRestElement(n)?Rr(n.argument,t):Rr(n,t));return t}return N.isAssignmentPattern(e)?(Rr(e.left,t),t):(N.isRestElement(e)&&Rr(e.argument,t),t)}function Jn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function ls(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 _N(e,t,n){e.set(t,{resolved:!0,value:n})}function Nd(e,t){e.set(t,{resolved:!1})}function Ey(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 Lt(e,t,n){if(N.isTSAsExpression(e)||N.isTSSatisfiesExpression(e)||N.isTSNonNullExpression(e)||N.isTypeCastExpression(e)||N.isParenthesizedExpression(e))return Lt(e.expression,t,n);if(N.isLogicalExpression(e))return ac([Lt(e.left,t,n),Lt(e.right,t,n)]);if(N.isBinaryExpression(e))return ac([N.isExpression(e.left)?Lt(e.left,t,n):null,N.isExpression(e.right)?Lt(e.right,t,n):null]);if(N.isConditionalExpression(e))return ac([Lt(e.consequent,t,n),Lt(e.alternate,t,n)]);if(N.isTemplateLiteral(e))return ac(e.expressions.filter(N.isExpression).map(i=>Lt(i,t,n)));if(N.isIdentifier(e))return{kind:"identifier",expression:e.name,base:e.name,path:[]};if(!N.isMemberExpression(e)&&!N.isOptionalMemberExpression(e))return null;let r=[],o=e;for(;N.isMemberExpression(o)||N.isOptionalMemberExpression(o);){if(o.computed)if(N.isNumericLiteral(o.property))r.unshift({kind:"index",index:o.property.value});else if(N.isStringLiteral(o.property))r.unshift({kind:"property",name:o.property.value});else if(n&&N.isExpression(o.property)){let i=Hr(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(!N.isIdentifier(o.property))return null;r.unshift({kind:"property",name:o.property.name})}o=o.object}return N.isIdentifier(o)?{kind:r.some(i=>i.kind==="index")?"index-expression":"member-expression",expression:Jn(e,t),base:o.name,path:r}:null}function ac(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 Ad(e,t,n){if(N.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&N.isExpression(r)?Lt(r,t,n):null}return N.isCallExpression(e)&&N.isMemberExpression(e.callee)&&!e.callee.computed&&N.isIdentifier(e.callee.property)&&["filter","slice","sort","toSorted","reverse","toReversed"].includes(e.callee.property.name)&&N.isExpression(e.callee.object)?Ad(e.callee.object,t,n):Lt(e,t,n)}function Hr(e,t){if(N.isStringLiteral(e)||N.isNumericLiteral(e)||N.isBooleanLiteral(e))return e.value;if(N.isNullLiteral(e))return null;if(N.isTemplateLiteral(e))return e.expressions.length===0&&e.quasis.length===1?e.quasis[0].value.cooked??e.quasis[0].value.raw:void 0;if(N.isIdentifier(e)){let n=ls(e.name,t.valueScopes);return n.kind==="resolved"?n.value:void 0}if(N.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||N.isSpreadElement(r))return;let o=Hr(r,t);if(o===void 0)return;n.push(o)}return n}if(N.isObjectExpression(e)){let n={};for(let r of e.properties){if(!N.isObjectProperty(r)||r.computed||!N.isExpression(r.value))return;let o=null;if(N.isIdentifier(r.key)?o=r.key.name:N.isStringLiteral(r.key)&&(o=r.key.value),!o)return;let i;if(r.shorthand){if(!N.isIdentifier(r.value))return;let s=ls(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Hr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(N.isMemberExpression(e)){let n=Lt(e,"",t);if(!n)return;let r=ls(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Ey(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(N.isCallExpression(e))return Iy(e,t)??void 0}function Sy(e,t,n){let r=Lt(e,n,t);if(!r)return N.isMemberExpression(e)||N.isBinaryExpression(e)||N.isLogicalExpression(e)||N.isConditionalExpression(e)||N.isCallExpression(e)?{value:Jn(e,n),source:null}:null;let o=ls(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Ey(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 _d(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:IN(),parentStack:[],valueScopes:i,importMap:o}}function Cd(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of Rr(o.id))Nd(n,s);if(!N.isIdentifier(o.id)||!o.init||!N.isExpression(o.init))continue;let i=Hr(o.init,t);i!==void 0&&_N(n,o.id.name,i)}}function kN(e){let t=[];for(let n of e){if(N.isVariableDeclaration(n)){t.push(n);continue}N.isExportNamedDeclaration(n)&&n.declaration&&N.isVariableDeclaration(n.declaration)&&t.push(n.declaration)}return t}function CN(e,t,n){let r=[],o=0;for(let i of e)if(N.isJSXText(i)){let s=i.value.trim();s&&r.push({index:o++,value:s,sourceRange:Zt(i),editable:!0,source:null})}else if(N.isJSXExpressionContainer(i)&&N.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Zt(i),editable:!0,source:null});else if(N.isJSXExpressionContainer(i)&&N.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:Zt(i),editable:!0,source:null}):r.push({index:o++,value:Jn(s,n),sourceRange:Zt(i),editable:!0,source:Lt(s,n,t)})}else if(N.isJSXExpressionContainer(i)&&N.isExpression(i.expression)){let s=Sy(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Zt(i),editable:!0,source:s.source})}return r}function RN(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!N.isJSXAttribute(i))continue;let s=NN(i.name);if(!s)continue;let a=Jn(i,n);if(N.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Zt(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:Zt(i),source:null,syntaxKind:"boolean-shorthand",raw:a,order:o,resolution:{status:"resolved",value:!0},resolvedValue:!0});continue}if(N.isJSXExpressionContainer(i.value)&&N.isExpression(i.value.expression)){let c=Hr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?Iy(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Zt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=Sy(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:DN(c),sourceRange:Zt(i),source:Lt(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=AN(i.value.expression,t),d=Lt(i.value.expression,n,t),p=l?.value??Jn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":p,sourceRange:Zt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function PN(e,t,n){return e.attributes.flatMap((r,o)=>!N.isJSXSpreadAttribute(r)||!N.isExpression(r.argument)?[]:[{raw:Jn(r.argument,n),sourceRange:Zt(r),order:o,source:Lt(r.argument,n,t)}])}function NN(e){return N.isJSXIdentifier(e)?e.name:N.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function AN(e,t){return ar(e,{resolveIdentifier(n){let r=ls(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=Hr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Iy(e,t){let n=si(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function si(e,t){if(N.isStringLiteral(e))return[e.value];if(N.isTemplateLiteral(e))return e.expressions.length>0?null:[e.quasis.map(n=>n.value.cooked??"").join("")];if(N.isNullLiteral(e))return[];if(N.isBooleanLiteral(e))return e.value?null:[];if(N.isIdentifier(e)||N.isMemberExpression(e)){if(N.isIdentifier(e)&&e.name==="undefined")return[];let n=Hr(e,t);return typeof n=="string"?[n]:null}if(N.isConditionalExpression(e)){let n=si(e.consequent,t),r=si(e.alternate,t);return!n||!r?null:[...n,...r]}if(N.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Hr(e.left,t);return n===!1||n===null?[]:si(e.right,t)}if(N.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||N.isSpreadElement(r))return null;let o=si(r,t);if(!o)return null;n.push(...o)}return n}if(N.isObjectExpression(e)){let n=[];for(let r of e.properties){if(!N.isObjectProperty(r))return null;let o=wN(r.key);if(!o)return null;n.push(o)}return n}if(N.isCallExpression(e)){let n=TN(e.callee);if(!n||!["cn","clsx","twMerge"].includes(n))return null;let r=[];for(let o of e.arguments){if(!N.isExpression(o))return null;let i=si(o,t);if(!i)return null;r.push(...i)}return r}return null}function TN(e){return N.isIdentifier(e)?e.name:N.isMemberExpression(e)&&N.isIdentifier(e.property)?e.property.name:null}function wN(e){return N.isIdentifier(e)?e.name:N.isStringLiteral(e)?e.value:null}function ON(e,t){let n=e.attributes.find(r=>N.isJSXAttribute(r)&&N.isJSXIdentifier(r.name)&&r.name.name===t);return!n||!N.isJSXAttribute(n)||!N.isJSXExpressionContainer(n.value)?null:n.value.expression}function LN(e,t){for(let n of t){let r=ON(e,n);if(r)return r}return null}function FN(e){return N.isJSXIdentifier(e.name)?e.name.name:null}function DN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function MN(e){if(!N.isCallExpression(e)&&!N.isOptionalCallExpression(e))return null;let t=e.callee;return!N.isMemberExpression(t)&&!N.isOptionalMemberExpression(t)||!N.isIdentifier(t.property)||t.property.name!=="map"||t.computed||!N.isExpression(t.object)?null:{call:e,collection:t.object,callback:e.arguments[0]}}function kd(e){return N.isArrowFunctionExpression(e)||N.isFunctionExpression(e)}function BN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function jN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function yy(e,t,n,r){if(!e||!N.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Jn(e,n),collectionSource:Ad(e,n,r)};if(t){let i=t.params[0],s=t.params[1];N.isIdentifier(i)&&(o.itemParamName=i.name),N.isIdentifier(s)&&(o.indexParamName=s.name)}return o}function Pr(e,t,n){if(!e)return[];if(N.isJSXElement(e)){if(Pd(e))return fc(e.children,t,n);let r=uc(e,t,n);return r?[r]:[]}return ai(e)?dc(e,t,n):N.isParenthesizedExpression(e)?Pr(e.expression,t,n):N.isExpression(e)?pc(e,t,n):[]}function cc(e,t,n){let r=new Map;for(let o of e.params)for(let i of Rr(o))Nd(r,i);t.valueScopes.push(r);try{if(!N.isBlockStatement(e.body))return Pr(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return vy(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function vy(e,t,n){let r=[];for(let o of e){if(N.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){Cd([o],t,i);for(let s of o.declarations)N.isIdentifier(s.id)&&(N.isJSXElement(s.init)||N.isJSXFragment(s.init))&&r.push(...Pr(s.init,t,n))}continue}r.push(...Rd(o,t,n))}return r}function Rd(e,t,n){if(N.isReturnStatement(e))return e.argument?Pr(e.argument,t,n):[];if(N.isBlockStatement(e))return Lo(e.body,t,n);if(N.isIfStatement(e)){let r=N.isBlockStatement(e.consequent)?Lo(e.consequent.body,t,n):Rd(e.consequent,t,n),o=e.alternate?N.isBlockStatement(e.alternate)?Lo(e.alternate.body,t,n):Rd(e.alternate,t,n):[];return[...r,...o]}if(N.isSwitchStatement(e))return Lo(e.cases.flatMap(r=>r.consequent),t,n);if(N.isTryStatement(e)){let r=Lo(e.block.body,t,n);return e.handler&&r.push(...Lo(e.handler.body.body,t,n)),e.finalizer&&r.push(...Lo(e.finalizer.body,t,n)),r}return[]}function Lo(e,t,n){let r=new Map;t.valueScopes.push(r);try{return vy(e,t,n)}finally{t.valueScopes.pop()}}function lc(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Zt(r),sourceCandidates:i&&i.length>0?i:void 0})}function $N(e,t,n,r){let o=LN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:xy(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!N.isJSXAttribute(s))continue;let a=FN(s);if(!a||!N.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!N.isJSXEmptyExpression(c)){if(BN(a)&&kd(c)){let l=cc(c,n,r),u=yy(o,c,r,n);lc(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(jN(a)){let l=kd(c)?cc(c,n,r):Pr(c,n,r);lc(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!N.isJSXExpressionContainer(s)||!kd(s.expression))continue;let a=cc(s.expression,n,r),c=yy(o,s.expression,r,n);lc(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function uc(e,t,n){let r=xy(e.openingElement);if(r==="Fragment"||Pd(e))return fc(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=bN(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=os(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},p=s?"component-boundary":null,g=CN(e.children,t,n),m=RN(e.openingElement,t,n),f=PN(e.openingElement,t,n),y,x,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(EN(r));S&&(y=S.specifier,x=S.exportName,E=Co(S.specifier,t.file))}let b={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Zt(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),$N(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),UN(e.children,t,n),t.parentStack.pop()),u}function dc(e,t,n){return fc(e.children,t,n)}function fc(e,t,n){let r=[];for(let o of e)if(N.isJSXElement(o))if(Pd(o))r.push(...fc(o.children,t,n));else{let i=uc(o,t,n);i&&r.push(i)}else ai(o)?r.push(...dc(o,t,n)):N.isJSXExpressionContainer(o)&&r.push(...pc(o.expression,t,n));return r}function UN(e,t,n){for(let r of e)N.isJSXElement(r)?uc(r,t,n):ai(r)?dc(r,t,n):N.isJSXExpressionContainer(r)&&pc(r.expression,t,n)}function VN(e){return e==="&&"||e==="||"||e==="??"}function pc(e,t,n){if(N.isJSXEmptyExpression(e))return[];let r=MN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Jn(r.collection,n),collectionSource:Ad(r.collection,n,t)};if(N.isArrowFunctionExpression(a)||N.isFunctionExpression(a)){let u=a.params[0],d=a.params[1];N.isIdentifier(u)&&(c.itemParamName=u.name),N.isIdentifier(d)&&(c.indexParamName=d.name)}s.push(c);let l={kind:"repeat-region",ownerKey:i?.key??"",childKeys:[],sourceRange:Zt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(N.isArrowFunctionExpression(a)||N.isFunctionExpression(a))&&l.childKeys.push(...cc(a,t,n)),l.childKeys}if(N.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Jn(e.test,n),conditionSource:Lt(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Zt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Pr(e.consequent,t,n)),s.childKeys.push(...Pr(e.alternate,t,n)),s.childKeys}if(N.isLogicalExpression(e)&&VN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Jn(e.left,n),conditionSource:Lt(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Zt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...Pr(e.right,t,n)),s.childKeys}if(N.isParenthesizedExpression(e))return pc(e.expression,t,n);if(N.isJSXElement(e)){let o=uc(e,t,n);return o?[o]:[]}return ai(e)?dc(e,t,n):[]}function JN(e){let t=e.argument;return t&&(N.isExpression(t)||ai(t))?t:null}function us(e,t){let n=[];for(let r of e){if(N.isReturnStatement(r)){let o=JN(r);o&&n.push({argument:o,statement:r,condition:t});continue}if(N.isIfStatement(r)){let o=N.isBlockStatement(r.consequent)?r.consequent.body:[r.consequent];if(n.push(...us(o,r.test)),r.alternate){let i=N.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...us(i,r.test))}continue}if(N.isSwitchStatement(r))for(let o of r.cases){let i=o.test?N.binaryExpression("===",r.discriminant,o.test):r.discriminant;n.push(...us(o.consequent,i))}}return n}function mc(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function _y(e){let{file:t,source:n,ast:r}=e,o=e.imports.map(p=>p.specifier);if(!N.traverseFast(r,p=>{if(N.isJSXElement(p)||N.isJSXFragment(p))return N.traverseFast.stop}))return{graph:mc(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=vN(r);xN(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(p){let g=SN(p);if(!g)return;let m=p.node,f=[];if(N.isArrowFunctionExpression(m))N.isExpression(m.body)||ai(m.body)?f=[{argument:m.body,statement:N.returnStatement(N.isExpression(m.body)?m.body:null)}]:N.isBlockStatement(m.body)&&(f=us(m.body.body));else{let I=m.body;N.isBlockStatement(I)&&(f=us(I.body))}if(f.length===0){p.skip();return}let y=new Map;Cd(kN(r.program.body),_d(t,g,s,a,u,[y]),y);let x=new Map;for(let I of m.params)for(let T of Rr(I))Nd(x,T);let E=N.isBlockStatement(m.body)?m.body.body:[],b=f[0]?.statement??null;for(let I of E){if(b&&I===b)break;N.isVariableDeclaration(I)&&Cd([I],_d(t,g,s,a,u,[y,x]),x)}let S=_d(t,g,s,a,u,[y,x]);for(let I of f){let T=Pr(I.argument,S,n);for(let C of T)c.includes(C)||c.push(C);if(I.condition){let C={kind:"conditional-branch",conditionExpression:Jn(I.condition,n),conditionSource:Lt(I.condition,n,S)};lc(S,"conditional-region","",I.statement,T,[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 Td(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function gc(e,t,n){return{...e,details:{...e.details??{},entryFile:t,importStack:n.map(r=>({...r}))}}}async function ky(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 ci(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??we,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:T}=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,A,P;if(C)A=mc(E),P=C;else{let X=a(E,b);if(!X.ok){g(gc(X.diagnostic,I,T));continue}u.set(E,X.module);let Z=o.validationOnly&&S<i?{graph:mc(E),localImports:X.module.imports.map(H=>H.specifier)}:_y(X.module);A=Z.graph,P=Z.localImports}let F=[...new Set([...A.elements.values()].map(X=>X.importedFrom).filter(X=>typeof X=="string"&&mt(X)))],B=F.length?await ky(F,X=>Na(E,X,r)):[],U=new Map(F.map((X,Z)=>[X,B[Z]]));for(let X of A.elements.values())if(X.importedFrom&&mt(X.importedFrom)){let Z=X.importedFrom,H=U.get(Z);H.ok?(X.importedFrom=H.path,vr(H.path)&&(X.isPublicUiComponent=!0)):Co(Z,E)||g(gc(H.diagnostic,I,Td(T,E,Z,H.diagnostic.path)))}if(l.set(E,A),S>=i)continue;let G=await ky(P,async X=>{if(ih(X))return null;let Z=U.get(X)??await Na(E,X,r);if(!Z.ok)return Co(X,E)?null:{diagnostic:gc(Z.diagnostic,I,Td(T,E,X,Z.diagnostic.path))};let H=Z.path;if(f.has(H)||vr(H))return null;let he=Td(T,E,X,H);try{let ue=await n(H);return{entry:{file:H,source:ue,depth:S+1,diagnosticEntryFile:I,importStack:he}}}catch(ue){return{diagnostic:gc({path:H,code:"import-read-failed",message:`Failed to read imported file: ${H}`,details:{fromFile:E,specifier:X,reason:ue instanceof Error?ue.message:String(ue)}},I,he)}}});for(let X of G)X&&"entry"in X?m.push(X.entry):X&&g(X.diagnostic)}let y=KN(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 KN(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 Cy(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 bA}from"@vcp-dev/contracts";import{createHash as XN,randomUUID as Ud}from"node:crypto";import St from"node:fs/promises";import vt from"node:path";var Dy=new WeakMap;function li(e){return Dy.get(e)?.()??e.readIndex()}var On=1,Od=1,zN=2,HN="index.json",WN="recovery.json",GN="transaction-journal.json",YN="document-version.json",xc={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Ae={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},Oe=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function Nr(){return{entries:new Map,blobSizes:new Map}}function hc(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)My(n,r,t);return n}function My(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 By(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 jy(e,t={}){let n=pA(e),r=yA(t.limits),o=wd(n),i=mA(n),s=await cn(i),a=await cn(o)||s;a||(await iA(n),await sA(n)),a||await xA(n);let c=Nr(),l=await Ec(n,c),u=new Set(a?(await kc(n)).map(E=>E.stageId):[]);a||await Ty(n,l.entryIds,c);let d=l.digest,p=hc(l.entryIds,c),g=async E=>{let{index:b,sizeBytes:S}=await gs(n);if(zy(b,E),b.digest!==d){let I=Nr();await Jy(n,b.entryIds,I,S),p=hc(b.entryIds,I),d=b.digest}return{...Cc(b),totalBytes:p.objectBytes+S}},m=async E=>{Vd(E),await g(),await Ny(n,p,[E.entryId],E.blobIds,E.stageId),await bc(n,E.stageId)},f=async(E,b)=>{let S=await g(b);Uy(E,S.entryIds.length);let I=Nr();for(let T of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await fs(n,T,I);return S},y=async()=>{if(await cn(o)||s)throw new Oe(Ae.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},x={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return Ly(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new Oe(Ae.INVALID_SCHEMA,"document version must be a non-negative integer");let b=await Ly(n);E<=b||await ds(Yy(n),{schemaVersion:1,version:Math.max(b,E)})},async stageAppend(E,b={}){await y();let S=await QN(E,r),I={schemaVersion:Od,stageId:Ud(),entryId:S.entryId,blobIds:S.blobs.map(T=>T.digest)};try{await eA(n,S),await nA(n,I,b.durableManifest!==!1)}catch(T){try{await m(I)}catch(C){throw new Oe(Ae.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:C})}throw T}return{stageId:I.stageId,entryId:I.entryId,blobIds:I.blobIds}},async discardStage(E){await y(),Dd(E);let b=await Ld(n,E);b&&await m(b)},async previewStagedAppend(E,b){await y();let S=await g(b);return(await Ry(n,r,E,S,p)).transition},async previewCursor(E,b){await y();let S=await f(E,b);return $y(S,S.entryIds,E)},async publishStagedAppend(E,b,S){if(await y(),Ic(E,"entryId"),S){Dd(S);let P=await Ld(n,S);if(!P||P.entryId!==E)throw new Oe(Ae.INVALID_SCHEMA,"history stage does not match the published entry")}let I=await g(b),T=p,C=await Ry(n,r,E,I,T),A=await Oy({rootDir:n,previousDigest:C.current.digest,entryIds:C.entryIds,cursor:C.cursor,readback:async()=>wy(n,C.usage),afterWrite:async()=>{S?await bc(n,S):await oA(n,E),await Ny(n,C.usage,[...T.entries.keys()].filter(P=>!C.usage.entries.has(P)),[...T.blobs.keys()].filter(P=>!C.usage.blobs.has(P)))}});return p=C.usage,d=A.digest,A},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 Ic(E,"entryId"),fs(n,E)},async readBlob(E){Ic(E,"blobId");let b=await qy(n,E),S=await ps(b,Ae.NOT_FOUND,"blob");return Gy(S,E,b),S},async readIndex(){let E=Nr(),b=await Ec(n,E);return p=hc(b.entryIds,E),d=b.digest,b},async readStatus(){let E=await Sc(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 cn(o)||await cn(i)}},async readUndoRedoIds(){let E=await Sc(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 Oy({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>wy(n,p)});return d=I.digest,I},async markRecoveryRequired(E){await cn(o)||await ds(wd(n),{schemaVersion:On,reason:gA(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await St.rm(wd(n),{force:!0})},async readTransactionJournal(){return await cn(i)?yc(i):null},async writeTransactionJournal(E){await y(),Zy(E);try{await ds(i,E)}catch(S){let I=await yc(i).catch(()=>null);if(I&&Buffer.from(ln(I)).equals(Buffer.from(ln(E))))return;throw I?new Oe(Ae.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let b=await yc(i);if(!Buffer.from(ln(b)).equals(Buffer.from(ln(E))))throw new Oe(Ae.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let b=await cn(i)?await yc(i):null;if(b&&b.transactionId!==E)throw new Oe(Ae.INVALID_SCHEMA,"transaction journal changed concurrently");try{await St.rm(i,{force:!0})}catch(S){if(!await cn(i))return;throw S}if(await cn(i))throw new Oe(Ae.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let S of u)await bc(n,S),u.delete(S);await aA(n);let E=Nr(),b=await Ec(n,E);await Ty(n,b.entryIds,E),p=hc(b.entryIds,E),d=b.digest}};return Dy.set(x,()=>Sc(n)),x}async function Ry(e,t,n,r,o){Ic(n,"entryId");let i=Nr(),s=await fs(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))By(a,u);My(a,s.id,i),c.push(s.id);let l=tA(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:$y(r,l.entryIds,l.cursor)}}function $y(e,t,n){return Uy(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:ZN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function ZN(e,t){return Wr(ln({schemaVersion:On,entryIds:e,cursor:t}))}function Uy(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new Oe(Ae.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function qN(e){if(!Kn(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!yn(e.expectedIndexDigest)||!yn(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!yn(n)?!1:t===-1?n===null:yn(n)}async function QN(e,t){if(!e.kind.trim())throw new Oe(Ae.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new Oe(Ae.INVALID_JSON,"history blob name must not be empty");let l=fA(c.data),u=Wr(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:On,kind:e.kind,manifest:e.manifest,blobs:r},i=ln({...o}),s=Wr(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new Oe(Ae.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function eA(e,t){let n=zd(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=>Py(Hd(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Gd(e,c.digest))),Py(n,ln(r),{kind:"entry",digest:t.entryId},Wd(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function Py(e,t,n,r){let o=await jd(e)??(r?await jd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new Oe(n.kind==="blob"?Ae.BLOB_CORRUPT:Ae.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await Hy(e,t)}function tA(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+ln(Xy(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new Oe(Ae.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");By(n,r.shift()),o-=1}}async function nA(e,t,n){Vd(t);let r=Xd(e,t.stageId);if(n){await ds(r,t);return}await dA(r,t)}async function Ld(e,t){let n=await jd(Xd(e,t));if(n===null)return null;let r=hs(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=Vd(r);if(o.stageId!==t)throw new Oe(Ae.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function kc(e){let t=[];for(let n of await _c(Kd(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);Dd(r);let o=await Ld(e,r);o&&t.push(o)}return t}async function Ny(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 kc(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 Ay(zd(e,a),Wd(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await Ay(Hd(e,a),Gd(e,a));await $d(ys(e)),await $d(xs(e))}async function bc(e,t){await Fd(Xd(e,t)),await rA(e)}async function rA(e){try{await St.rmdir(Kd(e))}catch(t){if(bs(t)||Kn(t)&&t.code==="ENOTEMPTY")return;throw t}}async function oA(e,t){for(let n of await kc(e))n.entryId===t&&await bc(e,n.stageId)}async function Fd(e){if(await St.rm(e,{force:!0}),await cn(e))throw new Oe(Ae.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function Ay(e,t){await Fd(e),await Fd(t)}function Vd(e){if(!Kn(e)||e.schemaVersion!==Od||typeof e.stageId!="string"||!Vy(e.stageId)||!yn(e.entryId))throw new Oe(Ae.INVALID_SCHEMA,"history stage schema is invalid");let t=Wy(e.blobIds,"history stage blobIds");return{schemaVersion:Od,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function Dd(e){if(!Vy(e))throw new Oe(Ae.INVALID_PATH,"history stageId must be a UUID")}function Vy(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 Ty(e,t,n=Nr()){let r=new Set(t),o=new Set;for(let l of t){let u=await fs(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await kc(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=ys(e),s=await _c(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=Fy(l.slice(0,-5));u&&!r.has(u)&&await vc(vt.join(i,l))}let a=xs(e),c=await _c(a);for(let l of c){let u=Fy(l);u&&!o.has(u)&&await vc(vt.join(a,l))}}async function Ec(e,t=Nr()){let{index:n,sizeBytes:r}=await gs(e),{totalBytes:o}=await Jy(e,n.entryIds,t,r);return{...Cc(n),totalBytes:o}}async function wy(e,t){let{index:n,sizeBytes:r}=await gs(e);return{...Cc(n),totalBytes:t.objectBytes+r}}async function gs(e){let t=Jd(e),n=await ps(t,Ae.NOT_FOUND,"index"),r=hs(Buffer.from(n).toString("utf8"),"index");return{index:cA(r),sizeBytes:n.byteLength}}async function Sc(e){return Cc((await gs(e)).index)}function Cc(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:On,digest:e.digest,entryIds:t,cursor:e.cursor,currentId:t[e.cursor]??null,undoIds:n,redoIds:r}}async function Jy(e,t,n,r){let o=0,i=new Set;o+=r??(await gs(e)).sizeBytes;for(let s of new Set(t)){let a=await fs(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 fs(e,t,n=Nr()){let r=n.entries.get(t);if(r)return r.entry;let o=await hA(e,t),i=await ps(o,Ae.NOT_FOUND,"entry"),s=hs(Buffer.from(i).toString("utf8"),`entry ${t}`),a=lA(s);if(a.id!==t)throw new Oe(Ae.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Wr(ln({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new Oe(Ae.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 qy(e,d),g=await ps(p,Ae.NOT_FOUND,"blob");return Gy(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 Ky(e,t,n){await ds(Jd(e),Xy(t,n))}function Xy(e,t){return{schemaVersion:On,digest:Wr(ln({schemaVersion:On,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function zy(e,t){if(t!==void 0&&e.digest!==t)throw new Oe(Ae.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function Oy(e){zy(await Sc(e.rootDir),e.previousDigest);let t=Wr(ln({schemaVersion:On,entryIds:e.entryIds,cursor:e.cursor}));try{await Ky(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new Oe(Ae.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Ec(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new Oe(Ae.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function iA(e){await St.mkdir(e,{recursive:!0}),await St.mkdir(ys(e),{recursive:!0}),await St.mkdir(xs(e),{recursive:!0}),await St.mkdir(ms(e),{recursive:!0})}async function sA(e){await St.rm(ms(e),{recursive:!0,force:!0}),await St.mkdir(ms(e),{recursive:!0})}async function aA(e){let t=ms(e);await St.mkdir(t,{recursive:!0});for(let n of await _c(t))n!=="stages"&&await St.rm(vt.join(t,n),{recursive:!0,force:!0})}function cA(e){if(!Kn(e))throw new Oe(Ae.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==On)throw new Oe(Ae.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Wy(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new Oe(Ae.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!yn(o))throw new Oe(Ae.INDEX_CORRUPT,"index digest is invalid");let i=Wr(ln({schemaVersion:On,entryIds:t,cursor:r}));if(o!==i)throw new Oe(Ae.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:On,digest:o,entryIds:t,cursor:r}}function lA(e){if(!Kn(e))throw new Oe(Ae.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==On)throw new Oe(Ae.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!yn(t))throw new Oe(Ae.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new Oe(Ae.ENTRY_CORRUPT,"entry kind is invalid");let r=Bd(e.manifest,"entry.manifest"),o=uA(e.blobs);return{id:t,schemaVersion:On,kind:n,manifest:r,blobs:o}}function uA(e){if(!Array.isArray(e))throw new Oe(Ae.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!Kn(t))throw new Oe(Ae.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new Oe(Ae.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!yn(o))throw new Oe(Ae.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new Oe(Ae.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function ds(e,t){await Hy(e,ln(t))}async function dA(e,t){let n=vt.dirname(e),r=vt.basename(e),o=vt.join(n,`.${r}.${process.pid}.${Ud()}.tmp`);await St.mkdir(n,{recursive:!0});try{await St.writeFile(o,ln(t),{flag:"wx"}),await St.rename(o,e)}finally{await vc(o)}}async function Hy(e,t){let n=vt.dirname(e),r=vt.basename(e),o=vt.join(n,`.${r}.${process.pid}.${Ud()}.tmp`);await St.mkdir(n,{recursive:!0});try{let i=await St.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await St.rename(o,e),await $d(n)}finally{await vc(o)}}function ln(e){return Buffer.from(JSON.stringify(Md(e)),"utf8")}function Md(e){if(Array.isArray(e))return e.map(t=>Md(t));if(Kn(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Md(e[n]);return t}return e}function hs(e,t){try{return JSON.parse(e)}catch(n){throw new Oe(Ae.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function Bd(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=>Bd(n,t));if(Kn(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=Bd(o,t);return n}break}throw new Oe(Ae.INVALID_JSON,`${t} must be JSON-serializable`)}function Wy(e,t){if(!Array.isArray(e))throw new Oe(Ae.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!yn(n))throw new Oe(Ae.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function Ic(e,t){if(!yn(e))throw new Oe(Ae.INVALID_PATH,`${t} must be a sha256 digest`)}function yn(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Wr(e){return`sha256:${XN("sha256").update(e).digest("hex")}`}function fA(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function ps(e,t,n){try{return await St.readFile(e)}catch(r){throw new Oe(t,`${n} not found: ${e}`,{cause:r})}}async function jd(e){try{return await St.readFile(e)}catch(t){if(bs(t))return null;throw t}}function Gy(e,t,n){if(Wr(e)!==t)throw new Oe(Ae.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function cn(e){try{return await St.access(e),!0}catch(t){if(bs(t))return!1;throw t}}async function vc(e){try{await St.rm(e,{force:!0,recursive:!0})}catch{}}async function $d(e){try{let t=await St.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function _c(e){try{return await St.readdir(e)}catch(t){if(bs(t))return[];throw t}}function pA(e){if(typeof e!="string"||e.trim().length===0)throw new Oe(Ae.INVALID_ROOT,"history store rootDir must be a non-empty string");return vt.resolve(e)}function Jd(e){return vt.join(e,HN)}function wd(e){return vt.join(e,WN)}function mA(e){return vt.join(e,GN)}function Yy(e){return vt.join(e,YN)}async function Ly(e){try{let t=await St.readFile(Yy(e),"utf8"),n=hs(t,"document version");if(!Kn(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new Oe(Ae.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(bs(t))return 0;throw t}}async function yc(e){let t=await ps(e,Ae.RECOVERY_PENDING,"transaction journal"),n=hs(Buffer.from(t).toString("utf8"),"transaction journal");return Zy(n),n}function Zy(e){if(!Kn(e)||e.schemaVersion!==zN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!qN(e.historyTransition)||!Array.isArray(e.files))throw new Oe(Ae.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!Kn(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!yn(t.preDigest)||t.postDigest!==null&&!yn(t.postDigest))throw new Oe(Ae.INVALID_SCHEMA,"transaction journal file digest is invalid")}function gA(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function ys(e){return vt.join(e,"entries")}function xs(e){return vt.join(e,"blobs")}function ms(e){return vt.join(e,"tmp")}function Kd(e){return vt.join(ms(e),"stages")}function Xd(e,t){return vt.join(Kd(e),`${t}.json`)}function zd(e,t){return vt.join(ys(e),`${ex(t)}.json`)}function Hd(e,t){return vt.join(xs(e),ex(t))}function Wd(e,t){return vt.join(ys(e),`${t}.json`)}function Gd(e,t){return vt.join(xs(e),t)}async function hA(e,t){return Qy(zd(e,t),Wd(e,t))}async function qy(e,t){return Qy(Hd(e,t),Gd(e,t))}async function Qy(e,t){return await cn(e)?e:await cn(t)?t:e}function ex(e){return e.slice(7)}function Fy(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return yn(t)?t:null}function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bs(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function yA(e){return{maxEntries:e?.maxEntries??xc.maxEntries,maxSessionBytes:e?.maxSessionBytes??xc.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??xc.maxEntryBytes}}async function xA(e){let t=Jd(e);await cn(t)||await Ky(e,[],-1)}var EA={affectedCompositions:[]};function ix(e){let t=null,n=new WeakMap;async function r(){return t??=SA(e),t}async function o(i){if(!i)return null;let s=Yd(i);return s?IA(e,s):i}return{async prepareAppend(i){let s=await li(e),a=await e.stageAppend(rx(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 li(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 li(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);tx(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,ui(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(Yd(c.at(-1))!==Yd(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);tx(l,i.historyTransition),Object.assign(a,ui(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await li(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,ui(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(rx(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,ui(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,ui(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 tx(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 Yd(e){return typeof e=="string"?e:e?.historyId}async function SA(e){let t=await li(e);return ui(t)}function ui(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function IA(e,t){let n=await e.readEntry(t),r=vA(n),o=r.provenance??EA;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 nx(e,n,r.preSnapshots),postSnapshots:await nx(e,n,r.postSnapshots)}}async function nx(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(CA(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function rx(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=_A(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 vA(e){if(!ax(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:sx(t.provenance)}:{},preSnapshots:ox(t.preSnapshots,"preSnapshots"),postSnapshots:ox(t.postSnapshots,"postSnapshots")}}function _A(e){if(e.provenance!==void 0)return sx(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function sx(e){let t=bA.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 ox(e,t){return e.map((n,r)=>{if(!ax(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&&!kA(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 kA(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function CA(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function ax(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as RA}from"@vcp-dev/contracts";var cx={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 Zd(){let e=RA.safeParse(cx);return e.success?e.data:null}import{randomBytes as PA}from"node:crypto";import Rc from"node:path";import{parse as gx}from"@babel/parser";import NA from"@babel/traverse";import*as hx from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Qd,PageResourceArtifactSchema as AA,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as TA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as wA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as OA,parseComponentI18nResourcesJson as LA}from"@vcp-dev/contracts";var ef="{{$INSTANCE}}",FA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,DA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,tf="components/site/generated",MA=/\.(?:tsx?|json)$/,BA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,jA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],$A=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),qd=NA,UA=typeof qd=="function"?qd:qd.default;async function nf(e){let t=AA.safeParse(e.artifact);if(!t.success)return It("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>PA(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=YA(r());if(!i)return It("Random instance suffix must be 8 lowercase hex chars.");let s=`${ZA(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=lx({materialization:b.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!S.ok)return S;for(let I of S.files){let T=dx(I,d,u);if(T)return T}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],T=lx({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:I.route_file_path,pageTitle:I.title});if(!T.ok)return T;for(let C of T.files){let A=dx(C,d,u);if(A)return A}p.add(T.entry),m.set(T.entry,T.entryExport),f.push({entry:T.entry,declaredComponentIds:new Set(S.components.map(C=>C.component_id))})}let x=JA(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?nf({...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=KA(u);return E||(u.sort((b,S)=>b.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function lx(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:ux(o.pathTemplate,e.packageInstanceId);if(!s)return It("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=VA(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?zA(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??ux(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?It("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function VA(e,t,n,r){let o,i=e.replace(FA,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return It(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(DA,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return It(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(ef,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?It("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function ux(e,t){let n=`${tf}/${t}`;if(e.split(ef).length>2)return null;let o=e.replace(ef,t),i=`${tf}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=Rc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!MA.test(a)||BA.test(a)?null:a}function dx(e,t,n){return t.has(e.file)?It(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function JA(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${tf}/${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 It("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Qd)&&!LA(g.content).success)return It("Materialization component i18n resources are invalid.",g.file);continue}try{let m=gx(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=WA(g.file,x,s,a);if(!E.allowed)return It(`Materialization import is outside the controlled package: ${x}`,g.file);E.internalPath&&c.get(g.file).add(E.internalPath)}let f;if(UA(m,{Identifier(y){y.isReferencedIdentifier()&&$A.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 It(`Materialization source uses forbidden capability: ${f}`,g.file)}catch{return It("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return It("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return It("Materialization JSON files cannot be package entries.");for(let[g,m]of i){let f=l.get(g);if(!f||!XA(f,m))return It("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=mx(g.entry,c);for(let f of g.declaredComponentIds){let y=r.get(f);if(!y||!m.has(y))return It(`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 It(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let m of mx(g,c))d.add(m);if(d.size!==e.length)return It("Every materialization file must be reachable from a package entry.");let p=GA(e,l,c);return p||{ok:!0}}function KA(e){if(e.length>TA)return It("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>wA)return It("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>OA?It("Page resource exceeds the aggregate content byte limit."):null}function XA(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 zA(e,t,n){let r;try{r=gx(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return It("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=fx(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&HA(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=fx(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 fx(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&hx.isExpression(t)?t:null}function HA(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function WA(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=px(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:jA.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=Rc.posix.normalize(Rc.posix.join(Rc.posix.dirname(e),t)),i=px(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function px(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 GA(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Qd))continue;let i=o.file.slice(0,-Qd.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return It("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 It("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function mx(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 YA(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function ZA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function It(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as vT}from"node:crypto";import Tr from"node:path";import{parse as _T}from"@babel/parser";import kT from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as Nc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as vx,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as CT,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as RT,SiteEditMaterializationSchema as PT,parseComponentI18nResourcesJson as NT}from"@vcp-dev/contracts";import{parse as pT}from"@babel/parser";import mT from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as gT,FormDefinitionIdSchema as hT}from"@vcp-dev/contracts";var xx={colorMixPolicy:"always",includeExtendedColorFunctions:!0},bx=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Ex=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,qA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,QA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,eT=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,tT=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,nT=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,rT=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,oT=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,iT=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,sT=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,aT=/\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,cT=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,lT=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function rf(e,t){let n=Pc([...Ln(e,qA),...Ln(e,QA),...Ln(e,eT),...Ln(e,t.includeRgbBackgroundImage?tT:nT),...t.includeExtendedColorFunctions?[...Ln(e,rT),...Ln(e,oT)]:[]]),r=Pc([...Ln(e,iT),...Ln(e,sT)]).filter(o=>t.colorMixPolicy==="always"||bx.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Ln(e,aT).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Ln(e,lT).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:Pc(Ln(e,Ex)),hardCodedSurfaceOccurrences:fT(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?uT(e):[]}}function uT(e){return Pc(Ln(e,cT))}function Ln(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var yx=160,dT=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function fT(e){let t=new RegExp(Ex.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=dT.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>yx?`${g.slice(0,yx-1)}\u2026`:g})}return o}function Pc(e){return[...new Set(e)]}var yT=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],xT=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Sx=new Set(["require","module","exports","__dirname","__filename"]),of=mT,bT=typeof of=="function"?of:of.default;function af(e,t={}){let n=[],r=ET(t.hostCapabilities),o=rf(e,t.style??xx),i;try{i=pT(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"&&IT(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 bT(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(sf(u.node))},OptionalMemberExpression(u){l(sf(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)&&hT.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&yT.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?ST(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||!xT.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:Sx.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:Sx.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function ET(e){if(e==null)return null;let t=gT.safeParse(e);return t.success?t.data:null}function ST(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)):Ix(n)===Ix(o)})}function Ix(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function IT(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function sf(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?sf(e.object):null}var Nx="components/site/generated",_x="{{$INSTANCE}}",Ac=5,AT=/^[a-z][a-z0-9-]{0,48}$/,TT=/^[a-f0-9]{8}$/,kx=/\.tsx?$/,wT=/\.json$/,OT=/\.(?:tsx?|json)$/,LT=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,cf=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),lf=kT,FT=typeof lf=="function"?lf:lf.default;function DT(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>vx)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=ZT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=PT.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=WT(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${Nx}.`,path:e.generatedRoot}};if(!Ax(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=Rx(r.data.files),s=Rx(e.controlledFiles);if(!qT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>vx)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>CT)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>RT?{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 MT(e){let t=DT(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=Ax(e.manifest.instanceBaseName),o=Math.max(1,Math.min(Ac,e.maxAttempts??Ac));for(let i=0;i<o;i+=1){let s=GT(e.instanceNameGenerator?.()??vT(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=wx(n,a),l=BT({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await $T(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 uf(e){let t=Math.max(1,Math.min(Ac,e.maxAttempts??Ac));for(let n=0;n<t;n+=1){let r=await MT({...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 BT(e){let t=jT(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=Es({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=Es({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=df({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 jT(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 $T(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function Es(e){if(e.pathTemplate.split(_x).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(_x,e.instanceName),n=YT(t);return n?wx(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||!OT.test(n)||LT.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 df(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(wT.test(g.path)){if(g.path.endsWith(Nc)){let x=NT(g.content);if(!x.success)return Ar("MATERIALIZATION_DATA_UNSUPPORTED",x.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return Ar("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let m;try{m=_T(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=af(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=VT(f.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,m)}for(let g of t){if(!kx.test(g.path))continue;let m=c.get(g.path),f=null;if(FT(m,{ImportDeclaration(y){let x=Cx({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&&!JT(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(Nc))){let E=XT({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=Cx({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=Px(y.node);x&&cf.has(x)&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let x=Px(y.node);x&&cf.has(x)&&(f??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${x}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&cf.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"||UT(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&&Tc(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&&Tc(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 Ar("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 Ar("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!kx.test(g.path))return Ar("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let m=c.get(g.path);if(!m)return Ar("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!zT(m,g.export))return Ar("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 Ar("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 HT(g.path,l))p.add(m);return p.size!==t.length?Ar("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function Tc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function UT(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"||Tc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!Tc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function VT(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 Cx(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 JT(e,t,n){if(n===null)return!0;let r=KT(e);return r===null||t.has(r)&&n.has(r)}function KT(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 XT(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,-Nc.length),i=`./${r}${Nc}`;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 zT(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 HT(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 Ar(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function WT(e){let t=Tx(e);return t===Nx?t:null}function GT(e){let t=e.trim().toLowerCase();return TT.test(t)?t:null}function Ax(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 AT.test(t)?t:null}function Tx(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 YT(e){let t=Tx(e);return!t||t!==e?null:t}function wx(...e){return Tr.posix.join(...e)}function Rx(e){return new Set(e.map(t=>t.pathTemplate))}function ZT(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 qT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Px(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 Mf}from"node:crypto";import Af from"@babel/traverse";function ff(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 wc(e){if(e.node.alternate||!QT(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 QT(e){let t=Ox(e);return e.traverse({enter(n){Ox(n)||(t=!1,n.stop())}}),t}function Ox(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 vw}from"node:crypto";import Kx from"node:path";import*as pi from"@babel/parser";import Sf from"@babel/traverse";import If from"@babel/generator";import*as _e from"@babel/types";import yf from"@babel/generator";import{parse as uw}from"@babel/parser";import xf from"@babel/traverse";import*as Ve from"@babel/types";import{PortableInvocationBindingSchema as dw}from"@vcp-dev/contracts";import pf from"@babel/traverse";import*as Xe from"@babel/types";var Lx=typeof pf=="function"?pf:pf.default;function qt(e){let t=Dx(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?Fx(t,e.allowNonRenderingGuards):Gr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function Fn(e){let t=ew(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?Fx(t.definition):t.kind==="imported"?!e.imported?.module&&!mt(t.specifier)?Gr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?qt({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):Gr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):Gr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):Gr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function Fx(e,t=!1){let n=iw(e.module.ast,e.node);if(!n)return Gr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=Mx(n,t);if(!r){let s=aw(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:Gr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=Bx(r);return Lc(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:Gr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function ew(e,t,n){let r={kind:"unresolved"};return Lx(e.ast,{JSXElement(o){if(!rw(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Xe.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(tw(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=nw(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function tw(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function nw(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&hf(t.node)?t.node:null}function rw(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 Dx(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=Ur(e.file,u,n),g=p?n.get(p):void 0;return g?Dx(g,d,n,i):null},a=u=>{let d=ow(e,u);if(d)return{...d,module:e};for(let p of e.ast.program.body)if(!(!Xe.isImportDeclaration(p)||p.importKind==="type")){for(let g of p.specifiers)if(g.local.name===u){if(Xe.isImportDefaultSpecifier(g))return s(p.source.value,"default");if(Xe.isImportSpecifier(g)&&g.importKind!=="type")return s(p.source.value,Oc(g.imported))}}return null};for(let u of e.ast.program.body){if(Xe.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(hf(d))return{node:d,name:lw(d)??"default",module:e};if(Xe.isIdentifier(d))return a(d.name)}if(!(!Xe.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=cw(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Xe.isExportSpecifier(d)&&d.exportKind!=="type"&&Oc(d.exported)===t)return u.source?s(u.source.value,Oc(d.local)):a(Oc(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Xe.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 ow(e,t){for(let n of e.ast.program.body){let r=Xe.isExportNamedDeclaration(n)?n.declaration:n;if(Xe.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Xe.isVariableDeclaration(r)){for(let o of r.declarations)if(Xe.isIdentifier(o.id)&&o.id.name===t&&hf(o.init))return{node:o.init,name:t}}}return null}function iw(e,t){let n=null;return Lx(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function Mx(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()||sw(i)||t&&i.isIfStatement()&&wc(i))?null:o.get("argument")}function sw(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(!Xe.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 aw(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=mf(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(!Xe.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=>!Xe.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Xe.isJSXSpreadAttribute(c)||Xe.isJSXAttribute(c)&&Xe.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function mf(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=>mf(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:mf(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function Lc(e,t){if(Bx(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()||!Lc(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()||Lc(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?Lc(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function gf(e){return["base","link","meta","script","style","title"].includes(e)}function Bx(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Xe.isJSXIdentifier(o)&&gf(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||!Xe.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=Mx(s);return a!==null&&n(a)}return!1};return n(e)&&t}function cw(e,t){return Xe.isFunctionDeclaration(e)?e.id?.name===t?t:null:Xe.isVariableDeclaration(e)&&e.declarations.some(n=>Xe.isIdentifier(n.id)&&n.id.name===t)?t:null}function hf(e){return Xe.isFunctionDeclaration(e)||Xe.isFunctionExpression(e)||Xe.isArrowFunctionExpression(e)}function lw(e){return"id"in e&&e.id&&Xe.isIdentifier(e.id)?e.id.name:null}function Oc(e){return Xe.isIdentifier(e)?e.name:e.value}function Gr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var bf=typeof yf=="function"?yf:yf.default,jx=typeof xf=="function"?xf:xf.default,Ux=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),fw=new Set(["sourceOrder","source_order","originalOrder","original_order"]),pw=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"]),mw=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,gw=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function Zr(e){if(!Jx(e)||!Array.isArray(e.bindings))return Yr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=bw(e);if(!t||!gw.test(t))return Yr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=Vx(e.targetBlockId);if(!n.ok)return n;let r=Ew(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!mw.test(o))return Yr("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=dw.safeParse(g);if(!m.success)return Yr("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 Yr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${f.propName}.`,`bindings.${p}.propName`);if(a.add(f.propName),fw.has(f.propName))return Yr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${p}`);if(Ux.has(f.propName)&&f.value.kind!=="target-block-id")return Yr("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 Yr("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(Ve.jsxAttribute(Ve.jsxIdentifier(f.propName),Ve.jsxExpressionContainer(yw(f.value,n.value,o))))}let d=Ve.jsxElement(Ve.jsxOpeningElement(xw(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:bf(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,requiresRouteParams:l,searchParamsIdentifier:c?o:null}}}function hw(e){if(!Jx(e)||e.jsx===void 0==(e.source===void 0))return di("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=Vx(e.targetBlockId);if(!t.ok)return di("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return di("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=we("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=uw(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return di("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=qt({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 jx(r,{JSXElement(g){$x(g)||i.push(g.node)},JSXFragment(g){$x(g)||i.push(g.node)}});if(i.length!==1)return di("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=Sw(a);if(!c)return di("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=Iw(g.node.name);!m||!pw.has(m)||(m==="data-site-block-id"||m==="data-vcp-block-id"||Ux.has(m)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):jx(r,{JSXAttribute:d}),c.openingElement.attributes.push(Ve.jsxAttribute(Ve.jsxIdentifier("data-site-block-id"),Ve.stringLiteral(t.value)),Ve.jsxAttribute(Ve.jsxIdentifier("data-site-block-order"),Ve.jsxExpressionContainer(Ve.numericLiteral(e.targetOrder))));let p=n?bf(a,{jsescOption:{minimal:!0}}).code:bf(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 yw(e,t,n){return e.kind==="route-params"?Ve.identifier("params"):e.kind==="route-search-params"?Ve.identifier(n):e.kind==="target-block-id"?Ve.stringLiteral(t):Ef(e.value)}function Ef(e){return e===null?Ve.nullLiteral():typeof e=="string"?Ve.stringLiteral(e):typeof e=="number"?Ve.numericLiteral(e):typeof e=="boolean"?Ve.booleanLiteral(e):Array.isArray(e)?Ve.arrayExpression(e.map(t=>Ef(t))):Ve.objectExpression(Object.entries(e).map(([t,n])=>Ve.objectProperty(Ve.stringLiteral(t),Ef(n))))}function xw(e){let t=e.split("."),n=Ve.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Ve.jsxMemberExpression(n,Ve.jsxIdentifier(r));return n}function bw(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 Vx(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 Ew(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 Sw(e){if(Ve.isJSXElement(e))return e;let t=e.children.filter(Ve.isJSXElement),n=e.children.some(r=>Ve.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function $x(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function Iw(e){return Ve.isJSXIdentifier(e)?e.name:null}function Jx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function di(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var vf=typeof If=="function"?If:If.default,_w=typeof Sf=="function"?Sf:Sf.default;function _s(e){let t=Yx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=Nf(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=Rw(n,o),s=Mw(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=kw(e);if(i){let m=_f(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??(Dc(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return Ss("Route page composition does not expose a verifiable container boundary.");let d=vs(l),p=zx(e.source,d,u,"Route page composition container");if(!p.ok)return p.result;let g=o.anchorSourceRange?vs(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return Ss("Route page composition placement does not expose a verifiable anchor boundary.");let m=zx(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 Rf(e){let t=we(e.entryFile,e.source);if(!t.ok)return qr("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 qr("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&&Dc(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,p)=>d+Wx(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 qr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return qr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=_s({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=ks({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 qr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=Tn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return qr("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 qr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=wn({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}}:qr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Wx(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Wx(r,t),0)}function qr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function kw(e){let t=Tw(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 ks(e){if(e.locator.root.kind!=="expression"||e.locator.path?.length)return Fo(e.source,"Root expression rewrite requires an exact expression locator.");let t=Zi(e.source,"value");if(!t.ok)return Fo(e.source,t.diagnostic.message);let n=Be(t.ast,e.locator);if(!n.ok)return Fo(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return Fo(e.source,"Resolved value locator does not point to an expression.");let o=fi(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return Fo(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(_e.nullLiteral()),{ok:!0,source:vf(t.ast,{}).code};let i;try{i=pi.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return Fo(e.source,s instanceof Error?s.message:String(s))}return!_e.isJSXElement(i)&&!_e.isJSXFragment(i)?Fo(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(Cw(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:vf(t.ast,{}).code})}function Cw(e,t,n,r){if(_e.isNullLiteral(e)||r)return t;let o=_e.isJSXFragment(e)?[...e.children]:[_e.isJSXElement(e)?e:_e.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return _e.jsxFragment(_e.jsxOpeningFragment(),_e.jsxClosingFragment(),s)}function Fo(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function Pf(e){let t=Yx(e);if(t)return{ok:!1,error:t};let n=e.projection,r=rb(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(Pw(n,o)){let f=_f(e);return f.ok?e.operation==="remove-node"&&!Xx(n,o.placementUnitKey)?Ss("The last editable page unit cannot be deleted."):e.operation==="move-node"?Ss("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=vs(o.sourceRange),a=ir(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?[]:[Is(a.diagnostic)]}};if(fi(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=_f(e);return f.ok?Xx(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}}}:Ss("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||!Aw(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=Nf(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=vs(d),g=ir(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?[]:[Is(g.diagnostic)]}};if(fi(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return Hx("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=vs(f),E=ir(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?[]:[Is(E.diagnostic)]}}:fi(e.source,E.match.node.start??null,E.match.node.end??null)!==y?Hx("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 Xx(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function Rw(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&Dc(n.sourceRange,e.mutationTarget.sourceRange)&&n.sourceHash===e.mutationTarget.sourceHash?!0:e.container.sourceRange===null&&(e.container.kind==="virtual-route-root"||e.container.kind==="starter-placeholder")}function Pw(e,t){return e.container.kind!=="jsx-container"&&Dc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function _f(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=ir(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?[]:[Is(r.diagnostic)]}}}:fi(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:Gx("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function zx(e,t,n,r){let o=ir(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?[]:[Is(o.diagnostic)]}}}:fi(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:Gx(`${r} hash no longer matches the current source.`)}:{ok:!0}}function Gx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Ss(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function Hx(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function Is(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function Yx(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&&!Nw(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 Nw(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function Aw(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function Tw(e,t){let n=Kx.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=Kx.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function vs(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function fi(e,t,n){return t==null||n==null?null:`sha256:${vw("sha256").update(e.slice(t,n)).digest("hex")}`}function Dc(e,t){return e===null||t===null?e===t:e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Zx(e){let t;try{t=pi.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=ww(t,e.step);return n.ok?{ok:!0,source:vf(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function ww(e,t){let n=tb(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Cf(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."}:Qx(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=qx(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?kf():Ow()),{ok:!0};let i=n.node.params[0],s=Cf(i);return s?(Lw(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function Ow(){return _e.objectPattern([_e.objectProperty(_e.identifier("searchParams"),_e.identifier("searchParams"),!1,!0)])}function kf(){let t=pi.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!_e.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!_e.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return _e.cloneNode(n,!0)}function Lw(e,t){let n=_e.objectProperty(_e.identifier("searchParams"),_e.identifier("searchParams"),!1,!0),r=e.properties.findIndex(_e.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=eb(e);if(!o){e.typeAnnotation=kf().typeAnnotation;return}if(!_e.isTSTypeLiteral(o.typeAnnotation))return;let i=kf().typeAnnotation;if(!i||!_e.isTSTypeAnnotation(i)||!_e.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!Fw(o.typeAnnotation)&&o.typeAnnotation.members.push(_e.cloneNode(s,!0))}function Fw(e){return e.members.some(t=>!("key"in t)||!t.key?!1:nb(t.key)==="searchParams")}function Dw(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 Mw(e){if(!e.invocation)return{ok:!0};let t=Zr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return Fc(t.error.message);if(t.plan.requiresRouteParams)return Fc("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=Bw(e.source,e.entryFile);if(!r.ok)return Fc(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=Zr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return Fc(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function Fc(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function Bw(e,t){let n;try{n=pi.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=tb(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=qx(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function qx(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=Cf(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Qx(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&&!jw(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Cf(e){return!e||_e.isTSParameterProperty(e)?null:_e.isObjectPattern(e)?e:_e.isAssignmentPattern(e)&&_e.isObjectPattern(e.left)?e.left:null}function Qx(e){for(let t of e.properties)if(!(!_e.isObjectProperty(t)||t.computed||nb(t.key)!=="searchParams"))return _e.isIdentifier(t.value)?t.value.name:_e.isAssignmentPattern(t.value)&&_e.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function jw(e){let t=eb(e);return t?_e.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function eb(e){return e.typeAnnotation&&_e.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function tb(e){let t=null;return _w(e,{ExportDefaultDeclaration(n){if(t)return;let r=Dw(n,n.get("declaration"));r&&(t=r)}}),t}function nb(e){return _e.isIdentifier(e)?e.name:_e.isStringLiteral(e)?e.value:null}var $w=typeof Af=="function"?Af:Af.default;function Xn(e){if(!e.ast)return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Ww(e.ast);if(!t)return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=Yw(t);if(!n.ok)return zn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=qw(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(eO(r,t))return zn(e,[Ft("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return wf(e,t,"virtual-route-root",r);if(Qw(r)){let o=oO({input:e,source:e.source,expression:r});return Tf(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!ft(r)&&!Rs(r)){let o=Ff(r),i=sb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return Tf(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=nO(r);if(!o.ok)return zn(e,[o.diagnostic]);let i=mi(o.path);if(i.unsupported)return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(tO(e.source,r,i.members))return wf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||ft(r);if(i.members.length===0&&s)return wf(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=sb({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return Tf(e,t,l,{kind:a,sourceKind:c},r)}return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function Nf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ft("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:Ft("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function rb(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Ft("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:Ft("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function ab(e){return e.ok?Uw(e.projection):Vw(e.projection)}function Uw(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)=>cb(e,u,f,y,e.container.placementKey)),p=d.filter(({member:f})=>f.isBusinessMember).map(({sourceMember:f})=>Kw(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:Jw(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function Vw(e){let t=e.diagnostics.map(Xw);return{status:"unsupported",version:e.version,composition:e.composition,reason:zw(e.diagnostics),diagnostics:t}}function Jw(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 cb(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)=>cb(e,t,a,c,i))]}function Kw(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function Xw(e){return{code:Hw(e),message:e.message}}function zw(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 Hw(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 Ww(e){let t=null;return $w(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=Gw(o.path);i&&(t=i,n.stop())}}),t}function Gw(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 Yw(e){let t=e.get("body");if(!t.isBlockStatement()){let s=Cs(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Ft("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:Ft("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Ft("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(!Zw(s)&&!wc(s))return{ok:!1,diagnostic:Ft("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(lb(s)||ub(s))return{ok:!1,diagnostic:Ft("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=Cs(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Ft("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Zw(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(lb(o)||ub(o))return null;return r}function lb(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function ub(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function qw(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=Cs(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 Qw(e){return e.isConditionalExpression()?ob(Cs(e.get("consequent")))&&ob(Cs(e.get("alternate"))):!1}function ob(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function Cs(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 eO(e,t){if(e.isIdentifier())return ib(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return ib(n.node.name,t)}return!1}function ib(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 tO(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&Lf(t)}function Lf(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(!Lf(t))return!1;continue}if(t.isJSXElement()&&!Lf(t))return!1}return!0}function nO(e){return{ok:!0,path:e}}function mi(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:Df(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:Dn(r.node.loc),businessMemberCount:0,parentSourceRange:Dn(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=mi(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=Rs(o)?mi(o):null;n||=i?.unsupported??!1,t.push({...Ff(o,i?.members),sourceRange:Dn(r.node.loc),parentSourceRange:Dn(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:Df(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:Dn(r.node.loc),businessMemberCount:1,parentSourceRange:Dn(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&ft(r)){let o=mi(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=Rs(r)?mi(r):null;n||=o?.unsupported??!1,t.push({...Ff(r,o?.members),parentSourceRange:Dn(e.node.loc)})}}return{members:t,unsupported:n}}function Ff(e,t){let n=e.isJSXElement()&&Rs(e)?t??mi(e).members:[],r=e.isJSXElement()&&!Rs(e)&&!ft(e);return{memberKey:Df(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:Dn(e.node.loc),businessMemberCount:r?1:db(n),parentSourceRange:Dn(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:rO(e)}}function Rs(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function rO(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 db(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function Mc(e){return e.length===0?0:Math.max(1,db(e))}function sb(e){let t=Dn(e.containerPath.node.loc),n=Bf(e.source,e.containerPath.node.start,e.containerPath.node.end),r=Mn(e.input,e.containerKind,e.sourceKind,t),o=Mn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:Mc(e.members)<=1,memberCount:Mc(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function oO(e){let t=Dn(e.expression.node.loc),n=Bf(e.source,e.expression.node.start,e.expression.node.end),r=Mn(e.input,"virtual-route-root","atomic-expression",t),o=Mn(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:Mn(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 fb(e,t){let n=Dn(t.node.loc),r=Bf(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function Tf(e,t,n,r,o){let i=fb(e,o);if(!i)return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=iO(e,n,s),c=ff(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:mb(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 iO(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:Mc(m)<=1,memberCount:Mc(m),sourceRange:p,sourceHash:p?Of(e.source,p):null,relation:l,containerSourceRange:f,containerSourceHash:f?Of(e.source,f):null,anchorSourceRange:g,anchorSourceHash:g?Of(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(l=>Mn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",Mn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=Mn(e,i,"placement-unit",l.sourceRange);r.push(o("before",Mn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",Mn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function wf(e,t,n,r){let o=fb(e,r);if(!o)return zn(e,[Ft("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=Mn(e,n,"empty-container",void 0),s=Mn(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=ff([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:mb(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 zn(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 Ft(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function Mn(e,t,n,r){return pb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function Df(e,t,n){return pb(["member",e,String(t??-1),String(n??-1)])}function pb(e){return`pc_${Mf("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function Bf(e,t,n){return t==null||n==null?null:`sha256:${Mf("sha256").update(e.slice(t,n)).digest("hex")}`}function Of(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:${Mf("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function Dn(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function mb(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 yO}from"node:crypto";import*as Wn from"@babel/types";function gb(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 jf from"@babel/traverse";import*as gi from"@babel/types";var aO=typeof jf=="function"?jf:jf.default,cO=32;function Hn(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=cO)return null;let o=new Set(r).add(e.ast),i;if(aO(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,p)=>{let g=Ur(e.file,d,n),m=g?n.get(g):void 0;return m?Hn(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,Bc(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(gi.getBindingIdentifiers(p.node),t)&&c.push(a(t));for(let g of d.node.specifiers)gi.isExportSpecifier(g)&&g.exportKind!=="type"&&Bc(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,Bc(g.local)):a(Bc(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 Bc(e){return gi.isIdentifier(e)?e.name:e.value}import*as Le from"@babel/types";var lO=32;function xn(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=lO)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return Ps(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return xn(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:Uf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=bn(e.node.property,e.node.computed),s=e.get("object"),a=xn(s,t,r);return i!==null&&a?Uc(a,i,t,r):null}if(e.isConditionalExpression())return Ps([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return Ps([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?xn(i,t,r):null}if(e.isCallExpression()&&Le.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!hi(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=xn(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?xn(p,c,r):null}return[e]}function Uf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return Ps(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=xn(o,t,n);if(!i)return null;let s=$f(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Uc(a,c,t,n),i):null}function jc(e){if(!e.params.every(n=>Le.isIdentifier(n)||Le.isAssignmentPattern(n)&&Le.isIdentifier(n.left)&&wr(n.right)))return!1;if(!Le.isBlockStatement(e.body))return wr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Le.isReturnStatement(t)&&!!t.argument&&wr(t.argument)}function hi(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return jc(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Le.isArrowFunctionExpression(n)||Le.isFunctionExpression(n)?jc(n):!1}function wr(e){let t=!0;return Le.traverseFast(e,n=>{(Le.isCallExpression(n)&&!$c(n)||Le.isOptionalCallExpression(n)||Le.isNewExpression(n)||Le.isAwaitExpression(n)||Le.isAssignmentExpression(n)||Le.isUpdateExpression(n)||Le.isUnaryExpression(n,{operator:"delete"})||Le.isYieldExpression(n)||Le.isTaggedTemplateExpression(n))&&(t=!1)}),t}function $c(e){return Le.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Le.isStringLiteral(e.arguments[0])}function Ps(e,t,n){let r=[];for(let o of e){let i=xn(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Uc(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()&&bn(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=>Le.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 Ps(o,n,r)}function Vf(e,t){let n=xn(e,t);return!!(n?.length&&n.every(r=>Le.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function bn(e,t){return!t&&Le.isIdentifier(e)?e.name:Le.isStringLiteral(e)||Le.isNumericLiteral(e)?String(e.value):null}function $f(e,t){if(Le.isIdentifier(e))return e.name===t?[]:null;if(Le.isObjectPattern(e))for(let n of e.properties){if(!Le.isObjectProperty(n)||n.computed)continue;let r=bn(n.key,!1),o=$f(n.value,t);if(r!==null&&o)return[r,...o]}if(Le.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=$f(r,t);if(o)return[String(n),...o]}return null}function hb(e,t=new Set,n){return yb(e.get("callee"),t,n)}function yb(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&&Ur(d.file,l,n),g=p?n.get(p):void 0,m=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?bn(r.path.node.imported,!1):null,f=g&&m&&i.node.importKind!=="type"?Hn(g,m,n):null;return f?yi(f,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=yi(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=yi(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=bn(e.node.property,e.node.computed),o=e.get("object"),i=xn(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()&&bn(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=yi(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 yi(e,new Set(t).add(e.node),n)}function yi(e,t,n){if(e.isIdentifier())return yb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return yi(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 Jc(e,t){return JSON.stringify([t,e])}var dO=new Set;function Ib(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)=>!Sb(f)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===m);function c(m,f,y,x,E,b=dO){if(m.isIdentifier())return x&&Vc(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,T=hb(I,b,e.parsedModules);return T.kind==="guard"||T.kind==="sources"&&T.sources.some(C=>c(C,[...e.parsedModules.values()].find(A=>A.ast.program===C.scope.getProgramParent().path.node)?.file??f,y,x,E,T.aliases))?!0:I.get("arguments").some(C=>c(C,f,y,x,E,b))||T.kind==="unknown"&&E}if(m.isJSXElement()){if(ft(m))return m.get("children").some(B=>c(B,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 B=e.parsedModules.get(I.sourceFile);if(!B)return!1;let U=Fn({module:B,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 U.ok?U.metadataOnly?!1:l(U,m,I.sourceFile,y,x,b):U.diagnostic.code==="component-external-module-opaque"?Ns(m).some(G=>c(G,f,y,x,!1,b)):a(B.file,U.diagnostic.code)}return m.get("children").some(B=>c(B,f,y,x,E,b))}let T=m.node.openingElement.name;if(!Wn.isJSXIdentifier(T))return!1;if(/^[a-z]/.test(T.name))return m.get("children").some(B=>c(B,f,y,x,E,b));let C=e.parsedModules.get(f),A=m.node.loc;if(!C||!A)return!1;let P=hO({path:m,file:f,componentName:T.name,parsedModules:e.parsedModules}),F=Fn({module:C,componentName:T.name,callSourceRange:{startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},...P?{imported:P}:{}});return F.ok?F.metadataOnly?!1:l(F,m,f,y,x,b):F.diagnostic.code==="component-external-module-opaque"?Ns(m).some(B=>c(B,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&&!Do(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(T=>Ns(T).some(C=>c(C,m.sourceFile,I,null,!1,b)))||m.roots.some(T=>c(T,m.sourceFile,I,null,!1,b))?!0:xb(m.roots).kind==="none"?!1:Eb(f).some(T=>c(T,y,I,E,!0,b))}function u(m){if(!m.path.isIdentifier())return m.unknownIsRelevant;let f=gb({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&&!Do(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 T of m.get("children"))d(T,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 T=n.get(I)??[];T.push(Jc(I,y)),n.set(I,T)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let T=e.parsedModules.get(S.sourceFile);if(!T)return;let C=Fn({module:T,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"){Ns(m).some(G=>c(G,f,x,b,!1))&&s(f);return}[...t].some(G=>e.graph.elements.get(G)?.sourceFile===T.file)&&!Sb(C.diagnostic.code)&&s(T.file);return}if(C.metadataOnly)return;let A=`${C.sourceFile}#${C.componentName}`;if(x.has(A)){s(T.file);return}let P=new Set(x).add(A);C.returnAlternatives?.some(G=>Ns(G).some(X=>c(X,C.sourceFile,P,b,!1)))&&s(C.sourceFile);let F=xb(C.roots),B=gO(m);if(F.kind==="unproven"||F.kind==="supported"&&B){for(let G of Eb(m))if(c(G,f,P,b,!0)){s(f);break}}let U=F.kind==="supported"&&!B?{bindingNode:F.bindingNode,children:m.get("children").map(G=>({path:G,file:f,substitution:b}))}:null;for(let G of C.roots)d(G,C.sourceFile,[...y,I],P,E,U);return}for(let T of m.get("children"))d(T,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(Vc(I,b)){for(let T of b.children)d(T.path,T.file,y,x,E,T.substitution);return}if(fO(S,b))for(let T of b.children)d(T.path,T.file,y,x,!1,T.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=qt({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 Do(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||Do(n)):t.isConditionalExpression()?Do(t.get("consequent"))&&Do(t.get("alternate")):t.isLogicalExpression()?Do(t.get("left"))&&Do(t.get("right")):!1}function Vc(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 fO(e,t){if(Vc(e,t))return!0;let n=!1;return e.traverse({Identifier(r){Vc(r,t)&&(n=!0,r.stop())}}),n}function xb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?bb(n.get("left"),!0):bb(n,!1):{kind:"none"}}function bb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){cr(i.get("value"))&&(r=!0);continue}let s=i.node.key;(Wn.isIdentifier(s)?s.name:Wn.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&cr(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>cr(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=>pO(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return cr(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=>mO(r))?{kind:"none"}:{kind:"unproven"}}return cr(e)?{kind:"unproven"}:{kind:"none"}}function cr(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?cr(e.get("left")):e.isRestElement()?cr(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?cr(t.get("value")):t.isRestElement()?cr(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?cr(t):!1):!0}function pO(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 mO(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?Wn.isStringLiteral(n)&&n.value!=="children":Wn.isIdentifier(n)&&n.name!=="children"}function gO(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(Wn.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&vb(t.get("argument")))return!0}return!1}function Eb(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(!Wn.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");vb(r)&&t.push(r)}}return t}function Ns(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 vb(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 hO(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=Ur(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":Wn.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 Sb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function Cb(e){let t=[],n=[];return Rb(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function Rb(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(gf(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=Fn({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=kb(E),S=b?_b(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=kb(E),S=b?_b(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}Rb(S[0],t,m,f,d.roots.length>1?S[0]:o,d.roots.length>1?m:i,y,a,c,x)}}function _b(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){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 Kc(e){let t=[],n=[];if(e.projection.entryFile!==e.entryFile||!Nb(e.projection.composition,e.composition)||e.graph.composition&&!Nb(e.graph.composition,e.composition))return{roots:[],diagnostics:[As("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[As("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(As("route-member-not-addressable",e.entryFile));continue}let s=bO(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(As(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=Cb({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=Ib(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=Jc(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(As("render-occurrence-unproven",i.element.sourceFile))}return{roots:xO(n,e.composition,o.occurrences),diagnostics:t}}function xO(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:yO("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(Jc(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=Pb(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(Pb(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function Pb(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function bO(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 Nb(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function As(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as EO,SiteEditPageBlockDescriptorSchema as SO,SiteEditSourcePathSchema as Tb}from"@vcp-dev/contracts";function Xc(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}),Ab(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function Ab(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}),Ab(s,t,n,r,o))}}function Ts(e){let t=[],n={...e.graph,composition:e.composition},r=oc(Xc(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=_O(a,e.graph),p=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!Tb.safeParse(a.sourceFile).success||!d||!p||!Tb.safeParse(d).success){t.push(Kf("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(Kf("block-key-ambiguous",a.sourceFile));continue}let g=Ue(u.source),m=SO.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:kO(a,e),capabilities:IO(c,r),...vO(c,r)});if(!m.success){t.push(Kf("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:Ue(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=EO.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 IO(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 vO(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 _O(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 kO(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 Kf(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import Xf from"@babel/traverse";import{BlockRenderRefSchema as CO,SiteEditPageBlockPositionSchema as RO,SiteEditPageBlockTargetSchema as PO}from"@vcp-dev/contracts";var NO=typeof Xf=="function"?Xf:Xf.default;function xi(e,t,n,r){if(!PO.safeParse(t).success)return un("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return un("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return un("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!CO.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?un("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:un("INVALID_TARGET","The page block target was not found.")}function zc(e,t){if(!RO.safeParse(t).success)return un("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return un("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return un("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return un("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 un("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=wb(n);if(!i)return un("INVALID_TARGET","The operation owner call site is unavailable.");let s=Ob(n,i);if(s===void 0)return un("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||!AO(Ob(u,wb(u)),s))return un("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return un("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 wb(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function Ob(e,t){if(!t)return;let n=we(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(NO(n.module.ast,{JSXElement(i){let s=zf(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=zf(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=zf(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 AO(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 zf(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 un(e,t){return{ok:!1,code:e,message:t}}import Db from"node:path";import{SiteEditSourcePathSchema as UO}from"@vcp-dev/contracts";import Hc from"node:path";import Hf from"@babel/traverse";import*as Qr from"@babel/types";import{SiteEditSourcePathSchema as Lb,SiteEditPageBlockTargetSchema as TO}from"@vcp-dev/contracts";var wO=typeof Hf=="function"?Hf:Hf.default;function Fb(e){if(!e.operationId)return Rt("INVALID_PARAMS","An operationId is required.");if(!TO.safeParse(e.target).success)return Rt("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 Rt("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return Rt("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return Rt("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return Rt("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!Lb.safeParse(t).success)return Rt("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return Rt("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(Ue(n)!==e.binding.ownerSourceHash)return Rt("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||Ue(r)!==e.binding.descriptor.source.contentHash)return Rt("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 Rt("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 Rt("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return Rt("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=LO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?ni({source:n,locator:OO(e.binding),node:{jsx:i.value.jsx}}):Tn({source:n,locator:Wf(o.parentLocator),anchorLocator:Wf(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return Rt("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=wn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return Rt("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 OO(e){return Wf(e.ownerLocator)}function Wf(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 LO(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}>`}}:Rt("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return Rt("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=FO(t,e.component.source,r);if(!o)return Rt("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=we(t,n);if(!i.ok)return Rt("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=DO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??BO(jO(e.component.exportName,o),MO(i.module.ast)),c=$O(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 FO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Hc.posix.normalize(Hc.posix.join(Hc.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=>Lb.safeParse(i).success&&n.has(i))??null:null}function DO(e,t,n){for(let r of e)if(!(!Qr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Qr.isImportDefaultSpecifier(o)||n!=="default"&&Qr.isImportSpecifier(o)&&(Qr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function MO(e){let t=new Set;return wO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function BO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function jO(e,t){let r=(e==="default"?Hc.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 $O(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return Rt("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return Rt("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return Rt("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function Rt(e,t){return{ok:!1,code:e,message:t}}function Mb(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Wc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&UO.safeParse(i.path).success))return Wc("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 Wc("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 Wc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=JO(t,e.materialization.entry.path),r=Fb({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:VO(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 VO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function JO(e,t){let n=Db.posix.relative(Db.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Wc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as eL}from"@vcp-dev/contracts";import oH from"node:fs";import sH from"node:path";var KO=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function ws(e){let t=e.map(r=>QO(r.path)),n=XO(t);return n?t.filter(r=>HO(n,r)).map(r=>({routeId:WO(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function Gf(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=qO(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function XO(e){return e.some(r=>r.startsWith("app/")&&!zO(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function zO(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function HO(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return KO.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function WO(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(YO).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function GO(e){return e.startsWith("(")&&e.endsWith(")")}function YO(e){return!e||e.startsWith("@")||e.startsWith("_")||GO(e)?null:ZO(e)}function ZO(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function qO(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function QO(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var Os=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function dn(e,t={}){throw new Os("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function Yf(e){return eL.safeParse(e).success||dn("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function Bb(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||dn("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return dn("invalid-template-key",{path:e})}return Yf(t)!==e&&dn("noncanonical-template-key",{path:e}),t}function tL(e){let t=Gf(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("(")||nL(r)&&!jb(r)))&&dn("invalid-public-route",{routeId:e}),t}function nL(e){return e.includes("[")||e.includes("]")}function jb(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function $b(e){return e.some(jb)}function Ub(e,t,n="app"){n!=="app"&&n!=="src/app"&&dn("invalid-app-root");let r=tL(e),o=Yf(t),i=$b(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))&&dn("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function Vb(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function Jb(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===".")&&dn("invalid-file-path",{path:i}),n.has(i)&&dn("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Yc(e){let t=Jb(e.files),n=ws([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new Os("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(!Vb(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||dn("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=$b(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,p=Bb(u),g=d.length?`/${d.join("/")}`:"/";Ub(g,p,a).templateEntryFile!==i&&dn("candidate-path-mismatch",{path:i,routeId:g});let f=r.get(g);(!f||!f.startsWith(`${a}/`))&&dn("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:p,entryFile:i,canonicalEntryFile:f,appRoot:a})}return o.sort((i,s)=>Gc(i.routeId,s.routeId)||Gc(i.templateId,s.templateId))}function Zc(e){let t=Jb(e.files),n=Yc({files:t}),r=ws([...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)=>Gc(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Gc(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function rL(e){let t=Gf(e.selector.routeId),n=Zc({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&dn("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||dn("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Gc(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as kL}from"@vcp-dev/contracts";import{parse as yL}from"@babel/parser";import{parse as IH}from"@babel/parser";import{FormBlockIdSchema as _H,FormSpecV1Schema as kH}from"@vcp-dev/contracts";import{posix as gH}from"node:path";import oL from"@babel/traverse";var Zf=oL,yH=typeof Zf=="function"?Zf:Zf.default,xH=Symbol("unknown-member");var Ls="components/site/generated/forms",RH=`${Ls}/vcp-form-runtime.tsx`,qc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",PH=new RegExp(`^${Ls}/form-(${qc})\\.spec\\.ts$`),NH=new RegExp(`^${Ls}/form-(${qc})\\.tsx$`),AH=new RegExp(`^@/${Ls}/form-(${qc})$`),TH=new RegExp(`(?:^|/)${Ls}/form-(${qc})(?:\\.tsx?)?$`);var wH=Symbol("invalid-literal");import{createHash as FH}from"node:crypto";import{posix as MH}from"node:path";import{parse as jH}from"@babel/parser";import{FormSpecV1Schema as UH}from"@vcp-dev/contracts";var VH=Symbol("dynamic");import{parse as iL}from"@babel/parser";function Qc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var sL=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function Kb(e){let t=sL.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 aL(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Xb(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function cL(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function qf(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(qf);if(t?.type==="ObjectExpression"){let n={};for(let r of Qc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Xb(r.key);if(!o)throw new Error("unsupported object key");n[o]=qf(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Qf(e,t){let n=[],r=Kb(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=iL(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 Qc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of Qc(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=cL(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 Qc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Xb(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=aL(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=qf(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 lL}from"@babel/parser";var zb=["page","anchor","external","email","phone","group","file"],uL=["link","cta"],Wb=["description","badge","iconKey"],ep=["label","targetType","href","role","openInNewTab","nofollow","children",...Wb],dL=new Set(ep);function Ds(e){return Array.isArray(e)?e:[]}function Fs(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function fL(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Hb(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function tp(e){let t=[],n;try{n=lL(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 Ds(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of Ds(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 Ds(r.elements).forEach((i,s)=>{let a=Gb(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function Gb(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 Ds(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=fL(l.key);u&&(r[u]=l.value)}let o=Fs(r.label),i=Fs(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!zb.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${zb.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 Wb){if(r[l]===void 0)continue;let u=Fs(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))dL.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 ${ep.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=[];Ds(r.children.elements).forEach((u,d)=>{let p=Gb(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=Fs(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=Fs(r.role);if(c!==void 0&&(uL.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=Hb(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=Hb(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 pL}from"@babel/parser";function Ms(e){return Array.isArray(e)?e:[]}function Yb(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function mL(e){let t;try{t=pL(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of Ms(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of Ms(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=Yb(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 np(e,t){let n=Zb(t);if(!n)return{status:"unsupported",source:e};let r=mL(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(tp(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=Ms(l.elements);for(let[d,p]of u.entries()){if(hL(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=gL(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 gL(e){if(e.type==="ObjectExpression")for(let t of Ms(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return Yb(t.value)}}function Zb(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function hL(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of Ms(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 qH}from"@vcp-dev/contracts";import{parse as tW}from"@babel/parser";function Bn(e,t){let n;try{n=yL(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(A){let P=A.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:A instanceof Error?A.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:P?.line??1}]}}let r=n.program,o=En(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=A=>{if(A?.type==="FunctionDeclaration"){let P=A.id;P?.type==="Identifier"&&typeof P.name=="string"&&s.set(P.name,A);return}if(A?.type==="VariableDeclaration")for(let P of En(A.declarations)){let F=P.id,B=P.init;F?.type==="Identifier"&&typeof F.name=="string"&&B&&(eo(B)?s.set(F.name,B):B.type==="Identifier"&&typeof B.name=="string"&&a.set(F.name,B.name))}};for(let A of o){if(A.type==="ImportDeclaration"){let P=A.source?.value;if(typeof P!="string")continue;for(let F of En(A.specifiers)){let B=F.local;if(!(B?.type!=="Identifier"||typeof B.name!="string")){if(F.type==="ImportDefaultSpecifier")i.set(B.name,{source:P,exportName:"default"});else if(F.type==="ImportNamespaceSpecifier")i.set(B.name,{source:P,exportName:"*"});else if(F.type==="ImportSpecifier"){let U=F.imported,G=U?.type==="Identifier"&&typeof U.name=="string"?U.name:U?.type==="StringLiteral"&&typeof U.value=="string"?U.value:"";G&&i.set(B.name,{source:P,exportName:G})}}}continue}A.type==="ExportNamedDeclaration"?l(A.declaration):l(A)}for(let A of o){if(A.type==="ExportDefaultDeclaration"){let B=A.declaration;B&&eo(B)?c.set("default",B):B?.type==="Identifier"&&typeof B.name=="string"&&c.set("default",B.name);continue}if(A.type!=="ExportNamedDeclaration")continue;let P=A.declaration;if(P?.type==="FunctionDeclaration"){let B=P.id;B?.type==="Identifier"&&typeof B.name=="string"&&c.set(B.name,B.name)}else if(P?.type==="VariableDeclaration")for(let B of En(P.declarations)){let U=B.id;U?.type==="Identifier"&&typeof U.name=="string"&&c.set(U.name,U.name)}let F=A.source?.value;for(let B of En(A.specifiers)){let U=eE(B.local),G=eE(B.exported);if(!(!U||!G))if(typeof F=="string"){let X=`#re-export:${G}`;i.set(X,{source:F,exportName:U}),c.set(G,X)}else c.set(G,U)}}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=(A,P="rendered")=>{let F=Qb(A,i);if(!F)return!1;let B=`${F.source}\0${F.exportName}`;if(P==="uncertain")return!p.has(B)&&!m.has(B)&&(m.add(B),g.push({source:F.source,export_name:F.exportName})),!0;if(!p.has(B)&&(p.add(B),d.push({source:F.source,export_name:F.exportName}),m.delete(B))){let U=g.findIndex(G=>G.source===F.source&&G.export_name===F.exportName);U>=0&&g.splice(U,1)}return!0},T=(A,P="rendered",F=[])=>{let B=`${P}\0${op(F)}`,U=b.get(A)??new Set,G=S.get(A)??new Set;if(U.has(B)||G.has(P))return;U.add(B),b.set(A,U),G.add(P),S.set(A,G);let X=new Map(s),Z=new Map,H=[],he=(O,L=!1)=>{if(el(O)){if(!L&&eo(O)){if(O.type==="FunctionDeclaration"){let z=O.id;z?.type==="Identifier"&&typeof z.name=="string"&&X.set(z.name,O)}return}if(O.type==="VariableDeclarator"){let z=O.id,j=O.init;z?.type==="Identifier"&&typeof z.name=="string"&&j&&(eo(j)?X.set(z.name,j):Z.set(z.name,j))}else if(O.type==="ReturnStatement"){let z=O.argument;z&&H.push(z)}if(O.type==="CallExpression"){let z=O.callee;if(z?.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}),Bs(z)==="cms.forms.getConfig"){let j=En(O.arguments)[0];j?.type==="StringLiteral"&&typeof j.value=="string"&&j.value.trim()?P==="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[z,j]of Object.entries(O))if(z!=="loc")if(Array.isArray(j))for(let K of j)he(K);else he(j)}};he(A,!0);let ue=new Set,je=new Set,He=(O,L=P,z=F)=>{if(!(!el(O)||eo(O))){if(O.type==="Identifier"&&typeof O.name=="string"){let j=Z.get(O.name),K=`${L}\0${O.name}\0${op(z)}`;j&&!ue.has(K)&&!je.has(O.name)?(ue.add(K),je.add(O.name),He(j,L,z),je.delete(O.name)):I(O.name,L);return}if(O.type==="CallExpression"){let j=O.callee,K=En(O.arguments),ee=Bs(j),pe=j?.type==="Identifier"&&typeof j.name=="string"?i.get(j.name):void 0;if(L==="rendered"&&(ee==="createElement"||ee.endsWith(".createElement")||pe?.source==="react"&&pe.exportName==="createElement")&&K[0]?.type==="StringLiteral"&&K[0].value==="form"&&(x=!0),j?.type==="Identifier"&&typeof j.name=="string"){let v=X.get(j.name);if(v){T(v,L,z);return}}if(j&&eo(j)){T(j,L,z);return}if(EL(j)){for(let v of K)if(eo(v))T(v,L,z);else if(v.type==="Identifier"&&typeof v.name=="string"){let $=X.get(v.name);$&&T($,L,z)}return}for(let v of K)SL(v)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:v.loc?.start.line??1});return}if(O.type==="JSXElement"){let j=O.openingElement,K=j?qb(z,xL(j)):z;He(j,L,K);for(let ee of En(O.children))He(ee,L,K);return}if(O.type==="JSXOpeningElement"){let j=tl(O.name);L==="rendered"&&j==="form"&&(x=!0);let K=j?Qb(j,i):void 0;if(L==="rendered"&&K&&typeof O.start=="number"){let ee=`${K.source}\0${K.exportName}\0${O.start}`,pe=y.get(ee);if(!pe){let v=IL(O).get("formBlockId");pe={source:K.source,export_name:K.exportName,start_offset:O.start,...typeof v=="string"?{static_form_block_id:v}:{}},y.set(ee,pe),f.push(pe)}z.length>0&&(pe.static_render_blockers=qb(pe.static_render_blockers??[],z))}if(j&&!I(j,L)){let ee=X.get(j);ee?T(ee,L,z):Z.has(j)?He(Z.get(j),L,z):bL(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 ee of En(O.attributes))He(ee,"uncertain",z);return}if(O.type==="JSXAttribute"){let j=O.value,K=j?.type==="JSXExpressionContainer"?j.expression:j;K&&eo(K)?T(K,"uncertain",z):He(K,"uncertain",z);return}for(let[j,K]of Object.entries(O))if(!(j==="loc"||j==="closingElement"))if(Array.isArray(K))for(let ee of K)He(ee,L,z);else He(K,L,z)}},ht=A.body;ht&&ht.type!=="BlockStatement"&&H.push(ht);for(let O of H)He(O);G.delete(P)},C=c.get(t.exportName);if(typeof C=="string"){let A=C,P=new Set;for(;a.has(A)&&!P.has(A);)P.add(A),A=a.get(A);if(!I(A)){let F=s.get(A);F?T(F):E.push(tE(t))}}else C?T(C):E.push(tE(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:f,renders_native_form:x,diagnostics:E}}function op(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function qb(e,t){return[...new Map([...e,...t].map(r=>[op([r]),r])).values()]}function xL(e){let t=new Map;for(let a of En(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=nE(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=tl(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:_L(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=rp(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 En(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,rp(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=rp(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 rp(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"&&En(e.expressions).length===0)return En(e.quasis)[0]?.value?.cooked}}function Qb(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 bL(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function eo(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function EL(e){let t=Bs(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 SL(e){let t=!1;return ip(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&Bs(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function eE(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function tE(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function Bs(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=Bs(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function IL(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=nE(o.name);i&&t.set(i,vL(o.value))}return t}function vL(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 nE(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function _L(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function ip(e,t){if(el(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)ip(o,t);continue}ip(r,t)}}}function el(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function tl(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=tl(t.object),r=tl(t.property);return n&&r?`${n}.${r}`:r||n}return""}function En(e){return Array.isArray(e)?e.filter(t=>el(t)):[]}var CL="components/site/generated/",js=[".tsx",".ts",".jsx",".js"];function rE(e){if(e.expectedUrlPath===kL)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(ws(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=Qf(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=Yc({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=RL(e.files);if(!i.ok)return i.error;let s=i.graph,a=TL(o,s),c=wL(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=np(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 RL(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")||!PL(r))continue;let s=we(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(NL(c))continue;let l=nr(r,c),u=AL(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 PL(e){let t=e.toLowerCase();return js.some(n=>t.endsWith(n))}function NL(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!js.some(n=>e.endsWith(n)))}function AL(e,t){let n=e.replace(/\\/g,"/");return(js.some(o=>n.endsWith(o))?[n]:[...js.map(o=>`${n}${o}`),...js.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function TL(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(CL)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function wL(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 oS from"@babel/parser";import*as Ye from"@babel/types";import*as bl from"node:path";import*as ot from"@babel/types";function oE(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 lr(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return Mo(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(ot.isObjectPattern(n)||ot.isArrayPattern(n))return Mo(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(LL(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function Mo(e,t,n=!1){return ot.isIdentifier(e)?e.name===t&&n:ot.isObjectPattern(e)?e.properties.some(r=>ot.isObjectProperty(r)?Mo(r.value,t,n):Mo(r.argument,t,n)):ot.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=ot.isRestElement(r)?r.argument:r;return Mo(o,t,n)}):ot.isAssignmentPattern(e)?Mo(e.left,t,!0):ot.isRestElement(e)?Mo(e.argument,t,n):!1}function bi(e,t){if(e.path.isObjectPattern()){if(t){let r=Gn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:lr(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:lr(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=iE(r),i=!1,s=o?o.initBinding&&sp(o.initBinding)?(i=lr(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=bi(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=Gn(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||lr(e)}}}}let n=ML(e);if(n){let r=OL(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||lr(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=FL(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:lr(e)}}let i=$s(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:lr(e)}:null}if(sp(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:lr(e)}}return null}function OL(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=iE(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=sp(i)?(a=lr(i),[...s]):(()=>{let u=bi(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=Gn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||lr(t)}:null}function iE(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=BL(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function sp(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function LL(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function FL(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=Gn(i.node,t);if(a)return a}return null}function sE(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=nl(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=$s(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=DL(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=$s(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 nl(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=$s(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Gn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=nl(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=nl(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=nl(r,t);if(o)return o}}return null}function Gn(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=$s(r);if(!o)continue;let i=Gn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(ot.isRestElement(r)){let o=Gn(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=Gn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return ot.isAssignmentPattern(e)?Gn(e.left,t,n):null}function DL(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function ML(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 $s(e){return e.computed?null:ot.isIdentifier(e.key)?e.key.name:ot.isStringLiteral(e.key)?e.key.value:null}function BL(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 fE from"@babel/parser";import lp from"@babel/traverse";import*as Ei from"@babel/types";import*as Je from"@babel/types";var aE=new WeakMap;function il(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?rl(n,t):null}if(e.isMemberExpression()){let n=KL(e.node),r=jL(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?rl(o,[...r,...t]):null}return e.isAwaitExpression()||cp(e.node)?to(zL(e.node),t,"awaited or fetched expression"):null}function jL(e){let t=[],n=e;for(;Je.isMemberExpression(n);){if(n.computed)if(Je.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Je.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Je.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Je.isIdentifier(n)?t:null}function rl(e,t=[],n){let r=$L(e,t);if(r)return r;let o=UL(e,t,n);if(o)return o;let i=VL(e,t,n);return i||null}function Vs(e){return e?.kind==="api-source"}function $L(e,t){if(e.path.isVariableDeclarator()&&Je.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&ap(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return to(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&Je.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>Je.isObjectProperty(c)&&uE(c)==="data"&&Us(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&ap(a.node))return to(e.identifier.name,t,"query hook data binding")}let n=JL(e);if(!n||uE(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()||!ap(i.node)?null:to(e.identifier.name,t,"query hook data binding")}function UL(e,t,n){if(e.path.isVariableDeclarator()&&Je.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!lE(c.node))return null;let[l,u]=e.path.node.id.elements;return!Je.isIdentifier(l)||l.name!==e.identifier.name||!Je.isIdentifier(u)?null:cE(e,u.name,n)?to(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()||!lE(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return Je.isIdentifier(a)&&cE(e,a.name,n)?to(e.identifier.name,t,"state setter is updated by API data"):null}function VL(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()?to(e.identifier.name,t,"awaited binding result"):cp(o.node,n)?to(e.identifier.name,t,"fetch-backed binding result"):null:null}function JL(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 Us(e,t){return Je.isIdentifier(e)?e.name===t:Je.isAssignmentPattern(e)?Us(e.left,t):Je.isObjectPattern(e)?e.properties.some(n=>Je.isObjectProperty(n)?Us(n.value,t):Us(n.argument,t)):Je.isArrayPattern(e)?e.elements.some(n=>!!n&&Us(Je.isRestElement(n)?n.argument:n,t)):!1}function cE(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=aE.get(n);c||(c=new WeakMap,aE.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){cp(c.node)&&(r=!0),(XL(c.node.callee,t)||c.node.arguments.some(l=>Je.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function ap(e){let t=sl(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function lE(e){return sl(e.callee)==="useState"}function cp(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=ol(e,o=>Je.isCallExpression(o)&&sl(o.callee)==="fetch");return t?.set(e,r),r}function KL(e){let t=e;for(;Je.isMemberExpression(t);)t=t.object;return Je.isIdentifier(t)?t.name:null}function uE(e){return e.computed?null:Je.isIdentifier(e.key)?e.key.name:Je.isStringLiteral(e.key)?e.key.value:null}function sl(e){return Je.isIdentifier(e)?e.name:Je.isMemberExpression(e)&&Je.isIdentifier(e.property)?e.property.name:null}function XL(e,t){return ol(e,n=>Je.isIdentifier(n)&&n.name===t)}function ol(e,t){if(t(e))return!0;let n=Je.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(Je.isNode(i)&&ol(i,t))return!0;continue}if(Je.isNode(o)&&ol(o,t))return!0}return!1}function zL(e){return Je.isIdentifier(e)?e.name:Je.isCallExpression(e)?sl(e.callee)??"api":Je.isAwaitExpression(e)?"awaited-api":"api"}function to(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:HL(e,t),reason:n}}function HL(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var pE=typeof lp=="function"?lp:lp.default;function mE(e,t){let n=hE(e);if(!n)return{allowed:!0};let r=!1;return pE(n,{CallExpression(o){if(!yE(o.node,t.sourceRange)||!WL(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||Vs(il(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function gE(e,t){let n=hE(e);if(!n)return{allowed:!0};let r=!1;return pE(n,{JSXExpressionContainer(o){yE(o.node,t.sourceRange)&&(Ei.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 hE(e){try{return fE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function WL(e){let t=e.callee;return Ei.isMemberExpression(t)&&Ei.isIdentifier(t.property)&&t.property.name==="map"}function yE(e,t){let n=e.loc;return n?dE({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&dE({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function dE(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 fe from"@babel/types";import*as xE from"@babel/parser";import up from"@babel/traverse";import*as yt from"@babel/types";import*as Si from"node:path";var Yn=typeof up=="function"?up:up.default;function $t(e){try{return xE.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function dp(e){return e.computed?yt.isStringLiteral(e.key)||yt.isNumericLiteral(e.key)?String(e.key.value):null:GL(e.key)}function GL(e){return yt.isIdentifier(e)?e.name:yt.isStringLiteral(e)||yt.isNumericLiteral(e)?String(e.value):null}function Bo(e){return yt.isParenthesizedExpression(e)||yt.isTSAsExpression(e)||yt.isTSSatisfiesExpression(e)||yt.isTSNonNullExpression(e)||yt.isTSTypeAssertion(e)?Bo(e.expression):yt.isExpression(e)?e:null}function fp(e){if(yt.isIdentifier(e))return[e.name];if((yt.isMemberExpression(e)||yt.isOptionalMemberExpression(e))&&!e.computed&&yt.isIdentifier(e.property)){let t=Bo(e.object),n=t?fp(t):null;return n?[...n,e.property.name]:null}return null}function jo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?Si.normalize(Si.join(Si.dirname(e),t)).replace(/\\/g,"/"):t}function Sn(e,t){return al(e)===al(t)}function al(e){let t=Ii(e);return t.endsWith("/index")?t.slice(0,-6):t}function Ii(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function SE(e,t,n){let r=kE(e,t);if(CE(e,r),RE(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 Yn(e,{JSXElement(s){TE(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:cl(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 IE(e,t){let n=new Map,r=i=>{let s=vi(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 YL(i,n))o=r(s)||o}return[...n.values()]}function YL(e,t){let n=[],r=ZL(e,t);for(let o of e.ast.program.body){if(fe.isExportDefaultDeclaration(o)&&fe.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=Js(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(fe.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=jo(e.file,o.source.value);for(let s of o.specifiers){if(fe.isExportNamespaceSpecifier(s)){let l=no(s.exported);for(let u of t.values())Sn(u.file,i)&&n.push({file:e.file,namespace:pp(l,u.namespace),exportName:u.exportName});continue}if(!fe.isExportSpecifier(s))continue;let a=no(s.local),c=[...t.values()].filter(l=>Sn(l.file,i)&&$o(l.namespace,a));if(c.length>0){let l=no(s.exported);for(let u of c){let d=Js(u.namespace,a,l);d&&n.push({file:e.file,namespace:d,exportName:u.exportName})}continue}t.has(vi({file:i,exportName:a}))&&n.push({file:e.file,exportName:no(s.exported)})}continue}if(fe.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!fe.isExportSpecifier(i))continue;let s=no(i.local),a=r.get(s)??[];if(a.length>0){let c=no(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Js(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(fe.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=jo(e.file,o.source.value),s=o.exported;if(s){let a=no(s);for(let c of t.values())Sn(c.file,i)&&n.push({file:e.file,namespace:pp(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())Sn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function pp(e,t){return t?`${e}.${t}`:e}function $o(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Js(e,t,n){return!$o(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function ZL(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(!fe.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=jo(e.file,i.source.value);for(let a of i.specifiers){if(fe.isImportDefaultSpecifier(a)){let c=t.get(vi({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>Sn(u.file,s)&&$o(u.namespace,"default"));for(let u of l){let d=Js(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(fe.isImportSpecifier(a)){let c=no(a.imported),l=[...t.values()].filter(d=>Sn(d.file,s)&&$o(d.namespace,c));for(let d of l)r(a.local.name,d);let u=t.get(vi({file:s,exportName:c}));u&&r(a.local.name,u);continue}if(fe.isImportNamespaceSpecifier(a))for(let c of t.values())Sn(c.file,s)&&r(a.local.name,{...c,namespace:pp(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(fe.isVariableDeclaration(i))for(let s of i.declarations){if(!fe.isIdentifier(s.id)||!s.init)continue;let a=Bo(s.init);if(!a||!fe.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(vi));for(let d of c){let p=Js(d.namespace,a.name,s.id.name),g=p?{...d,namespace:p}:d,m=vi(g);u.has(m)||(r(s.id.name,g),u.add(m),o=!0)}}}return n}function vi(e){let t=e.namespace?`${e.namespace}.${e.exportName}`:e.exportName;return`${al(e.file)}#${t}`}function no(e){return fe.isIdentifier(e)?e.name:e.value}function vE(e,t){for(let n of e.program.body){if(fe.isExportDefaultDeclaration(n)){let o=n.declaration;if((fe.isFunctionDeclaration(o)||fe.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(fe.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!fe.isExportNamedDeclaration(n))continue;let r=n.declaration;if((fe.isFunctionDeclaration(r)||fe.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(fe.isVariableDeclaration(r)){for(let o of r.declarations)if(fe.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!fe.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:fe.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function gp(e){let t=qL(e),n=[],r=RE(e.ast,t);return Yn(e.ast,{JSXElement(o){Sn(e.file,e.sourceFile)&&cl(o)===e.sourceComponent||TE(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function _E(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function kE(e,t){let n=_E();return Yn(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function qL(e){let t=_E();return Sn(e.file,e.sourceFile)&&QL(t,kE(e.ast,e.sourceComponent)),Yn(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=jo(e.file,o),s=e.componentIdentities.filter(a=>Sn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(fe.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),fe.isImportDefaultSpecifier(a)){let l=s.filter(u=>$o(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let p=EE(d,"default");p&&u.add(p)}t.namespaceMembers.set(c,u)}continue}if(fe.isImportSpecifier(a)){let l=fe.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>$o(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let p of u){let g=EE(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(fe.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)}}}}}),CE(e.ast,t),t}function QL(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 CE(e,t){Yn(e,{VariableDeclarator(n){if(!n.node.init)return;let r=Bo(n.node.init);if(r){if(fe.isIdentifier(n.node.id)){let o=Uo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&mp(t,i,o);return}if(fe.isObjectPattern(n.node.id)){let o=Uo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&AE(n.node.id,o.namespaceMembers,t,n)}}}})}function RE(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Yn(e,{ReferencedIdentifier(r){if(n){r.stop();return}eF(r)||!r.isIdentifier()||!PE(r,t)||tF(r,t)||nF(r)||(n=!0,r.stop())}}),n}function eF(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 PE(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 tF(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!bE(e,r))return!1;let o=PE(e,t);if(!o)return!1;if(Bo(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()&&bE(e,a)&&!!Uo(a.node,t,a)}function nF(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function bE(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function Uo(e,t,n){let r=Bo(e);if(!r)return null;if(fe.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(fe.isObjectExpression(r))return rF(r,t,n);let o=fp(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?NE(s,o.slice(1).join(".")):null}function rF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!fe.isObjectProperty(i))continue;let s=dp(i);if(!s||!fe.isExpression(i.value)){fe.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 NE(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 mp(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 AE(e,t,n,r){for(let o of e.properties){if(fe.isRestElement(o)){if(fe.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&mp(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!fe.isObjectProperty(o))continue;let i=dp(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=NE(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=fe.isAssignmentPattern(o.value)?o.value.left:o.value;if(fe.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&mp(n,c,s);continue}if(fe.isObjectPattern(a)&&s.namespaceMembers.size>0){AE(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function EE(e,t){if(!$o(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 TE(e,t){let n=e.node.openingElement.name;if(fe.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=wE(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 wE(e){if(fe.isJSXIdentifier(e))return[e.name];if(fe.isJSXMemberExpression(e)){let t=wE(e.object);return t?[...t,e.property.name]:null}return null}function cl(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()&&fe.isIdentifier(n.node.id))return n.node.id.name}return null}function OE(e,t){let n=$t(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=gp({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 rt(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 ur(e,t){let n=tt(e);return!!(n&&In(t,n))}function In(e,t){return t.start>=e.start&&t.end<=e.end}function jn(e,t){let n=Be(e,rt(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:ll(e,t)}function _i(e,t){let n=tt(t);return n?e.slice(n.start,n.end):""}function LE(e,t){return e.start===t.start&&e.end===t.end}function ll(e,t){let n=null;return Yn(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 ul(e,t){return hp(e,t).length>0}function dl(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()&&!oF(o,n,r)))return!0;o=o.parentPath}return!1}function oF(e,t,n){let r=tt(e.node.consequent);if(r&&In(r,t)&&!In(r,n))return!1;let o=e.node.alternate?tt(e.node.alternate):null;return!(o&&In(o,t)&&!In(o,n))}function hp(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()&&yp(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 yp(e){return e==="&&"||e==="||"||e==="??"}function FE(e,t){let n=tt(e.consequent);if(n&&In(n,t))return n;let r=tt(e.alternate);return r&&In(r,t)?r:null}function DE(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=>Ii(a.file)));if(!t.has(Ii(e.sourceFile))||!t.has(Ii(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(Ii(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=vE(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=$t(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=IE(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=gp({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!Sn(s.file,e.targetFile)||cl(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 uF}from"@vcp-dev/contracts";function fl(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 Ks();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return Ks();let u=iF(a,l,o?.instanceCount);if(!u)return Ks();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"?Ks():{ok:!0,target:{kind:"jsx-attribute"}}}function Ks(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function iF(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 dr from"@babel/types";import{SiteEditSetPropsParamsSchema as sF}from"@vcp-dev/contracts";function ME(e){let t=e.changes??(e.change?[e.change]:[]);if(!sF.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return Xs("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return Xs("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 Xs("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=Be(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return Xs("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?aF(r):cF(c.match.path.node,r.name);if(!l)return Xs("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 aF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function cF(e,t){let n=e.properties.filter(i=>dr.isObjectProperty(i)&&lF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!dr.isExpression(r.value))return null;let o=ar(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function lF(e){return dr.isIdentifier(e)?e.name:dr.isStringLiteral(e)?e.value:dr.isNumericLiteral(e)?String(e.value):null}function Xs(e,t){return{ok:!1,errorCode:e,reason:t}}function BE(e){if(e.change.name!=="className"&&e.change.name!=="class")return zs("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return zs("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return zs("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return zs("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 zs("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 zs(e,t){return{ok:!1,errorCode:e,reason:t}}async function $E(e){let t=uF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return ro("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 ro("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 dF(e,r);if(o){if(!o.ok)return ro("owner-plan-failed",o.reason);jE(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return ro("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return ro("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if(mF(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=fl({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return ro(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){xp(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=ME({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return ro("repeat-target-failed",l.reason);jE(n,l.steps);continue}xp(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:fF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),pF(n)?ro("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function dF(e,t){return t.name!=="className"&&t.name!=="class"?null:BE({node:e.node,change:t,classNameSource:e.classNameSource})}function fF(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 pF(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 jE(e,t){for(let n of t)xp(e,{...n,order:e.length})}function xp(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 mF(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?bp(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function bp(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)=>bp(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=>bp(n[i],r[i]))}return!1}function ro(e,t){return{ok:!1,errorCode:e,reason:t}}import*as Ci from"@babel/types";import*as Ee from"@babel/types";function Ep(e,t,n){let r=jn(t,n);return r?fr(e,r):null}function fr(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=_i(e,u.node),p=r.node.params.map(f=>_i(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:pl(u.node),callbackPath:r,collectionPath:u}}function Hs(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function gF(e,t){let n=tt(e.node);return n?hF(t).some(r=>{let o=tt(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function hF(e){let t=e.callbackPath.node.body;return Ee.isBlockStatement(t)?oo(t.body):io(t)}function oo(e){let t=[];for(let n of e){if(Ee.isReturnStatement(n)){n.argument&&t.push(...io(n.argument));continue}if(Ee.isBlockStatement(n)){t.push(...oo(n.body));continue}if(Ee.isIfStatement(n)){let r=Ee.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...oo(r)),n.alternate){let o=Ee.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...oo(o))}continue}if(Ee.isSwitchStatement(n)){for(let r of n.cases)t.push(...oo(r.consequent));continue}Ee.isTryStatement(n)&&(t.push(...oo(n.block.body)),n.handler&&t.push(...oo(n.handler.body.body)),n.finalizer&&t.push(...oo(n.finalizer.body)))}return t}function io(e){return Ee.isJSXElement(e)?yF(e)?UE(e.children):[e]:Ee.isJSXFragment(e)?UE(e.children):Ee.isParenthesizedExpression(e)||Ee.isTSAsExpression(e)||Ee.isTSSatisfiesExpression(e)||Ee.isTSNonNullExpression(e)||Ee.isTSTypeAssertion(e)?io(e.expression):Ee.isConditionalExpression(e)?[...io(e.consequent),...io(e.alternate)]:Ee.isLogicalExpression(e)&&yp(e.operator)?io(e.right):[]}function UE(e){return e.flatMap(t=>Ee.isJSXElement(t)||Ee.isJSXFragment(t)?io(t):Ee.isJSXExpressionContainer(t)&&(Ee.isJSXElement(t.expression)||Ee.isJSXFragment(t.expression)||Ee.isConditionalExpression(t.expression)||Ee.isLogicalExpression(t.expression))?io(t.expression):[])}function yF(e){let t=e.openingElement.name;return Ee.isJSXIdentifier(t)?t.name==="Fragment":Ee.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function VE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function pl(e){return!(Ee.isIdentifier(e)||Ee.isThisExpression(e)||Ee.isMemberExpression(e)||Ee.isOptionalMemberExpression(e)||Ee.isCallExpression(e)||Ee.isOptionalCallExpression(e))}function JE(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=$t(e);if(!n)return t.isRepeatItemRoot===!0;let r=Be(n,rt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ll(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=fr(e,o);return i?gF(o,i):t.isRepeatItemRoot===!0}function KE(e,t){let n=$t(e);if(!n)return!1;let r=Be(n,rt(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:ll(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 Sp(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 xF(e,t){let n=tt(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||ur(a.path.node,n)||so(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Sp(i.node.name);s&&o(s,i)}}),[...r].sort()}function Ip(e,t,n){let r=$t(e);if(!r)return{ok:!0};let o=Be(r,rt(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Be(r,rt(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=ss(o.match.path,i.match.path);if(ul(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=xF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function zE(e){let t=e;for(;at.isTSQualifiedName(t);)t=t.left;return at.isIdentifier(t)?t.name:null}function Ws(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function ml(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 vp(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=XE(e),i=XE(t);if(!o||!i||!LE(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=FE(s.node,n);if(a&&!In(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&&In(a,n)&&!In(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())&&JE(s)){let a=tt(s.node.body)??tt(s.node);if(a&&!In(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 XE(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 so(e,t,n){return n.scope.getBinding(t)===e}function _p(e,t,n,r={}){if(!r.preserveConditionalBoundary&&ul(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=>ml(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||ur(u.path.node,o)||i.has(u.path.node)||so(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Sp(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function kp(e,t,n){let r=tt(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>ml(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Ws(e,s=>{let a=s.scope.getBinding(s.node.name);!a||ur(a.path.node,r)||o.has(a.path.node)||so(a,s.node.name,t)||i.add(s.node.name)}),i.size>0?{ok:!1,bindingNames:[...i].sort()}:{ok:!0}}function HE(e,t){let n=new Set(e.callbackPath.node.params.flatMap(a=>ml(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)||so(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(Ci.isIdentifier(l))o(l.name,c);else{let u=zE(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function Cp(e,t){let n=tt(e.node),r=new Set;return Ws(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&ur(i.path.node,n)||so(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 WE(e){let t=[];for(let n of e.callbackPath.node.params){if(Ci.isIdentifier(n)){t.push(n.name);continue}if(Ci.isRestElement(n)&&Ci.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 GE(e,t){return{...e,callbackParams:t}}function Rp(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Gs(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 YE(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 Vo(e){return{file:e.file,component:e.component}}function bF(e){return e.target.kind==="node"?e.target.key:null}function EF(e){return"kind"in e&&e.kind==="page-composition"}function yl(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function gl(e){return!EF(e)&&!yl(e)}function wp(e,t){let n=bl.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=bl.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function Pp(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=ir(n,rt(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function Lp(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 SF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function IF(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 Np(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function vF(e){let t=SE(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=vp(t.path,e.targetParentPath);if(!n.ok)return{ok:!1,reason:n.reason};let r=_F({source:e.source,sourceContext:e.sourceContext,callSitePath:t.path,targetParentPath:e.targetParentPath});if(!r.ok)return r;let o=iS(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?pl(o):!0}}}function _F(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||ur(a.path.node,t))return;let c=RF(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=NF(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=kF(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=Cp(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}so(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:AF(e.source,t,[...n.values()])}}function kF(e,t){if(t.length===0)return e;let n=iS(e);if(!n)return null;let r=pl(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=CF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function CF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function RF(e,t,n){let r=PF(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=bi(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 PF(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!ur(n.node,t)||n.node.computed||!Ye.isIdentifier(n.node.property))return null;let r=tt(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function NF(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()&&Ye.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=_i(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 AF(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 iS(e){try{let n=oS.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=Ye.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&Ye.isExpression(r)?r:null}catch{return null}}function TF(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||ur(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||!wF(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 Ws(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 wF(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=OF(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=jo(t,i),a=i.startsWith(".")?wp(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=Ye.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 OF(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function qE(e,t,n,r){let o=hp(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=_i(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=LF(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${DF(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function LF(e,t){return FF(e.node)?t:`(${t})`}function FF(e){return Ye.isIdentifier(e)||Ye.isThisExpression(e)||Ye.isSuper(e)||Ye.isMemberExpression(e)||Ye.isOptionalMemberExpression(e)||Ye.isCallExpression(e)||Ye.isOptionalCallExpression(e)||Ye.isBooleanLiteral(e)||Ye.isNumericLiteral(e)||Ye.isStringLiteral(e)||Ye.isNullLiteral(e)||Ye.isUnaryExpression(e)}function DF(e){return e.trim().startsWith("<")?e:`(${e})`}var MF={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 hl(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=MF[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 BF(e,t){for(let n of e.program.body){if(!Ye.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>Ye.isImportDefaultSpecifier(o));if(r&&Ye.isImportDefaultSpecifier(r))return r.local.name}return null}function jF(e,t,n){for(let r of e.program.body){if(!Ye.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>Ye.isImportSpecifier(i)&&(Ye.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&Ye.isImportSpecifier(o))return o.local.name}return null}function QE(e){let t=new Set;return Yn(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function eS(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function $F(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=Lp(e),o=$t(t);if(n.exportName!=="default"){let a=o?jF(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?eS(r,QE(o)):r;return{localName:c,importStep:Ap(e,c)}}if(!o)return{localName:r,importStep:Ap(e,r)};let i=BF(o,n.source);if(i)return{localName:i};let s=eS(r,QE(o));return{localName:s,importStep:Ap(e,s)}}function UF(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??Lp(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 VF(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?JF(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function JF(e){return Object.fromEntries(Object.entries(e).filter(t=>Op(t[1])))}function Op(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Op):typeof e=="object"?Object.values(e).every(Op):!1}function Ap(e,t=Lp(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 tS(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 KF(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function Ri(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function Fp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function Ys(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:Fp(e,t.slice(0,n)),index:r.index}}return null}function Tp(e,t){return e.locator?e.collectionPathMap?.[t]?Fp(e.locator,e.collectionPathMap[t]):Ys(e.locator)?zF(e.locator,HF(t,e.collectionIndexMap)):null:null}function XF(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:sS(o,t)}function sS(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=sS(r,t);return o===void 0?void 0:{[n.name]:o}}function zF(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},Fp(e,i)}return null}function HF(e,t){return t?.[e]??e}function nS(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 WF(e,t){return GF(e.root,t.root)&&ZF(e.path??[],t.path??[])}function GF(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&&YF(e.sourceRange,t.sourceRange)}}function YF(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function ZF(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 xl=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:Ri(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:Ri(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:Ri(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:Ri(t.kind,t.params.kind)};let r=t;if(yl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!gl(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=tS(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:Ri(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:Ri(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=bF(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):rS(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 rS(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:rt(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?$E({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=Tp(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:rt(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=Tp(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:rt(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=$t(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Be(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!SF(a.match.path))return{ok:!0,value:r};let c=IF(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=Tp(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=$t(this.graph.getFileContent(t));if(!o)return!1;let i=Be(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=Ys(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=Gs(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:rt(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||OE(n,t)>1)return null;let r=wp(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(!gl(n.params.position))return yl(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=Gs(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=mE(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=hl(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"?$F(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:rt(r),node:{jsx:UF(n.params.node,x?.localName)},placement:n.params.position.relation,anchorLocator:i?rt(i):void 0}),this.buildPlan(t,n,f,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!gl(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:VF(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(!gl(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=Ys(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=XF(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"?nS(0,a.collectionIndexMap):nS(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=Gs(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:")||KE(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=$t(c);if(!l)return null;let u=jn(l,r),d=jn(l,o);if(!u||!d)return null;let p=fr(c,u),g=fr(c,d);if(!Hs(p,g))return null;if(a&&(s==="before"||s==="after")){let f=jn(l,a),y=f?fr(c,f):null;if(!Hs(p,y))return null}if(dl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=Ip(c,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:rt(r),targetParentLocator:rt(o),placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Vo(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=$t(c);if(!l)return null;let u=jn(l,r),d=jn(l,o);if(!u||!d)return null;let p=fr(c,u);if(!p)return null;let g=fr(c,d);if(Hs(p,g))return null;if(g&&!VE(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=Ep(c,l,a);if(g&&!Hs(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=hl(o,{kind:"native-tag",tag:r.tag});if(b)return{ok:!1,errorCode:"unsupported-operation",reason:b}}let m=Pp(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(dl(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let f=qE(c,u,d,m);for(let b of f.conditionPaths){let S=kp(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=_p(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=HE(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=vF({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=Cp(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:rt(r),targetParentLocator:rt(o),placement:s,anchorLocator:a?rt(a):void 0,repeatExpression:Rp(E,f.sourceJsx),selectionContext:Vo(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=$t(c),d=$t(l);if(!u||!d)return null;let p=DE({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=jn(u,r),m=jn(d,o);if(!g||!m)return null;let f=vp(p.callSitePath,m);if(!f.ok)return{ok:!1,errorCode:"unsupported-operation",reason:f.reason};let y=fr(c,g);if(!y)return null;if(fr(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")&&Ep(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 P=hl(o,{kind:"native-tag",tag:r.tag});if(P)return{ok:!1,errorCode:"unsupported-operation",reason:P}}let E=Pp(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(dl(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let b=qE(c,g,m,E);for(let P of b.conditionPaths){let F=kp(P,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=_p(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=TF({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:m});if(!I.ok)return{ok:!1,errorCode:"unsupported-operation",reason:I.reason};let T=WE(y);if(!T.ok)return{ok:!1,errorCode:"unsupported-operation",reason:T.reason};let C=GE(y,T.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:rt(r),removeWhitespace:!0}];for(let P of I.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:P.moduleSpecifier,imports:P.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:rt(o),expression:Rp(C,b.sourceJsx),placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Vo(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(yl(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 T=this.graph.getFileContent(r.file),C=$t(T),A=C?jn(C,r):null,P=C?jn(C,S):null,F=A?.parentPath,B=P?.parentPath;if(!A||!P||!F||!B||F.node!==B.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 U=F.node.loc;return U?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:rt(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:U.start.line,startColumn:U.start.column,endLine:U.end.line,endColumn:U.end.column}},placement:b.relation,anchorLocator:rt(S),selectionContext:Vo(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=tS(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(KF(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=Gs(r,c,p);if(g&&!Np(g)&&!YE(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=Ys(b.locator),T=Ys(S.locator);if(I&&T&&b.file===S.file&&WF(I.locator,T.locator)){let C=I.index,A=T.index,P=u==="before"?A-(C<A?1:0):A+(C<A?0:1);return this.buildPlan(t,n,[{order:0,file:b.file,type:"move-array-item",locator:I.locator,fromIndex:C,toIndex:P}],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=Np(g)?g:m;if(f&&Np(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=hl(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=Ip(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:rt(r),targetParentLocator:rt(s),placement:u,anchorLocator:d?rt(d):void 0,selectionContext:Vo(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=Pp(this.graph,r)??`<${r.component} />`,p=gE(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:rt(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,y={moduleSpecifier:wp(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:rt(o),node:{jsx:d},placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Vo(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:rt(o),node:{jsx:d},placement:s,anchorLocator:a?rt(a):void 0,selectionContext:Vo(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:Ue(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 rS(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 Vp from"@babel/generator";import{parse as dD,parseExpression as fD}from"@babel/parser";import*as k from"@babel/types";import*as pr from"@babel/types";import Dp from"@babel/generator";import*as it from"@babel/types";var qF=typeof Dp=="function"?Dp:Dp.default,QF=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,eD=/^((?:https?:)?\/\/)[^/@\s]+@/i,tD=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function cS(e,t){let n=vn(e.callee);if(!n)return null;if(n==="fetch")return Mp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(aS(r))return Mp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(aS(r))return Mp(e.arguments[0],r,t,["ky client contract"])}return null}function Mp(e,t,n,r){if(!e||it.isSpreadElement(e)||it.isJSXNamespacedName(e))return iD(t,n,r,"missing url argument");let o=Zs(e);return{sourceKind:oD(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 Zs(e){if(it.isStringLiteral(e))return Jo(e.value);if(it.isTemplateLiteral(e))return Jo(nD(e));if(it.isBinaryExpression(e)&&e.operator==="+"){let t=Zs(e.left),n=Zs(e.right);return!t&&!n?void 0:Jo(`${t??Bp(e.left)}${n??Bp(e.right)}`)}if(it.isMemberExpression(e)){let t=lS(e);if(t)return`env:${t}`}if(!(it.isCallExpression(e)&&vn(e.callee)==="new URL")){if(it.isNewExpression(e)&&it.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!it.isSpreadElement(t)?Zs(t):void 0,o=n&&!it.isSpreadElement(n)?Zs(n):void 0;return o&&r?Jo(`${o} + ${r}`):r??o}if(it.isIdentifier(e))return`:${e.name}`}}function nD(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+=Bp(r))}return t}function Bp(e){if(it.isIdentifier(e))return`:${e.name}`;if(it.isMemberExpression(e)){let t=lS(e);if(t)return`env:${t}`}return`:${rD(e)}`}function rD(e){return qF(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function Jo(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(eD,"$1<redacted>@").replace(tD,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?QF.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function oD(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 iD(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function aS(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function lS(e){return!it.isMemberExpression(e.object)||!it.isIdentifier(e.object.object,{name:"process"})||!sD(e.object.property,"env")?null:it.isIdentifier(e.property)?e.property.name:it.isStringLiteral(e.property)?e.property.value:null}function sD(e,t){return it.isIdentifier(e)&&e.name===t}function vn(e){if(it.isIdentifier(e))return e.name;if(it.isMemberExpression(e)){let t=vn(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 aD=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),cD=new Set(["getConfig","submit"]);function $n(e,t){let n=uS(vn(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!aD.has(i))return null;let s=jp(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(!cD.has(i))return null;let s=jp(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=jp(e,0)??lD(e,0,"path")??"/cms/:path",s=uD(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 uS(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 dS(e,t){let n=vn(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 El(e,t){let n=vn(e.callee),r=t?uS(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function jp(e,t){let n=e.arguments[t];return pr.isStringLiteral(n)?n.value:null}function lD(e,t,n){let r=e.arguments[t];if(!pr.isObjectExpression(r))return null;for(let o of r.properties)if(pr.isObjectProperty(o)&&!o.computed&&(pr.isIdentifier(o.key)&&o.key.name===n||pr.isStringLiteral(o.key)&&o.key.value===n)&&pr.isStringLiteral(o.value))return o.value.value;return null}function uD(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function Pi(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as Tt from"@babel/types";var $p=new WeakMap;function rn(e,t){let n=$p.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;Tt.isMemberExpression(u)||Tt.isOptionalMemberExpression(u);)u=u.object;return Tt.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,Tt.traverseFast(e,l=>{if(!Tt.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(Tt.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(Tt.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;Tt.traverseFast(e,l=>{(Tt.isAssignmentExpression(l)&&s(l.left)||Tt.isUpdateExpression(l)&&s(l.argument)||Tt.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=$p.get(e)??new Map;return c.set(t,a),$p.set(e,c),a}function fS(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 Qt from"@babel/types";import{posix as Up}from"node:path";function Ni(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if(Qt.isBooleanLiteral(e))return e.value;if(Qt.isUnaryExpression(e,{operator:"!"})){let l=Ni(e.argument,t,r);return l===void 0?void 0:!l}if(Qt.isLogicalExpression(e)){let l=Ni(e.left,t,r),u=Ni(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(!Qt.isCallExpression(e)||!Qt.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?Up.normalize(Up.join(Up.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=Qt.isExpression(s.body)?s.body:s.body.body.length===1&&Qt.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!Qt.isExpression(a))return;let c=s.params.flatMap(l=>Qt.isIdentifier(l)?[l.name]:[]);return Ni(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 sG=typeof Vp=="function"?Vp:Vp.default,IS=new WeakMap;function vS(e){let t=new Map;return IS.set(t,new Map([...e].map(n=>[n.file,n]))),t}var pD={maxFunctionDepth:8,maxImportDepth:6},mD=new Set(["src","href","alt","poster","content","title","aria-label"]),pS=new WeakMap;function gD(e,t,n){let r=pS.get(t.fileCache);r||(r=new WeakMap,pS.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 Al(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")&&gS(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=Wp(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...pD,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:BS(n,e.element.componentName),scopeFunction:Gp(n,e.element.componentName)};await _S(e.element.componentName,e.graph,r);let o=[];o.push(...await bD(e.element,e.graph,r),...await ED(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await SD(s,e.element,e.graph,r);a&&o.push(Pl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=gS(s,e.element);if(!a)continue;let c=await RS(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&Xo(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(Tl(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)&&!NS(u.value.expression,e.element,e.graph)&&(c=await gt(u.value.expression,r))}c&&o.push(Pl(c,a,s.name))}let i=OD(o).sort(DS);return{hasDynamicData:i.length>0,bindings:i}}async function _S(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 gD(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 hD(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 CS(l.sourceFile,n);if(!d)continue;let p=uo(d,n,{importDepth:n.importDepth+1});p.paramSources.clear(),p.scopeVariables=BS(d,l.componentName),p.scopeFunction=Gp(d,l.componentName),p.lexicalContext=void 0,await _S(l.componentName,t,p);let g=await yD(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=Hp(u);d.length===1&&c.set(l,d[0])}xD(o,c,n)}var mS=new WeakMap;function hD(e,t,n,r){let o=mS.get(r.fileCache);return o||(o=fS(),mS.set(r.fileCache,o)),o.resolve({fromFile:e,exportName:t,targetFile:n,maxImportDepth:r.options.maxImportDepth},()=>kS(e,t,n,r))}async function kS(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 CS(e,r))?.imports.get(t);if(!s||!mt(s.source))return!1;let a=await Zp(e,s.source,r.exists);return a?a===n?!0:kS(a,s.importedName,n,r,o):!1}async function yD(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(Tl(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?Xo(c.base,e,t):null)?await wl(c,e,t,n):NS(a,e,t)?null:await gt(a,n);u&&i.set(s,u)}return i}function Tl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function CS(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 Wp(e,r,t.fileCache)}function xD(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,Rl(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,Xt(o))}}function gS(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":mD.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function bD(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 Ol(i.collectionSource,n);s&&r.push(Pl(ao(s),"repeat-region",i.collectionExpression))}return r}async function ED(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 Ol(i.conditionSource,n);s&&r.push(Pl(ao(s),"conditional-region",i.conditionExpression))}return r}async function SD(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(Tl(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)&&El(i.expression)?PS(i.expression,t,n,r):null}return RS(e.source,t,n,r)}async function RS(e,t,n,r){return e&&Xo(e.base,t,n)?wl(e,t,n,r):Ol(e,r)}async function wl(e,t,n,r,o){if(!e)return null;let i=Xo(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?Xo(s.base,t,n,i.region):null)?await wl(s,t,n,r,i.region):s?await Ol(s,r):await ID(i.candidate.collectionExpression,t,n,r,i.region);return c?qs(c,e.path,!0):null}async function ID(e,t,n,r,o){let i;try{i=fD(e,{plugins:["typescript","jsx"]})}catch{return null}return PS(i,t,n,r,o)}async function PS(e,t,n,r,o){let i=uo(r.analysis,r),s=new Set;k.traverseFast(e,a=>{k.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=Xo(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await wl({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 Xo(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&&!hS(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||hS(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function hS(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 NS(e,t,n){let r=!1;return k.traverseFast(e,o=>{!r&&k.isIdentifier(o)&&Xo(o.name,t,n)&&(r=!0)}),r}async function Ol(e,t){if(!e)return null;let n=await Xp(e.base,t);return n?qs(n,e.path,!1):null}async function Xp(e,t){let n=t.paramSources.get(e);if(n)return Xt(n);if(t.variableCache.has(e))return LD(t.variableCache.get(e)??null);let r=lo(e,t);if(r&&r!==t)return Xp(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await _D(e,t);if(o)return t.variableCache.set(e,Xt(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 vD(e,t):await gt(s,t);return t.variableCache.set(e,c?Xt(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 Yp(a,t);if(c){let l=uo(c,t,{importDepth:t.importDepth+1}),u=jS(a,c);if(u){let g=(await Ko(u,[],l)).returnSource;return t.variableCache.set(e,g?Xt(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?Xt(p):null),t.resolvingVariables.delete(e),p}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function lo(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>co(n).includes(e))?t:t.lexicalContext?lo(e,t.lexicalContext):void 0}function Sl(e,t,n=new Set){if(k.isIdentifier(e)){let s=lo(e.name,t);if(s&&s!==t)return Sl(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=lo(e.name,t),o=t.paramArguments.get(e.name);if(o)return Sl(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?Sl(i,t,n):null}function mr(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=lo(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?mr(s.expression,s.context,r):a?mr(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=mr(e.left,t,r),i=mr(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+=(mr(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=mr(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)?mr(e.expression,t,r):null}async function vD(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)&&(co(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(Kp(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=uo(d.analysis,d),m=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;p&&m&&kl(m,Kp(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=Hp(r);return!o&&i===1&&l.length===1?ao(l[0]):null}async function _D(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 Xp(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?dS(e,{file:t.file}):null;if(n)return LS(n);let r=await kD(e,t);if(!r)return null;let o=wD(e);return qs(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 Ti(await gt(e.callee.object,t));if(k.isCallExpression(e))return TS(e,t);if(k.isObjectExpression(e)){let n=await OS(e,t);return Object.keys(n).length>0?Rl(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?Rl(n,t.file):null}if(k.isConditionalExpression(e)){let n=await gt(e.consequent,t),r=await gt(e.alternate,t);return Ti(bS(n,r))}if(k.isLogicalExpression(e)){let n=await gt(e.left,t),r=await gt(e.right,t);return Ti(bS(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 kD(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 AS(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=lo(e,t);if(r){if(r.scopeFunction&&rn(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&k.isIdentifier(s.expression)?AS(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)||rn(t.analysis.ast,e))return null;let i=await Zp(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function TS(e,t){let n=e.arguments[0],r=k.isExpression(n)?Sl(n,t):null,i=vn(e.callee)?.split(".")[0],s=i?await AS(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=wS(n,"path"),E=x&&mr(x,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(b=>k.isObjectProperty(b)&&Oi(b)==="path"?{...b,value:k.stringLiteral(Jo(E))}:b)},...e.arguments.slice(1)]})}let c=$n(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=yS(n,"query"),E=k.isObjectExpression(x)?yS(x,"path"):null,b=E&&mr(E,t),S=b&&Pi(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 Or(e.callee,t);if(x&&!Il(x.node))return null;if(x&&Il(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=mr(n,t);x?.startsWith("/")&&(c.endpointPattern=Jo(x))}return LS(c)}if(vn(e.callee)==="Promise.all"&&k.isArrayExpression(n))return gt(n,t);if(El(e)){if(!El(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!k.isExpression(e.callee))return null;let x=await Or(e.callee,t);if(x)return Il(x.node)?Jp(e,t,{node:x.node,context:x.context}):null;let E=e.arguments[0];if(E&&k.isExpression(E))return Ti(await gt(E,t))}let l=await CD(e,t);if(l)return l;let u=cS(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 PD(e,t);if(d)return d;let p=await ND(e,t);if(p)return p;let g=await AD(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=Hp(f);return y.length===1?Ti(y[0]):null}async function CD(e,t){let n=vn(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=RD(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await wi(s.name,t);if(a)return(await Ko(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return vl(t.file,`${n} without static options`);let o=wS(r,"queryFn");if(!o)return vl(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await wi(o.name,t);return i?(await Ko(i.node,[],i.context)).returnSource:vl(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await Ko(o,[],t)).returnSource:k.isCallExpression(o)?TS(o,t):null}function wS(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(Oi(n)===t)return n.value}return null}function yS(e,t){let n=new Set;for(let i of e.properties){if(!k.isObjectProperty(i)||i.computed)return null;let s=Oi(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>k.isObjectProperty(i)&&Oi(i)===t);if(r.length!==1)return null;let o=r[0];return k.isObjectProperty(o)&&k.isExpression(o.value)?o.value:null}function RD(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 PD(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 ao(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await wi(o.name,t);if(!i)return ao(r);let s=await Ko(i.node,[r],i.context);return{...ao(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await Ko(o,[r],t);return{...ao(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return ao(r)}async function ND(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 AD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:Ti(await gt(e.callee.object,t))}async function Jp(e,t,n){let r=n;if(!r&&k.isIdentifier(e.callee))r=await wi(e.callee.name,t)??void 0;else if(!r&&k.isMemberExpression(e.callee)){let s=await Or(e.callee,t);s&&Il(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(vl(t.file,`unsupported argument for ${vn(e.callee)??"call"}`));continue}let a=await gt(s,t);o.push(a)}return(await Ko(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function Il(e){return k.isFunctionDeclaration(e)||Nl(e)||k.isObjectMethod(e)&&e.kind==="method"}async function Or(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 Or(e.expression,t,o);if(k.isIdentifier(e)){let i=lo(e.name,t),s=i??t;if(rn(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return Or(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return Or(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 Yp(u,s);return d?Or(k.identifier(u.importedName),uo(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 Or(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)?Or(c.value,s.context,o):null}return{node:e,context:t}}async function wi(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),Nl(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return wi(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 Yp(i,t);if(!s)return null;let a=uo(s,t,{importDepth:t.importDepth+1}),c=jS(i,s);return c?{node:c,context:a}:wi(i.importedName,a)}async function Ko(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=uo(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 co(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&&kl(d,Kp(f),o)});let a=TD(e,o),c=null,l,u=!1;for(let d of a){let p=uo(n.analysis,o);if(k.isObjectExpression(d)){l={...l??{},...await OS(d,p)},c=c??Rl(l,n.file);continue}let g=await gt(d,p);if(g){if(!c){c=g;continue}let m=zp(c,g);if(!m){u=!0,c=null;continue}c=m}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function kl(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Xt(t));return}if(k.isAssignmentPattern(e)){kl(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=qs(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&kl(i,o,n)}}function TD(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=Ni(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!lo(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 OS(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=Oi(r);if(!o||!k.isExpression(r.value))continue;let i=await gt(r.value,t);i&&(n[o]=i)}return n}function Oi(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function wD(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 qs(e,t,n){if(t.length===0)return Xt(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?qs(s,t.slice(1),n):null}let i=Xt(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=Ai(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=Ai(i.valuePath,"data")),i.fieldPath=Ai(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=Ai(i.fieldPath,s.join(".")),i):(i.valuePath=Ai(i.valuePath,xS(t)),i)}return i.valuePath=Ai(i.valuePath,xS(t)),i}function xS(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function Ai(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function LS(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 ao(e){let t=Xt(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function Kp(e){let t=Xt(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function Ti(e){return e?{...Xt(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function bS(e,t){return e?t?zp(e,t):Xt(e):t?Xt(t):null}function zp(e,t){if(Cl(e)!==Cl(t))return null;let n=MS(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Hp(e){let t=new Map;for(let n of e){let r=Cl(n),o=t.get(r);t.set(r,o?zp(o,n):Xt(n))}return[...t.values()]}function Cl(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Cl(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 Rl(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 vl(e,t){return{sourceKind:"unknown-api",sourceType:"api-field",confidence:"unknown",readonly:!0,evidence:[{file:e,reason:t}]}}function Pl(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 FS(e){let t=[...e].sort(DS),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 OD(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 DS(e,t){return ES(e.targetKind)-ES(t.targetKind)||MS(e.confidence,t.confidence)||SS(e.sourceKind)-SS(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function ES(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function SS(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function MS(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function Wp(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=IS.get(n)?.get(e),i=o?.source===t?o.ast:dD(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=Tl({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 _l(d.id,k.isExpression(d.init)?d.init:null))m.set(f,y);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&vn(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)&&Nl(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)&&Nl(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 _l(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?_l(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?_l(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=Oi(n);return r?_l(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function co(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?co(t.value):co(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?co(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?co(e.left):k.isRestElement(e)?co(e.argument):[]}function Nl(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function BS(e,t){let n=Gp(e,t);return n?e.functionVariables.get(n):void 0}function Gp(e,t){return e.functions.get(t)??e.functions.get("default")}async function Yp(e,t){let n=await Zp(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return Wp(n,r,t.fileCache)}function jS(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function Zp(e,t,n){return mt(t)?vo(e,t,n):null}function uo(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 LD(e){return e?Xt(e):null}function Xt(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Xt(n)]))}:{}}}import*as Qp from"@babel/parser";import qp from"@babel/traverse";import*as Se from"@babel/types";import{classifySiteEditPropertyName as FD}from"@vcp-dev/contracts";var em=typeof qp=="function"?qp:qp.default;function tm(e){let t=FD(e.propertyName);if(t.owner!=="generic")return _n("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return _n("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return _n("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return _n("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Qp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return _n("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=DD(r,e.element.sourceRange);if(!o)return _n("repeat-not-found","The selected element is not inside a supported map repeat");if(!Se.isIdentifier(o.callback.params[0]))return _n("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=MD(r,o.collection,e.file,e.sources);if(!i)return _n("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)||!XS(x))return _n("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 _n("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let p=n.instanceIndex;if(p>=d)return _n("index-out-of-range",`Selected repeat instance ${p} is outside the source collection`);let g=s.elements[p];if(!g||!Se.isObjectExpression(g))return _n("unsafe-collection","Selected repeat item is not an object");let m=JD(e.element,e.propertyName),f=UD(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:VD(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:_n("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function DD(e,t){let n=[];return em(e,{CallExpression(r){let o=$S(r.node);o&&VS(o.callback,t)&&n.push({...o,span:US(r.node)})},OptionalCallExpression(r){let o=$S(r.node);o&&VS(o.callback,t)&&n.push({...o,span:US(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function $S(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 MD(e,t,n,r){let o=Qs(t);if(o&&Se.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:HS(o)}},sourceFile:n};if(!Se.isIdentifier(t))return null;let i=[];if(em(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=Qs(i[0].init);return!s||!Se.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return BD(e,t.name,n,r)}function BD(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=$D(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=Qp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=jD(l,a),d=u?Qs(u):null;return!d||!Se.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function jD(e,t){let n=null;return em(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 $D(e,t,n){let r=nr(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 Qs(e){return Se.isParenthesizedExpression(e)?Qs(e.expression):Se.isTSAsExpression(e)?KS(e.typeAnnotation)?Qs(e.expression):null:Se.isTSSatisfiesExpression(e)?null:e}function KS(e){return Se.isTSTypeReference(e)&&Se.isIdentifier(e.typeName)&&e.typeName.name==="const"}function XS(e){return e.properties.every(t=>!Se.isObjectProperty(t)||t.computed||!Se.isExpression(t.value)?!1:Ll(t.value))}function Ll(e){if(Se.isTSAsExpression(e)&&KS(e.typeAnnotation))return Ll(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:Ll(n));if(Se.isObjectExpression(e))return XS(e);let t=ar(e);return t.status==="resolved"||t.status==="undefined"}function UD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&zS(o.key)===t);if(n.length>1)return null;let r=n[0];return r?Se.isExpression(r.value)?Ll(r.value)?"static":Se.isIdentifier(r.value)||Se.isMemberExpression(r.value)?"binding":null:null:"missing"}function VD(e,t){let n=e.properties.filter(o=>Se.isObjectProperty(o)&&zS(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!Se.isExpression(r.value)?{status:"undefined"}:ar(r.value)}function JD(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function zS(e){return Se.isIdentifier(e)?e.name:Se.isStringLiteral(e)?e.value:Se.isNumericLiteral(e)?String(e.value):null}function HS(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 US(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function VS(e,t){let n=HS(e);return JS(n.startLine,n.startColumn,t.startLine,t.startColumn)<=0&&JS(n.endLine,n.endColumn,t.endLine,t.endColumn)>=0}function JS(e,t,n,r){return e===n?t-r:e-n}function _n(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as RM}from"@vcp-dev/contracts";import*as ke from"@babel/types";import oa from"node:path";import*as ae from"@babel/types";import*as QS from"@babel/parser";import nm from"@babel/traverse";import*as Te from"@babel/types";function Dl(e,t){let n=[],r=e;for(;Te.isMemberExpression(r);){if(r.computed)if(Te.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Te.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Te.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Te.isIdentifier(r)||r.name!==t?null:n}function WS(e){if(Te.isIdentifier(e))return{base:e.name,path:[]};if(!Te.isMemberExpression(e))return null;let t=[],n=e;for(;Te.isMemberExpression(n);){if(n.computed)if(Te.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Te.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Te.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Te.isIdentifier(n)?{base:n.name,path:t}:null}function en(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 gr=Symbol("not-closed-literal");function Fl(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:gr;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return Fl(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Te.isSpreadElement(n))return gr;let r=Fl(n);if(r===gr)return gr;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Te.isObjectProperty(n)||n.computed||n.shorthand||!Te.isExpression(n.value))return gr;let r=Te.isIdentifier(n.key)?n.key.name:Te.isStringLiteral(n.key)?n.key.value:null;if(!r)return gr;let o=Fl(n.value);if(o===gr)return gr;t[r]=o}return t}default:return gr}}function GS(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let p=Fl(i);if(p!==gr)return p;if(!Te.isTemplateLiteral(i)){if(Te.isTSAsExpression(i)||Te.isTSSatisfiesExpression(i)||Te.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(Te.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(Te.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||Te.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(Te.isObjectExpression(i)){let g={};for(let m of i.properties){if(!Te.isObjectProperty(m)||m.computed)return;let f=null;if(Te.isIdentifier(m.key)?f=m.key.name:Te.isStringLiteral(m.key)&&(f=m.key.value),!f)return;if(m.shorthand){if(!Te.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(!Te.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(Te.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:en(f.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!Te.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(Te.isIdentifier(i))return{base:i.name,path:[]};if(!Te.isMemberExpression(i))return null;let p=[],g=i;for(;Te.isMemberExpression(g);){if(g.computed){let m=g.property;if(Te.isNumericLiteral(m))p.unshift({kind:"index",index:m.value});else if(Te.isStringLiteral(m))p.unshift({kind:"property",name:m.value});else{let f=Te.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(!Te.isIdentifier(g.property))return null;p.unshift({kind:"property",name:g.property.name})}g=g.object}return Te.isIdentifier(g)?{base:g.name,path:p}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var eI=typeof nm=="function"?nm:nm.default,YS=new WeakMap;function tI(e){try{return QS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function Ml(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=tI(n);return e.set(t,{source:n,ast:o}),o}function Bl(e,t){return rm(ea(e).expressionRanges,t,!1)}function nI(e,t){return ea(e).exactExpressions.get(rI(t))??null}function jl(e,t){return rm(ea(e).jsxRanges,t,!0)}function ea(e){let t=YS.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return eI(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=rI(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(qS),n.jsxRanges.sort(qS),YS.set(e,n),n}function ZS(e,t){let n=ta(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function rI(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function qS(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function rm(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 ta(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 Li(e,t){if(t)return om(e,t);let n=WS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function om(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function na(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of ea(e).expressions){if(om(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function oI(e,t,n,r){return rm(ea(e).expressionRanges,r,!0,o=>om(o.node,t)===n)}function Fi(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function ra(e){let t=null;if(eI(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Zn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=tI(o),s={source:o,ast:i};return n.set(e,s),s}function KD(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 XD(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 zD(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 iI(e,t){let n=zD(e.path);if(!n)return null;let r=bi(e,t);return r?{...n,...r}:null}function sI(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function im(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 sm(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 aI(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,T=`${y}::${x.kind}::${x.identifier.name}`;if(I.has(T))return null;I.add(T);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 A=x.path.node.init;if(!A||!ae.isExpression(A))return null;let P=XD(A);if(P&&!x.path.scope.getBinding("Proxy")&&!x.path.scope.getBinding("Reflect")){let U=x.path.scope.getBinding(P),G=U?await s({...f,binding:U}):null;if(G?.kind==="static"&&G.value!==null&&!Array.isArray(G.value)&&typeof G.value=="object")return G}let F=x.path.get("init");if(F&&!Array.isArray(F)&&F.isExpression()){let U=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(U)return U;if(F.isCallExpression()){let G=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(G)return G}}let B=await r(A,x.path.scope,y,E,b,S,I);return B===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:B,sourceKind:"binding"}}if(x.path.isIdentifier()&&x.path.parentPath?.isExportDefaultDeclaration()){let A=x.path.parentPath.node.declaration;if(!ae.isExpression(A))return null;let P=await r(A,x.path.scope,y,E,b,S,I);return P===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:x.identifier.name},value:P,sourceKind:"binding"}}return null}finally{I.delete(T)}}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 T=x.path,C=T.node.init;if(!C||!ae.isCallExpression(C))return null;let A=KD(C);if(!A||!ae.isArrayPattern(T.node.id)||T.node.id.elements.findIndex(G=>ae.isIdentifier(G)&&G.name===x.identifier.name)!==0)return null;let F=A==="useReducer"?1:0,B=C.arguments[F];if(!B||!ae.isExpression(B))return null;let U=await r(B,T.scope,y,E,b,S,I);return U===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:x.identifier.name,hook:A},value:U,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=iI(y,f.sourceInfo);if(!x)return null;let E=[...f.graph.elements.values()].filter(S=>sI(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 Zn(S.sourceFile,f.readFile,f.fileCache),T=I.ast?jl(I.ast,S.sourceRange):null;if(!T)return null;let C=T.parentPath;for(;C&&!C.isFunction();){if(C.isJSXElement()){let X=C.node.openingElement.name;if(!ae.isJSXIdentifier(X)||!/^[a-z]/.test(X.name))return null}else if(!C.isJSXFragment()&&!C.isReturnStatement()&&!C.isBlockStatement())return null;C=C.parentPath}if(!C)return null;let A=T.get("openingElement").get("attributes").filter(X=>X.isJSXAttribute()&&ae.isJSXIdentifier(X.node.name,{name:x.propName}));if(A.length!==1)return null;let P=A[0];if(!P?.isJSXAttribute())return null;let F=P.get("value"),B=F.isJSXExpressionContainer()?F.get("expression"):F;if(!B.isExpression())return null;let U=await r(B.node,B.scope,S.sourceFile,f.readFile,f.exists,f.fileCache,f.visited),G=U===void 0?void 0:en(U,x.remainingPath);if(G===void 0)return null;b.push(G)}return b}async function l(f){let y=iI(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(P=>sI(P,f.currentFile,y.componentName,y.exportName));if(E.length!==1)return null;let b=E[0],S=b.attributes?.find(P=>P.name===y.propName);if(S&&!S.source){let P=await d({caller:b,propName:y.propName,remainingPath:y.remainingPath,readFile:f.readFile,fileCache:f.fileCache});if(P)return im(P,{componentName:y.componentName,propName:y.propName,file:b.sourceFile})}if(!S?.source){let P=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(P)return im(P,{componentName:y.componentName,propName:y.propName,file:b.sourceFile});let F=sE(f.binding,y.componentName,y.propName);if(!F||F.propName!==y.propName)return null;let B=await r(F.expressionPath.node,F.expressionPath.scope,f.currentFile,f.readFile,f.exists,f.fileCache,f.visited);if(B===void 0)return null;let U=y.remainingPath;return U.length>0&&en(B,U)===void 0?null:{kind:"value",file:f.currentFile,root:{kind:"binding",name:y.propName},path:U,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 Zn(b.sourceFile,f.readFile,f.fileCache);if(!I.ast)return null;let T=oI(I.ast,I.source,S.source.expression,S.sourceRange)??na(I.ast,I.source,S.source.expression);if(!T)return null;let C={...S.source,expression:Fi(S.source.expression,y.remainingPath),path:[...S.source.path,...y.remainingPath]},A=await o({currentFile:b.sourceFile,expressionPath:T,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 A?im(A.kind==="external"?A:{...A,displayExpression:C.expression},{componentName:y.componentName,propName:y.propName,file:b.sourceFile}):null}async function d(f){let y=await Zn(f.caller.sourceFile,f.readFile,f.fileCache);if(!y.ast)return null;let x=jl(y.ast,f.caller.sourceRange);if(!x)return null;let E=x.get("openingElement").get("attributes").find(T=>T.isJSXAttribute()&&T.node.name.type==="JSXIdentifier"&&T.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=ta(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 Zn(f.caller.sourceFile,f.readFile,f.fileCache);if(!y.ast)return null;let x=jl(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 T=[{kind:"property",name:f.propName},...f.remainingPath],C={...I,expression:Fi(I.expression,T),path:[...I.path,...T]},A=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(A)return A.kind==="external"?A:{...A,displayExpression:C.expression}}return null}async function g(f){let{currentFile:y,binding:x,readFile:E,exists:b,fileCache:S,visited:I}=f,T=x.path.parentPath;if(!T||!T.isImportDeclaration())return null;let C=T.node.source.value;if(typeof C!="string")return null;let A=await vo(y,C,b);if(!A)return null;if(x.path.isImportDefaultSpecifier()){let X=await Zn(A,E,S),Z=X.ast?sm(X.ast,"default"):null,H=await m({file:A,exportName:"default",readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});return!H||H.kind!=="static"?null:{kind:"static",file:Z?.kind==="default-expression"?H.file:A,root:Z?.kind==="default-expression"?H.root:{kind:"default-export"},value:H.value,sourceKind:"imported-binding"}}if(!x.path.isImportSpecifier())return null;let P=x.path.node.imported,F=ae.isIdentifier(P)?P.name:P.value,B=await Zn(A,E,S),U=B.ast?sm(B.ast,F):null,G=await m({file:A,exportName:F,readFile:E,exists:b,graph:f.graph,externalSourceResolvers:f.externalSourceResolvers,externalAdapters:f.externalAdapters,functionCallContracts:f.functionCallContracts,fileCache:S,visited:I});return G?G.kind==="external"?G:{kind:"static",file:U?.kind==="re-export"?G.file:A,root:U?.kind==="re-export"||G.root.kind==="binding"&&G.root.name!==U?.name?G.root:{kind:"named-export",name:F},value:G.value,sourceKind:"imported-binding"}:null}async function m(f){let{file:y,exportName:x,readFile:E,exists:b,fileCache:S,visited:I}=f,T=`export::${y}::${x}`;if(!I.has(T)){I.add(T);try{let C=await Zn(y,E,S);if(!C.ast)return;let A=sm(C.ast,x);if(!A)return;if(A.kind==="default-expression"){let U=A.expression;if(!U||!ae.isIdentifier(U))return;let G=ra(C.ast).getBinding(U.name);return G?await s({currentFile:y,binding:G,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(A.kind==="re-export"){if(!A.source||!A.name)return;let U=await vo(y,A.source,b);return U?m({...f,file:U,exportName:A.name}):void 0}let P=A.name;if(!P)return;let F=ra(C.ast).getBinding(P);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(T)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as be from"@babel/types";function cm(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=Gn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!HD(s,r)?null:{callPath:s,basePath:i}}function HD(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 dI(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:il(r,t)}function cI(e,t){return e?be.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function lI(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=am(i,t,n,r,o);return typeof s=="number"?s:void 0}function am(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=Dl(e,t);if(i)return en(r,i);let s=Dl(e,n);return s?en(o,s):void 0}if(be.isBinaryExpression(e)&&e.operator==="-"){let i=be.isExpression(e.left)?am(e.left,t,n,r,o):void 0,s=be.isExpression(e.right)?am(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function WD(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 GD(e,t,n){let r=zo(e,t,n);return typeof r=="boolean"?r:void 0}function zo(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=Dl(e,t);return r?en(n,r):void 0}if(be.isUnaryExpression(e)&&e.operator==="!"){let r=zo(e.argument,t,n);return r===void 0?void 0:!r}if(be.isLogicalExpression(e)){let r=zo(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&zo(e.right,t,n);if(e.operator==="||")return r||zo(e.right,t,n)}if(be.isBinaryExpression(e)){let r=be.isExpression(e.left)?zo(e.left,t,n):void 0,o=be.isExpression(e.right)?zo(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 fI(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 pI(e){return e.some(t=>t.kind==="dynamic")}function uI(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function mI(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 YD(e,t){let n=[],r=[];for(let o of t){let i=en(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 gI(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 T=y.get("callee");if(!T.isMemberExpression())return null;let C=T.get("object");if(Array.isArray(C)||!C.isExpression())return null;let A=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!A||!Array.isArray(A.value)||A.value.length===0?null:A}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 T=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 T?.kind==="static"?T: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=ta(y.node);if(!I)return null;let T=await n(y.node,y.scope,f,x,E,b,S);return Array.isArray(T)?{kind:"static",file:f,root:{kind:"expression",sourceRange:I},value:T,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 T=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(!T||T.kind==="external")return null;let C=await c({currentFile:f,expressionPath:y,provenance:T,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(T.collectionPathMap?.length){let P=YD(C.value,T.collectionPathMap);if(P)return{kind:"static",file:T.file,root:T.root,value:P.value,sourceKind:T.sourceKind,collectionPathMap:P.collectionPathMap}}let A=en(C.value,T.path);return Array.isArray(A)?{kind:"static",file:T.file,root:T.root,value:A,sourceKind:T.sourceKind,pathPrefix:T.path,collectionIndexMap:T.collectionIndexMap,collectionPathMap:T.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 Zn(f.file,m.readFile,m.fileCache);b=S.ast?ra(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 Zn(f.file,m.readFile,m.fileCache);if(!y.ast)return null;let x=nI(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 T=WD(S);if(!T)return null;let C=[],A=[],P=[];for(let[F,B]of b.value.entries()){let U=GD(T,I.name,B);if(typeof U!="boolean")return null;if(U){C.push(B),A.push(b.collectionIndexMap?.[F]??F);let G=b.collectionPathMap?.[F];G&&P.push(G)}}return{...b,value:C,pathPrefix:b.pathPrefix,collectionIndexMap:A,...P.length>0?{collectionPathMap:P}:{}}}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,T=cI(S,0),C=cI(I,b.value.length);if(T===null||C===null)return null;let A=Math.max(0,T<0?b.value.length+T:T),P=Math.max(0,C<0?b.value.length+C:C),F=b.value.map((U,G)=>b.collectionIndexMap?.[G]??G).slice(A,P),B=b.collectionPathMap?.slice(A,P);return{...b,value:b.value.slice(A,P),pathPrefix:b.pathPrefix,collectionIndexMap:F,...B?{collectionPathMap:B}:{}}}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,T]=S.params;if(!be.isIdentifier(I)||!be.isIdentifier(T))return null;let C=b.value.map((P,F)=>({value:P,sourceIndex:b.collectionIndexMap?.[F]??F,originalIndex:F})),A=[...C];for(let P of C)for(let F of C)if(lI(S,I.name,T.name,P.value,F.value)===void 0)return null;return A.sort((P,F)=>{let B=lI(S,I.name,T.name,P.value,F.value)??0;return B===0?P.originalIndex-F.originalIndex:B}),{...b,value:A.map(P=>P.value),pathPrefix:b.pathPrefix,collectionIndexMap:A.map(P=>P.sourceIndex),...b.collectionPathMap?{collectionPathMap:A.map(P=>b.collectionPathMap?.[P.originalIndex]).filter(P=>!!P)}:{}}}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 T=cm(m.expressionPath,I.base),C;if(T){y=!0;let A=await s({currentFile:m.currentFile,callPath:T.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(!A||!Array.isArray(A.value))return null;C=A.value.map((P,F)=>{let B=en(A.value,[{kind:"index",index:F},...T.basePath,...I.path]);return uI(B)}),x??=A.collectionIndexMap}else{let A=await i({...m,sourceInfo:I});if(!A)return null;C=A.map(uI)}if(C.some(A=>A===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],T=0;for(let C of m.segments){if(C.kind==="dynamic"){let A=E[T]?.[S];if(!A)return null;I.push(A),T+=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:ZD,evaluateStaticExpression:$l}=GS({resolveBindingTarget:e=>Ul(e)}),{resolveRepeatCollectionTarget:qD,resolveCollectionCallTarget:QD,resolveDynamicMemberPathMap:eM}=gI({resolveBindingTarget:e=>Ul(e),evaluateStaticExpression:$l,buildExpressionSourceInfo:hr,resolveSourceInfoProvenance:Un,resolveComponentPropValues:e=>rM(e)}),{resolveExportValue:tM,resolveComponentPropBinding:nM,resolveComponentPropValues:rM,resolveBindingTarget:Ul}=aI({resolveExternalExpression:gm,resolveCollectionCallTarget:QD,evaluateStaticExpression:$l,resolveSourceInfoProvenance:Un,buildExpressionSourceInfo:hr});function _I(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var hI=new WeakMap;function oM(e){let t=hI.get(e);return t||(t=new WeakMap,hI.set(e,t)),t}function yI(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 kI(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=Ml(s,t,n);if(!a)return null;let c=Bl(a,r.sourceRange);if(!c)return null;let l=await hr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let p=await bm({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?dm(p,Li(c.node,n)):null}let u=new Set,d=await CM({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?dm(d,l.expression):null}async function Di(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ml(i,t,n);if(!s)return null;let a=e.sourceRange?Bl(s,e.sourceRange):e.expression!==void 0?na(s,n,e.expression):null;if(!a)return null;let c=Vl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await hr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Un({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 OI({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 dm(d,e.expression??Li(c.node,n))}async function mm(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=Ml(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"?iM({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}):sM({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function hr(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 ZD(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:Li(e.expression,e.source),base:t.base,path:t.path}:null}function dm(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 iM(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=Bl(r,o.sourceRange),u=l?await hr({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 xI(t,o.value);let p=await bm({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"?vI(t,p):pm(t,Li(l.node,n),p):aM({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 Un({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=fm(l.node);if(p)return kn(p.code,p.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=fm(g.path.node.init);if(m)return kn(m.code,m.message)}return g?.path.isVariableDeclarator()&&ke.isCallExpression(g.path.node.init)?cM("unsupported-expression",AI(g.path.node.init,e.functionCallContracts)):kn("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?vI(t,d):pm(t,u.expression,d)}async function sM(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=na(r,n,o.conditionExpression);if(!l)return kn("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Un({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=pm(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 xI(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 aM(e){let t=await RI(e);if(t.length===0)return kn("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(lM(e.expression))return CI(t);if(NI(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 cM(e,t){return CI([{code:e,message:t}])}function CI(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function lM(e){return ke.isCallExpression(e)||ke.isConditionalExpression(e)||ke.isLogicalExpression(e)||ke.isBinaryExpression(e)}function ia(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 RI(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=fm(t);if(l)return[l];if(ke.isCallExpression(t))return[{code:"unsupported-expression",message:AI(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 $l(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)?ia([...await lm(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)?ia([...await lm(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)?ia([...await lm(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 fm(e){return NI(e)?bI("i18n helpers require a static message id string"):mM(e)?bI("CMS helpers require static entry id and field path string arguments"):null}async function lm(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await RI({...t,expression:o}));return r}function uM(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:[dM(e.sourceType)]}}async function gm(e){for(let n of xM){if(!EI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return II(SI(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(!EI(e.expressionPath,n.helperNames))continue;let r=await n.resolve(t);if(r)return II(SI(r),e.externalAdapters)}return null}function dM(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function fM(e){return{code:"external-source-readonly",message:e}}function bI(e){return{code:"unsupported-expression",message:e}}function hm(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 EI(e,t){if(!t||t.length===0)return!0;let n=hm(e.node);return n?t.includes(n):!1}function SI(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:ia(e.diagnostics??[])}:{match:e,diagnostics:[]}}function II(e,t){let n=uM(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:ia([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function pM(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 mM(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 PI(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 NI(e){return PI(e)===null}async function gM(e,t,n){let r=new Set,o=oa.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=oa.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"]:[oa.posix.join(i,"locales"),oa.posix.join(i,"messages")];for(let a of s){let c=oa.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function hM(e){let t=PI(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await gM(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function yM(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 $l(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:[fM("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var xM=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>pM(e)},{helperNames:["apiField"],resolve:e=>yM(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>hM({currentFile:e,expressionPath:t,exists:n})}];function ym(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function vI(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 pm(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=kM(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 bM=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function xm(e,t){let n=[...bM,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function AI(e,t){let n=e.callee;return ke.isIdentifier(n)&&xm(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 bm(e){let t=await gm(e);if(t)return t;let n=await TI({...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 hr({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 Un({...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 vM(e)}async function TI(e){let t=await qn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=Vl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:ym(t.provenance)}async function qn(e){let t=Vl(e.expressionPath),n=IM(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 hr({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 Un({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 hr({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 Un({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 qn({...e,expressionPath:r,allowComposed:!0}),a=await qn({...e,expressionPath:o,allowComposed:!1}),c=await qn({...e,expressionPath:i,allowComposed:!1});return um(s,a,c)}if(t.isCallExpression())return EM({...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 qn({...e,expressionPath:r,allowComposed:!0}),s=await qn({...e,expressionPath:o,allowComposed:!0});return um(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 qn({...e,expressionPath:r,allowComposed:!0}),s=await qn({...e,expressionPath:o,allowComposed:!0});return um(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:qn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function Vl(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 EM(e){let t=hm(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:qn({...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:qn({...e,expressionPath:o,allowComposed:!1})}}return null}function um(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!SM(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function SM(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 IM(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function vM(e){if(!e.expressionPath.isCallExpression())return null;let t=hm(e.expressionPath.node);if(!t)return null;let n=xm(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 wI({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?ym(i):null}async function wI(e){let t=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});if(t)return t;let n=await hr({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 Un({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 bm({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 _M(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=xm(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 wI({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?ym(a):null}function kM(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=Fi(t,e.path);return{sourceId:o,displayPath:o}}async function CM(e){let t=e.segment.source;return t?Un({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 Un(e){let t=e.sourceInfo,n=cm(e.expressionPath,t.base);if(n){let l=await qD({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=dI(n.callPath,[...n.basePath,...t.path]);return Vs(f)?yI(e.currentFile,f.sourceId,f.displayPath):null}let u=mI(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 en(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 vo(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let p=await tM({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 en(p.value,g)===void 0?null:{kind:"value",file:p.file,root:p.root,path:g,sourceKind:"imported-binding",collectionIndexMap:p.collectionIndexMap}}let o=oE(r);if(o){let l=o.expressionPath,u=await hr({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 Un({...e,expressionPath:l,sourceInfo:{...u,expression:Fi(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 OI({...e,expressionPath:Vl(l),memberSuffix:t.path});if(p?.kind==="value")return p}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await TI({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 nM({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 _M({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=rl(r,t.path,oM(e.fileCache));if(Vs(s))return yI(e.currentFile,s.sourceId,s.displayPath);let a=await Ul({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:en(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 OI(e){let t=fI(e.expressionPath.node);if(!t||!pI(t.segments))return null;let n=await Un({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 eM({...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 Ul({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>en(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:Li(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function LI(e){let t=RM(e.propertyName);if(t.owner==="blocked")return fo(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return fo(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 fo("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 NM(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 fo("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}:fo("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?fo("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):PM(e,s.attribute)}async function PM(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await Di({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}}:fo("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 Di({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"?fo("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 NM(e,t){let n=t.source?.expression;if(!n)return;let r=await Di({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:AM(r,e.propertyName)}}function AM(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 fo(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function FI(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(Ho(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=>LM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>TM({...r,graph:e},n)}function TM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=OM(n,r,o,t),a=s?.tag??(Ho(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=DM(s),u=MM(n,r,o,i,s),d=wM(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:FM(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:BM(d),alternativeStrategies:jM(d)}}function wM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Em(e,n)?"instance":!Ho(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function OM(e,t,n,r){if(Ho(t.tag))return t;let o=Em(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function LM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function FM(e,t){return Ho(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function DM(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 MM(e,t,n,r,o){let i=new Set,s=Em(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&&Ho(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Em(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Ho(r.tag))return r;n=r.parentKey}return null}function Ho(e){return/^[A-Z]/.test(e)}function BM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function jM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function BI(e){let t=e.isRepeat??(e.graph?WM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=HM(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>$M({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:GM(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 $M(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=UM(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:fl({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=VM(t,n,l,e.isRepeat),d=c?XM(c,e.element,t.name):void 0,p=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=p.length>0?KM(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",f=zM(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 UM(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 VM(e,t,n,r){return n?DI(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:DI(JM(e))}function JM(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 DI(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function KM(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 XM(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:MI({...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:MI(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function zM(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 HM(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function WM(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 MI(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 GM(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 YM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var ZM=160;function jI(e,t,n,r={}){let o=ii(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 $I(e,t,n,r,o,i,s,a,c,l,u){let d=ii(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=XI(p.textSegments,s),y=zI(e,t,p,m,f),x=f?tB(f):void 0,E=nB(i,f),b=p.textSegments.map(C=>({index:C.index,value:C.value,editable:HI(C,m,s?.get(C.index)??null),source:o.get(C.index)??null})),S=JI(p,t),I=p.childKeys.map(C=>{let A=t.elements.get(C);return A?{key:C,tag:A.tag,label:A.tag}:null}).filter(C=>C!==null),T=[];if(p.parentKey){let C=t.elements.get(p.parentKey);if(C)for(let A of C.childKeys){if(A===e)continue;let P=t.elements.get(A);P&&T.push({key:A,tag:P.tag,label:P.tag})}}return{composition:d,key:e,tag:p.tag,componentName:p.componentName,sourceFile:p.sourceFile,sourceLocator:VI(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:T}}function UI(e,t,n,r,o,i,s,a){let c=ii(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=XI(l.textSegments,i),g=qM(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:VI(l),label:l.tag,capabilities:zI(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:HI(m,d,i?.get(m.index)??null),source:f?{kind:f.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:JI(l,t)}}function qM(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 VI(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:QM(e.sourceRange),structuralPath:e.identity.structuralPath,...eB(e.textSegments)}}function JI(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 QM(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function eB(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,ZM)}:{}}function KI(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 XI(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function zI(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&&WI(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 HI(e,t,n){return!e.editable||!t.canUpdateText?!1:n?WI(n.editMode):!0}function WI(e){return e==="direct"||e==="proxy"||e==="upstream"}function tB(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 nB(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}:YM(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 Sm=["set-class-name-source","apply-style-draft"];function GI(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Sm,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:Sm,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Sm}}import YI from"node:path";function vm(){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 qI(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=sB(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 Jl(e){let t=()=>rB(e);return e.mutex?e.mutex.runExclusive(t):t()}async function rB(e){let t=await qI(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=oB(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 Im({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 Im({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 Im({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 oB(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 Im(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:iB(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 iB(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 sB(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)||YI.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=YI.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 aB=50,cB=8*1024*1024;function nv(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??aB),s=Math.max(0,t.maxUndoBytes??cB);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(C){let A=[...C.steps].sort((X,Z)=>X.order-Z.order),P=A.filter(X=>X.type!=="invoke-external-adapter");if(P.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let F=new Set(P.map(X=>X.file)),B=await E(F),U=new Map(B.map(X=>[X.file,X.exists===!1?"":X.content])),G;for(let X of P){let Z=tv(X,U.get(X.file)??"");if(!Z.ok)return{ok:!1,errorCode:Z.errorCode,reason:Z.reason};U.set(X.file,Z.source),G=Z.selectionRef??G}return{ok:!0,filePlan:{operationId:C.operationId,kind:"source-edit",target:C.target,documentVersion:C.documentVersion,conflictPolicy:"compare-and-swap",edits:[...U].map(([X,Z])=>({operation:"upsert",file:X,content:Z,baseContentHash:B.find(H=>H.file===X)?.sha256??null}))},...G?{selectionRef:G}:{}}}async function c(C){let A=[...C.steps].sort((H,he)=>H.order-he.order),P=A.filter(H=>H.type!=="invoke-external-adapter"),F=A.filter(H=>H.type==="invoke-external-adapter"),B=new Set(P.map(H=>H.file));if(P.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(P.length===0)return y(C,F);let U=await E(B),G=new Map;for(let H of U)G.set(H.file,H.exists===!1?"":H.content);let X;for(let H of P){let he=G.get(H.file)??"",ue=tv(H,he);if(!ue.ok)return{ok:!1,operationId:C.operationId,errorCode:ue.errorCode,reason:ue.reason,rolledBack:!1};G.set(H.file,ue.source),ue.selectionRef&&(X=ue.selectionRef)}let Z=await S([...G].map(([H,he])=>({file:H,content:he,exists:!0,version:0,sha256:Ue(he)})),U);return Z.ok===!1?{ok:!1,operationId:C.operationId,errorCode:Z.rolledBack?"writeback-failed":"rollback-failed",reason:Z.reason,rolledBack:Z.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:U,postSnapshots:Z.snapshots,plan:C}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...Z.snapshots.map(H=>H.version)),affectedFiles:[...B],...X?{selectionRef:X}:{}})}async function l(C){let A=new Set(C.edits.map(Z=>Z.file)),P=await E(A),F=x(C,P);if(F)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:F.reason,affectedFiles:[F.file],rolledBack:!1};let B=new Map(P.map(Z=>[Z.file,Z])),U=C.edits.find(Z=>Z.operation==="create-only"&&B.get(Z.file)?.exists!==!1);if(U)return{ok:!1,operationId:C.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${U.file}`,affectedFiles:[U.file],rolledBack:!1};let G=C.edits.map(Z=>Z.operation==="delete"?{file:Z.file,content:"",exists:!1,version:0}:{file:Z.file,content:Z.content,exists:!0,version:0,sha256:Ue(Z.content)}),X=await S(G,P,new Set(C.edits.filter(Z=>Z.operation==="create-only").map(Z=>Z.file)));return X.ok===!1?{ok:!1,operationId:C.operationId,errorCode:X.rolledBack?"writeback-failed":"rollback-failed",reason:X.reason,rolledBack:X.rolledBack}:(n.push({operationId:C.operationId,preSnapshots:P,postSnapshots:X.snapshots,plan:{operationId:C.operationId,kind:C.kind,target:C.target,documentVersion:C.documentVersion,steps:[],preSnapshots:P}}),p(),r.length=0,{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:Math.max(...X.snapshots.map(Z=>Z.version)),affectedFiles:[...A]})}async function u(){let C=n.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await S(C.preSnapshots,C.postSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(C),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(P=>P.version)),affectedFiles:C.preSnapshots.map(P=>P.file)})}async function d(){let C=r.at(-1);if(!C)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await S(C.postSnapshots,C.preSnapshots);return A.ok===!1?{ok:!1,operationId:C.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(C),p(),{ok:!0,operationId:C.operationId,kind:C.plan.kind,target:C.plan.target,resultVersion:Math.max(...A.snapshots.map(P=>P.version)),affectedFiles:C.postSnapshots.map(P=>P.file)})}function p(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((C,A)=>C+m(A),0)}function m(C){return f(C.preSnapshots)+f(C.postSnapshots)}function f(C){return C.reduce((A,P)=>A+P.file.length+P.content.length,0)}async function y(C,A){let P=[];for(let F of A){let B=F.capability??"write-text",U=o.find(X=>X.sourceType===F.sourceType&&(F.adapterId===void 0||X.adapterId===F.adapterId)&&(X.capabilities===void 0||X.capabilities.includes(B)));if(!U)return{ok:!1,operationId:C.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${F.sourceType}`,rolledBack:!1};let G=await U.execute(F);if(!G.ok)return{ok:!1,operationId:C.operationId,errorCode:"writeback-failed",reason:G.reason??`External adapter failed for ${F.sourceType}`,rolledBack:!1};P.push(F.file)}return{ok:!0,operationId:C.operationId,kind:C.kind,target:C.target,resultVersion:0,affectedFiles:P}}function x(C,A){if(C.conflictPolicy!=="compare-and-swap")return null;let P=new Map(A.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 B=P.get(F.file),U=F.baseContentHash;if(U===null){if(B?.exists!==!1)return{file:F.file,reason:`Source file ${F.file} was created or changed before save.`};continue}if(!U)return{file:F.file,reason:`Source file ${F.file} is missing baseContentHash. Reopen the file before saving.`};if(B?.exists===!1||B?.sha256!==U)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 A=[];for(let P of C)A.push(await b(P));return A}async function b(C){if(!await e.exists(C))return{file:C,content:"",version:0,exists:!1};let P=Math.max(1,e.getVersion(C)),F=await e.readFile(C);return{file:C,content:F,version:P,exists:!0,sha256:Ue(F)}}async function S(C,A,P=new Set){let F=[];try{for(let B of C){if(P.has(B.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(B.file,B.content)}else await I(B);let U=e.bumpVersion(B.file);F.push(B.file),B.version=U}}catch(B){let U=await T(A.filter(X=>F.includes(X.file)));if(U.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${U.failedFiles.join(", ")}: ${ev(B)}`,rolledBack:!1,instanceConflict:QI(B)};let G=QI(B);return{ok:!1,reason:`${G?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${ev(B)}`,rolledBack:!0,instanceConflict:G}}return{ok:!0,snapshots:C.map(lB)}}async function I(C){if(C.exists===!1){await e.deleteFile(C.file);return}await e.writeFile(C.file,C.content)}async function T(C){let A=[];for(let P of C)try{await I(P),e.bumpVersion(P.file)}catch{A.push(P.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function QI(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function lB(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ue(e.content)}:{}}}function ev(e){return e instanceof Error?e.message:String(e)}function tv(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 zt(wn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return zt(oi({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return zt(To({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return zt(Tn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return zt(Ha({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return zt(cs({source:t,locator:e.locator,next:e.value}));case"update-array-item":return zt(cs({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return zt(Qa({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return zt(Wa({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return zt(ec({source:t,locator:e.locator,index:e.index}));case"move-array-item":return zt(tc({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return zt(Oo({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return zt(Ga({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 uB(e,t);case"set-property-changes":return zt(Ya({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return zt(Za({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return zt(qa({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return zt(rc({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function uB(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!gy(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!==Ue(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:my({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function zt(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 Kl,SiteEditCompositionContextSchema as dB,SiteEditCompositionSelectorSchema as fB}from"@vcp-dev/contracts";var tn=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function rv(e,t){throw new tn("INVALID_COMPOSITION",e,{value:t})}function Xl(e){let t=dB.safeParse(e);return t.success?t.data:rv("Invalid SiteEditCompositionContext.",e)}function ov(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=Xl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new tn("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Kl(u);if(n.has(d))throw new tn("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let p=r.get(l.entryFile);if(p)throw new tn("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 tn("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=Xl(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new tn("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=Kl(u);if(!n.has(d))throw new tn("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new tn("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=fB.safeParse(l);if(!u.success)return rv("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 tn("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new tn("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=Xl(l),d=Kl(u),p=n.get(d);if(!p)throw new tn("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return p}function a(l){let u=Xl(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new tn("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=Kl(u),p=n.get(d);if(p){if(p.entryFile===l.entryFile)return p;throw new tn("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 tn("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 _m(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 iv(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 pB,stripSiteEditRepeatInstanceKeys as sv}from"@vcp-dev/contracts";function av(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=sv(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 mB(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 zl(e){return e?.map(t=>({...t}))}function km(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=zl(e.collectionPathMap?.[t])??zl(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:zl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>zl(o)??[])}}function cv(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)=>pB(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 gB(E))b.length<=m.length||hB(b,m)&&f.add(b[m.length])}}return f.size>0?f.size:mB(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 lv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function uv(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((sv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function gB(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 hB(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 dv(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 fv(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 pv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function yB(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var sa=class extends Error{constructor(t){let n=t.map(pv);super(yB(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function mv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof sa?{routeId:e,message:n,diagnostics:t.diagnostics.map(pv)}:{routeId:e,message:n}}function Cm(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function Rm(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function aa(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function gv(e,t){for(let n of t){if(n.exists===!1){e.delete(n.file);continue}e.set(n.file,n.content)}}function Hl(e,t,n,r){if(!e.has(t)&&e.size>=r){let o=e.keys().next().value;o&&e.delete(o)}e.set(t,n)}function hv(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 kB=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,CB=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],yv=32,Gl=256;function RB(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var xv={maxEntries:50,maxBytes:8*1024*1024};function PB(){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 sc(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 bv(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 NB(){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>xv.maxEntries||AB(e)>xv.maxBytes;)e.shift()}}function AB(e){return e.reduce((t,n)=>t+TB(n),0)}function TB(e){return Ev(e.preSnapshots)+Ev(e.postSnapshots)+wB(e.provenance)}function wB(e){return e?new TextEncoder().encode(JSON.stringify(e)).byteLength:0}function Ev(e){return e.reduce((t,n)=>t+n.file.length+n.content.length,0)}function Sv(e,t){return{key:bB(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 Yl=class extends Error{constructor(t){super(t.reason),this.result=t}},Wo=class extends Error{constructor(t){super(Cm(t)),this.failedRoutes=t}};function Iv(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=fn(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(fn(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function OB(e,t,n){if(!n)return;let r=fn(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 LB=/\.(?:[cm]?[jt]sx?)$/i,FB=/\.json$/i,DB=/\.(?:css|scss|sass)$/i,MB=/\.mdx$/i,BB=/\.ya?ml$/i;function jB(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 $B(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function UB(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=Pv(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(VB(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 VB(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function Pv(e){return Array.isArray(e)?{files:e}:e}function JB(e){if(!SB(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!==vB||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=EB(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(LB.test(e.path)){let t=rr({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(FB.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${on(t)}`,details:{path:e.path}}}if(DB.test(e.path)){let t=vv({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(MB.test(e.path)){let t=vv({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(BB.test(e.path))try{_B(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${on(t)}`,details:{path:e.path}}}return{ok:!0}}function vv({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 Mi(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 Mi(t,`Unexpected closing token "${p}" in ${t}.`);l=!1;continue}l=p===`
14
- `||p==="\r"}if(s)return Mi(t,`Unterminated block comment in ${t}.`);if(o)return Mi(t,`Unterminated string literal in ${t}.`);if(c)return Mi(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?Mi(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function Mi(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Zl(e){let t="idle",n=e.fileSystem??PB(),r=hy(),o=ov({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?ix(e.historyStore):NB()),u=nv(n,{externalAdapters:e.externalAdapters}),d=new Map,p=Cy(Gl),g=new Set,m=0,f=e.historyStore?.recoveryRequired??!1,y=vm(),x=I();function E(h){return(Wl.isAbsolute(h)?Wl.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function b(h,R){let _=Wl.posix.dirname(h),w=R.replace(/\.(?:tsx?|jsx?)$/i,""),V=Wl.posix.relative(_,w);return V.startsWith(".")?V:`./${V}`}function S(h,R){return h.startLine===R.startLine&&h.startColumn===R.startColumn&&h.endLine===R.endLine&&h.endColumn===R.endColumn}async function I(){let h=e.historyStore;if(h)try{let R=await h.readTransactionJournal();if(!R)return;let _=await h.readIndex(),w=await Promise.all(R.files.map(async J=>await n.exists(J.path)?Ue(await n.readFile(J.path)):null));if(hv({journal:R,index:_,observedFileDigests:w})!=="ambiguous"){await h.clearTransactionJournal(R.transactionId);let J=await h.readStatus();J.recoveryRequired||(await h.cleanupTmp(),J=await h.readStatus()),f=J.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${R.transactionId} at phase ${R.phase}`),f=!0}catch(R){f=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${on(R)}`).catch(()=>{})}}function T(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let R=Sv(h.context,h.entryFile);i.set(h.key,R),C(R,R.dependencyFiles)}function C(h,R){let _=new Set(R);A(h),h.dependencyFiles=_;for(let w of h.dependencyFiles){let V=s.get(w);V||(V=new Set,s.set(w,V)),V.add(h.key)}}function A(h){for(let R of h.dependencyFiles){let _=s.get(R);_&&(_.delete(h.key),_.size===0&&s.delete(R))}h.dependencyFiles.clear()}function P(h){let R=new Set;for(let _ of h)for(let w of s.get(_)??[])R.add(w);return R}function F(h){for(let R of h)if(!s.has(R))return!1;return!0}async function B(h,R,_,w,V,J){let Q=new Map,ne=FI(h),le=_I(V.values()),oe=vS(V.values()),re=typeof J.exists=="function"?me=>J.exists(me):async()=>!1;for(let[me,ve]of h.elements){let $e=R.nodes.get(me);if(!$e)continue;let xe=_.get(ve.sourceFile)??w.get(ve.sourceFile),ze=new Map,Me=new Map,Y=new Map,ce=[];for(let dt of ve.textSegments){if(!xe){ze.set(dt.index,null);continue}let Yi=await kI({file:ve.sourceFile,source:xe,segment:dt,readFile:hn=>J.readFile(hn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:hn,adapterId:Io,capabilities:Uu})=>({sourceType:hn,adapterId:Io,capabilities:Uu})),functionCallContracts:e.functionCallContracts,fileCache:le}),nn=await mm({file:ve.sourceFile,source:xe,target:{kind:"text-segment",segment:dt},readFile:hn=>J.readFile(hn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:hn,adapterId:Io,capabilities:Uu})=>({sourceType:hn,adapterId:Io,capabilities:Uu})),functionCallContracts:e.functionCallContracts,fileCache:le}),Pn=jB(Yi);ze.set(dt.index,Pn),Me.set(dt.index,Yi),Y.set(dt.index,nn),ce.push({editable:dt.editable,source:Pn})}let Ne=new Map,Ke=new Map;if(xe)for(let dt of ve.attributes??[]){let Yi=await Di({file:ve.sourceFile,source:xe,sourceRange:dt.sourceRange,expression:dt.source?.expression??dt.value,sourceInfo:dt.source,readFile:Pn=>J.readFile(Pn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Pn,adapterId:hn,capabilities:Io})=>({sourceType:Pn,adapterId:hn,capabilities:Io})),functionCallContracts:e.functionCallContracts,fileCache:le}),nn=await LI({element:ve,file:ve.sourceFile,source:xe,propertyName:dt.name,readFile:Pn=>J.readFile(Pn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Pn,adapterId:hn,capabilities:Io})=>({sourceType:Pn,adapterId:hn,capabilities:Io})),functionCallContracts:e.functionCallContracts,fileCache:le});Ke.set(dt.name,nn),Ne.set(dt.name,Yi)}let We=KI($B($e.writeTarget),ce),Et=ne({key:me,element:ve,provenances:Y}),jr=GI(ve),tr=xe?await Al({element:ve,graph:h,file:ve.sourceFile,source:xe,readFile:dt=>J.readFile(dt),exists:re,fileCache:oe}):void 0,So=h.regions.find(dt=>dt.kind==="conditional-region"&&dt.childKeys.includes(me)),Jt,Rn=So?.sourceCandidates?.[0];if(xe&&So&&Rn?.kind==="conditional-branch"){let dt=await mm({file:ve.sourceFile,source:xe,target:{kind:"conditional-branch",candidate:Rn},readFile:nn=>J.readFile(nn),exists:re,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:nn,adapterId:Pn,capabilities:hn})=>({sourceType:nn,adapterId:Pn,capabilities:hn})),functionCallContracts:e.functionCallContracts,fileCache:le});Jt={currentBranch:So.childKeys.indexOf(me)<=0?"then":"else",availableBranches:So.childKeys.length>1?["then","else"]:["then"],conditionExpression:Rn.conditionExpression,provenance:{finalSource:dt.finalSource?{kind:dt.finalSource.kind,file:dt.finalSource.file,displayPath:dt.finalSource.displayPath}:null,chain:dt.chain.map(nn=>({kind:nn.kind,file:nn.file,displayName:nn.displayName,canEditHere:nn.canEditHere})),confidence:dt.confidence,editMode:dt.editMode,diagnostics:dt.diagnostics.map(nn=>({code:nn.code,message:nn.message}))}}}Q.set(me,{textSources:ze,textTargets:Me,elementPropertyTargets:Ne,propertyProvenances:Ke,isRepeat:ij(me,h),provenances:Y,writeTarget:We,componentSemantic:Et,styleSource:jr,conditional:Jt,dynamicData:tr})}return Q}function U(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function G(h,R){let _=o.initialVersions.get(h.key)??0;for(let w of R.values())_=Math.max(_,w);return Math.max(_,h.graph?.version??0)}function X(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function Z(h){try{return X(o.resolveSelector(h.composition).key)}catch{return 0}}async function H(h,R,_=n,w={}){let V=await ci(h,R,J=>_.readFile(J),J=>_.exists(J),{additionalEntries:await ue(h,_),...w});if(V.diagnostics.length>0)throw new sa(V.diagnostics);return w.validationOnly||p.remember(V.parsedModules.values()),V}async function he(h,R,_={}){let w=i.get(h);if(!w)return null;let V=_.sourceCache??Rm(d,[]),J=_.fileSystem??_m(n),{graph:Q,allSources:ne,parsedModules:le,entryModule:oe}=await H(w.entryFile,R,J,{version:w.graph?.version??1}),re=new Map;for(let Jt of ne.keys())re.set(Jt,U(Jt));let me=Math.max(G(w,re),_.minimumVersion??0);_.changed&&me<=(w.graph?.version??0)&&(me=(w.graph?.version??0)+1),Q.version=me;for(let[Jt,Rn]of ne)Hl(V,Jt,Rn,Gl);let ve=await je(w.composition,w.entryFile,ne,V,J);Q.routeId=w.routeId,Q.composition=w.composition;let $e=Xc(Q),xe=oc($e,Q),ze=await B(Q,$e,ne,V,le,J);L(xe,ze);let Me=O(Q,xe,ze),Y=ht(ze),ce=cv(jI(Q,$e,xe,{canUpdateTextByKey:Me,dynamicDataSummaryByKey:Y}),Q,ze),Ne=Xn({route:w.routeId,composition:w.composition,entryFile:w.entryFile,version:me,source:R,ast:oe?.ast}),Ke=ab(Ne),We=null,Et=[];if(Ne.ok){XB(ce,Q,Ne.projection,le);let Jt=Kc({composition:w.composition,entryFile:w.entryFile,graph:Q,parsedModules:le,projection:Ne.projection});if(Jt.diagnostics.length===0){let Rn=Ts({composition:w.composition,entryFile:w.entryFile,graph:Q,parsedModules:le,projection:Ne.projection,documentVersion:me,roots:Jt.roots});Rn.diagnostics.length===0&&(We=Rn,Et=Rn.descriptors)}}let jr={...ce,composition:w.composition,pageBlocks:Et,...ve?{styleContext:ve}:{},pageComposition:Ke},tr=new Set([w.entryFile,...ne.keys()]);if(ve){tr.add(ve.entryCss.path);for(let Jt of ve.stylesheets)tr.add(Jt.path)}let So={...w,dependencyFiles:tr,graph:Q,topology:$e,capabilities:xe,document:jr,pageBlockIndex:We,pageComposition:Ke,pageCompositionProjection:Ne.projection,pagePlacementByKey:Ne.ok?Ne.projection.placementByKey:null,pagePlacementUnitByKey:Ne.ok?Ne.projection.placementUnitByKey:null,pageUnitByKey:Ne.ok?Ne.projection.unitByKey:null,pagePlacementsByUnitKey:Ne.ok?Ne.projection.placementsByUnitKey:null,documentIndex:av(jr),detailProjections:ze,fileVersions:re,styleContext:ve};if(_.publish===!1)return So;for(let Jt of tr){let Rn=ne.get(Jt)??V.get(Jt);Rn!==void 0&&(Hl(d,Jt,Rn,Gl),g.delete(Jt))}return C(w,tr),Object.assign(w,So),w}async function ue(h,R=n){let _=[];for(let w of QB(h))typeof R.exists=="function"&&await R.exists(w)&&_.push({file:w,source:await R.readFile(w)});return _}async function je(h,R,_,w,V){let J=[];for(let[re,me]of _){if(Pm(re)){J.push(re);continue}for(let ve of tj(me)){let $e=Rv(re,ve);$e&&J.push($e)}}if(!J.length){for(let re of ej(R))if(await V.exists(re)){J.push(re);break}}let Q=new Map,ne=oj(J).slice(0,yv);for(;ne.length>0&&Q.size<yv;){let re=ne.shift();if(Q.has(re)||!Pm(re))continue;let me=await He(re,w,V);if(me!==null){Q.set(re,{path:re,content:me});for(let ve of nj(me)){let $e=Rv(re,ve);$e&&!Q.has($e)&&!ne.includes($e)&&ne.push($e)}}}let le=[...Q.values()].map(re=>({...re,hash:Ue(re.content)})),oe=le[0];return oe?{composition:h,revision:Ue(JSON.stringify(le.map(({path:re,hash:me})=>({path:re,hash:me})))),entryCss:oe,stylesheets:le.slice(1)}:null}async function He(h,R,_){let w=R.get(h);if(w!==void 0)return w;if(!await _.exists(h))return null;let V=await _.readFile(h);return Hl(R,h,V,Gl),V}function ht(h){let R=new Map;for(let[_,w]of h)w.dynamicData?.bindings.length&&R.set(_,FS(w.dynamicData.bindings));return R}function O(h,R,_){let w=new Map;for(let[V,J]of h.elements){if(!R.get(V)?.canUpdateText){w.set(V,!1);continue}let ne=_.get(V),le=J.textSegments.some(oe=>{if(!oe.editable)return!1;let re=ne?.provenances.get(oe.index)??null;return!re||z(re)});w.set(V,le)}return w}function L(h,R){for(let[_,w]of R){let V=h.get(_);V?.canUpdateText&&w.dynamicData?.bindings.some(J=>J.readonly&&(J.targetKind==="text"||J.targetKind==="richtext"))&&h.set(_,{...V,canUpdateText:!1})}}function z(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function j(h,R={}){let _=[...new Set(h)],w=R.affectedCompositionKeys!==void 0,V=w?new Set(R.affectedCompositionKeys):P(_);if(!w&&(V.size===0||!F(_)))for(let oe of i.values())Ie(oe,_)&&V.add(oe.key);let J=!w&&V.size===0&&_.some(Cv),Q=R.publish===!1?Rm(d,_):void 0,ne={rebuiltRoutes:[],failedRoutes:[],...R.publish===!1?{candidateRouteStates:[],candidateSourceCache:Q}:{}},le=_m(n);for(let oe of i.values())if(!(R.excludedCompositionKeys?.has(oe.key)||!(V.has(oe.key)||J)))try{let me=!!oe.graph,ve=await le.readFile(oe.entryFile),$e=await he(oe.key,ve,{...R,fileSystem:le,...Q?{sourceCache:Q}:{}});$e?.graph&&(ne.rebuiltRoutes.push({documentChanged:me,composition:oe.composition,routeId:oe.routeId,version:$e.graph.version}),ne.candidateRouteStates?.push({composition:oe.composition,key:oe.key,routeId:oe.routeId,state:$e}))}catch(me){ne.failedRoutes.push({...mv(oe.routeId,me),composition:oe.composition})}return ne}function K(h){let R=[...new Set(h)],_=P(R);if(_.size>0&&F(R))return[..._];for(let w of i.values())Ie(w,R)&&_.add(w.key);return[..._]}function ee(h){let R=new Set(K(h));return o.entries.filter(_=>R.has(_.key)).map(_=>_.context)}function pe(h){return[...new Set(K(h))].sort((_,w)=>_<w?-1:_>w?1:0).map(_=>o.getByKey(_)?.context).filter(_=>_!==void 0)}function v(h,R){let _=new Set(K(R)),w=h.provenance?.affectedCompositions??[];if(w.length===0)return _;if([...new Set(w.map(J=>o.resolveContext(J).key))].some(J=>!_.has(J)))throw new Error("History provenance does not match the affected composition index.");return _}function $(h,R){let _=h.composition??h.provenance?.initiatingComposition;if(_){let J=o.resolveContext(_);return{context:J.context,key:J.key}}let w=[...new Set(K(R))];if(w.length!==1)throw new Error(`Legacy history entry cannot be attributed to a unique composition (affected composition count: ${w.length}).`);let V=o.getByKey(w[0]);if(!V)throw new Error("Legacy history entry references an unknown affected composition.");return{context:V.context,key:V.key}}function te(h,R){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:_,version:w}of R.rebuiltRoutes)r.emit({type:"document-changed",composition:_,version:w});for(let{composition:_,message:w}of R.failedRoutes)r.emit({type:"graph-error",composition:_,message:w})}function Ie(h,R){return R.some(_=>h.dependencyFiles.has(_)||h.entryFile===_||h.graph?.fileIndex.has(_))}function Re(h){for(let R of h)a.add(R);c||T()||(c=(async()=>{t="building";let R=!1;try{for(;a.size>0;){if(T())return;await Pe(),await y.runExclusive(async()=>{if(m>0||T())return;let _=[...a];a.clear();let w=await nt(_);if(w.length===0)return;let V=K(w);for(let ne of V){let le=i.get(ne)?.composition;le&&r.emit({type:"graph-invalidated",composition:le})}let{rebuiltRoutes:J,failedRoutes:Q}=await j(w,{changed:!0});for(let{documentChanged:ne,composition:le,version:oe}of J)r.emit({type:"graph-ready",composition:le,version:oe}),ne&&r.emit({type:"document-changed",composition:le,version:oe});for(let{composition:ne,message:le}of Q)R=!0,r.emit({type:"graph-error",composition:ne,message:le})})}}finally{c=null,t!=="disposed"&&(t=!R&&[...i.values()].some(_=>_.graph)?"ready":"idle"),a.size>0&&Re([])}})())}async function Pe(){for(;m>0;)await new Promise(h=>setTimeout(h,0))}async function nt(h){let R=[];for(let _ of new Set(h)){let w=d.get(_);if(w===void 0){if(g.has(_)&&!await n.exists(_))continue;g.delete(_),R.push(_);continue}try{await n.readFile(_)!==w&&(g.delete(_),R.push(_))}catch(V){if(!KB(V))try{if(await n.exists(_))continue}catch{continue}g.add(_),R.push(_)}}return R}function Ut(h){gv(d,h);for(let R of h)R.exists===!1?g.add(R.file):g.delete(R.file)}function Vt(h){g.clear();for(let R of h)g.add(R)}async function pt(h){let R=await nt(h);if(R.length===0)return;let _=K(R);for(let J of _){let Q=i.get(J)?.composition;Q&&r.emit({type:"graph-invalidated",composition:Q})}let{rebuiltRoutes:w,failedRoutes:V}=await j(R,{changed:!0});for(let{documentChanged:J,composition:Q,version:ne}of w)r.emit({type:"graph-ready",composition:Q,version:ne}),J&&r.emit({type:"document-changed",composition:Q,version:ne});for(let{composition:J,message:Q}of V)r.emit({type:"graph-error",composition:J,message:Q})}async function Vn(h,R){let _=ei(h,R);if(!_?.graph)return;let w=fn(h)??h,V=_.graph.elements.get(w);V&&await pt([V.sourceFile])}async function Ir(h){let R=new Set;if(h.target.kind==="node"){let _=ei(h.target.key,h.composition),w=fn(h.target.key)??h.target.key,V=_?.graph?.elements.get(w);V&&R.add(V.sourceFile)}else if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-unit"){let _=i.get(o.resolveSelector(h.target.composition).key);_&&R.add(_.entryFile)}else if(h.target.kind==="page-block"){let _=i.get(o.resolveSelector(h.target.composition).key),w=_?.pageBlockIndex?.bindings.get(h.target.blockKey);if(w&&(R.add(w.ownerFile),R.add(w.descriptor.source.file)),_?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let V=_.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);V&&(R.add(V.ownerFile),R.add(V.descriptor.source.file))}}else if(h.target.kind==="source-file")R.add(h.target.path);else if(h.target.kind==="source-batch")for(let _ of h.target.paths)R.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 w of _){let V=ei(w,h.composition),J=fn(w)??w,Q=V?.graph?.elements.get(J);Q&&R.add(Q.sourceFile)}}await pt(R)}async function Bt(h){if(h.params.kind!=="source-edit")return Mu(h,"invalid-params","source-edit requires source-edit params");for(let R of h.params.edits){let _=JB(R);if(!_.ok)return Mu(h,_.errorCode,_.message,_.details)}m+=1;try{let R=await Qk(h.params.edits);if(!R.ok)return Mu(h,R.errorCode,R.message,R.details);await Ir(h);let _={operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:h.params.conflictPolicy,edits:h.params.edits.map(w=>w.operation==="delete"?{operation:"delete",file:w.path,baseContentHash:w.baseContentHash??null}:{operation:"upsert",file:w.path,baseContentHash:w.baseContentHash??null,content:w.content})};return await Br({request:h,filePlan:_})}catch(R){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(h),error:{code:q.INTERNAL_ERROR,message:on(R)}}}finally{m-=1}}async function Mr(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 R=await qi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(w=>w.materialization.files.map(V=>({path:V.pathTemplate,content:V.content}))),...h.params.artifact.pages.flatMap(w=>w.materialization.files.map(V=>({path:V.pathTemplate,content:V.content})))],exists:w=>n.exists(w),readFile:w=>n.readFile(w)});if(!R.ok)return se(h,q.MATERIALIZATION_REJECTED,R.message);let _=await nf({artifact:h.params.artifact,exists:w=>n.exists(w)});return _.ok?await Br({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"}):se(h,_.code==="MATERIALIZATION_CONFLICT"?q.MATERIALIZATION_CONFLICT:q.MATERIALIZATION_REJECTED,_.message,_.path?{path:_.path}:void 0)}catch(R){return se(h,q.INTERNAL_ERROR,on(R))}finally{m-=1}}async function Gi(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 R=Pv(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(R.truncated)return se(h,q.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:R.truncated.reasons});let _=R.files.filter(({path:Q})=>/\.(?:tsx?|jsx?)$/.test(Q)),w=Object.fromEntries(await Promise.all(_.map(async({path:Q})=>[Q,await n.readFile(Q)]))),V=rE({expectedUrlPath:h.params.expectedUrlPath,files:w});if(!V.ok)return se(h,V.code==="HOME_PAGE_LOCKED"?q.HOME_PAGE_LOCKED:V.code==="ROUTE_NOT_FOUND"?q.ROUTE_NOT_FOUND:q.PLAN_FAILED,V.message);let J=await Promise.all(V.edits.map(async Q=>({...Q,baseContentHash:Ue(await n.readFile(Q.file))})));return Br({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:J},output:{kind:"delete-page-source",deleted_files:V.deletedFiles,updated_files:V.updatedFiles,preserved_shared_files:V.preservedSharedFiles,warnings:V.warnings},historyPolicy:"none"})}catch(R){return se(h,q.INTERNAL_ERROR,on(R))}finally{m-=1}}async function Hk(h,R){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 _=R.document,w=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!w||w.status!=="supported")return se(h,q.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||w.documentVersion!==_.version)return se(h,q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let V=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!V)return se(h,q.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let J=h.params.kind==="insert-child"?h.params.position:null,Q=await qi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:V.files.map(oe=>({path:oe.pathTemplate,content:oe.content})),exists:oe=>n.exists(oe),readFile:oe=>n.readFile(oe)});if(!Q.ok)return se(h,q.MATERIALIZATION_REJECTED,Q.message);let ne=await bv(n,Object.keys(V.projectDependencies??{})),le=await uf({manifest:V,generatedRoot:"components/site/generated",controlledFiles:V.files.map(oe=>({pathTemplate:oe.pathTemplate})),exists:oe=>n.exists(oe),availableHostDependencies:ne,hostCapabilities:Zd(),commit:async oe=>{let re=await n.readFile(R.entryFile),me=R.document,ve=R.pageCompositionProjection;if(!me||me.pageComposition?.status!=="supported"||me.version!==h.documentVersion||!ve||ve.status!=="supported"||ve.documentVersion!==me.version)return{ok:!0,data:se(h,q.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let $e=oe.entry.path,xe=sC(oe.instanceName),ze,Me=[];if(h.params.kind==="insert-child"){if(!J||!("kind"in J)||J.kind!=="page-composition")return{ok:!0,data:se(h,q.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Ke=_s({routeId:R.routeId,entryFile:R.entryFile,currentDocumentVersion:me.version,expectedDocumentVersion:h.documentVersion,source:re,projection:ve,placementKey:J.placementKey,component:{source:$e,exportName:oe.entry.export.kind==="default"?"default":oe.entry.export.name,localName:xe}});if(!Ke.ok)return{ok:!0,data:se(h,$u(Ke.error.code),Ke.error.message,{diagnostics:Ke.error.diagnostics})};let We=Ke.plan.rewriteStep,Et;switch(We.kind){case"insert-root-expression":Et=ks({source:re,locator:We.locator,expectedSourceHash:We.sourceHash,action:{kind:"insert",jsx:We.node.jsx,placement:We.placement,replaceOriginal:We.replaceOriginal}});break;case"insert-child":Et=Tn({source:re,locator:We.parentLocator,node:We.node,placement:We.placement,...We.anchorLocator?{anchorLocator:We.anchorLocator}:{}});break;default:Et={ok:!1,source:re,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(We)}`}}}if(!Et.ok)return{ok:!0,data:se(h,q.AST_PARSE_ERROR,Et.diagnostic.message)};ze=Et.source}else{let Ke=Pf({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:me.version,expectedDocumentVersion:h.documentVersion,source:re,projection:ve,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Ke.ok)return{ok:!0,data:se(h,$u(Ke.error.code),Ke.error.message,{diagnostics:Ke.error.diagnostics})};let We=Ke.plan.rewriteStep,Et;switch(We.kind){case"replace-root-expression":Et=ks({source:re,locator:We.locator,expectedSourceHash:We.sourceHash,action:{kind:"replace",jsx:`<${xe} />`}});break;case"replace-node":Et=ni({source:re,locator:We.locator,node:{jsx:`<${xe} />`}});break;default:Et={ok:!1,source:re,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${We.kind}`}}}if(!Et.ok)return{ok:!0,data:se(h,q.AST_PARSE_ERROR,Et.diagnostic.message)};let jr=await Du({routeState:R,placementUnitKey:h.target.placementUnitKey,source:re,mutatedSource:Et.source});ze=jr.source,Me=await Promise.all(jr.files.map(async tr=>({operation:"delete",file:tr,baseContentHash:Ue(await n.readFile(tr))})))}let Y=wn({source:ze,moduleSpecifier:b(R.entryFile,$e),imports:oe.entry.export.kind==="default"?[{kind:"default",local:xe}]:[{kind:"named",imported:oe.entry.export.name,local:xe}]});if(!Y.ok)return{ok:!0,data:se(h,q.AST_PARSE_ERROR,Y.diagnostic.message)};let ce=oe.files.map(Ke=>({operation:"create-only",file:Ke.path,content:Ke.content})),Ne=[{operation:"upsert",file:R.entryFile,content:Y.source,baseContentHash:Ue(re)},...ce,...Me];m+=1;try{let Ke=await Br({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:Ne}});return!Ke.ok&&Ke.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Ke.error?.message??"Static prefab instance conflicted during commit."}}:{ok:!0,data:Ke}}finally{m-=1}}});return le.ok?le.data:se(h,le.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?q.MATERIALIZATION_CONFLICT:q.MATERIALIZATION_REJECTED,le.error.message,{materializationCode:le.error.code})}async function Wk(h,R){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 _=R.document,w=R.pageBlockIndex;if(!_||!w||w.diagnostics.length>0)return se(h,q.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||w.documentVersion!==_.version)return se(h,q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let V=xi(w,h.target,h.documentVersion,h.selectionRef);if(!V.ok)return se(h,ka(V.code),V.message);let J=V.binding;if(!(h.kind==="insert-child"?J.descriptor.capabilities.insert:J.descriptor.capabilities.replace)){let xe=J.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 le=ne.node;if(le.kind!=="component-call"||!le.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 ze=zc(w,xe);if(!ze.ok)return se(h,ka(ze.code),ze.message);oe=ze.boundary}let re=le.materialization,me=await qi({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 ve=await bv(n,Object.keys(re.projectDependencies??{})),$e=await uf({manifest:re,generatedRoot:"components/site/generated",controlledFiles:re.files.map(xe=>({pathTemplate:xe.pathTemplate})),exists:xe=>n.exists(xe),availableHostDependencies:ve,hostCapabilities:Zd(),commit:async xe=>{let ze=R.document,Me=R.pageBlockIndex;if(!ze||!Me||ze.version!==h.documentVersion||Me.documentVersion!==ze.version||!Me.bindings.has(J.blockKey))return{ok:!0,data:se(h,q.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let Y=Me.bindings.get(J.blockKey);if(!Y||Y.ownerFile!==J.ownerFile||Y.ownerSourceHash!==J.ownerSourceHash||Y.sourceHash!==J.sourceHash)return{ok:!0,data:se(h,q.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let ce=new Set([J.ownerFile,J.descriptor.source.file,...oe?[oe.ownerFile,oe.anchorLocator.file,...oe.parentLocator?[oe.parentLocator.file]:[]]:[]]),Ne=new Map;try{for(let We of ce)Ne.set(We,await n.readFile(We))}catch{return{ok:!0,data:se(h,q.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Ke=Mb({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:J,...oe?{boundary:oe}:{},operation:ne.kind,materialization:xe,files:Ne});if(!Ke.ok){let We=qk(Ke.code);return{ok:!0,data:se(h,We,Ke.message,{materializationCode:Ke.code})}}m+=1;try{let We=await Br({request:h,filePlan:Ke.plan});return!We.ok&&We.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:We.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:We}}finally{m-=1}}});return $e.ok?$e.data:se(h,$e.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?q.MATERIALIZATION_CONFLICT:q.MATERIALIZATION_REJECTED,$e.error.message,{materializationCode:$e.error.code})}async function Gk(h,R){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 _=R.document,w=R.pageCompositionProjection;if(!_||_.pageComposition?.status!=="supported"||!w||w.status!=="supported")return se(h,q.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==_.version||w.documentVersion!==_.version)return se(h,q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let V=await n.readFile(R.entryFile),J=Pf({routeId:R.routeId,composition:R.composition,entryFile:R.entryFile,currentDocumentVersion:_.version,expectedDocumentVersion:h.documentVersion,source:V,projection:w,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(!J.ok)return se(h,$u(J.error.code),J.error.message,{diagnostics:J.error.diagnostics});let Q=J.plan.rewriteStep,ne;switch(Q.kind){case"move-node":ne=Oo({source:V,locator:Q.locator,targetParentLocator:Q.targetParentLocator,placement:Q.placement,...Q.anchorLocator?{anchorLocator:Q.anchorLocator}:{}});break;case"remove-node":ne=To({source:V,locator:Q.locator});break;case"remove-root-expression":ne=ks({source:V,locator:Q.locator,expectedSourceHash:Q.sourceHash,action:{kind:"remove"}});break;default:ne={ok:!1,source:V,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${Q.kind}`}}}if(!ne.ok)return se(h,q.AST_PARSE_ERROR,ne.diagnostic.message);let le=ne.source,oe=[];if(h.kind==="remove-node"){let me=await Du({routeState:R,placementUnitKey:h.target.placementUnitKey,source:V,mutatedSource:le});le=me.source,oe=await Promise.all(me.files.map(async ve=>({operation:"delete",file:ve,baseContentHash:Ue(await n.readFile(ve))})))}let re=[{operation:"upsert",file:R.entryFile,content:le,baseContentHash:Ue(V)},...oe];m+=1;try{return await Br({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:R.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:re}})}finally{m-=1}}async function Yk(h,R){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 _=R.document,w=R.pageBlockIndex;if(!_||!w||w.diagnostics.length>0)return se(h,q.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==_.version||w.documentVersion!==_.version)return se(h,q.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${_.version}).`);let V=xi(w,h.target,h.documentVersion,h.selectionRef);if(!V.ok)return se(h,ka(V.code),V.message);let J=V.binding;if(J.documentVersion!==_.version)return se(h,q.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?J.descriptor.capabilities.move:J.descriptor.capabilities.remove)){let Me=J.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return se(h,q.UNSUPPORTED_OPERATION,Me)}if(h.kind==="remove-node"){let Me=[...i.values()].filter(Y=>Y.dependencyFiles.has(J.ownerFile));if(Me.includes(R)||Me.push(R),Me.some(Y=>!Y.pageBlockIndex||Y.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===J.blockKey)return se(h,q.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Me=zc(w,h.params.target);if(!Me.ok)return se(h,ka(Me.code),Me.message);let Y=w.bindings.get(h.params.target.anchorBlockKey);if(!Y||!J.descriptor.siblingBlockKeys.includes(Y.blockKey)||!Y.descriptor.siblingBlockKeys.includes(J.blockKey)||Y.ownerFile!==J.ownerFile||Y.root.ownerNode.kind!==J.root.ownerNode.kind||Y.root.ownerNode.key!==J.root.ownerNode.key||Y.root.parentStructuralPath!==J.root.parentStructuralPath)return se(h,q.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(ne=Me.boundary,ne.ownerFile!==J.ownerFile||ne.sourceHash!==J.ownerSourceHash||!ne.parentLocator)return se(h,q.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let le=J.ownerFile,oe=await n.readFile(le);if(Ue(oe)!==J.ownerSourceHash)return se(h,q.VERSION_STALE,"The page-block owner source changed after resolution.");let re=J.descriptor.source.file===le?oe:await n.readFile(J.descriptor.source.file);if(Ue(re)!==J.descriptor.source.contentHash)return se(h,q.VERSION_STALE,"The selected page-block source changed after resolution.");let me=Zk(J),ve=h.kind==="remove-node"?To({source:oe,locator:me}):Oo({source:oe,locator:me,targetParentLocator:Fu(ne.parentLocator),anchorLocator:Fu(ne.anchorLocator),placement:ne.placement});if(!ve.ok)return se(h,q.AST_PARSE_ERROR,ve.diagnostic.message);let $e=ve.source,xe=[];if(h.kind==="remove-node"&&J.root.ownerNode.kind==="route-member"&&J.root.callChain.length>0&&J.descriptor.placementUnitKey){let Me=await Du({routeState:R,placementUnitKey:J.descriptor.placementUnitKey,source:oe,mutatedSource:$e});$e=Me.source,xe=Me.files}let ze=[{operation:"upsert",file:le,content:$e,baseContentHash:J.ownerSourceHash},...await Promise.all(xe.map(async Me=>({operation:"delete",file:Me,baseContentHash:Ue(await n.readFile(Me))})))];m+=1;try{return await Br({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:ze}})}finally{m-=1}}function Zk(h){return Fu(h.ownerLocator)}function Fu(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 ka(h){return h==="VERSION_STALE"?q.VERSION_STALE:h==="INVALID_PARAMS"?q.INVALID_PARAMS:q.INVALID_TARGET}function qk(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 Du(h){let R={source:h.mutatedSource,files:[]},_=h.routeState.graph,w=h.routeState.pageCompositionProjection;if(!_||!w||w.status!=="supported"||!n.listFiles)return R;let J=w.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!J)return R;let Q=[..._.elements.values()].find(Y=>Y.sourceFile===h.routeState.entryFile&&Y.importedFrom&&S(Y.sourceRange,J));if(!Q?.importedFrom||!Q.exportName)return R;let ne=E(Q.importedFrom),le="components/site/generated/";if(!ne.startsWith(le))return R;let oe=ne.slice(le.length).split("/")[0];if(!oe||!/-[0-9a-f]{8}$/i.test(oe))return R;let re=`${le}${oe}`;if([..._.elements.values()].filter(Y=>Y.sourceFile===h.routeState.entryFile&&E(Y.importedFrom??"")===ne).length!==1)return R;let ve=await n.listFiles({maxFiles:5e3,maxDepth:32}),$e=Array.isArray(ve)?ve:ve.files;if(!Array.isArray(ve)&&ve.truncated)return R;let xe=$e.map(({path:Y})=>Y).filter(Y=>Y===re||Y.startsWith(`${re}/`));if(xe.length===0||!xe.includes(ne))return R;for(let{path:Y}of $e)if(!(Y===h.routeState.entryFile||Y===re||Y.startsWith(`${re}/`)))try{if((await n.readFile(Y)).includes(oe))return R}catch{return R}let ze=b(h.routeState.entryFile,ne),Me=oi({source:h.mutatedSource,moduleSpecifier:ze,imports:Q.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:Q.exportName}]});return Me.ok?Me.source.includes(oe)?{source:Me.source,files:[]}:{source:Me.source,files:xe.sort((Y,ce)=>Y.localeCompare(ce))}:R}async function Qk(h){if(n.getFileInfo){for(let Q of h)if(await n.exists(Q.path)&&await n.getFileInfo(Q.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${Q.path}`,details:{path:Q.path}}}for(let Q of h){if(Q.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(Q.path))continue;let ne=await n.exists(Q.path)?await nd(n,Q.path):null;if(ne?.ok){let le=xB(ne.content,Q.content);if(!le.ok)return{ok:!1,errorCode:"invalid-params",message:le.message,details:{path:Q.path,code:le.code}}}}let R=eC(h);if(R.length===0)return{ok:!0};let _=UB(n,h),w=new Map,V=(Q,ne)=>{let le=w.get(Q);if(le?.source===ne)return le.result;let oe=we(Q,ne);return w.set(Q,{source:ne,result:oe}),oe},J;try{J=await iv(R,async Q=>{let ne=i.get(Q);return ne?[...(await H(ne.entryFile,await _.readFile(ne.entryFile),_,{validationOnly:!0,parseModule:V,validatedImports:p.getImports})).parsedModules.values()]:[]})}catch(Q){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${on(Q)}`,details:{compositionKeys:R}}}for(let Q of J)p.remember(Q);return{ok:!0}}function eC(h){return h.map(_=>_.path).some(Cv)?[...i.keys()]:[]}function Mu(h,R,_,w){let V=ca(R);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(h),error:{code:V,message:_,...w?{details:w}:{}}}}async function Bu(h){let R=[];for(let _ of new Set(h))R.push(await tC(_));return R}async function tC(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,U(h)),exists:!1};let _=await n.readFile(h);return{file:h,content:_,version:Math.max(1,U(h)),exists:!0,sha256:Ue(_)}}async function Gg(h,R,_,w){if(!e.historyStore)return null;let V=new Map(R.map(ne=>[ne.file,ne])),J=new Map(_.map(ne=>[ne.file,ne])),Q=[...new Set([...V.keys(),...J.keys()])].sort().map(ne=>{let le=V.get(ne),oe=J.get(ne);return{path:ne,preDigest:le?.exists===!1||!le?null:Ue(le.content),postDigest:oe?.exists===!1||!oe?null:Ue(oe.content)}});return{schemaVersion:2,transactionId:`${h}:${w.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:w,files:Q}}async function Yg(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 ju(h,R){let _=[];try{for(let w of h)await Zg(w),typeof n.bumpVersion=="function"&&n.bumpVersion(w.file),_.push(w.file)}catch(w){let V=await nC(R.filter(J=>_.includes(J.file)));return V.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${on(w)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${V.failedFiles.join(", ")}: ${on(w)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(rC)}}async function Zg(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function nC(h){let R=[];for(let _ of h)try{await Zg(_),typeof n.bumpVersion=="function"&&n.bumpVersion(_.file)}catch{R.push(_.file)}return R.length===0?{ok:!0}:{ok:!1,failedFiles:R}}function rC(h){let R=h.exists!==!1;return{file:h.file,content:R?h.content:"",version:h.version,exists:R,...R?{sha256:Ue(h.content)}:{}}}async function Br(h){return y.runExclusive(()=>oC(h))}async function oC(h){let R=h.filePlan.edits.map(Y=>Y.file),_=o.resolveSelector(h.request.composition),w=_.context,V=h.historyPolicy==="none"?void 0:{initiatingComposition:w,affectedCompositions:pe(R)},J=await Bu(R),Q=new Map(J.filter(Y=>Y.exists!==!1).map(Y=>[Y.file,Y.content])),ne=Qg(),le=new Map(d),oe=new Set(g),re=new Set([...i.values()].filter(Y=>h.filePlan.edits.some(ce=>ce.operation==="delete"&&ce.file===Y.entryFile)).map(Y=>Y.key)),me=h.filePlan.edits.map(Y=>Y.operation==="delete"?{file:Y.file,content:"",version:0,exists:!1}:{file:Y.file,content:Y.content,version:0,exists:!0,sha256:Ue(Y.content)}),ve={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(Y=>Y.operation==="delete"?{kind:"delete",path:Y.file}:{kind:Y.operation==="create-only"?"create-only":"upsert",path:Y.file,content:Y.content})},$e=null,xe=!1,ze=await Jl({overlay:Q,exists:Y=>n.exists(Y),plan:ve,buildCandidate:async({plan:Y})=>({plan:Y}),prepareHistory:async()=>{let Y=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:J,postSnapshots:me,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...V?{provenance:V}:{}}),ce=Y?.historyTransition?Y.historyTransition:e.historyStore?RB(await e.historyStore.readIndex()):null;if(e.historyStore&&!ce)throw new Error("Durable history did not provide an exact index transition.");return $e=await Gg(h.request.id,J,me,ce),$e=await Yg($e),{history:Y,historyTransition:ce}},reverify:async()=>{},writeCandidate:async()=>{let Y=await u.executeFilePlan(h.filePlan);if(!Y.ok)throw new Yl(Y);return{postSnapshots:await Bu(Y.affectedFiles),affectedFiles:Y.affectedFiles,internalResultVersion:Y.resultVersion}},validateCandidate:async({candidate:Y,receipt:ce})=>{let Ne=await j(ce.affectedFiles,{changed:!0,minimumVersion:ce.internalResultVersion,publish:!1,excludedCompositionKeys:re});if(Ne.failedRoutes.length>0)throw new Wo(Ne.failedRoutes);let Ke=th(ne,Ne.candidateRouteStates??[]),We=eh(Ke,_.key);return{...Y,rebuild:Ne,routeSnapshots:Ke,resultVersion:We,...Iv(h.selectionRef,Ke.map(Et=>Et.state.document))?{selectionRef:Iv(h.selectionRef,Ke.map(Et=>Et.state.document))}:{}}},publishCandidate:async({candidate:Y,history:ce,receipt:Ne})=>{ce?.history&&(await l.publishPrepared(ce.history),xe=!0);let Ke=Y.resultVersion??Ne.internalResultVersion;return{composition:w,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Ke,affectedFiles:Ne.affectedFiles,fileChanges:Ne.postSnapshots.map(We=>({path:We.file,operation:We.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...Y.selectionRef?{selectionRef:Y.selectionRef}:{}}},swapCandidate:({candidate:Y,receipt:ce})=>{Y.routeSnapshots&&Ca(Y.routeSnapshots),Y.rebuild?.candidateSourceCache&&aa(d,Y.rebuild.candidateSourceCache),Ut(ce.postSnapshots)},finalizeCandidate:async()=>{await Qo($e);for(let Y of re)i.delete(Y)},emitCommitted:({candidate:Y,published:ce})=>{te(ce,Y.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:Y,receipt:ce})=>{if(xe)throw new Error("history was published before transaction finalization failed");if(ce){let Ne=await ju(J,ce.postSnapshots);if(!Ne.ok)throw new Error(Ne.reason)}Ca(ne),aa(d,le),Vt(oe),Y?.history&&await l.discardPrepared?.(Y.history),await Qo($e)}});if(ze.ok)return ze.published;if(ze.stage==="precheck"||ze.stage==="build")try{await Qo($e)}catch(Y){let ce=await Pa(on(Y));return se(h.request,ce,"Unable to clear an uncommitted transaction journal.")}if(ze.recoveryRequired){let Y=await Pa(ze.reason);return se(h.request,Y===q.RECOVERY_PERSIST_FAILED?Y:q.ROLLBACK_FAILED,ze.reason)}let Me=ze.error;return Me instanceof Yl?{...se(h.request,ca(Me.result.errorCode),Me.result.reason),...Me.result.affectedFiles?{affectedFiles:Me.result.affectedFiles}:{}}:Me instanceof Wo?se(h.request,q.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${Cm(Me.failedRoutes)}`,{failedRoutes:Me.failedRoutes}):se(h.request,rh(ze.stage),on(Me))}async function qg(h){return y.runExclusive(async()=>{let R=h==="undo"?await l.prepareUndo():await l.prepareRedo();return R?iC(h,R):{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 iC(h,R){let _=R.entry,w=h==="undo"?_.preSnapshots:_.postSnapshots,V=h==="undo"?_.postSnapshots:_.preSnapshots,J=w.map(ce=>ce.file),{context:Q,key:ne}=$(_,J),le=await Bu(J),oe=new Map(le.filter(ce=>ce.exists!==!1).map(ce=>[ce.file,ce.content])),re=X(ne),me=Qg(),ve=new Map(d),$e=new Set(g),xe=null,ze=!1,Me,Y=await Jl({overlay:oe,plan:{operationId:`${h}:${_.operationId}`,intents:w.map(ce=>ce.exists===!1?{kind:"delete",path:ce.file}:{kind:"upsert",path:ce.file,content:ce.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(xe=await Gg(`${h}:${_.operationId}`,le,w,R.historyTransition),xe=await Yg(xe),R),reverify:async()=>{},writeCandidate:async()=>{let ce=await ju(w,V);if(!ce.ok)throw new Error(ce.reason);return{snapshots:ce.snapshots}},validateCandidate:async({candidate:ce})=>{Me=v(_,J);let Ne=await j(J,{changed:!0,minimumVersion:re+1,publish:!1,affectedCompositionKeys:Me});if(Ne.failedRoutes.length>0)throw new Wo(Ne.failedRoutes);let Ke=th(me,Ne.candidateRouteStates??[]),We=eh(Ke,ne);return{...ce,rebuild:Ne,routeSnapshots:Ke,resultVersion:We}},publishCandidate:async({candidate:ce,history:Ne,receipt:Ke})=>{if(!Ne)throw new Error("history cursor intent is missing");await l.publishPrepared(Ne),ze=!0;let We=ce.resultVersion??re+1;return{composition:Q,requestId:h,kind:_.kind,target:_.target,ok:!0,resultVersion:We,affectedFiles:J,fileChanges:Ke.snapshots.map(Et=>({path:Et.file,operation:Et.exists===!1?"delete":"upsert"})),..._.output?{output:_.output}:{}}},swapCandidate:({candidate:ce,receipt:Ne})=>{ce.routeSnapshots&&Ca(ce.routeSnapshots),ce.rebuild?.candidateSourceCache&&aa(d,ce.rebuild.candidateSourceCache),Ut(Ne.snapshots)},finalizeCandidate:async()=>{await Qo(xe)},emitCommitted:({candidate:ce,published:Ne})=>te(Ne,ce.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:ce,receipt:Ne})=>{if(ze)throw new Error("history cursor was published before transaction finalization failed");if(Ne){let Ke=await ju(V,Ne.snapshots);if(!Ke.ok)throw new Error(Ke.reason)}Ca(me),aa(d,ve),Vt($e),ce&&await l.discardPrepared?.(ce),await Qo(xe)}});if(Y.ok)return Y.published;if(Y.stage==="precheck"||Y.stage==="build")try{await Qo(xe)}catch(ce){let Ne=await Pa(on(ce));return{composition:Q,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:re,error:{code:Ne,message:"Unable to clear an uncommitted transaction journal."}}}if(Y.recoveryRequired){let ce=await Pa(Y.reason);return{composition:Q,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:re,affectedFiles:J,error:{code:ce===q.RECOVERY_PERSIST_FAILED?ce:q.ROLLBACK_FAILED,message:Y.reason}}}return{composition:Q,requestId:h,kind:_.kind,target:_.target,ok:!1,resultVersion:re,affectedFiles:J,error:{code:Y.error instanceof Wo?q.ROUTE_REBUILD_FAILED:rh(Y.stage),message:on(Y.error),...Y.error instanceof Wo?{details:{failedRoutes:Y.error.failedRoutes}}:{}}}}function Qg(){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 eh(h,R){return h.find(w=>w.key===R)?.state.graph?.version??o.initialVersions.get(R)??0}function th(h,R){let _=new Map(h.map(w=>[w.key,w]));for(let w of R)_.set(w.key,w);return[..._.values()]}function Ca(h){for(let R of i.values())A(R);for(let R of h){let _={...R.state,dependencyFiles:new Set(R.state.dependencyFiles),fileVersions:new Map(R.state.fileVersions)};i.set(R.key,_),C(_,_.dependencyFiles)}}async function Ra(h){let R=i.get(h);if(!R)throw new Error(`Composition not found: ${h}`);if(R.graph)return;let _=await n.readFile(R.entryFile);await he(h,_)}function ei(h,R){let _=i.get(o.resolveSelector(R).key)??null;return!_||!nh(_,h)?null:_}function nh(h,R){if(h.documentIndex?.entriesByKey.has(R)||h.graph?.elements.has(R))return!0;let _=fn(R);return _&&_!==R?h.graph?.elements.has(_)===!0:!1}function se(h,R,_,w){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(h),error:{code:R,message:_,...w?{details:w}:{}}}}function rh(h){return h==="validate"?q.ROUTE_REBUILD_FAILED:h==="publish"?q.HISTORY_COMMIT_FAILED:q.WRITE_IO_ERROR}async function Pa(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 sC(h){let _=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return _?`Prefab${_}`:"GeneratedPrefab"}function $u(h){return h==="VERSION_STALE"?q.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?q.CROSS_PAGE_MOVE_UNSUPPORTED:q.UNSUPPORTED_OPERATION}async function oh(h){if(h.target.kind==="route"){let _=i.get(o.resolveSelector(h.target.composition).key)??null;return _?(_.graph||await Ra(_.key),_):se(h,q.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 Ra(_.key),_):se(h,q.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 Ra(_.key),_):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 R=i.get(o.resolveSelector(h.composition).key)??null;return R?(R.graph||await Ra(R.key),nh(R,h.target.key)?R: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,R){let _=o.register({context:h,entryFile:R}),w=i.get(_.key);if(w?.entryFile===R)return;w&&A(w);let V=Sv(_.context,R);i.set(_.key,V),C(V,V.dependencyFiles),r.emit({type:"graph-invalidated",composition:_.context})},unregisterComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);_&&(A(_),i.delete(R.key),o.unregister(R.key),i.size===0&&(t="idle"),r.emit({type:"graph-invalidated",composition:R.context}))},getCompositionEntryFiles(){return[...i.values()].map(h=>h.entryFile)},getCompositionContext(h){return o.resolveSelector(h).context},async initializeComposition(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(_.graph)t="ready";else{t="building";try{let w=await n.readFile(_.entryFile);await he(R.key,w),t="ready",r.emit({type:"graph-ready",composition:R.context,version:i.get(R.key)?.graph?.version??0})}catch(w){throw t="idle",r.emit({type:"graph-error",composition:R.context,message:on(w)}),w}}},getDocument(h){let R=o.resolveSelector(h),_=i.get(R.key);if(!_)throw new Error(`Composition not registered: ${R.key}`);if(!_.document)throw new Error(`Composition not built: ${R.key}`);return _.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,R,_){let w=ei(h,R),V=fn(h)??h;if(w?.graph&&w.topology&&w.capabilities&&w.detailProjections){let J=w.detailProjections.get(V);if(J){let Q=w.graph.elements.get(V);if(!Q)throw new Error(`Key not found: ${h}`);let ne=OB(h,V,_),le=new Map;if(J.isRepeat&&ne?.instanceIndex!==void 0)for(let me of Q.attributes??[])le.set(me.name,tm({file:Q.sourceFile,source:d.get(Q.sourceFile)??"",element:Q,propertyName:me.name,selectionRef:ne,graph:w.graph,sources:d}));let oe=BI({element:Q,graph:w.graph,source:d.get(Q.sourceFile),documentVersion:w.graph.version,selectionRef:_,isRepeat:J.isRepeat,propertyProvenance:J.propertyProvenances,repeatTargets:le}),re=UI(V,w.graph,w.topology,w.capabilities,J.textSources,J.provenances,J.dynamicData,oe);return h===V?re:fv(re,h,w.document??null,w.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,R){let _=ei(h,R),w=fn(h)??h;if(_?.graph&&_.topology&&_.capabilities&&_.detailProjections){let V=_.detailProjections.get(w);if(V){let J=$I(w,_.graph,_.topology,_.capabilities,V.textSources,V.writeTarget,V.provenances,V.conditional,V.componentSemantic,V.styleSource,V.dynamicData);return h===w?J:dv(J,h,_.document??null,_.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,R){let _=ei(h,R),w=fn(h)??h;if(!_?.graph)throw new Error(`Key not found: ${h}`);let V=_.graph.elements.get(w);if(!V)throw new Error(`Key not found: ${h}`);let J=d.get(V.sourceFile);if(J===void 0)throw new Error(`Source not loaded: ${V.sourceFile}`);return Sd({key:w,route:{composition:_.composition,routeId:_.routeId,graph:_.graph,source:J}})},refreshSourceForKey:Vn,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 Bt(h);if(h.kind==="insert-page-resource")return Mr(h);if(h.kind==="delete-page-source")return Gi(h);let R=await oh(h);if("ok"in R)return R;await Ir(h);let _=await oh(h);if("ok"in _)return _;let w=_;if(h.target.kind==="page-unit"){let re=h;return h.kind==="insert-child"||h.kind==="replace-node"?Hk(re,w):h.kind==="move-node"||h.kind==="remove-node"?Gk(re,w):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"?Wk(re,w):h.kind==="move-node"||h.kind==="remove-node"?Yk(re,w):se(h,q.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let J=h.params,Q=h.target.kind==="node"?h.target.key:null;if(J.kind==="move-node"&&"kind"in J.target&&J.target.kind==="source-sibling"){let re=J.target,me=Q?w.document?.entries.find(ce=>ce.key===Q):null,ve=w.document?.entries.find(ce=>ce.key===re.anchorKey),$e=me?.pageCompositionActionScope,xe=$e?.kind==="source-siblings"?$e.siblingKeys:null,ze=xe?.indexOf(me?.key??"")??-1,Me=xe?.indexOf(re.anchorKey)??-1,Y=re.relation==="before"?ze-1:ze+1;if(!me||!ve||!xe||ze<0||Me!==Y||ve.pageCompositionActionScope?.kind!=="source-siblings"||ve.pageCompositionActionScope.siblingKeys.length!==xe.length||ve.pageCompositionActionScope.siblingKeys.some((ce,Ne)=>ce!==xe[Ne])||!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(!w.graph||!w.topology||!w.capabilities)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(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=ZB(w,w.graph,w.capabilities,d,i),le=await new xl(ne).plan(h);if(!le.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(h),error:{code:ca(le.errorCode),message:le.reason}};let oe=le.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:Z(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:Z(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,ca(me.errorCode),me.reason);let ve={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(Z(h),me.resultVersion),affectedFiles:me.affectedFiles,...me.selectionRef?{selectionRef:me.selectionRef}:{}};return te(ve,{rebuiltRoutes:[],failedRoutes:[]}),ve}let re=await u.prepareRewritePlan(oe);return re.ok?await Br({request:h,filePlan:re.filePlan,...re.selectionRef?{selectionRef:re.selectionRef}:{}}):se(h,ca(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:Z(h),error:{code:q.INTERNAL_ERROR,message:on(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:X(o.entries[0].key),error:{code:q.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await qg("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:X(o.entries[0].key),error:{code:q.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await qg("redo")}finally{m-=1}},notifyFileChanged(h){Re([h])},getAffectedCompositions(h){return ee(h)},subscribe(h){return r.subscribe(h)}}}function KB(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function XB(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&&la(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=fn(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&&la(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(x=>x.members.some(E=>E.sourceRange!==null&&(la(g.sourceRange,E.sourceRange)||YB(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)}zB(e,t,n,r)}function zB(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&&la(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!==(fn(p.key)??p.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let f=Be(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&&_v(y)&&(p.pageCompositionActionScope={kind:"route-unit"});continue}if(!_v(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(HB(E))continue;if(!WB(E)){y=!1;break}let b=[...t.elements.values()].find(I=>I.sourceFile===g.element.sourceFile&&I.componentName===g.element.componentName&&la(I.sourceRange,GB(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 _v(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function HB(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function WB(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function GB(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 la(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function YB(e,t){return kv(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&kv(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function kv(e,t,n,r){return e!==n?e-n:t-r}function ZB(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=fn(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:Sd({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 km(e.detailProjections?.get(p.baseKey)?.textTargets.get(d)??null,p.repeatIndex)},async getElementPropertyWriteTarget(u,d){let p=c(u);return km(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 tm({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=IB(u);return d?{baseKey:d.baseKey,repeatIndex:uv(e.document??null,u,d.baseKey,e.documentIndex)??lv(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let p=fn(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 qB={"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 ca(e){return qB[e]}function on(e){return e instanceof Error&&e.message?e.message:String(e)}function Cv(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function QB(e){let t=Go(e);if(!kB.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=>CB.map(a=>`${s}/${a}`))}function ej(e){let n=Go(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function tj(e){return Nv(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function nj(e){return Nv(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function Nv(e,t){let n=[];for(let r of e.matchAll(t)){let o=Av(r[1]??"");o&&n.push(o)}return n}function Rv(e,t){let n=Av(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Go(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Go(`${rj(e)}/${n}`):n.startsWith("/")?Go(n.slice(1)):Pm(n)?Go(n):null}function Av(e){return e.split(/[?#]/,1)[0]?.trim()??""}function Pm(e){return/\.css$/i.test(e)}function rj(e){let t=Go(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function oj(e){return Array.from(new Set(e))}function Go(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 ij(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 ql=class{constructor(t){this.options=t,this.fileSystem=new Qi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return Fa(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 Da(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ja(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return $a(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ua(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=aj.safeParse(t);if(!n.success)return{result:La(t,n.error.issues.map(i=>i.message))};let r=new Qi(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:Po(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=cj.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>lj(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 Zl({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=Ma(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 lj(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ue(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ue(e.before)},fullContent:e.after}}function uj(e){return new ql(e)}import{SiteEditOperationRequestSchema as pj}from"@vcp-dev/contracts";import Qn from"node:fs/promises";import sn from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as dj,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as fj}from"@vcp-dev/contracts";var Ql=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Zl({...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 ja(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return $a(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ua(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 Qn.readFile(sn.join(n,r),"utf8")},async readFileBytes(r){return Qn.readFile(sn.join(n,r))},async getFileInfo(r){let o=sn.join(n,...r.split("/"));try{let i=await Qn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await sc(sn.join(n,r),o)},async createExclusive(r,o){let i=sn.join(n,r);await Qn.mkdir(sn.dirname(i),{recursive:!0});let s=await Qn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Qn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Qn.rm(sn.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=sn.join(n,i),a=sn.dirname(sn.join(n,o));for(;a!==s&&a.startsWith(`${s}${sn.sep}`);){try{await Qn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=sn.dirname(a);continue}break}a=sn.dirname(a)}},async exists(r){try{return await Qn.access(sn.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...fj,...dj],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=sn.join(n,...d.split("/")),f;try{f=await Qn.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 Qn.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 Nm(e){return new Ql(e)}var eu=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=Nm({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=Ma(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:Fa(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:Da(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=pj.safeParse(r);if(!o.success)return La(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:Po(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:Po(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:Po(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 mj(e){return new eu(e)}import{GeneratedSiteCapabilitiesSchema as Ej}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as gj}from"@vcp-dev/contracts";function Bi(e){let t=yj(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)?Lr(e.node,"platform-managed","controlled platform package"):t?xj(e.node.path,t)?Lr(e.node,"host-public","declared Starter runtime dependency"):Lr(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):Lr(e.node,"unknown","trusted host capability contract is invalid"):Tv(e.node.path,n)?Lr(e.node,"platform-managed","controlled platform path"):t?Ov(e.node.path,t.generated_sections_path)?Lr(e.node,"private","site-generated section path"):Tv(e.node.path,t.public_paths)?Lr(e.node,"host-public","declared Starter public path"):Lr(e.node,"private","site-local file outside host public paths"):Lr(e.node,"unknown","trusted host capability contract is invalid")}function hj(e){return e.nodes.map(t=>Bi({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function Lr(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function yj(e){let t=gj.safeParse(e);return t.success?t.data:null}function xj(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function Tv(e,t){return t.some(n=>Ov(e,n))}function Ov(e,t){let n=bj(t),r=Lv(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):wv(r)===wv(n)}function bj(e){return Lv(e.split("#",1)[0]??e)}function Lv(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function wv(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function tu(e){let t=Ej.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=Bi({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=Sj(n).sort(Ij);return{complete:o.length===0,nodes:r.sort(vj),edges:[...e.closure.edges].sort(_j),errors:o}}function Sj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Ij(e,t){return Cn(e.path,t.path)||Cn(e.code,t.code)||Cn(e.specifier??"",t.specifier??"")||Cn(e.message,t.message)}function vj(e,t){return Cn(e.path,t.path)||Cn(e.kind,t.kind)||Cn(e.ownership,t.ownership)||Cn(e.status,t.status)}function _j(e,t){return Cn(e.from,t.from)||Cn(e.target??"",t.target??"")||Cn(e.specifier??"",t.specifier??"")||Cn(e.kind,t.kind)||Cn(e.resolution,t.resolution)}function Cn(e,t){return e<t?-1:e>t?1:0}var Fv={helper:"text",tsType:"string"},Am={helper:"images",tsType:"MediaItem[]",importName:"MediaItem"},Dv={helper:"image",tsType:"MediaItem | null",importName:"MediaItem"},Mv=/(gallery|galleries|images|photos|pics|pictures|album|attachments|files|media)$/i;function kj(e,t,n){switch(e){case"text":case"date":return Fv;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"||Mv.test(n)?Am:Dv;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 Tm(e,t,n){if(n){let r=kj(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{...Mv.test(t)?Am:Dv};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{...Fv}}}function wm(e,t,n={}){let r=`${Rj(e)}View`,o=t.filter(l=>l.front_display!=="forbidden").map(l=>{let u={key:Cj(l.name)?`${l.name}_field`:l.name,source:l.name,...Tm(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(`
1
+ import*as O_ from"@babel/parser";import*as Mt from"@babel/types";import*as vr from"node:path";var hu=[".tsx",".ts",".jsx",".js"],F_=hu.map(e=>`/index${e}`),L_=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 Fg(e){let t=e.replace(/[?#].*$/,""),n=/\.([a-z0-9]+)$/i.exec(t);return n!==null&&L_.has(n[1].toLowerCase())}function Lg(e){let t=[];for(let n of e.program.body)Mt.isImportDeclaration(n)&&typeof n.source.value=="string"&&pt(n.source.value)&&t.push(n.source.value),Mt.isExportNamedDeclaration(n)&&n.source&&typeof n.source.value=="string"&&pt(n.source.value)&&t.push(n.source.value),Mt.isExportAllDeclaration(n)&&typeof n.source.value=="string"&&pt(n.source.value)&&t.push(n.source.value);return Mt.traverseFast(e.program,n=>{let r=Mt.isImportExpression(n)?n.source:Mt.isCallExpression(n)&&Mt.isImport(n.callee)?n.arguments[0]:null;Mt.isStringLiteral(r)&&pt(r.value)&&t.push(r.value)}),t}function pt(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("@/")}function $n(e,t){if(t.startsWith("@/"))return t.slice(2).replace(/\\/g,"/");let n=vr.dirname(e);return vr.join(n,t).replace(/\\/g,"/")}async function D_(e,t){for(let n of Dg(e))if(await t(n))return n;return null}function Dg(e){return[...hu.some(t=>e.endsWith(t))?[e]:[],...hu.map(t=>`${e}${t}`),...F_.map(t=>`${e}${t}`)]}function Ir(e,t,n){let r=$n(e,t);if(!pt(t)||!Mg(e,t,r))return null;for(let o of Dg(r))if(n.has(o))return o;return null}async function no(e,t,n){let r=await ca(e,t,n);return r.ok?r.path:null}async function ca(e,t,n){let r=$n(e,t);try{if(!Mg(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 D_(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 Mg(e,t,n){if(!pt(t)||t.includes("\0")||t.includes("\\")||vr.posix.isAbsolute(n))return!1;let r=vr.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!vr.posix.isAbsolute(e)}import{createHash as B_}from"node:crypto";import*as Bg from"@babel/parser";function ro(e,t,n,r){return{code:e,message:t,locatorKind:n,details:r}}function ne(e,t,n,r,o){return{ok:!1,source:e,diagnostic:ro(t,n,r,o)}}function yu(e,t,n,r,o){return{ok:!1,source:e,diagnostic:ro(t,n,r,o)}}var M_={"tsx-module":["jsx","typescript"],"ts-module":["typescript"],"next-app-entry":["jsx","typescript"]};function Un(e){let{source:t,profile:n}=e;try{return{ok:!0,ast:Bg.parse(t,{sourceType:"module",plugins:M_[n]})}}catch(r){return{ok:!1,source:t,diagnostic:ro("parse-failed",`AST parse failed: ${r instanceof Error?r.message:String(r)}`)}}}function bu(e,t){return Un({source:e,profile:jg(t.kind)})}function Ti(e,t){return Un({source:e,profile:jg(t)})}function jg(e){return"next-app-entry"}function oo(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 _e=(e,t)=>{let n=Un({source:t,profile:oo({filePath:e,source:t})});return n.ok?{ok:!0,module:{file:e,source:t,sourceHash:`sha256:${B_("sha256").update(t).digest("hex")}`,ast:n.ast,imports:Lg(n.ast).map(r=>({specifier:r}))}}:{ok:!1,diagnostic:{path:e,code:"parse-failed",message:n.diagnostic.message}}};function j_(e,t){return _e(e,t)}function $_(e,t){return $n(e,t)}import{COMPONENT_I18N_FILE_SUFFIX as U_,parseComponentI18nResourcesJson as V_,resolveSiteTextDirection as K_,SiteLocaleSchema as J_}from"@vcp-dev/contracts";var X_=["i18next","react-i18next"],z_="components/ui/site-locale-provider.tsx",H_="components/ui/component-i18n-provider.tsx",$g="app/layout.tsx";async function wi(e){let t=e.files.filter(f=>f.path.endsWith(U_));if(t.length===0)return{ok:!0};for(let f of["package.json",$g,z_,H_])if(!await e.exists(f))return kr(`Target snapshot is missing required i18n host file: ${f}`);let n;try{n=JSON.parse(await e.readFile("package.json"))}catch{return kr("Target snapshot package.json is invalid.")}let r=Ug(n)&&Ug(n.dependencies)?n.dependencies:{},o=X_.filter(f=>typeof r[f]!="string"||r[f].trim().length===0);if(o.length>0)return kr(`Target snapshot must already declare: ${o.join(", ")}.`);let i=await e.readFile($g),s=xu(i,"html","lang"),a=xu(i,"html","dir"),c=xu(i,"SiteLocaleProvider","locale"),l=J_.safeParse(s);if(!l.success||!a||!c||s!==c||a!==K_(l.data))return kr("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 kr("Target snapshot root layout is not wired to SiteLocaleProvider.");let u=l.data;if(e.targetLocale&&e.targetLocale!==u)return kr("Target snapshot locale does not match the authoritative site language.");let d=u.split("-")[0];for(let f of t){let g=V_(f.content);if(!g.success)return kr(`Component i18n resource is invalid: ${f.path}.`);if(!e.deferTargetLocale&&!Object.hasOwn(g.data,u)&&!Object.hasOwn(g.data,d))return kr(`Component i18n resource ${f.path} has no locale for ${u} or ${d}.`)}return{ok:!0}}function xu(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 Ug(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kr(e){return{ok:!1,message:e}}import Su from"@babel/generator";import*as Hg from"@babel/parser";import vu from"@babel/traverse";import*as tt from"@babel/types";import{computeSiteEditSourceIdentityKey as G_}from"@vcp-dev/contracts";var Vg="data-vcp-ui-component",la="components/ui";function sr(e){if(!e)return!1;let t=Eu(e);return t===la||t.startsWith(`${la}/`)||t.includes(`/${la}/`)||t.endsWith(`/${la}`)}function io(e,t){return e?e.startsWith("@/")||e.startsWith("~/")?sr(e.slice(2)):e.startsWith("./")||e.startsWith("../")?sr(Eu(`${W_(t)}/${e}`)):sr(e):!1}function Eu(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 W_(e){let t=Eu(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}import{stripSiteEditRepeatInstanceKeys as nV}from"@vcp-dev/contracts";import{isSiteEditRuntimeContainerTag as oV,isSiteEditRuntimeTextTag as iV}from"@vcp-dev/contracts/site-edit-runtime-capability";var Kg={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 Y_=typeof Su=="function"?Su:Su.default,Z_=typeof vu=="function"?vu:vu.default,q_=new Set(["base","body","head","html","link","meta","noscript","script","style","template","title"]),Q_="suppressHydrationWarning",eR=new Set(["SiteEditBootstrap"]);function tR(e){let t=oR(e.file,e.projectRoot);if(!rR(e.source)||sr(t))return{code:e.source,elements:[]};let n=e.attributes??Kg,r=Hg.parse(e.source,{sourceType:"module",plugins:["jsx","typescript"]}),o=[],i=sR(r,t);return Z_(r,{JSXElement(s){let a=s.node.openingElement,c=a.name;if(!cR(c)||Wg(a,n.key))return;let l=uR(s)??"default",u=fR(s),d=G_(t,l,u),f=da(c)??"unknown",g=iR(c)?"jsx":"component-call";if(g==="component-call"&&!dR(s.node.children)&&eR.has(f))return;let m=g==="component-call"&&aR(f,i);lR(a,n.key,d),m&&Jg(a,Vg),nR(s)&&Jg(a,Q_),o.push({key:d,tag:f,componentName:l,sourceFile:t,sourceKind:g})}}),o.length===0?{code:e.source,elements:o}:{code:Y_(r,{jsescOption:{minimal:!0}}).code,elements:o}}function nR(e){return!e.findParent(t=>t.isJSXElement())}function rR(e){return/(?:^|[=(:,?;\[{>&|\n\r]|return\s+)\s*<(?:[A-Za-z][\w.:-]*|>)(?:\s|>|\/)/m.test(e)}function oR(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 iR(e){return tt.isJSXIdentifier(e)&&/^[a-z]/.test(e.name)}function da(e){return tt.isJSXIdentifier(e)?e.name:tt.isJSXMemberExpression(e)?Yg(e):null}function sR(e,t){let n=new Set;for(let r of e.program.body)if(!(!tt.isImportDeclaration(r)||!io(r.source.value,t)))for(let o of r.specifiers)n.add(o.local.name);return n}function aR(e,t){let n=e.split(".")[0]??e;return t.has(n)}function cR(e){let t=da(e);return!t||t==="Fragment"||t.endsWith(".Fragment")?!1:!q_.has(t)}function Wg(e,t){return e.attributes.some(n=>tt.isJSXAttribute(n)&&tt.isJSXIdentifier(n.name,{name:t}))}function lR(e,t,n){Gg(e,tt.jsxAttribute(tt.jsxIdentifier(t),tt.stringLiteral(n)))}function Jg(e,t){Wg(e,t)||Gg(e,tt.jsxAttribute(tt.jsxIdentifier(t),null))}function Gg(e,t){let n=e.attributes.findIndex(r=>tt.isJSXSpreadAttribute(r));if(n>=0){e.attributes.splice(n,0,t);return}e.attributes.push(t)}function Yg(e){return`${tt.isJSXIdentifier(e.object)?e.object.name:Yg(e.object)}.${e.property.name}`}function uR(e){let t=e;for(;t;){if(t.isFunctionDeclaration()||t.isClassDeclaration())return t.node.id?.name??null;if(t.isVariableDeclarator()&&tt.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 dR(e){return e.some(t=>tt.isJSXElement(t)||tt.isJSXFragment(t))}var Xg=new WeakMap,ua=new WeakMap,Iu=new WeakMap;function fR(e){let t=Xg.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=pR(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return Xg.set(e.node,o),o}function pR(e){let t=da(e.node.openingElement.name);return!t||t==="Fragment"||t.endsWith(".Fragment")?null:/^[A-Z]/.test(t)?`component:${t}#${zg(e,t)}`:`${t}#${zg(e,t)}`}function zg(e,t){let n=Zg(e)??e.getFunctionParent();if(!n)return 0;let r=Iu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Iu.get(n.node);o||(o=new Map,Iu.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()?fa(n):mR(n);for(let c of a)if(da(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 mR(e){let t=ua.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!Zg(r)&&n.push(r)}}),ua.set(e.node,n),n}function Zg(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 fa(e){let t=ua.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(...fa(o));continue}o.isJSXExpressionContainer()&&n.push(...so(o.get("expression")))}return ua.set(e.node,n),n}function so(e){if(e.isJSXElement())return[e];if(e.isJSXFragment())return fa(e);if(e.isParenthesizedExpression())return so(e.get("expression"));if(e.isLogicalExpression()&&e.node.operator==="&&")return so(e.get("right"));if(e.isConditionalExpression())return[...so(e.get("consequent")),...so(e.get("alternate"))];if(e.isCallExpression()&&hR(e.node)){let t=e.get("arguments")[0];return gR(t)}return[]}function gR(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return[t];if(t.isJSXFragment())return fa(t);if(t.isParenthesizedExpression())return so(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?so(r):[]}return[]}function hR(e){return tt.isMemberExpression(e.callee)&&tt.isIdentifier(e.callee.property)&&e.callee.property.name==="map"}import{SiteEditOperationRequestSchema as OB,SiteEditPatchPlanSchema as FB}from"@vcp-dev/contracts";function ao(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 pa(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 ma(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 ga(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:yR(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 ha(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:ao(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 yR(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 JM,computeSiteEditCompositionKey as XM,getSiteEditSourceDeleteProtectionReason as zM,isSiteEditTextSourcePath as HM,parseSiteEditRepeatInstanceKey as WM,SITE_EDIT_SOURCE_DELETE_CAPABILITY as GM,stripSiteEditRepeatInstanceKeys as qt}from"@vcp-dev/contracts";import Pl from"node:path";import{parse as YM}from"yaml";import Pu from"node:path";import{TextDecoder as xR}from"node:util";import{SITE_EDIT_SOURCE_ALLOWED_APP_FILES as Qg,SITE_EDIT_SOURCE_ALLOWED_DIRS as eh,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as th,SiteEditCompositionContextSchema as ER,SiteEditSourceFileResponseSchema as ku,SiteEditSourceLocationSchema as SR,SiteEditSourcePathSchema as ya,SiteEditSourceTreeResponseSchema as vR,isSiteEditTextSourcePath as IR}from"@vcp-dev/contracts";import{createHash as bR}from"node:crypto";var Oi=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 Ae(e){return`sha256:${bR("sha256").update(e).digest("hex")}`}var kR=[...th,...Qg,...eh];function Nu(e){if(!e.composition)throw new Error("Composition unavailable for source access policy.");return ER.parse(e.composition)}var _u=2e3,Ru=12,Cu=24*1024*1024,qg=512*1024,_R=new Set(["image/avif","image/gif","image/jpeg","image/png","image/webp","image/x-icon"]),RR={".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"},CR={".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"},PR=new xR("utf-8",{fatal:!0});async function ba(e,t={}){let n=Nu(t),{files:r,truncated:o}=await LR(e,t),i=BR(r.map(s=>s.metadata));return vR.parse({composition:n,nodes:i,defaultPath:jR(r.map(s=>s.metadata)),totalFiles:r.length,...o?{truncated:o}:{}})}async function xa(e,t,n={}){let r=Nu(n),o=ya.parse(t.path),i=await AR(e,o,n);if(!i)throw new Error(`Source file not found: ${o}`);if(Tu(o)){let a=oh(o),c=await wR(e,{path:o,sizeBytes:i.sizeBytes,mimeType:a});return ku.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:i.sizeBytes,mimeType:a,readonly:!0,...c})}let s=await Au(e,o);return s.ok?ku.parse({composition:r,path:o,kind:"text",language:ih(o),sizeBytes:s.sizeBytes,contentHash:Ae(s.content),readonly:!1,content:s.content}):ku.parse({composition:r,path:o,kind:"binary",language:null,sizeBytes:s.sizeBytes,mimeType:"application/octet-stream",readonly:!0,previewUnavailableReason:"unsupported-mime"})}async function Au(e,t){if(e.readFileBytes){let o=await e.readFileBytes(t),i=NR(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 NR(e){if(e.includes(0))return null;try{return PR.decode(e)}catch{return null}}async function AR(e,t,n){if(!OR(t,n))return null;let r=await TR(e,t);return r?{path:t,sizeBytes:r.sizeBytes}:null}async function TR(e,t){if(e.getFileInfo)return e.getFileInfo(t);if(e.listFiles){let o=nh(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(Tu(t))return{path:t,sizeBytes:0};let n=await e.readFile(t);return{path:t,sizeBytes:Buffer.byteLength(n,"utf8")}}async function wR(e,t){if(!_R.has(t.mimeType))return{previewUnavailableReason:"unsupported-mime"};if(t.sizeBytes>qg)return{previewUnavailableReason:"too-large"};if(!e.readFileBytes)return{previewUnavailableReason:"bytes-unavailable"};let n=await e.readFileBytes(t.path);return n.byteLength>qg?{previewUnavailableReason:"too-large"}:{contentBase64:Buffer.from(n).toString("base64")}}function OR(e,t){return th.some(n=>n===e)||Qg.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=ya.safeParse(n);return r.success&&r.data===e})}function Ea(e,t){if(!t.sourceLocator)throw new Error(`Source location not available for key: ${e.key}`);return SR.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 nh(e){return Array.isArray(e)?{files:e}:e}function FR(e){return["max-files","max-depth","max-total-bytes"].filter(n=>e.includes(n))}async function LR(e,t){if(!e.listFiles)throw new Error("Source file listing is unavailable.");let n=nh(await e.listFiles({roots:DR(t),maxFiles:_u+1,maxDepth:Ru,maxTotalBytes:Cu+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=ya.safeParse(a.path);if(!c.success)continue;let l=c.data;if(l.split("/").length>Ru){o.add("max-depth");continue}if(r.size>=_u){o.add("max-files");break}if(i+a.sizeBytes>Cu){o.add("max-total-bytes");break}r.set(l,{path:l,sizeBytes:a.sizeBytes,metadata:MR(l,a.sizeBytes,Nu(t))}),i+=a.sizeBytes}return{files:[...r.values()].sort((a,c)=>a.path.localeCompare(c.path)),...o.size>0?{truncated:{reasons:FR([...o]),maxFiles:_u,maxDepth:Ru,maxTotalBytes:Cu}}:{}}}function DR(e){let t=new Set(kR);for(let n of e.routeEntryFiles??[]){let r=ya.safeParse(n);r.success&&(r.data.startsWith("app/")||r.data.startsWith("src/app/"))&&t.add(r.data)}return[...t]}function MR(e,t,n){return Tu(e)?{composition:n,path:e,kind:"binary",language:null,sizeBytes:t,mimeType:oh(e),readonly:!0}:{composition:n,path:e,kind:"text",language:ih(e),sizeBytes:t,readonly:!1}}function BR(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 rh(t)}function rh(e){return e.map(t=>t.kind==="directory"?{...t,children:rh(t.children)}:t).sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}function jR(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 Tu(e){return!IR(e)}function oh(e){let t=Pu.posix.extname(e).toLowerCase();return!t&&Pu.posix.basename(e).toLowerCase()==="favicon"?"image/x-icon":RR[t]??"application/octet-stream"}function ih(e){let t=Pu.posix.extname(e).toLowerCase();return CR[t]??"plaintext"}import*as lo from"@babel/types";import wu from"@babel/traverse";import*as Vn from"@babel/types";function it(e){if(e.isJSXFragment())return!0;if(!e.isJSXElement())return!1;let t=e.node.openingElement.name;if(Vn.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(Vn.isIdentifier(s)&&s.name==="Fragment"||Vn.isStringLiteral(s)&&s.value==="Fragment")&&sh(i.parentPath)}if(!Vn.isJSXMemberExpression(t)||!Vn.isJSXIdentifier(t.property)||t.property.name!=="Fragment"||!Vn.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())&&sh(r.parentPath)}function sh(e){return e?.isImportDeclaration()===!0&&e.node.source.value==="react"}var _r=typeof wu=="function"?wu:wu.default,Sa=new WeakMap,va=new WeakMap;function Kn(e,t){let n=bu(e,t);if(!n.ok)return yu(e,n.diagnostic.code,n.diagnostic.message,t.kind);let r=Pe(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}}:yu(e,r.diagnostic.code,r.diagnostic.message,t.kind,r.diagnostic.details)}function Pe(e,t){return t.kind==="jsx-node"?uh(e,t):t.kind==="jsx-attribute"?XR(e,t):t.kind==="value"?zR(e,t):t.kind==="expression"?HR(e,t):t.kind==="directive"?WR(e,t):t.kind==="export"?GR(e,t):{ok:!1,diagnostic:ro("unsupported-syntax",`Unsupported locator kind: ${t.kind}`)}}function uh(e,t){return t.strategy==="source-range"?$R(e,t):UR(e,t)}function $R(e,t){let n=null;if(_r(e,{JSXElement(o){if(!co(o.node,t.sourceRange))return;let i=bt("jsx-node",o);if(i){if(!n){n=i;return}i.end-i.start<n.end-n.start&&(n=i)}},JSXFragment(o){if(!co(o.node,t.sourceRange))return;let i=bt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXExpressionContainer(o){if(!co(o.node,t.sourceRange))return;let i=bt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)},JSXText(o){if(!co(o.node,t.sourceRange))return;let i=bt("jsx-node",o);i&&(!n||i.end-i.start<n.end-n.start)&&(n=i)}}),!n)return vt("jsx-node","locator-miss","JSX node not found for source-range locator");let r=n;return t.expectedIdentity&&!aC(r.path,t.expectedIdentity)?vt("jsx-node","locator-miss","JSX node failed expected identity validation"):{ok:!0,match:r}}function UR(e,t){if(t.structuralPath===""){let r=KR(e,t.component);if(r){let o=JR(r);if(o)return o}}let n=null;return _r(e,{JSXElement(r){if(Li(r)!==t.component||Fu(r)!==t.structuralPath)return;let i=bt("jsx-node",r);i&&(n=i,r.stop())},JSXFragment(r){if(Li(r)!==t.component||Fu(r)!==t.structuralPath)return;let i=bt("jsx-node",r);i&&(n=i,r.stop())}}),!n&&t.expectedRange&&(n=VR(e,t.component,t.expectedRange)),n?{ok:!0,match:n}:vt("jsx-node","locator-miss","JSX node not found for structural-path locator")}function VR(e,t,n){let r=null;return _r(e,{JSXElement(o){if(Li(o)!==t||!co(o.node,n))return;let i=bt("jsx-node",o);i&&(r=i,o.stop())},JSXFragment(o){if(Li(o)!==t||!co(o.node,n))return;let i=bt("jsx-node",o);i&&(r=i,o.stop())}}),r}function KR(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 JR(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 vt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}return null}return(t.isParenthesizedExpression()?t.get("expression"):t).isJSXFragment()?vt("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 vt("jsx-node","unsupported-syntax","JSXFragment is not a supported edit target")}}}return null}function XR(e,t){let n=uh(e,t.element);if(!n.ok)return n;let s=n.match.path.get("openingElement").get("attributes").find(c=>cC(c,t.name));if(!s||!s.isJSXAttribute())return vt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' not found`);let a=bt("jsx-attribute",s);return a?{ok:!0,match:a}:vt("jsx-attribute","locator-miss",`JSX attribute '${t.name}' has no source range`)}function zR(e,t){let n=YR(e,t);if(!n.ok)return n;let r=ZR(n.match.path,t.path??[]);return r.ok?t.expectedRange&&!cr(r.match.path.node.loc,t.expectedRange)?vt("value","locator-miss","Resolved value does not match expected range"):{ok:!0,match:r.match}:r}function HR(e,t){let n=null;return _r(e,{Identifier(r){if(!rC(r))return;let o=ch(r);if(!o||!lh(o,t))return;let i=bt("expression",r);i&&(t.expectedRange&&!cr(r.node.loc,t.expectedRange)||(n=i,r.stop()))},MemberExpression(r){let o=ch(r);if(!o||!lh(o,t))return;let i=bt("expression",r);i&&(t.expectedRange&&!cr(r.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:vt("expression","locator-miss","Expression not found")}function WR(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&&!cr(i.node.loc,t.expectedRange))return;let s=bt("directive",i);s&&(n=s,r.stop())}}),n?{ok:!0,match:n}:vt("directive","locator-miss",`Directive '${t.value}' not found`)}function GR(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 f=bt("export",c);if(!f||t.expectedRange&&!cr(c.node.loc,t.expectedRange))return;n=f,r.stop();return}if(!c.isVariableDeclaration())return;let l=Lu(c,"generateMetadata");if(!l||!l.isVariableDeclarator())return;let u=l.get("init");if(!u.node)return;let d=bt("export",u);if(!d||t.expectedRange&&!cr(u.node.loc,t.expectedRange))return;n=d,r.stop();return}let o=r.get("declaration");if(!o.isVariableDeclaration())return;let i=Lu(o,t.exportKind==="named"?t.name:"metadata");if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node||t.expectedRange&&!cr(s.node.loc,t.expectedRange))return;let a=bt("export",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(t.exportKind!=="default")return;let o=r.get("declaration"),i=bt("export",o);i&&(t.expectedRange&&!cr(o.node.loc,t.expectedRange)||(n=i,r.stop()))}}),n?{ok:!0,match:n}:vt("export","export-not-found",`Export '${sC(t)}' not found`)}function YR(e,t){let n=null;return _r(e,{Expression(r){if(n||t.root.kind!=="expression"||!co(r.node,t.root.sourceRange))return;let o=bt("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=bt("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 f=bt("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=Lu(o,t.root.name);if(!i||!i.isVariableDeclarator())return;let s=i.get("init");if(!s.node)return;let a=bt("value",s);a&&(n=a,r.stop())},ExportDefaultDeclaration(r){if(n||t.root.kind!=="default-export")return;let o=r.get("declaration"),i=bt("value",o);i&&(n=i,r.stop())}}),n?{ok:!0,match:n}:vt("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 ZR(e,t){let n=Ou(e);for(let o of t){if(n=Ou(n),o.kind==="property"){if(!n.isObjectExpression())return vt("value","unsupported-syntax","Property path requires object expression");let a=n.get("properties");if(a.some(l=>!l.isObjectProperty()))return vt("value","unsupported-syntax","Spread properties are not supported");let c=a.find(l=>lC(l,o.name));if(!c||!c.isObjectProperty())return vt("value","property-not-found",`Property '${o.name}' not found`);n=c.get("value");continue}if(!n.isArrayExpression())return vt("value","unsupported-syntax","Array index path requires array expression");let i=n.get("elements");if(i.some(a=>a.node?.type==="SpreadElement"))return vt("value","unsupported-syntax","Spread array elements are not supported");let s=i[o.index];if(!s?.node)return vt("value","array-index-out-of-range",`Array index ${o.index} is out of range`);n=s}n=Ou(n);let r=bt("value",n);return r?{ok:!0,match:r}:vt("value","locator-miss","Resolved value has no source range")}function Ou(e){let t=e;for(;t.isTSAsExpression()||t.isTSSatisfiesExpression()||t.isTSNonNullExpression();)t=t.get("expression");return t}function bt(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 co(e,t){return cr(e.loc,t)}function cr(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(!it(n)){let o=fh(n.node.openingElement);o&&(/^[A-Z]/.test(o)?t.unshift(`component:${o}#${ah(n,o)}`):t.unshift(`${o}#${ah(n,o)}`))}}else n.isJSXFragment()&&n.node===r&&t.unshift("fragment");if(!n.parentPath||tC(n.parentPath)&&!nC(n.parentPath))break;n=n.parentPath}return t.join("/")}function ah(e,t){let n=dh(e)??e.getFunctionParent();if(!n)return 0;let r=Sa.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=0,i=Sa.get(n.node)?.get(t);if(!i){let a=Sa.get(n.node);a||(a=new Map,Sa.set(n.node,a)),i=new WeakMap,a.set(t,i)}let s=n.isJSXElement()||n.isJSXFragment()?Fi(n):qR(n);for(let a of s)if(fh(a.node.openingElement)===t){if(i.set(a.node,o),a.node===e.node)return o;o++}return i.get(e.node)??0}function qR(e){let t=va.get(e.node);if(t)return t;let n=[];return e.traverse({JSXElement(r){r.getFunctionParent()?.node===e.node&&!dh(r)&&n.push(r)}}),va.set(e.node,n),n}function dh(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(it(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function Fi(e){let t=va.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(it(o)){n.push(...Fi(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...Fi(o));continue}o.isJSXExpressionContainer()&&n.push(...ar(o.get("expression")))}return va.set(e.node,n),n}function ar(e){if(e.isJSXElement())return it(e)?Fi(e):[e];if(e.isJSXFragment())return Fi(e);if(e.isParenthesizedExpression())return ar(e.get("expression"));if(e.isLogicalExpression()&&QR(e.node.operator))return ar(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(...ar(c))}if(s.isReturnStatement()){let a=s.get("argument");a.isExpression()&&i.push(...ar(a));break}}return i}else if(o.node&&o.isExpression())return ar(o)}}}}return e.isConditionalExpression()?[...ar(e.get("consequent")),...ar(e.get("alternate"))]:e.isArrayExpression()?e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:ar(t)):[]}function QR(e){return e==="&&"||e==="||"||e==="??"}function fh(e){return e.name.type==="JSXIdentifier"?e.name.name:e.name.type==="JSXMemberExpression"?eC(e.name):null}function eC(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 Li(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 tC(e){return!!(e.isFunctionDeclaration()||e.isFunctionExpression()||e.isArrowFunctionExpression())}function nC(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 rC(e){return!(!e.isExpression()||e.parentPath?.isMemberExpression({property:e.node}))}function ch(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 lh(e,t){return e.base===t.base&&oC(e.path,t.path??[])}function oC(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 iC(e){return e.key.type==="Identifier"?e.key.name:e.key.type==="StringLiteral"?e.key.value:null}function sC(e){return e.exportKind==="named"?e.name:e.exportKind}function vt(e,t,n,r){return{ok:!1,diagnostic:ro(t,n,e,r)}}function aC(e,t){return Li(e)!==t.component?!1:Fu(e)===t.structuralPath}function cC(e,t){return!e.isJSXAttribute()||e.node.name.type!=="JSXIdentifier"?!1:e.node.name.name===t}function Lu(e,t){return e.get("declarations").find(n=>!n.isVariableDeclarator()||n.node.id.type!=="Identifier"?!1:n.node.id.name===t)}function lC(e,t){return e.isObjectProperty()?iC(e.node)===t:!1}import*as mh from"@babel/parser";import{arrayExpression as mC,booleanLiteral as gC,identifier as hC,jsxAttribute as yC,jsxExpressionContainer as bC,jsxIdentifier as xC,nullLiteral as EC,numericLiteral as SC,objectExpression as vC,objectProperty as IC,stringLiteral as Mu}from"@babel/types";import Du from"@babel/generator";var uC=typeof Du=="function"?Du:Du.default;function dC(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 fC(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 pC(e,t){return e.split(`
3
+ `).map(r=>fC(r,t)).join(`
4
+ `)}function Ia(e){let{ast:t,source:n}=e;try{let r=dC(n),i=uC(t,{comments:!0,jsescOption:{minimal:!0,quotes:"single"}},n).code;return r!=="2"&&(i=pC(i,r)),{ok:!0,source:i}}catch(r){return ne(n,"printer-failed",`AST print failed: ${r instanceof Error?r.message:String(r)}`)}}function ph(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 Di(e,t,n){return{ok:!0,source:t,operation:{type:n.kind,nodeId:n.target,kind:n.kind,target:n.target,beforeSourceHash:ph(e),afterSourceHash:ph(t),inverse:n.inverse}}}function Xe(e,t,n){let r=Ia({ast:e,source:t});return r.ok?Di(t,r.source,n):r}function nt(e,t){let n=Ti(e,t);return n.ok?{ok:!0,ast:n.ast}:{ok:!1,result:{ok:!1,source:e,diagnostic:n.diagnostic}}}function ka(e,t){return Ia({ast:e,source:t})}function kC(e,t,n){let r=Pe(e,t);return r.ok?{ok:!0,match:r.match}:{ok:!1,result:{ok:!1,source:n,diagnostic:r.diagnostic}}}function Mo(e,t,n){let r=kC(e,t,n);return r.ok?r.match.path.isJSXElement()?r:{ok:!1,result:ne(n,"unsupported-syntax","JSX locator must resolve to JSXElement","jsx-node")}:r}function Rr(e){return typeof e=="string"?Mu(e):typeof e=="number"?SC(e):typeof e=="boolean"?gC(e):e===null?EC():Array.isArray(e)?mC(e.map(t=>Rr(t))):vC(Object.entries(e).map(([t,n])=>{let r=IC(Bu(t),Rr(n));return t==="__proto__"&&(r.computed=!0),r}))}function _C(e){return typeof e=="string"?Mu(e):bC(Rr(e))}function Mi(e,t){return yC(xC(e),_C(t))}function _a(e,t){try{let r=mh.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:ne(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:ne(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function Bu(e){return/^[$A-Z_][0-9A-Z_$]*$/i.test(e)?hC(e):Mu(e)}function Ra(e){let{source:t,locator:n,segmentIndex:r,newText:o}=e,i=nt(t,"jsx-node");if(!i.ok)return i.result;let s=Pe(i.ast,n);if(!s.ok)return{ok:!1,source:t,diagnostic:s.diagnostic};let c=RC(s.match.path)[r];if(!c)return ne(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?[lo.jsxText(d)]:[],lo.jsxExpressionContainer(lo.stringLiteral("")),...f?[lo.jsxText(f)]:[]]);break}let u=CC(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 Xe(i.ast,t,{kind:"update-text",target:"jsx-node",inverse:"restore-text"})}function RC(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=PC(r.get("expression"));o.length>0&&t.push(...o)}}return t}function CC(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"";return`${n}${t.trim()}${r}`}function PC(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 ju}from"@babel/types";function uo(e){let{source:t,locator:n}=e,r=nt(t,"jsx-node");if(!r.ok)return r.result;let o=Pe(r.ast,n);return o.ok?(NC(o.match.path),Xe(r.ast,t,{kind:"remove-node",target:"jsx-node",inverse:"insert-child"})):{ok:!1,source:t,diagnostic:o.diagnostic}}function NC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(ju());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(ju());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(ju());return}e.remove()}import{cloneNode as AC}from"@babel/types";function Bo(e){let t=nt(e.source,"jsx-node");if(!t.ok)return t.result;let n=Pe(t.ast,e.locator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};let r=_a(e.source,e.node.jsx);return r.ok?(n.match.path.replaceWith(AC(r.node,!0)),Xe(t.ast,e.source,{kind:"replace-node",target:"jsx-node",inverse:"replace-node"})):r.result}import{cloneNode as UC}from"@babel/types";import $u from"@babel/traverse";import*as ye from"@babel/types";function Bi(e,t,n){return`${e}::${t}::${n}`}var J={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 TC=typeof $u=="function"?$u:$u.default;function yn(e,t,n,r){if(!e.ok)return e;let o=hn(n,t);if(!o)return e;let i=wC(t,o,r);return i?{...e,selectionRef:i}:e}function wC(e,t,n){let r=OC(e,t);if(!r)return;let o=n.sourceLocator?gh(n.sourceLocator):void 0,i=n.targetParentLocator?gh(n.targetParentLocator):void 0,s=n.file??i?.file??o?.file,a=n.component??LC(r)??i?.component??o?.component;if(!(!s||!a))return{key:Bi(s,a,DC(r))}}function gh(e){return e.strategy==="structural-path"?{file:e.file,component:e.component,structuralPath:e.structuralPath}:e.expectedIdentity}function OC(e,t){let n=Sh(e,t);return!n||n.node.type!=="JSXElement"?null:n}function Sh(e,t){let n=null;return TC(e,{JSXElement(r){r.node===t&&(n=r,r.stop())},JSXFragment(r){r.node===t&&(n=r,r.stop())}}),n}function hn(e,t){if(!e)return null;if(ye.isJSXElement(e))return $C(t,e)?hh(e.children,t):e;if(ye.isJSXFragment(e))return hh(e.children,t);if(ye.isJSXExpressionContainer(e)||ye.isParenthesizedExpression(e)||ye.isTSAsExpression(e)||ye.isTSSatisfiesExpression(e)||ye.isTSTypeAssertion(e)||ye.isTSNonNullExpression(e))return hn(e.expression,t);if(ye.isLogicalExpression(e))return hn(e.right,t);if(ye.isConditionalExpression(e))return hn(e.consequent,t)??hn(e.alternate,t);if(ye.isCallExpression(e)||ye.isOptionalCallExpression(e))return vh(e)?FC(e.arguments[0],t):null;if(ye.isArrayExpression(e))for(let n of e.elements){if(!n)continue;let r=hn(n,t);if(r)return r}return null}function hh(e,t){for(let n of e){let r=hn(n,t);if(r)return r}return null}function FC(e,t){return!e||!ye.isArrowFunctionExpression(e)&&!ye.isFunctionExpression(e)?null:ye.isBlockStatement(e.body)?ji(e.body.body,t):hn(e.body,t)}function ji(e,t){for(let n of e){if(ye.isReturnStatement(n)){let r=hn(n.argument,t);if(r)return r;continue}if(ye.isBlockStatement(n)){let r=ji(n.body,t);if(r)return r;continue}if(ye.isIfStatement(n)){let r=yh(n.consequent,t);if(r)return r;let o=n.alternate?yh(n.alternate,t):null;if(o)return o;continue}if(ye.isSwitchStatement(n))for(let r of n.cases){let o=ji(r.consequent,t);if(o)return o}}return null}function yh(e,t){return ye.isBlockStatement(e)?ji(e.body,t):ji([e],t)}function LC(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(ye.isFunctionDeclaration(n))return n.id?.name??"default"}if(t.isVariableDeclarator()&&ye.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,xh=new WeakMap,Uu=new WeakMap;function DC(e){let t=bh.get(e.node);if(t!==void 0)return t;let n=[],r=e;for(;r;){if(r.isJSXElement()){let i=MC(r);i&&n.unshift(i)}r=r.parentPath}let o=n.join("/");return bh.set(e.node,o),o}function MC(e){let t=Ih(e.node.openingElement.name);return!t||it(e)?null:/^[A-Z]/.test(t)?`component:${t}#${Eh(e,t)}`:`${t}#${Eh(e,t)}`}function Eh(e,t){let n=BC(e);if(!n)return 0;let r=Uu.get(n.node)?.get(t)?.get(e.node);if(r!==void 0)return r;let o=Uu.get(n.node);o||(o=new Map,Uu.set(n.node,o));let i=o.get(t);i||(i=new WeakMap,o.set(t,i));let s=0;for(let a of fo(n))if(Ih(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 BC(e){let t=e.parentPath,n=null;for(;t;){if(t.isJSXFragment()){n=t,t=t.parentPath;continue}if(t.isJSXElement()){if(it(t)){t=t.parentPath;continue}return t}t=t.parentPath}return n}function fo(e){let t=xh.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(it(o)){n.push(...fo(o));continue}n.push(o);continue}if(o.isJSXFragment()){n.push(...fo(o));continue}o.isJSXExpressionContainer()&&n.push(...Jn(o.get("expression")))}return xh.set(e.node,n),n}function Jn(e){if(e.isJSXElement())return it(e)?fo(e):[e];if(e.isJSXFragment())return fo(e);if(e.isParenthesizedExpression())return Jn(e.get("expression"));if(e.isLogicalExpression())return Jn(e.get("right"));if(e.isConditionalExpression())return[...Jn(e.get("consequent")),...Jn(e.get("alternate"))];if(e.isArrayExpression())return e.get("elements").flatMap(t=>Array.isArray(t)||!t.node||!t.isExpression()?[]:Jn(t));if((e.isCallExpression()||e.isOptionalCallExpression())&&vh(e.node)){let t=e.get("arguments"),n=Array.isArray(t)?t[0]:void 0;return n?jC(n):[]}return[]}function jC(e){if(!e.isArrowFunctionExpression()&&!e.isFunctionExpression())return[];let t=e.get("body");if(t.isJSXElement())return it(t)?fo(t):[t];if(t.isJSXFragment())return fo(t);if(t.isParenthesizedExpression())return Jn(t.get("expression"));if(t.isLogicalExpression()||t.isConditionalExpression())return Jn(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(...Jn(s))}if(!r.isReturnStatement())continue;let o=r.get("argument");return o.node&&n.push(...Jn(o)),n}return n}function vh(e){let t=e.callee;return(ye.isMemberExpression(t)||ye.isOptionalMemberExpression(t))&&ye.isIdentifier(t.property)&&t.property.name==="map"&&!t.computed}function $C(e,t){let n=Sh(e,t);return n?it(n):!1}function Ih(e){return ye.isJSXIdentifier(e)?e.name:ye.isJSXMemberExpression(e)?kh(e):ye.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function kh(e){return`${ye.isJSXIdentifier(e.object)?e.object.name:kh(e.object)}.${e.property.name}`}function Cr(e,t){if(t.parentPath===e&&t.listKey==="children"&&Vu(e))return e;if(!t.parentPath||t.listKey!=="children")return null;let n=t.parentPath;if(!Vu(n))return null;let r=n;for(;r&&r!==e;){if(!Vu(r)||!it(r)||r.listKey!=="children")return null;r=r.parentPath}return r===e?n:null}function Vu(e){return e.isJSXElement()||e.isJSXFragment()}function bn(e){let{source:t,locator:n,node:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=nt(t,"jsx-node");if(!a.ok)return a.result;let c=Pe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};if(!c.match.path.isJSXElement()&&!c.match.path.isJSXFragment())return ne(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 ne(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=_a(t,r.jsx);if(!u.ok)return u.result;let d=UC(u.node,!0),f=l.node.children,g={...s,targetParentLocator:n},m=x=>s?yn(x,a.ast,d,g):x;if(o==="append")return f.push(d),m(Xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return f.unshift(d),m(Xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"}));if(!i)return ne(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let p=Pe(a.ast,i);if(!p.ok)return{ok:!1,source:t,diagnostic:p.diagnostic};let y=Cr(c.match.path,p.match.path);if(!y)return ne(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,E=b.findIndex(x=>x===p.match.path.node);return E===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?E:E+1,0,d),m(Xe(a.ast,t,{kind:"insert-child",target:"jsx-node",inverse:"remove-child"})))}import*as _h from"@babel/parser";import{cloneNode as VC}from"@babel/types";function Ca(e){let{source:t,locator:n,expression:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=nt(t,"jsx-node");if(!a.ok)return a.result;let c=KC(t,r);if(!c.ok)return c.result;let l=Pe(a.ast,n);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ne(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 ne(t,"self-closing-element","Cannot insert child into self-closing element","jsx-node")}let u=l.match.path,d=null;if(i){let b=Pe(a.ast,i);if(!b.ok)return{ok:!1,source:t,diagnostic:b.diagnostic};let E=Cr(l.match.path,b.match.path);if(!E)return ne(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=E,d=b.match.path.node}else if(o==="before"||o==="after")return ne(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=VC(c.node,!0),g=u.node.children,m={...s,targetParentLocator:n},p=b=>s?yn(b,a.ast,f,m):b;if(o==="append")return g.push(f),p(Xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));if(o==="prepend")return g.unshift(f),p(Xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"}));let y=g.findIndex(b=>b===d);return y===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(g.splice(o==="before"?y:y+1,0,f),p(Xe(a.ast,t,{kind:"insert-jsx-expression-child",target:"jsx-node",inverse:"remove-child"})))}function KC(e,t){try{let r=_h.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:ne(e,"unsupported-syntax","Expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ne(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}import{cloneNode as JC,nullLiteral as Ku}from"@babel/types";import*as Pr from"@babel/types";import*as Rh from"@babel/types";function $i(e,t){let n=e.parentPath;if(!n?.isConditionalExpression()||e.key!=="consequent"||!Rh.isNullLiteral(n.node.alternate))return e;let r=n.parentPath;return!r?.isJSXExpressionContainer()||r.parentPath?.node!==t.node||r.listKey!=="children"?e:r}function po(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,selectionContext:s}=e,a=nt(t,"jsx-node");if(!a.ok)return a.result;let c=Pe(a.ast,n);if(!c.ok)return{ok:!1,source:t,diagnostic:c.diagnostic};let l=Pe(a.ast,r);if(!l.ok)return{ok:!1,source:t,diagnostic:l.diagnostic};if(!l.match.path.isJSXElement()&&!l.match.path.isJSXFragment())return ne(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 ne(t,"self-closing-element","Cannot move child into self-closing element","jsx-node")}let d=null;if(i){let x=Pe(a.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let S=x.match.path.isJSXElement()?$i(x.match.path,l.match.path):x.match.path,v=Cr(l.match.path,S);if(!v)return ne(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");u=v,d=S}else if(o==="before"||o==="after")return ne(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");let f=d&&typeof d.key=="number"?d.key:-1;if(d&&f===-1)return ne(t,"locator-miss","Anchor node does not exist in target parent","jsx-node");let g=c.match.path.isJSXElement()?$i(c.match.path,l.match.path):c.match.path,m=JC(g.node,!0);if(!Pr.isJSXElement(m)&&!Pr.isJSXExpressionContainer(m)&&!Pr.isJSXFragment(m)&&!Pr.isJSXText(m))return ne(t,"unsupported-syntax","move-node source must resolve to a JSX child","jsx-node");let p=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 ne(t,"invalid-parent-child-relation","Cannot move a node relative to itself","jsx-node");XC(g);let y=u.node.children,b={...s,sourceLocator:n,targetParentLocator:r};if(o==="append")return y.push(m),yn(ka(a.ast,t),a.ast,m,b);if(o==="prepend")return y.unshift(m),yn(ka(a.ast,t),a.ast,m,b);let E=f-(p!==-1&&p<f?1:0);return y.splice(o==="before"?E:E+1,0,m),yn(ka(a.ast,t),a.ast,m,b)}function XC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ku());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ku());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ku());return}e.remove()}import*as Ch from"@babel/parser";import{cloneNode as zC,nullLiteral as Ju}from"@babel/types";function Pa(e){let{source:t,locator:n,targetParentLocator:r,placement:o,anchorLocator:i,repeatExpression:s,selectionContext:a}=e,c=nt(t,"jsx-node");if(!c.ok)return c.result;let l=HC(t,s);if(!l.ok)return l.result;let u=Pe(c.ast,n);if(!u.ok)return{ok:!1,source:t,diagnostic:u.diagnostic};let d=Pe(c.ast,r);if(!d.ok)return{ok:!1,source:t,diagnostic:d.diagnostic};if(!d.match.path.isJSXElement()&&!d.match.path.isJSXFragment())return ne(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 ne(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=Pe(c.ast,i);if(!x.ok)return{ok:!1,source:t,diagnostic:x.diagnostic};let S=Cr(d.match.path,x.match.path);if(!S)return ne(t,"invalid-parent-child-relation","Anchor node is not a direct child of the target parent","jsx-node");f=S,g=x.match.path.node}else if(o==="before"||o==="after")return ne(t,"locator-miss",`Placement '${o}' requires anchorLocator`,"jsx-node");if(!u.match.path.isJSXElement())return ne(t,"unsupported-syntax","move-repeat-template-child source must be a JSXElement","jsx-node");let m=f.node,p=zC(l.node,!0);WC(u.match.path);let y={...a,sourceLocator:n,targetParentLocator:r},b=m.children;if(o==="append")return b.push(p),yn(Xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,p,y);if(o==="prepend")return b.unshift(p),yn(Xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,p,y);let E=b.findIndex(x=>x===g);return E===-1?ne(t,"locator-miss","Anchor node no longer exists in target parent","jsx-node"):(b.splice(o==="before"?E:E+1,0,p),yn(Xe(c.ast,t,{kind:"move-repeat-template-child",target:"jsx-node",inverse:"move-repeat-template-child"}),c.ast,p,y))}function HC(e,t){try{let r=Ch.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:ne(e,"unsupported-syntax","Repeat expression must parse as a JSX expression container","jsx-node")}:{ok:!0,node:i}}catch(n){return{ok:!1,result:ne(e,"parse-failed",`AST parse failed: ${n instanceof Error?n.message:String(n)}`,"jsx-node")}}}function WC(e){if(e.parentPath?.isConditionalExpression()&&(e.key==="consequent"||e.key==="alternate")){e.replaceWith(Ju());return}if(e.parentPath?.isArrowFunctionExpression()&&e.key==="body"){e.replaceWith(Ju());return}if(e.parentPath?.isReturnStatement()&&e.key==="argument"){e.replaceWith(Ju());return}e.remove()}import{SiteEditSetPropsParamsSchema as GC,classifySiteEditPropertyName as YC}from"@vcp-dev/contracts";import*as jo from"@babel/types";function Na(e){let t=GC.safeParse({kind:"set-props",scope:"selection",changes:e.changes});if(!t.success)return ne(e.source,"unsupported-syntax","Invalid typed JSX property changes","jsx-node",{issues:t.error.issues});let n=nt(e.source,"jsx-node");if(!n.ok)return n.result;let r=Mo(n.ast,e.locator,e.source);if(!r.ok)return r.result;for(let a of t.data.changes){let c=YC(a.name);if(c.owner!=="generic")return ne(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(jo.isJSXAttribute),s=new Map;for(let a of i){let c=ZC(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 ne(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=Mi(a.name,a.value).value;c?c.value=l:o.attributes.push(Mi(a.name,a.value))}return Xe(n.ast,e.source,{kind:"set-props",target:"jsx-node",inverse:"set-props"})}function ZC(e){return jo.isJSXIdentifier(e.name)?e.name.name:jo.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{SiteEditOperationParamsSchema as qC}from"@vcp-dev/contracts";import*as se from"@babel/types";var Ph=["prefetch","replace","scroll","locale","onNavigate"],QC=/^on(?:Click|DoubleClick|AuxClick|MouseDown|MouseUp|PointerDown|PointerUp|TouchStart|TouchEnd|KeyDown|KeyUp|ContextMenu)(?:Capture)?$/;function eP(e){let t=e;for(;t;){if(t.isJSXElement()&&t.node.openingElement.attributes.some(n=>se.isJSXAttribute(n)&&se.isJSXIdentifier(n.name)&&QC.test(n.name.name)))return!0;t=t.parentPath}return!1}function Aa(e){let t=nt(e.source,"jsx-node");if(!t.ok)return t.result;let n=Mo(t.ast,e.locator,e.source);if(!n.ok)return n.result;let r=qC.safeParse({kind:"set-link-target",scope:"selection",link:e.link,changes:e.changes});if(!r.success||r.data.kind!=="set-link-target")return lr(e.source,"Invalid typed link-target changes");let o=n.match.path,i=o.node,s=i.openingElement,a=aP(s.name);if(!a)return lr(e.source,"Unsupported JSX link tag");if(s.attributes.some(se.isJSXSpreadAttribute))return lr(e.source,"Link elements with spread props cannot be transformed safely");let c=new Map;for(let m of s.attributes){if(!se.isJSXAttribute(m))continue;let p=zu(m);if(!p)return lr(e.source,"Unsupported JSX attribute name");let y=c.get(p)??[];y.push(m),c.set(p,y)}if([...c.values()].some(m=>m.length>1))return lr(e.source,"Duplicate JSX attributes cannot be transformed safely");let l=c.get("href")?.[0];if(l&&!sP(l))return lr(e.source,"Dynamic link href cannot be transformed safely");let u=a==="a",d=u?null:rP(o,s.name);if(!u&&!d)return lr(e.source,"Only native anchors and imported next/link components are supported");if(e.link.kind==="none"&&eP(o))return lr(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 m=oP(t.ast,o);if(!m.ok)return lr(e.source,m.reason);f=m.localName}if(d&&e.link.kind!=="internal-route"){let m=se.jsxIdentifier("a");s.name=m,i.closingElement&&(i.closingElement.name=se.jsxIdentifier("a")),iP(t.ast,d,o)}else f&&u&&(s.name=se.jsxIdentifier(f),i.closingElement&&(i.closingElement.name=se.jsxIdentifier(f)));let g=new Set;return e.link.kind==="none"?(g.add("href"),g.add("target"),g.add("rel"),Ph.forEach(m=>g.add(m))):(g.add("href"),e.link.kind==="native-link"&&Ph.forEach(m=>g.add(m))),s.attributes=s.attributes.filter(m=>{if(!se.isJSXAttribute(m))return!0;let p=zu(m);return!p||!g.has(p)}),e.link.kind!=="none"&&s.attributes.push(se.jsxAttribute(se.jsxIdentifier("href"),se.stringLiteral(e.link.href))),tP(s,e.changes),Xe(t.ast,e.source,{kind:"set-link-target",target:"jsx-node",inverse:"set-link-target"})}function tP(e,t){for(let n of t){let r=e.attributes.find(s=>se.isJSXAttribute(s)&&zu(s)===n.name);if(n.operation==="remove"){e.attributes=e.attributes.filter(s=>s!==r);continue}let o=typeof n.value=="string"?se.stringLiteral(n.value):se.jsxExpressionContainer(Xu(n.value)),i=se.jsxAttribute(se.jsxIdentifier(n.name),o);r&&se.isJSXAttribute(r)?r.value=i.value:e.attributes.push(i)}}function Xu(e){return e===null?se.nullLiteral():typeof e=="string"?se.stringLiteral(e):typeof e=="number"?se.numericLiteral(e):typeof e=="boolean"?se.booleanLiteral(e):Array.isArray(e)?se.arrayExpression(e.map(t=>Xu(t))):typeof e=="object"?se.objectExpression(Object.entries(e).map(([t,n])=>se.objectProperty(se.isValidIdentifier(t)?se.identifier(t):se.stringLiteral(t),Xu(n)))):se.nullLiteral()}function nP(e){return se.isImportDefaultSpecifier(e)||se.isImportSpecifier(e)&&e.importKind!=="type"&&(se.isIdentifier(e.imported,{name:"default"})||se.isStringLiteral(e.imported,{value:"default"}))}function Nh(e){return!e.parentPath?.isImportDeclaration()||e.parentPath.node.importKind==="type"?!1:e.isImportDefaultSpecifier()||e.isImportSpecifier()&&e.node.importKind!=="type"&&(se.isIdentifier(e.node.imported,{name:"default"})||se.isStringLiteral(e.node.imported,{value:"default"}))}function rP(e,t){if(!se.isJSXIdentifier(t))return null;let n=e.scope.getBinding(t.name);if(!n||!Nh(n.path))return null;let r=n.path.parentPath;return!r?.isImportDeclaration()||r.node.source.value!=="next/link"?null:t.name}function oP(e,t){let n=e.program.body.filter(c=>se.isImportDeclaration(c)&&c.source.value==="next/link"&&c.importKind!=="type"),r=n[0],o=n.flatMap(c=>c.specifiers).find(nP);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=se.importDefaultSpecifier(se.identifier(s));if(r)r.specifiers.unshift(a);else{let c=se.importDeclaration([a],se.stringLiteral("next/link")),l=0;for(;l<e.program.body.length&&se.isImportDeclaration(e.program.body[l]);)l+=1;e.program.body.splice(l,0,c)}return{ok:!0,localName:s}}function iP(e,t,n){let r=n.scope.getProgramParent();r.crawl();let o=r.getBinding(t);if(!o||!Nh(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 sP(e){return!e.value||se.isStringLiteral(e.value)}function aP(e){return se.isJSXIdentifier(e)?e.name:null}function zu(e){return se.isJSXIdentifier(e.name)?e.name.name:null}function lr(e,t){return ne(e,"unsupported-syntax",t,"jsx-node")}import*as Nt from"@babel/types";import{classifySiteEditPropertyName as Ah}from"@vcp-dev/contracts";function Ta(e){let t=Ah(e.name),n=Ah(e.property);if(t.owner!=="generic"||n.owner!=="generic")return ne(e.source,"unsupported-syntax","Property binding is only available for generic properties","jsx-node");if(!Th(e.object))return ne(e.source,"unsupported-syntax","Property binding object must be a single identifier","jsx-node");if(e.property.length===0)return ne(e.source,"unsupported-syntax","Property binding requires a non-empty property name","jsx-node");let r=nt(e.source,"jsx-node");if(!r.ok)return r.result;let o=Mo(r.ast,e.locator,e.source);if(!o.ok)return o.result;let i=o.match.path.node.openingElement,s=i.attributes.filter(l=>Nt.isJSXAttribute(l)&&lP(l)===e.name);if(s.length>1)return ne(e.source,"unsupported-syntax",`JSX attribute '${e.name}' has multiple sources`,"jsx-node");let a=cP(e.object,e.property),c=s[0];if(c)c.value=Nt.jsxExpressionContainer(a);else{let l=Mi(e.name,"");l.value=Nt.jsxExpressionContainer(a),i.attributes.push(l)}return Xe(r.ast,e.source,{kind:"set-property-binding",target:"jsx-node",inverse:"restore-property-binding"})}function cP(e,t){return Th(t)?Nt.memberExpression(Nt.identifier(e),Nt.identifier(t)):Nt.memberExpression(Nt.identifier(e),Nt.stringLiteral(t),!0)}function Th(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(e)}function lP(e){return Nt.isJSXIdentifier(e.name)?e.name.name:Nt.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:null}import{getBindingIdentifiers as dP,identifier as Ui,importDeclaration as fP,importDefaultSpecifier as pP,importNamespaceSpecifier as mP,importSpecifier as gP,isImportDefaultSpecifier as wh,isImportNamespaceSpecifier as Oh,isImportSpecifier as Fh,stringLiteral as hP}from"@babel/types";function xn(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(y=>!_P(y));if(o!==-1){let y=r[o],b=y&&typeof y=="object"&&"kind"in y?y.kind:void 0;return ne(t,"unsupported-syntax",`Unsupported import spec kind: ${String(b)}`)}let i=vP(r);if(!i.ok)return ne(t,"unsupported-syntax",i.message);let s=nt(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 E=RP(y,b);return E?[E]:[]}))),d=i.imports.filter(y=>!u.has($h(y)));if(d.length===0)return Di(t,t,{kind:"add-import",target:"import",inverse:"remove-import"});let f=IP(c.body),g=d.find(y=>f.has(Hu(y)));if(g)return ne(t,"unsupported-syntax",`Import local binding already exists: ${Hu(g)}`);let m=SP(d);if(m.reduce((y,b)=>y+b.length,0)!==d.length)return ne(t,"unsupported-syntax","Unsupported import specifier grouping");for(let y of m){if(!Bh(Dh(y)))return ne(t,"unsupported-syntax","Unsupported import specifier combination");let b=l.find(E=>yP(E,y));if(b)bP(b,y);else{let E=fP(Lh(y),hP(n));kP(c.body,E),l.push(E)}}return Xe(a,t,{kind:"add-import",target:"import",inverse:"remove-import"})}function yP(e,t){return e.importKind==="type"?!1:Bh(EP(xP(e),Dh(t)))}function bP(e,t){let n=!1,r=new Set(e.specifiers.map(o=>Wu(o)));for(let o of Lh(t)){let i=Wu(o);r.has(i)||(e.specifiers.push(o),r.add(i),n=!0)}return jh(e.specifiers),{changed:n}}function Lh(e){let t=e.map(n=>{switch(n.kind){case"named":return gP(n.local?Ui(n.local):Ui(n.imported),Ui(n.imported));case"default":return pP(Ui(n.local));case"namespace":return mP(Ui(n.local));default:return n}});return jh(t),t}function Dh(e){let t=Mh();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 xP(e){let t=Mh();for(let n of e.specifiers)wh(n)?t.defaultLocals.add(n.local.name):Oh(n)?t.namespaceLocals.add(n.local.name):t.hasNamed=!0;return t}function Mh(){return{defaultLocals:new Set,hasNamed:!1,namespaceLocals:new Set}}function EP(e,t){return{defaultLocals:new Set([...e.defaultLocals,...t.defaultLocals]),hasNamed:e.hasNamed||t.hasNamed,namespaceLocals:new Set([...e.namespaceLocals,...t.namespaceLocals])}}function Bh(e){return e.defaultLocals.size>1||e.namespaceLocals.size>1?!1:!(e.hasNamed&&e.namespaceLocals.size>0)}function jh(e){let t=[...e.filter(n=>wh(n)),...e.filter(n=>Oh(n)),...e.filter(n=>Fh(n))];e.splice(0,e.length,...t)}function SP(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 vP(e){let t=new Map,n=new Map;for(let r of e){let o=$h(r);if(t.has(o))continue;let i=Hu(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 IP(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(dP(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 kP(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 _P(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 $h(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 Hu(e){return e.kind==="named"?e.local??e.imported:e.local}function RP(e,t){return e.importKind==="type"||Fh(t)&&t.importKind==="type"?null:Wu(t)}function Wu(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 $o(e){let{source:t,moduleSpecifier:n,imports:r}=e,o=r.findIndex(u=>!PP(u));if(o!==-1){let u=r[o],d=u&&typeof u=="object"&&"kind"in u?u.kind:void 0;return ne(t,"unsupported-syntax",`Unsupported remove import spec kind: ${String(d)}`)}let i=nt(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 Di(t,t,{kind:"remove-import",target:"import",inverse:"add-import"});let l=a.body[c];return r.length===0?(a.body.splice(c,1),Xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"})):(l.specifiers=l.specifiers.filter(u=>!r.some(d=>CP(u,d))),l.specifiers.length===0&&a.body.splice(c,1),Xe(s,t,{kind:"remove-import",target:"import",inverse:"add-import"}))}function CP(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 PP(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 Vi(e){let{source:t,locator:n,next:r}=e,o=La(t,n);return o.ok?(o.path.replaceWith(Rr(r)),Xe(o.ast,t,{kind:"update-value",target:"value",inverse:"restore-value"})):o.result}function wa(e){let{source:t,locator:n,index:r,value:o}=e,i=La(t,n);return i.ok?i.path.isArrayExpression()?i.path.node.elements.some(s=>s?.type==="SpreadElement")?ne(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>i.path.node.elements.length?ne(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(i.path.node.elements.splice(r,0,Rr(o)),Xe(i.ast,t,{kind:"insert-array-element",target:"value",inverse:"remove-array-element"})):ne(t,"unsupported-syntax","Array operations require array expression target","value"):i.result}function Oa(e){let{source:t,locator:n,index:r}=e,o=La(t,n);return o.ok?o.path.isArrayExpression()?o.path.node.elements.some(i=>i?.type==="SpreadElement")?ne(t,"unsupported-syntax","Spread array elements are not supported","value"):r<0||r>=o.path.node.elements.length?ne(t,"array-index-out-of-range",`Array index ${r} is out of range`,"value"):(o.path.node.elements.splice(r,1),Xe(o.ast,t,{kind:"remove-array-element",target:"value",inverse:"insert-array-element"})):ne(t,"unsupported-syntax","Array operations require array expression target","value"):o.result}function Fa(e){let{source:t,locator:n,fromIndex:r,toIndex:o}=e,i=La(t,n);if(!i.ok)return i.result;if(!i.path.isArrayExpression())return ne(t,"unsupported-syntax","Array operations require array expression target","value");if(i.path.node.elements.some(c=>c?.type==="SpreadElement"))return ne(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 ne(t,"array-index-out-of-range","Array move indices are out of range","value");let[s]=i.path.node.elements.splice(r,1),a=Math.min(o,i.path.node.elements.length);return i.path.node.elements.splice(a,0,s),Xe(i.ast,t,{kind:"move-array-element",target:"value",inverse:"move-array-element-back"})}function La(e,t){let n=nt(e,"value");if(!n.ok)return{ok:!1,result:n.result};let r=Pe(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 Ot from"@babel/types";function Da(e){let t=nt(e.source,"value");if(!t.ok)return t.result;let n=Pe(t.ast,e.objectLocator);if(!n.ok)return{ok:!1,source:e.source,diagnostic:n.diagnostic};if(!n.match.path.isObjectExpression())return ne(e.source,"unsupported-syntax","Object property upsert requires an ObjectExpression parent","value");let r=n.match.path.node;if(r.properties.some(a=>Ot.isSpreadElement(a)||Ot.isObjectProperty(a)&&a.computed))return ne(e.source,"unsupported-syntax","Object property upsert does not support spreads or computed keys","value");let o=r.properties.filter(a=>Ot.isObjectProperty(a)&&NP(a.key)===e.name);if(o.length>1)return ne(e.source,"unsupported-syntax",`Object property '${e.name}' has multiple sources`,"value");let i=e.value.kind==="undefined"?Ot.unaryExpression("void",Ot.numericLiteral(0)):Rr(e.value.value),s=o[0];if(s)s.value=i,s.shorthand=!1;else{let a=Ot.objectProperty(Bu(e.name),i);e.name==="__proto__"&&(a.computed=!0),r.properties.push(a)}return Xe(t.ast,e.source,{kind:"upsert-object-property",target:"value",inverse:"restore-object-property"})}function NP(e){return Ot.isIdentifier(e)?e.name:Ot.isStringLiteral(e)?e.value:Ot.isNumericLiteral(e)?String(e.value):null}import{isSiteEditRuntimeContainerTag as AP,isSiteEditRuntimeVoidElementTag as TP}from"@vcp-dev/contracts/site-edit-runtime-capability";function Uo(e){if(!e.composition)throw new Error("Composition unavailable for render source graph.");return e.composition}function wP(e,t,n){let r=Uo(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,f=!d&&TP(u),g=d||AP(u),m=d&&i.childKeys.length>0&&!i.isPublicUiComponent,p=i.textSegments.length>0&&i.textSegments.some(S=>S.editable);f&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' is void: children cannot be inserted`}),!f&&!g&&!s.some(S=>S.kind==="void-element")&&s.push({kind:"void-element",message:`Element '${i.tag}' cannot contain structured children`});let y=p&&(!a||i.importedFrom==="next/link"),b=!i.isPublicUiComponent&&!f&&g&&(!a||m);return{composition:r,key:e,canUpdateText:y,canInsertChild:b,canMove:!l,canRemove:!l,constraints:s}}function Ma(e,t){let n=new Map;for(let r of e.nodes.keys())n.set(r,wP(r,e,t));return n}function Gu(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:Ae(e.route.source)},diagnostics:[{code:"source-locator-warning",message:`Key not found: ${e.key}`}]};let n=OP(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:Ae(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:Vh(r),version:{documentVersion:e.route.graph.version,contentHash:Ae(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()?FP(l.get("expression")):void 0;return{...i,sourceKind:a,attrRaw:Uh(e.route.source,o),valueRaw:s?Uh(e.route.source,s):null,...u===void 0?{}:{resolvedClassName:u},attrRange:Vh(o),diagnostics:[]}}function Kh(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 OP(e,t){let n=Un({source:e,profile:oo({filePath:t.sourceFile,source:e})});if(!n.ok)return null;let r=Pe(n.ast,{kind:"jsx-node",strategy:"structural-path",file:t.identity.file,component:t.identity.component,structuralPath:t.identity.structuralPath,expectedRange:LP(t.sourceRange)});return!r.ok||!r.match.path.isJSXElement()?null:r.match.path}function FP(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 Jh(e){let t=Un({source:`const __v = <div ${e} />;`,profile:"tsx-module"});if(!t.ok)return!1;let n=t.ast.program.body[0],o=(n?.type==="VariableDeclaration"?n.declarations[0]:null)?.init;if(o?.type!=="JSXElement")return!1;let i=o.openingElement.attributes;return i.length===1&&i[0]?.type==="JSXAttribute"&&i[0].name.type==="JSXIdentifier"&&i[0].name.name==="className"}function Uh(e,t){return t.start==null||t.end==null?"":e.slice(t.start,t.end)}function Vh(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 LP(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function Xh(){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 DP}from"node:crypto";import Ba from"node:fs/promises";import Yu from"node:path";import{setTimeout as MP}from"node:timers/promises";var BP={async mkdir(e,t){await Ba.mkdir(e,t)},async writeFile(e,t,n){await Ba.writeFile(e,t,n)},async rename(e,t){await Ba.rename(e,t)},async rm(e,t){await Ba.rm(e,t)}},jP=new Set(["EACCES","EBUSY","EPERM"]),$P=[10,20,40,80,160];async function UP(e,t,n){for(let r of $P)try{await e.rename(t,n);return}catch(o){if(!VP(o))throw o;await MP(r)}await e.rename(t,n)}function VP(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&jP.has(e.code)}async function ja(e,t,n=BP){let r=Yu.dirname(e),o=Yu.basename(e),i=Yu.join(r,`.${o}.${process.pid}.${DP()}.tmp`),s=!1;try{await n.mkdir(r,{recursive:!0}),await n.writeFile(i,t,"utf8"),await UP(n,i,e),s=!0}finally{if(!s)try{await n.rm(i,{force:!0})}catch{}}}import Zu from"@babel/traverse";import*as P from"@babel/types";import*as Be from"@babel/types";function Xn(e,t={}){if(Be.isTSAsExpression(e)||Be.isTSSatisfiesExpression(e)||Be.isTSNonNullExpression(e)||Be.isTypeCastExpression(e)||Be.isParenthesizedExpression(e))return Xn(e.expression,t);if(Be.isStringLiteral(e))return{status:"resolved",value:e.value};if(Be.isNumericLiteral(e))return Number.isFinite(e.value)?{status:"resolved",value:e.value}:{status:"unresolved"};if(Be.isBooleanLiteral(e))return{status:"resolved",value:e.value};if(Be.isNullLiteral(e))return{status:"resolved",value:null};if(Be.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(Be.isIdentifier(e))return e.name==="undefined"&&!t.resolveIdentifier?{status:"undefined"}:t.resolveIdentifier?.(e.name)??{status:"unresolved"};if(Be.isUnaryExpression(e)&&e.operator==="void"&&Be.isNumericLiteral(e.argument)&&e.argument.value===0)return{status:"undefined"};if(Be.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||Be.isSpreadElement(r))return{status:"unresolved"};let o=Xn(r,t);if(o.status!=="resolved")return{status:"unresolved"};n.push(o.value)}return{status:"resolved",value:n}}if(Be.isObjectExpression(e)){let n=Object.create(null);for(let r of e.properties){if(!Be.isObjectProperty(r)||r.computed||!Be.isExpression(r.value))return{status:"unresolved"};let o=KP(r.key);if(o===null)return{status:"unresolved"};let i=Xn(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 Be.isMemberExpression(e)||Be.isOptionalMemberExpression(e)?t.resolveMember?.(e)??{status:"unresolved"}:{status:"unresolved"}}function KP(e){return Be.isIdentifier(e)?e.name:Be.isStringLiteral(e)?e.value:Be.isNumericLiteral(e)?String(e.value):null}var JP=typeof Zu=="function"?Zu:Zu.default;function Bt(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 XP(e){return/^[A-Z]/.test(e)}function nd(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 Ko(e){return P.isJSXFragment(e)}function Hh(e){return P.isJSXIdentifier(e.name)?e.name.name:P.isJSXMemberExpression(e.name)?Wh(e.name):P.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`:"unknown"}function Wh(e){return P.isJSXIdentifier(e.object)?`${e.object.name}.${e.property.name}`:P.isJSXMemberExpression(e.object)?`${Wh(e.object)}.${e.property.name}`:e.property.name}function zP(e){return e.split(".")[0]??e}function HP(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 WP(){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 GP(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 ur(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)?ur(n.value,t):P.isRestElement(n)&&ur(n.argument,t);return t}if(P.isArrayPattern(e)){for(let n of e.elements)n&&(P.isRestElement(n)?ur(n.argument,t):ur(n,t));return t}return P.isAssignmentPattern(e)?(ur(e.left,t),t):(P.isRestElement(e)&&ur(e.argument,t),t)}function Nn(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ki(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 YP(e,t,n){e.set(t,{resolved:!0,value:n})}function rd(e,t){e.set(t,{resolved:!1})}function Gh(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 _t(e,t,n){if(P.isTSAsExpression(e)||P.isTSSatisfiesExpression(e)||P.isTSNonNullExpression(e)||P.isTypeCastExpression(e)||P.isParenthesizedExpression(e))return _t(e.expression,t,n);if(P.isLogicalExpression(e))return $a([_t(e.left,t,n),_t(e.right,t,n)]);if(P.isBinaryExpression(e))return $a([P.isExpression(e.left)?_t(e.left,t,n):null,P.isExpression(e.right)?_t(e.right,t,n):null]);if(P.isConditionalExpression(e))return $a([_t(e.consequent,t,n),_t(e.alternate,t,n)]);if(P.isTemplateLiteral(e))return $a(e.expressions.filter(P.isExpression).map(i=>_t(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=Nr(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:Nn(e,t),base:o.name,path:r}:null}function $a(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 od(e,t,n){if(P.isArrayExpression(e)){let r=e.elements[0];return e.elements.length===1&&P.isExpression(r)?_t(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)?od(e.callee.object,t,n):_t(e,t,n)}function Nr(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=Ki(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=Nr(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=Ki(r.value.name,t.valueScopes);if(s.kind!=="resolved")return;i=s.value}else i=Nr(r.value,t);if(i===void 0)return;n[o]=i}return n}if(P.isMemberExpression(e)){let n=_t(e,"",t);if(!n)return;let r=Ki(n.base,t.valueScopes);if(r.kind!=="resolved")return;let o=Gh(r.value,n.path);return o.kind==="resolved"?o.value:void 0}if(P.isCallExpression(e))return Zh(e,t)??void 0}function Yh(e,t,n){let r=_t(e,n,t);if(!r)return P.isMemberExpression(e)||P.isBinaryExpression(e)||P.isLogicalExpression(e)||P.isConditionalExpression(e)||P.isCallExpression(e)?{value:Nn(e,n),source:null}:null;let o=Ki(r.base,t.valueScopes),i=r.kind==="identifier"?o:o.kind==="resolved"?Gh(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 qu(e,t,n,r,o,i){return{file:e,componentName:t,elements:n,regions:r,ordinalTracker:WP(),parentStack:[],valueScopes:i,importMap:o}}function ed(e,t,n){for(let r of e)for(let o of r.declarations){for(let s of ur(o.id))rd(n,s);if(!P.isIdentifier(o.id)||!o.init||!P.isExpression(o.init))continue;let i=Nr(o.init,t);i!==void 0&&YP(n,o.id.name,i)}}function ZP(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 qP(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:Bt(i),editable:!0,source:null})}else if(P.isJSXExpressionContainer(i)&&P.isStringLiteral(i.expression))r.push({index:o++,value:i.expression.value,sourceRange:Bt(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:Bt(i),editable:!0,source:null}):r.push({index:o++,value:Nn(s,n),sourceRange:Bt(i),editable:!0,source:_t(s,n,t)})}else if(P.isJSXExpressionContainer(i)&&P.isExpression(i.expression)){let s=Yh(i.expression,t,n);s&&r.push({index:o++,value:s.value,sourceRange:Bt(i),editable:!0,source:s.source})}return r}function QP(e,t,n){let r=[];for(let[o,i]of e.attributes.entries()){if(!P.isJSXAttribute(i))continue;let s=tN(i.name);if(!s)continue;let a=Nn(i,n);if(P.isStringLiteral(i.value)){r.push({name:s,value:i.value.value,sourceRange:Bt(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:Bt(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=Nr(i.value.expression,t);if(s==="className"){let g=typeof c=="string"?c:c===void 0?Zh(i.value.expression,t):null;if(g){r.push({name:s,value:g,sourceRange:Bt(i),source:null,resolvedValue:g,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:g}});continue}}let l=Yh(i.value.expression,t,n);if(c!==void 0){r.push({name:s,value:cN(c),sourceRange:Bt(i),source:_t(i.value.expression,n,t),resolvedValue:c,syntaxKind:"expression",raw:a,order:o,resolution:{status:"resolved",value:c}});continue}let u=nN(i.value.expression,t),d=_t(i.value.expression,n,t),f=l?.value??Nn(i.value.expression,n);r.push({name:s,value:u.status==="undefined"?"undefined":f,sourceRange:Bt(i),source:l?.source??d,syntaxKind:"expression",raw:a,order:o,resolution:u})}}return r}function eN(e,t,n){return e.attributes.flatMap((r,o)=>!P.isJSXSpreadAttribute(r)||!P.isExpression(r.argument)?[]:[{raw:Nn(r.argument,n),sourceRange:Bt(r),order:o,source:_t(r.argument,n,t)}])}function tN(e){return P.isJSXIdentifier(e)?e.name:P.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function nN(e,t){return Xn(e,{resolveIdentifier(n){let r=Ki(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=Nr(n,t);return r===void 0?{status:"unresolved"}:{status:"resolved",value:r}}})}function Zh(e,t){let n=Vo(e,t);return n&&n.map(o=>o.trim()).filter(Boolean).join(" ")||null}function Vo(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=Nr(e,t);return typeof n=="string"?[n]:null}if(P.isConditionalExpression(e)){let n=Vo(e.consequent,t),r=Vo(e.alternate,t);return!n||!r?null:[...n,...r]}if(P.isLogicalExpression(e)){if(e.operator!=="&&")return null;let n=Nr(e.left,t);return n===!1||n===null?[]:Vo(e.right,t)}if(P.isArrayExpression(e)){let n=[];for(let r of e.elements){if(!r||P.isSpreadElement(r))return null;let o=Vo(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=oN(r.key);if(!o)return null;n.push(o)}return n}if(P.isCallExpression(e)){let n=rN(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=Vo(o,t);if(!i)return null;r.push(...i)}return r}return null}function rN(e){return P.isIdentifier(e)?e.name:P.isMemberExpression(e)&&P.isIdentifier(e.property)?e.property.name:null}function oN(e){return P.isIdentifier(e)?e.name:P.isStringLiteral(e)?e.value:null}function iN(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 sN(e,t){for(let n of t){let r=iN(e,n);if(r)return r}return null}function aN(e){return P.isJSXIdentifier(e.name)?e.name.name:null}function cN(e){return e===null?"null":typeof e=="boolean"?e?"true":"false":JSON.stringify(e)}function lN(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 Qu(e){return P.isArrowFunctionExpression(e)||P.isFunctionExpression(e)}function uN(e){return e==="render"||e==="itemRender"||e==="rowRender"||e==="children"}function dN(e){return e==="empty"||e==="emptyRender"||e==="loading"||e==="loadingRender"||e==="error"||e==="errorRender"||e==="fallback"||e==="headerRender"||e==="footerRender"}function zh(e,t,n,r){if(!e||!P.isExpression(e))return null;let o={kind:"repeat-template",collectionExpression:Nn(e,n),collectionSource:od(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 dr(e,t,n){if(!e)return[];if(P.isJSXElement(e)){if(nd(e))return Xa(e.children,t,n);let r=Ka(e,t,n);return r?[r]:[]}return Ko(e)?Ja(e,t,n):P.isParenthesizedExpression(e)?dr(e.expression,t,n):P.isExpression(e)?za(e,t,n):[]}function Ua(e,t,n){let r=new Map;for(let o of e.params)for(let i of ur(o))rd(r,i);t.valueScopes.push(r);try{if(!P.isBlockStatement(e.body))return dr(e.body,t,n);let o=new Map;t.valueScopes.push(o);try{return qh(e.body.body,t,n)}finally{t.valueScopes.pop()}}finally{t.valueScopes.pop()}}function qh(e,t,n){let r=[];for(let o of e){if(P.isVariableDeclaration(o)){let i=t.valueScopes[t.valueScopes.length-1];if(i){ed([o],t,i);for(let s of o.declarations)P.isIdentifier(s.id)&&(P.isJSXElement(s.init)||P.isJSXFragment(s.init))&&r.push(...dr(s.init,t,n))}continue}r.push(...td(o,t,n))}return r}function td(e,t,n){if(P.isReturnStatement(e))return e.argument?dr(e.argument,t,n):[];if(P.isBlockStatement(e))return mo(e.body,t,n);if(P.isIfStatement(e)){let r=P.isBlockStatement(e.consequent)?mo(e.consequent.body,t,n):td(e.consequent,t,n),o=e.alternate?P.isBlockStatement(e.alternate)?mo(e.alternate.body,t,n):td(e.alternate,t,n):[];return[...r,...o]}if(P.isSwitchStatement(e))return mo(e.cases.flatMap(r=>r.consequent),t,n);if(P.isTryStatement(e)){let r=mo(e.block.body,t,n);return e.handler&&r.push(...mo(e.handler.body.body,t,n)),e.finalizer&&r.push(...mo(e.finalizer.body,t,n)),r}return[]}function mo(e,t,n){let r=new Map;t.valueScopes.push(r);try{return qh(e,t,n)}finally{t.valueScopes.pop()}}function Va(e,t,n,r,o,i){o.length!==0&&e.regions.push({kind:t,ownerKey:n,childKeys:o,sourceRange:Bt(r),sourceCandidates:i&&i.length>0?i:void 0})}function fN(e,t,n,r){let o=sN(e.openingElement,["items","dataSource","data"]),i={key:t,tag:Hh(e.openingElement)};n.parentStack.push(i);try{for(let s of e.openingElement.attributes){if(!P.isJSXAttribute(s))continue;let a=aN(s);if(!a||!P.isJSXExpressionContainer(s.value))continue;let c=s.value.expression;if(!P.isJSXEmptyExpression(c)){if(uN(a)&&Qu(c)){let l=Ua(c,n,r),u=zh(o,c,r,n);Va(n,"repeat-region",t,s,l,u?[u]:void 0);continue}if(dN(a)){let l=Qu(c)?Ua(c,n,r):dr(c,n,r);Va(n,"conditional-region",t,s,l)}}}if(o)for(let s of e.children){if(!P.isJSXExpressionContainer(s)||!Qu(s.expression))continue;let a=Ua(s.expression,n,r),c=zh(o,s.expression,r,n);Va(n,"repeat-region",t,s,a,c?[c]:void 0)}}finally{n.parentStack.pop()}}function Ka(e,t,n){let r=Hh(e.openingElement);if(r==="Fragment"||nd(e))return Xa(e.children,t,n),null;let o=t.parentStack[t.parentStack.length-1]??null,i=o?.key??null,s=XP(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=Bi(t.file,t.componentName,l),d={file:t.file,component:t.componentName,structuralPath:l,key:u},f=s?"component-boundary":null,g=qP(e.children,t,n),m=QP(e.openingElement,t,n),p=eN(e.openingElement,t,n),y,b,E=!1;if(s){let S=t.importMap.get(r)??t.importMap.get(zP(r));S&&(y=S.specifier,b=S.exportName,E=io(S.specifier,t.file))}let x={identity:d,tag:r,componentName:t.componentName,sourceFile:t.file,sourceRange:Bt(e),parentKey:i,childKeys:[],textSegments:g,attributes:m.length>0?m:void 0,attributeSpreads:p.length>0?p:void 0,boundaryKind:f,isOpaque:s,...E?{isPublicUiComponent:!0}:{},importedFrom:y,exportName:b};return t.elements.set(u,x),i&&t.elements.has(i)&&t.elements.get(i).childKeys.push(u),fN(e,u,t,n),(!s||e.children.length>0)&&(t.parentStack.push({key:u,tag:r}),pN(e.children,t,n),t.parentStack.pop()),u}function Ja(e,t,n){return Xa(e.children,t,n)}function Xa(e,t,n){let r=[];for(let o of e)if(P.isJSXElement(o))if(nd(o))r.push(...Xa(o.children,t,n));else{let i=Ka(o,t,n);i&&r.push(i)}else Ko(o)?r.push(...Ja(o,t,n)):P.isJSXExpressionContainer(o)&&r.push(...za(o.expression,t,n));return r}function pN(e,t,n){for(let r of e)P.isJSXElement(r)?Ka(r,t,n):Ko(r)?Ja(r,t,n):P.isJSXExpressionContainer(r)&&za(r.expression,t,n)}function mN(e){return e==="&&"||e==="||"||e==="??"}function za(e,t,n){if(P.isJSXEmptyExpression(e))return[];let r=lN(e);if(r){let o=r.call,i=t.parentStack[t.parentStack.length-1]??null,s=[],a=r.callback,c={kind:"repeat-template",collectionExpression:Nn(r.collection,n),collectionSource:od(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:Bt(o),sourceCandidates:s.length>0?s:void 0};return t.regions.push(l),(P.isArrowFunctionExpression(a)||P.isFunctionExpression(a))&&l.childKeys.push(...Ua(a,t,n)),l.childKeys}if(P.isConditionalExpression(e)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Nn(e.test,n),conditionSource:_t(e.test,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Bt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...dr(e.consequent,t,n)),s.childKeys.push(...dr(e.alternate,t,n)),s.childKeys}if(P.isLogicalExpression(e)&&mN(e.operator)){let o=t.parentStack[t.parentStack.length-1]??null,i={kind:"conditional-branch",conditionExpression:Nn(e.left,n),conditionSource:_t(e.left,n,t)},s={kind:"conditional-region",ownerKey:o?.key??"",childKeys:[],sourceRange:Bt(e),sourceCandidates:[i]};return t.regions.push(s),s.childKeys.push(...dr(e.right,t,n)),s.childKeys}if(P.isParenthesizedExpression(e))return za(e.expression,t,n);if(P.isJSXElement(e)){let o=Ka(e,t,n);return o?[o]:[]}return Ko(e)?Ja(e,t,n):[]}function gN(e){let t=e.argument;return t&&(P.isExpression(t)||Ko(t))?t:null}function Ji(e,t){let n=[];for(let r of e){if(P.isReturnStatement(r)){let o=gN(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(...Ji(o,r.test)),r.alternate){let i=P.isBlockStatement(r.alternate)?r.alternate.body:[r.alternate];n.push(...Ji(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(...Ji(o.consequent,i))}}return n}function Ha(e){return{routeId:e,rootKeys:[],elements:new Map,regions:[],fileIndex:new Map,version:1,diagnostics:[]}}function Qh(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:Ha(t),localImports:o};let s=new Map,a=[],c=[],l=new Map,u=GP(r);JP(r,{"FunctionDeclaration|FunctionExpression|ArrowFunctionExpression"(f){let g=HP(f);if(!g)return;let m=f.node,p=[];if(P.isArrowFunctionExpression(m))P.isExpression(m.body)||Ko(m.body)?p=[{argument:m.body,statement:P.returnStatement(P.isExpression(m.body)?m.body:null)}]:P.isBlockStatement(m.body)&&(p=Ji(m.body.body));else{let v=m.body;P.isBlockStatement(v)&&(p=Ji(v.body))}if(p.length===0){f.skip();return}let y=new Map;ed(ZP(r.program.body),qu(t,g,s,a,u,[y]),y);let b=new Map;for(let v of m.params)for(let N of ur(v))rd(b,N);let E=P.isBlockStatement(m.body)?m.body.body:[],x=p[0]?.statement??null;for(let v of E){if(x&&v===x)break;P.isVariableDeclaration(v)&&ed([v],qu(t,g,s,a,u,[y,b]),b)}let S=qu(t,g,s,a,u,[y,b]);for(let v of p){let N=dr(v.argument,S,n);for(let R of N)c.includes(R)||c.push(R);if(v.condition){let R={kind:"conditional-branch",conditionExpression:Nn(v.condition,n),conditionSource:_t(v.condition,n,S)};Va(S,"conditional-region","",v.statement,N,[R])}}f.skip()}});let d=[...s.keys()];return d.length>0&&l.set(t,d),{graph:{routeId:t,rootKeys:c,elements:s,regions:a,fileIndex:l,version:1,diagnostics:[]},localImports:o}}function id(e,t,n,r){return[...e.map(o=>({...o})),{fromFile:t,specifier:n,targetPath:r}]}function Wa(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 Jo(e,t,n,r,o={}){let i=o.maxDepth??10,s=o.version??1,a=o.parseModule??_e,c=new Map,l=new Map,u=new Map,d=[],f=new Set,g=b=>{let E=`${b.path}\0${b.code}\0${b.message}\0${JSON.stringify(b.details??{})}`;f.has(E)||(f.add(E),d.push(b))},m=[{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:[]}))],p=new Set;for(;m.length>0;){let b=m.shift(),{file:E,source:x,depth:S,diagnosticEntryFile:v,importStack:N}=b;if(p.has(E))continue;p.add(E),c.set(E,x);let R=o.validationOnly&&S<i?o.validatedImports?.(E,x):void 0,A,C;if(R)A=Ha(E),C=R;else{let B=a(E,x);if(!B.ok){g(Wa(B.diagnostic,v,N));continue}u.set(E,B.module);let G=o.validationOnly&&S<i?{graph:Ha(E),localImports:B.module.imports.map(K=>K.specifier)}:Qh(B.module);A=G.graph,C=G.localImports}let w=[...new Set([...A.elements.values()].map(B=>B.importedFrom).filter(B=>typeof B=="string"&&pt(B)))],M=w.length?await ey(w,B=>ca(E,B,r)):[],D=new Map(w.map((B,G)=>[B,M[G]]));for(let B of A.elements.values())if(B.importedFrom&&pt(B.importedFrom)){let G=B.importedFrom,K=D.get(G);K.ok?(B.importedFrom=K.path,sr(K.path)&&(B.isPublicUiComponent=!0)):io(G,E)||g(Wa(K.diagnostic,v,id(N,E,G,K.diagnostic.path)))}if(l.set(E,A),S>=i)continue;let U=await ey(C,async B=>{if(Fg(B))return null;let G=D.get(B)??await ca(E,B,r);if(!G.ok)return io(B,E)?null:{diagnostic:Wa(G.diagnostic,v,id(N,E,B,G.diagnostic.path))};let K=G.path;if(p.has(K)||sr(K))return null;let ge=id(N,E,B,K);try{let oe=await n(K);return{entry:{file:K,source:oe,depth:S+1,diagnosticEntryFile:v,importStack:ge}}}catch(oe){return{diagnostic:Wa({path:K,code:"import-read-failed",message:`Failed to read imported file: ${K}`,details:{fromFile:E,specifier:B,reason:oe instanceof Error?oe.message:String(oe)}},v,ge)}}});for(let B of U)B&&"entry"in B?m.push(B.entry):B&&g(B.diagnostic)}let y=hN(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 hN(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 ty(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 XN}from"@vcp-dev/contracts";import{createHash as yN,randomUUID as gd}from"node:crypto";import dt from"node:fs/promises";import gt from"node:path";var dy=new WeakMap;function Xo(e){return dy.get(e)?.()??e.readIndex()}var En=1,ad=1,bN=2,xN="index.json",EN="recovery.json",SN="transaction-journal.json",vN="document-version.json",Za={maxEntries:100,maxSessionBytes:512*1024*1024,maxEntryBytes:128*1024*1024},Ee={INVALID_ROOT:"INVALID_ROOT",INVALID_PATH:"INVALID_PATH",INVALID_SCHEMA:"INVALID_SCHEMA",INVALID_JSON:"INVALID_JSON",INDEX_CORRUPT:"INDEX_CORRUPT",ENTRY_CORRUPT:"ENTRY_CORRUPT",BLOB_CORRUPT:"BLOB_CORRUPT",RECOVERY_PENDING:"RECOVERY_PENDING",CAPACITY_EXCEEDED:"CAPACITY_EXCEEDED",NOT_FOUND:"NOT_FOUND"},ve=class extends Error{constructor(t,n,r){super(n),this.name="FileHistoryStoreError",this.code=t,r?.cause!==void 0&&(this.cause=r.cause)}};function fr(){return{entries:new Map,blobSizes:new Map}}function Ga(e,t){let n={entries:new Map,blobs:new Map,objectBytes:0};for(let r of e)fy(n,r,t);return n}function fy(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 py(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 my(e,t={}){let n=jN(e),r=KN(t.limits),o=sd(n),i=$N(n),s=await Wt(i),a=await Wt(o)||s;a||(await TN(n),await wN(n)),a||await JN(n);let c=fr(),l=await Qa(n,c),u=new Set(a?(await oc(n)).map(E=>E.stageId):[]);a||await sy(n,l.entryIds,c);let d=l.digest,f=Ga(l.entryIds,c),g=async E=>{let{index:x,sizeBytes:S}=await Gi(n);if(Sy(x,E),x.digest!==d){let v=fr();await by(n,x.entryIds,v,S),f=Ga(x.entryIds,v),d=x.digest}return{...ic(x),totalBytes:f.objectBytes+S}},m=async E=>{hd(E),await g(),await oy(n,f,[E.entryId],E.blobIds,E.stageId),await qa(n,E.stageId)},p=async(E,x)=>{let S=await g(x);hy(E,S.entryIds.length);let v=fr();for(let N of S.entryIds.slice(Math.min(S.cursor,E)+1,Math.max(S.cursor,E)+1))await zi(n,N,v);return S},y=async()=>{if(await Wt(o)||s)throw new ve(Ee.RECOVERY_PENDING,"history store requires explicit recovery before accepting writes")},b={rootDir:n,recoveryRequired:a,async readDocumentVersion(){return ly(n)},async writeDocumentVersion(E){if(await y(),!Number.isInteger(E)||E<0)throw new ve(Ee.INVALID_SCHEMA,"document version must be a non-negative integer");let x=await ly(n);E<=x||await Xi(_y(n),{schemaVersion:1,version:Math.max(x,E)})},async stageAppend(E,x={}){await y();let S=await _N(E,r),v={schemaVersion:ad,stageId:gd(),entryId:S.entryId,blobIds:S.blobs.map(N=>N.digest)};try{await RN(n,S),await PN(n,v,x.durableManifest!==!1)}catch(N){try{await m(v)}catch(R){throw new ve(Ee.INDEX_CORRUPT,"staged history cleanup failed after preparation error",{cause:R})}throw N}return{stageId:v.stageId,entryId:v.entryId,blobIds:v.blobIds}},async discardStage(E){await y(),ud(E);let x=await cd(n,E);x&&await m(x)},async previewStagedAppend(E,x){await y();let S=await g(x);return(await ny(n,r,E,S,f)).transition},async previewCursor(E,x){await y();let S=await p(E,x);return gy(S,S.entryIds,E)},async publishStagedAppend(E,x,S){if(await y(),tc(E,"entryId"),S){ud(S);let C=await cd(n,S);if(!C||C.entryId!==E)throw new ve(Ee.INVALID_SCHEMA,"history stage does not match the published entry")}let v=await g(x),N=f,R=await ny(n,r,E,v,N),A=await cy({rootDir:n,previousDigest:R.current.digest,entryIds:R.entryIds,cursor:R.cursor,readback:async()=>ay(n,R.usage),afterWrite:async()=>{S?await qa(n,S):await AN(n,E),await oy(n,R.usage,[...N.entries.keys()].filter(C=>!R.usage.entries.has(C)),[...N.blobs.keys()].filter(C=>!R.usage.blobs.has(C)))}});return f=R.usage,d=A.digest,A},async append(E){await y();let x=await g(),S=await b.stageAppend(E);try{return await b.publishStagedAppend(S.entryId,x.digest,S.stageId)}catch(v){throw await b.discardStage(S.stageId),v}},async readEntry(E){return tc(E,"entryId"),zi(n,E)},async readBlob(E){tc(E,"blobId");let x=await Cy(n,E),S=await Hi(x,Ee.NOT_FOUND,"blob");return ky(S,E,x),S},async readIndex(){let E=fr(),x=await Qa(n,E);return f=Ga(x.entryIds,E),d=x.digest,x},async readStatus(){let E=await ec(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 Wt(o)||await Wt(i)}},async readUndoRedoIds(){let E=await ec(n);return{undoIds:E.undoIds,redoIds:E.redoIds,currentId:E.currentId}},async setCursor(E,x){await y();let S=await p(E,x),v=await cy({rootDir:n,previousDigest:S.digest,entryIds:S.entryIds,cursor:E,readback:async()=>ay(n,f)});return d=v.digest,v},async markRecoveryRequired(E){await Wt(o)||await Xi(sd(n),{schemaVersion:En,reason:UN(E),createdAt:new Date().toISOString()})},async clearRecoveryRequired(){await dt.rm(sd(n),{force:!0})},async readTransactionJournal(){return await Wt(i)?Ya(i):null},async writeTransactionJournal(E){await y(),Ry(E);try{await Xi(i,E)}catch(S){let v=await Ya(i).catch(()=>null);if(v&&Buffer.from(Gt(v)).equals(Buffer.from(Gt(E))))return;throw v?new ve(Ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous",{cause:S}):S}let x=await Ya(i);if(!Buffer.from(Gt(x)).equals(Buffer.from(Gt(E))))throw new ve(Ee.INDEX_CORRUPT,"transaction journal publish outcome is ambiguous")},async clearTransactionJournal(E){let x=await Wt(i)?await Ya(i):null;if(x&&x.transactionId!==E)throw new ve(Ee.INVALID_SCHEMA,"transaction journal changed concurrently");try{await dt.rm(i,{force:!0})}catch(S){if(!await Wt(i))return;throw S}if(await Wt(i))throw new ve(Ee.INDEX_CORRUPT,"transaction journal clear outcome is ambiguous");s=!1},async cleanupTmp(){await y();for(let S of u)await qa(n,S),u.delete(S);await ON(n);let E=fr(),x=await Qa(n,E);await sy(n,x.entryIds,E),f=Ga(x.entryIds,E),d=x.digest}};return dy.set(b,()=>ec(n)),b}async function ny(e,t,n,r,o){tc(n,"entryId");let i=fr(),s=await zi(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))py(a,u);fy(a,s.id,i),c.push(s.id);let l=CN(c,t,a);return{current:r,entryIds:l.entryIds,cursor:l.cursor,usage:a,transition:gy(r,l.entryIds,l.cursor)}}function gy(e,t,n){return hy(n,t.length),{expectedIndexDigest:e.digest,publishedIndexDigest:IN(t,n),publishedCursor:n,publishedCurrentId:t[n]??null}}function IN(e,t){return Ar(Gt({schemaVersion:En,entryIds:e,cursor:t}))}function hy(e,t){if(!Number.isInteger(e)||e<-1||e>=t)throw new ve(Ee.INVALID_SCHEMA,`history cursor is out of bounds: ${e}`)}function kN(e){if(!An(e))return!1;let t=e.publishedCursor,n=e.publishedCurrentId;return!rn(e.expectedIndexDigest)||!rn(e.publishedIndexDigest)||!Number.isInteger(t)||t<-1||n!==null&&!rn(n)?!1:t===-1?n===null:rn(n)}async function _N(e,t){if(!e.kind.trim())throw new ve(Ee.INVALID_JSON,"history entry kind must not be empty");let n=[],r=[];for(let c of e.blobs??[]){if(!c.name.trim())throw new ve(Ee.INVALID_JSON,"history blob name must not be empty");let l=BN(c.data),u=Ar(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:En,kind:e.kind,manifest:e.manifest,blobs:r},i=Gt({...o}),s=Ar(i),a=i.byteLength+n.reduce((c,l)=>c+l.sizeBytes,0);if(a>t.maxEntryBytes)throw new ve(Ee.CAPACITY_EXCEEDED,`history entry exceeds maxEntryBytes (${a} > ${t.maxEntryBytes})`);return{entryBody:o,entryId:s,blobs:n}}async function RN(e,t){let n=Ed(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=>ry(Sd(e,c.digest),c.bytes,{kind:"blob",digest:c.digest},Id(e,c.digest))),ry(n,Gt(r),{kind:"entry",digest:t.entryId},vd(e,t.entryId))],a=(await Promise.allSettled(i)).find(c=>c.status==="rejected");if(a)throw a.reason}async function ry(e,t,n,r){let o=await pd(e)??(r?await pd(r):null);if(o!==null){if(Buffer.compare(o,t)!==0)throw new ve(n.kind==="blob"?Ee.BLOB_CORRUPT:Ee.ENTRY_CORRUPT,`${n.kind} content mismatch for ${n.digest}`);return}await vy(e,t)}function CN(e,t,n){let r=[...e],o=r.length-1;for(;;){if(n.objectBytes+Gt(Ey(r,o)).byteLength<=t.maxSessionBytes&&r.length<=t.maxEntries)return{entryIds:r,cursor:o};if(o<=0||r.length===0)throw new ve(Ee.CAPACITY_EXCEEDED,"history store exceeds capacity limits and the current entry cannot be trimmed");py(n,r.shift()),o-=1}}async function PN(e,t,n){hd(t);let r=xd(e,t.stageId);if(n){await Xi(r,t);return}await MN(r,t)}async function cd(e,t){let n=await pd(xd(e,t));if(n===null)return null;let r=Yi(Buffer.from(n).toString("utf8"),`history stage ${t}`),o=hd(r);if(o.stageId!==t)throw new ve(Ee.INVALID_SCHEMA,`history stage id mismatch: ${t}`);return o}async function oc(e){let t=[];for(let n of await rc(bd(e))){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);ud(r);let o=await cd(e,r);o&&t.push(o)}return t}async function oy(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 oc(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 iy(Ed(e,a),vd(e,a));for(let a of new Set(r))!t.blobs.has(a)&&!s.has(a)&&await iy(Sd(e,a),Id(e,a));await md(Zi(e)),await md(qi(e))}async function qa(e,t){await ld(xd(e,t)),await NN(e)}async function NN(e){try{await dt.rmdir(bd(e))}catch(t){if(Qi(t)||An(t)&&t.code==="ENOTEMPTY")return;throw t}}async function AN(e,t){for(let n of await oc(e))n.entryId===t&&await qa(e,n.stageId)}async function ld(e){if(await dt.rm(e,{force:!0}),await Wt(e))throw new ve(Ee.INDEX_CORRUPT,`unable to remove staged history object: ${e}`)}async function iy(e,t){await ld(e),await ld(t)}function hd(e){if(!An(e)||e.schemaVersion!==ad||typeof e.stageId!="string"||!yy(e.stageId)||!rn(e.entryId))throw new ve(Ee.INVALID_SCHEMA,"history stage schema is invalid");let t=Iy(e.blobIds,"history stage blobIds");return{schemaVersion:ad,stageId:e.stageId,entryId:e.entryId,blobIds:t}}function ud(e){if(!yy(e))throw new ve(Ee.INVALID_PATH,"history stageId must be a UUID")}function yy(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 sy(e,t,n=fr()){let r=new Set(t),o=new Set;for(let l of t){let u=await zi(e,l,n);for(let d of u.blobs)o.add(d.digest)}for(let l of await oc(e)){r.add(l.entryId);for(let u of l.blobIds)o.add(u)}let i=Zi(e),s=await rc(i);for(let l of s){if(!l.endsWith(".json"))continue;let u=uy(l.slice(0,-5));u&&!r.has(u)&&await nc(gt.join(i,l))}let a=qi(e),c=await rc(a);for(let l of c){let u=uy(l);u&&!o.has(u)&&await nc(gt.join(a,l))}}async function Qa(e,t=fr()){let{index:n,sizeBytes:r}=await Gi(e),{totalBytes:o}=await by(e,n.entryIds,t,r);return{...ic(n),totalBytes:o}}async function ay(e,t){let{index:n,sizeBytes:r}=await Gi(e);return{...ic(n),totalBytes:t.objectBytes+r}}async function Gi(e){let t=yd(e),n=await Hi(t,Ee.NOT_FOUND,"index"),r=Yi(Buffer.from(n).toString("utf8"),"index");return{index:FN(r),sizeBytes:n.byteLength}}async function ec(e){return ic((await Gi(e)).index)}function ic(e){let t=[...e.entryIds],n=t.slice(0,e.cursor+1).reverse(),r=t.slice(e.cursor+1);return{schemaVersion:En,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 Gi(e)).sizeBytes;for(let s of new Set(t)){let a=await zi(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 zi(e,t,n=fr()){let r=n.entries.get(t);if(r)return r.entry;let o=await VN(e,t),i=await Hi(o,Ee.NOT_FOUND,"entry"),s=Yi(Buffer.from(i).toString("utf8"),`entry ${t}`),a=LN(s);if(a.id!==t)throw new ve(Ee.ENTRY_CORRUPT,`entry id mismatch for ${t}`);if(Ar(Gt({schemaVersion:a.schemaVersion,kind:a.kind,manifest:a.manifest,blobs:a.blobs}))!==t)throw new ve(Ee.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 Cy(e,d),g=await Hi(f,Ee.NOT_FOUND,"blob");return ky(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,m=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(E){f.push({index:b,error:E})}}}),p=await Promise.allSettled(m),y=f.sort((b,E)=>b.index-E.index)[0];if(y)throw y.error;for(let b of p)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 xy(e,t,n){await Xi(yd(e),Ey(t,n))}function Ey(e,t){return{schemaVersion:En,digest:Ar(Gt({schemaVersion:En,entryIds:e,cursor:t})),entryIds:e,cursor:t}}function Sy(e,t){if(t!==void 0&&e.digest!==t)throw new ve(Ee.INVALID_SCHEMA,`history index changed concurrently (expected ${t}, current ${e.digest})`)}async function cy(e){Sy(await ec(e.rootDir),e.previousDigest);let t=Ar(Gt({schemaVersion:En,entryIds:e.entryIds,cursor:e.cursor}));try{await xy(e.rootDir,e.entryIds,e.cursor),await e.afterWrite?.();let n=await e.readback();if(n.digest!==t)throw new ve(Ee.INDEX_CORRUPT,"history index readback did not match the published transition");return n}catch(n){let r=await Qa(e.rootDir).catch(()=>null);if(r?.digest===t)return r;throw r?.digest===e.previousDigest?n:new ve(Ee.INDEX_CORRUPT,"history index publish outcome is ambiguous",{cause:n})}}async function TN(e){await dt.mkdir(e,{recursive:!0}),await dt.mkdir(Zi(e),{recursive:!0}),await dt.mkdir(qi(e),{recursive:!0}),await dt.mkdir(Wi(e),{recursive:!0})}async function wN(e){await dt.rm(Wi(e),{recursive:!0,force:!0}),await dt.mkdir(Wi(e),{recursive:!0})}async function ON(e){let t=Wi(e);await dt.mkdir(t,{recursive:!0});for(let n of await rc(t))n!=="stages"&&await dt.rm(gt.join(t,n),{recursive:!0,force:!0})}function FN(e){if(!An(e))throw new ve(Ee.INDEX_CORRUPT,"index.json must be an object");if(e.schemaVersion!==En)throw new ve(Ee.INVALID_SCHEMA,`unsupported index schemaVersion: ${String(e.schemaVersion)}`);let t=Iy(e.entryIds,"index.entryIds"),n=e.cursor;if(!Number.isInteger(n)||n<-1||n>=t.length)throw new ve(Ee.INDEX_CORRUPT,"index cursor is out of bounds");let r=n,o=e.digest;if(!rn(o))throw new ve(Ee.INDEX_CORRUPT,"index digest is invalid");let i=Ar(Gt({schemaVersion:En,entryIds:t,cursor:r}));if(o!==i)throw new ve(Ee.INDEX_CORRUPT,"index digest mismatch");return{schemaVersion:En,digest:o,entryIds:t,cursor:r}}function LN(e){if(!An(e))throw new ve(Ee.ENTRY_CORRUPT,"entry must be an object");if(e.schemaVersion!==En)throw new ve(Ee.INVALID_SCHEMA,`unsupported entry schemaVersion: ${String(e.schemaVersion)}`);let t=e.id;if(!rn(t))throw new ve(Ee.ENTRY_CORRUPT,"entry id is invalid");let n=e.kind;if(typeof n!="string"||n.trim().length===0)throw new ve(Ee.ENTRY_CORRUPT,"entry kind is invalid");let r=fd(e.manifest,"entry.manifest"),o=DN(e.blobs);return{id:t,schemaVersion:En,kind:n,manifest:r,blobs:o}}function DN(e){if(!Array.isArray(e))throw new ve(Ee.ENTRY_CORRUPT,"entry blobs must be an array");return e.map((t,n)=>{if(!An(t))throw new ve(Ee.ENTRY_CORRUPT,`entry blob ref ${n} must be an object`);let r=t.name;if(typeof r!="string"||r.trim().length===0)throw new ve(Ee.ENTRY_CORRUPT,`entry blob ref ${n} name is invalid`);let o=t.digest;if(!rn(o))throw new ve(Ee.ENTRY_CORRUPT,`entry blob ref ${n} digest is invalid`);let i=t.sizeBytes;if(!Number.isInteger(i)||i<0)throw new ve(Ee.ENTRY_CORRUPT,`entry blob ref ${n} sizeBytes is invalid`);return{name:r,digest:o,sizeBytes:i}})}async function Xi(e,t){await vy(e,Gt(t))}async function MN(e,t){let n=gt.dirname(e),r=gt.basename(e),o=gt.join(n,`.${r}.${process.pid}.${gd()}.tmp`);await dt.mkdir(n,{recursive:!0});try{await dt.writeFile(o,Gt(t),{flag:"wx"}),await dt.rename(o,e)}finally{await nc(o)}}async function vy(e,t){let n=gt.dirname(e),r=gt.basename(e),o=gt.join(n,`.${r}.${process.pid}.${gd()}.tmp`);await dt.mkdir(n,{recursive:!0});try{let i=await dt.open(o,"wx");try{await i.writeFile(t),await i.sync()}finally{await i.close()}await dt.rename(o,e),await md(n)}finally{await nc(o)}}function Gt(e){return Buffer.from(JSON.stringify(dd(e)),"utf8")}function dd(e){if(Array.isArray(e))return e.map(t=>dd(t));if(An(e)){let t={};for(let n of Object.keys(e).sort())t[n]=dd(e[n]);return t}return e}function Yi(e,t){try{return JSON.parse(e)}catch(n){throw new ve(Ee.INVALID_JSON,`${t} is not valid JSON`,{cause:n})}}function fd(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=>fd(n,t));if(An(e)){let n={};for(let[r,o]of Object.entries(e))n[r]=fd(o,t);return n}break}throw new ve(Ee.INVALID_JSON,`${t} must be JSON-serializable`)}function Iy(e,t){if(!Array.isArray(e))throw new ve(Ee.INDEX_CORRUPT,`${t} must be an array`);return e.map((n,r)=>{if(!rn(n))throw new ve(Ee.INDEX_CORRUPT,`${t}[${r}] is invalid`);return n})}function tc(e,t){if(!rn(e))throw new ve(Ee.INVALID_PATH,`${t} must be a sha256 digest`)}function rn(e){return typeof e=="string"&&/^sha256:[a-f0-9]{64}$/u.test(e)}function Ar(e){return`sha256:${yN("sha256").update(e).digest("hex")}`}function BN(e){return typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}async function Hi(e,t,n){try{return await dt.readFile(e)}catch(r){throw new ve(t,`${n} not found: ${e}`,{cause:r})}}async function pd(e){try{return await dt.readFile(e)}catch(t){if(Qi(t))return null;throw t}}function ky(e,t,n){if(Ar(e)!==t)throw new ve(Ee.BLOB_CORRUPT,`blob hash mismatch for ${n}`)}async function Wt(e){try{return await dt.access(e),!0}catch(t){if(Qi(t))return!1;throw t}}async function nc(e){try{await dt.rm(e,{force:!0,recursive:!0})}catch{}}async function md(e){try{let t=await dt.open(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function rc(e){try{return await dt.readdir(e)}catch(t){if(Qi(t))return[];throw t}}function jN(e){if(typeof e!="string"||e.trim().length===0)throw new ve(Ee.INVALID_ROOT,"history store rootDir must be a non-empty string");return gt.resolve(e)}function yd(e){return gt.join(e,xN)}function sd(e){return gt.join(e,EN)}function $N(e){return gt.join(e,SN)}function _y(e){return gt.join(e,vN)}async function ly(e){try{let t=await dt.readFile(_y(e),"utf8"),n=Yi(t,"document version");if(!An(n)||n.schemaVersion!==1||!Number.isInteger(n.version)||n.version<0)throw new ve(Ee.INVALID_SCHEMA,"document version schema is invalid");return n.version}catch(t){if(Qi(t))return 0;throw t}}async function Ya(e){let t=await Hi(e,Ee.RECOVERY_PENDING,"transaction journal"),n=Yi(Buffer.from(t).toString("utf8"),"transaction journal");return Ry(n),n}function Ry(e){if(!An(e)||e.schemaVersion!==bN||typeof e.transactionId!="string"||e.transactionId.length===0||typeof e.operationId!="string"||e.operationId.length===0||!["prepared","files-written","history-published"].includes(e.phase)||!kN(e.historyTransition)||!Array.isArray(e.files))throw new ve(Ee.INVALID_SCHEMA,"transaction journal schema is invalid");for(let t of e.files)if(!An(t)||typeof t.path!="string"||t.path.length===0||t.preDigest!==null&&!rn(t.preDigest)||t.postDigest!==null&&!rn(t.postDigest))throw new ve(Ee.INVALID_SCHEMA,"transaction journal file digest is invalid")}function UN(e){return e.replace(/[\r\n]+/g," ").slice(0,512)}function Zi(e){return gt.join(e,"entries")}function qi(e){return gt.join(e,"blobs")}function Wi(e){return gt.join(e,"tmp")}function bd(e){return gt.join(Wi(e),"stages")}function xd(e,t){return gt.join(bd(e),`${t}.json`)}function Ed(e,t){return gt.join(Zi(e),`${Ny(t)}.json`)}function Sd(e,t){return gt.join(qi(e),Ny(t))}function vd(e,t){return gt.join(Zi(e),`${t}.json`)}function Id(e,t){return gt.join(qi(e),t)}async function VN(e,t){return Py(Ed(e,t),vd(e,t))}async function Cy(e,t){return Py(Sd(e,t),Id(e,t))}async function Py(e,t){return await Wt(e)?e:await Wt(t)?t:e}function Ny(e){return e.slice(7)}function uy(e){let t=e.startsWith("sha256:")?e:`sha256:${e}`;return rn(t)?t:null}function An(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qi(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function KN(e){return{maxEntries:e?.maxEntries??Za.maxEntries,maxSessionBytes:e?.maxSessionBytes??Za.maxSessionBytes,maxEntryBytes:e?.maxEntryBytes??Za.maxEntryBytes}}async function JN(e){let t=yd(e);await Wt(t)||await xy(e,[],-1)}var zN={affectedCompositions:[]};function Fy(e){let t=null,n=new WeakMap;async function r(){return t??=HN(e),t}async function o(i){if(!i)return null;let s=kd(i);return s?WN(e,s):i}return{async prepareAppend(i){let s=await Xo(e),a=await e.stageAppend(wy(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 Xo(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 Xo(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);Ay(c,i.historyTransition),i.entry.historyId=s.entryId,Object.assign(a,zo(c))}else{if(s.cursor===void 0)throw new Error("prepared cursor is missing");let c=i.kind==="undo"?a.undo:a.redo;if(kd(c.at(-1))!==kd(i.entry))throw new Error("history state changed before publish");let l=await e.setCursor(s.cursor,s.expectedDigest);Ay(l,i.historyTransition),Object.assign(a,zo(l))}n.delete(i)},async discardPrepared(i){let s=n.get(i);if(!s)return;let a=i.historyTransition;if(a){let c=await Xo(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,zo(d));return}catch(d){throw s.redo.push(i),d}}let c=await e.append(wy(i)),l=c.currentId;if(!l)throw new Error("history store did not publish an entry");i.historyId=l,Object.assign(s,zo(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,zo(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 Ay(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 kd(e){return typeof e=="string"?e:e?.historyId}async function HN(e){let t=await Xo(e);return zo(t)}function zo(e){return{undo:[...e.undoIds].reverse(),redo:[...e.redoIds].reverse(),entryIds:[...e.entryIds],cursor:e.cursor}}async function WN(e,t){let n=await e.readEntry(t),r=GN(n),o=r.provenance??zN;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 Ty(e,n,r.preSnapshots),postSnapshots:await Ty(e,n,r.postSnapshots)}}async function Ty(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(qN(r,o.blobName))).toString("utf8"):"";return{file:o.file,content:i,version:o.version,exists:o.exists,...o.sha256?{sha256:o.sha256}:{}}}))}function wy(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=YN(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 GN(e){if(!Dy(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:Ly(t.provenance)}:{},preSnapshots:Oy(t.preSnapshots,"preSnapshots"),postSnapshots:Oy(t.postSnapshots,"postSnapshots")}}function YN(e){if(e.provenance!==void 0)return Ly(e.provenance);if(e.composition)return{initiatingComposition:e.composition,affectedCompositions:[]}}function Ly(e){let t=XN.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 Oy(e,t){return e.map((n,r)=>{if(!Dy(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&&!ZN(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 ZN(e){return/^sha256:[0-9a-f]{64}$/.test(e)}function qN(e,t){let n=e.get(t);if(!n)throw new Error(`durable history blob is missing: ${t}`);return n}function Dy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{GeneratedSiteCapabilitiesSchema as QN}from"@vcp-dev/contracts";var My={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 _d(){let e=QN.safeParse(My);return e.success?e.data:null}import{randomBytes as eA}from"node:crypto";import sc from"node:path";import{parse as Jy}from"@babel/parser";import tA from"@babel/traverse";import*as Xy from"@babel/types";import{COMPONENT_I18N_FILE_SUFFIX as Cd,PageResourceArtifactSchema as nA,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as rA,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as oA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as iA,parseComponentI18nResourcesJson as sA}from"@vcp-dev/contracts";var Pd="{{$INSTANCE}}",aA=/\{\{\$PAGE_ROUTE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,cA=/\{\{\$PAGE_TITLE:([a-zA-Z0-9][a-zA-Z0-9_-]*)\}\}/g,Nd="components/site/generated",lA=/\.(?:tsx?|json)$/,uA=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,dA=["react","react/","next","next/","lucide-react","@/components/ui/","@/components/site/","@/lib/","@/hooks/"],fA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Rd=tA,pA=typeof Rd=="function"?Rd:Rd.default;async function Ad(e){let t=nA.safeParse(e.artifact);if(!t.success)return ft("Page resource artifact failed contract validation.");let n=t.data,r=e.randomHex??(()=>eA(4).toString("hex")),o=Math.max(1,Math.min(e.maxAttempts??5,5)),i=vA(r());if(!i)return ft("Random instance suffix must be 8 lowercase hex chars.");let s=`${IA(n.resource_id)}-${i}`,a=new Map,c=new Map,l=[];for(let x of n.pages){let S=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/${S}/page.tsx`})}let u=[],d=new Set,f=new Set,g=new Map,m=new Map,p=[],y=new Set(n.pages.flatMap(x=>x.components.map(S=>S.component_id)));for(let x of n.components){if(!y.has(x.component_id))continue;let S=By({materialization:x.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c});if(!S.ok)return S;for(let v of S.files){let N=$y(v,d,u);if(N)return N}f.add(S.entry),m.set(S.entry,S.entryExport),g.set(x.component_id,S.entry)}for(let[x,S]of n.pages.entries()){let v=l[x],N=By({materialization:S.materialization,packageInstanceId:s,routeByPage:a,titleByPage:c,pageEntryTarget:v.route_file_path,pageTitle:v.title});if(!N.ok)return N;for(let R of N.files){let A=$y(R,d,u);if(A)return A}f.add(N.entry),m.set(N.entry,N.entryExport),p.push({entry:N.entry,declaredComponentIds:new Set(S.components.map(R=>R.component_id))})}let b=gA(u,f,s,g,p,m);if(!b.ok)return b;for(let x of u)if(await e.exists(x.file))return!x.file.startsWith("app/")&&o>1?Ad({...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 E=hA(u);return E||(u.sort((x,S)=>x.file.localeCompare(S.file)),{ok:!0,packageInstanceId:s,pages:l,files:u})}function By(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:jy(o.pathTemplate,e.packageInstanceId);if(!s)return ft("Materialization path cannot be mapped into the package namespace.",o.pathTemplate);let a=mA(o.content,e.packageInstanceId,e.routeByPage,e.titleByPage);if(!a.ok)return a;let c=i&&e.pageTitle!==void 0?bA(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??jy(t,e.packageInstanceId);return!r||!n.some(o=>o.file===r)?ft("Materialization entry must match one controlled source file.",t):{ok:!0,files:n,entry:r,entryExport:e.materialization.entry.export}}function mA(e,t,n,r){let o,i=e.replace(aA,(c,l)=>{let u=n.get(l);return u||(o=l,c)});if(o)return ft(`Page route placeholder references unknown template page: ${o}`);let s=i.replace(cA,(c,l)=>{let u=r.get(l);return u?JSON.stringify(u):(o=l,c)});if(o)return ft(`Page title placeholder references unknown template page: ${o}`);let a=s.replaceAll(Pd,t);return a.includes("{{$PAGE_ROUTE:")||a.includes("{{$PAGE_TITLE:")||a.includes("{{$INSTANCE}}")?ft("Materialization contains an unresolved placeholder."):{ok:!0,data:a}}function jy(e,t){let n=`${Nd}/${t}`;if(e.split(Pd).length>2)return null;let o=e.replace(Pd,t),i=`${Nd}/${t}/`,s=o.startsWith(i)?o:`${n}/${o}`,a=sc.posix.normalize(s);return a!==s||!a.startsWith(`${n}/`)||!lA.test(a)||uA.test(a)?null:a}function $y(e,t,n){return t.has(e.file)?ft(`Page resource materializations resolve duplicate target: ${e.file}`,e.file):(t.add(e.file),n.push(e),null)}function gA(e,t,n,r,o,i){let s=new Set(e.map(g=>g.file)),a=`${Nd}/${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 ft("Materialization JSON file must contain valid JSON.",g.file)}if(g.file.endsWith(Cd)&&!sA(g.content).success)return ft("Materialization component i18n resources are invalid.",g.file);continue}try{let m=Jy(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 b=y.source.value,E=EA(g.file,b,s,a);if(!E.allowed)return ft(`Materialization import is outside the controlled package: ${b}`,g.file);E.internalPath&&c.get(g.file).add(E.internalPath)}let p;if(pA(m,{Identifier(y){y.isReferencedIdentifier()&&fA.has(y.node.name)&&(p??=y.node.name,y.stop())},JSXOpeningElement(y){y.node.name.type==="JSXIdentifier"&&y.node.name.name.toLowerCase()==="style"&&(p??="style element",y.stop())}}),p)return ft(`Materialization source uses forbidden capability: ${p}`,g.file)}catch{return ft("Materialization source must parse as TS/TSX.",g.file)}}if([...t].some(g=>!s.has(g)))return ft("Materialization entry is outside the controlled package.");for(let g of t)if(g.endsWith(".json"))return ft("Materialization JSON files cannot be package entries.");for(let[g,m]of i){let p=l.get(g);if(!p||!yA(p,m))return ft("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=Ky(g.entry,c);for(let p of g.declaredComponentIds){let y=r.get(p);if(!y||!m.has(y))return ft(`Page entry does not reach declared component: ${p}`,g.entry)}for(let p of m){let y=u.get(p);if(y&&!g.declaredComponentIds.has(y))return ft(`Page entry imports undeclared component: ${y}`,g.entry)}}let d=new Set;for(let g of t)for(let m of Ky(g,c))d.add(m);if(d.size!==e.length)return ft("Every materialization file must be reachable from a package entry.");let f=SA(e,l,c);return f||{ok:!0}}function hA(e){if(e.length>rA)return ft("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>oA)return ft("Page resource file exceeds the content byte limit.",n.file);t+=r}return t>iA?ft("Page resource exceeds the aggregate content byte limit."):null}function yA(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 bA(e,t,n){let r;try{r=Jy(e,{sourceType:"module",sourceFilename:n,plugins:["jsx","typescript"]})}catch{return ft("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=Uy(s.init);if(a?.type!=="ObjectExpression")return{ok:!0,data:e};let c=a.properties.find(u=>u.type==="ObjectProperty"&&!u.computed&&xA(u.key));if(!c||c.type!=="ObjectProperty")return{ok:!0,data:e};let l=Uy(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 Uy(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression"||t?.type==="TSNonNullExpression";)t=t.expression;return t&&Xy.isExpression(t)?t:null}function xA(e){return e.type==="Identifier"&&e.name==="title"||e.type==="StringLiteral"&&e.value==="title"}function EA(e,t,n,r){if(t.startsWith(`@/${r}/`)){let s=t.slice(2),a=Vy(s,n);return a?{allowed:!0,internalPath:a}:{allowed:!1}}if(!t.startsWith("."))return{allowed:dA.some(s=>s.endsWith("/")?t.startsWith(s):t===s)};if(t.includes("\\")||t.includes("\0"))return{allowed:!1};let o=sc.posix.normalize(sc.posix.join(sc.posix.dirname(e),t)),i=Vy(o,n);return i&&(i.startsWith(`${r}/`)||i.startsWith("app/"))?{allowed:!0,internalPath:i}:{allowed:!1}}function Vy(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 SA(e,t,n){let r=new Set(e.map(o=>o.file));for(let o of e){if(!o.file.endsWith(Cd))continue;let i=o.file.slice(0,-Cd.length),s=[`${i}.tsx`,`${i}.ts`].find(u=>r.has(u));if(!s)return ft("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 ft("Component i18n resources must have exactly one same-name Client Component static importer.",s)}return null}function Ky(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 vA(e){return/^[a-f0-9]{8}$/.test(e)?e:null}function IA(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"page-resource"}function ft(e,t){return{ok:!1,code:"MATERIALIZATION_REJECTED",message:e,...t?{path:t}:{}}}import{randomBytes as GA}from"node:crypto";import mr from"node:path";import{parse as YA}from"@babel/parser";import ZA from"@babel/traverse";import{COMPONENT_I18N_FILE_SUFFIX as cc,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as qy,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as qA,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as QA,SiteEditMaterializationSchema as eT,parseComponentI18nResourcesJson as tT}from"@vcp-dev/contracts";import{parse as jA}from"@babel/parser";import $A from"@babel/traverse";import{GeneratedSiteCapabilitiesSchema as UA,FormDefinitionIdSchema as VA}from"@vcp-dev/contracts";var Hy={colorMixPolicy:"always",includeExtendedColorFunctions:!0},Wy=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\(/i,Gy=/\b(?:bg-black|bg-white|text-white|text-black)(?:\b|\/)/g,kA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke)-\[#(?:[0-9a-fA-F]{3,8})\](?:\/\d+)?/g,_A=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*#[0-9a-fA-F]{3,8}[^'"]*['"]/g,RA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*rgba?\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,CA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,PA=/\b(?:color|backgroundColor|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*rgba?\([^)]+\)[^'"]*['"]/gi,NA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*(?:oklch|lab|lch|hsla?)\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,AA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*(?:oklch|lab|lch|hsla?)\([^)]+\)[^'"]*['"]/gi,TA=/\b(?:bg|text|border|ring|outline|decoration|divide|from|via|to|fill|stroke|shadow)-\[[^\]]*color-mix\([^\]]+\)[^\]]*\](?:\/\d+)?/gi,wA=/\b(?:color|backgroundColor|backgroundImage|background|borderColor|boxShadow|textShadow)\s*:\s*['"][^'"]*color-mix\([^'"]*['"]/gi,OA=/\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,FA=/var\(\s*--(?:_|private-|vcp-)[^)]+\)/gi,LA=/#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|hwb|oklch|oklab|lab|lch|color)\s*\([^)]*\)/gi;function Td(e,t){let n=ac([...Sn(e,kA),...Sn(e,_A),...Sn(e,RA),...Sn(e,t.includeRgbBackgroundImage?CA:PA),...t.includeExtendedColorFunctions?[...Sn(e,NA),...Sn(e,AA)]:[]]),r=ac([...Sn(e,TA),...Sn(e,wA)]).filter(o=>t.colorMixPolicy==="always"||Wy.test(o));return n.push(...r.filter(o=>!n.includes(o))),t.rejectTailwindPalette&&n.push(...Sn(e,OA).filter(o=>!n.includes(o))),t.rejectAnyRawColorLiteral&&n.push(...Sn(e,LA).filter(o=>!n.includes(o))),{hardCodedSurfaceHits:ac(Sn(e,Gy)),hardCodedSurfaceOccurrences:BA(e),rawColorHits:n,privateTokenHits:t.rejectPrivateTokens?DA(e):[]}}function DA(e){return ac(Sn(e,FA))}function Sn(e,t){return e.match(new RegExp(t.source,t.flags))??[]}var zy=160,MA=/((?:[a-z][a-z0-9-]*(?:\[[^\]]*\])?:)+)$/;function BA(e){let t=new RegExp(Gy.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=MA.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>zy?`${g.slice(0,zy-1)}\u2026`:g})}return o}function ac(e){return[...new Set(e)]}var KA=["@/components/site/","@/lib/generated/","@/lib/cms","@/lib/cms/"],JA=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Yy=new Set(["require","module","exports","__dirname","__filename"]),wd=$A,XA=typeof wd=="function"?wd:wd.default;function Fd(e,t={}){let n=[],r=zA(t.hostCapabilities),o=Td(e,t.style??Hy),i;try{i=jA(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"&&WA(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 XA(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(Od(u.node))},OptionalMemberExpression(u){l(Od(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)&&VA.safeParse(/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(u)?.[1]).success)&&!(u.startsWith("./")||u.startsWith("../"))){if(t.allowSiteOwnedImports&&KA.some(d=>d.endsWith("/")?u.startsWith(d):u===d)){c(u);return}r?HA(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||!JA.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:Yy.has(u)?"commonjs-forbidden":"browser-global-forbidden",message:Yy.has(u)?`Generated source cannot depend on the CommonJS global ${u}.`:`Generated source cannot depend on the restricted global ${u}.`,name:u})}}}function zA(e){if(e==null)return null;let t=UA.safeParse(e);return t.success?t.data:null}function HA(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)):Zy(n)===Zy(o)})}function Zy(e){return e.replace(/\.(?:jsx?|tsx?|json)$/i,"")}function WA(e){return e.hardCodedSurfaceHits.length>0||e.rawColorHits.length>0||e.privateTokenHits.length>0}function Od(e){return e.type==="Identifier"?e.name:e.type==="MemberExpression"||e.type==="OptionalMemberExpression"?Od(e.object):null}var ob="components/site/generated",Qy="{{$INSTANCE}}",lc=5,nT=/^[a-z][a-z0-9-]{0,48}$/,rT=/^[a-f0-9]{8}$/,eb=/\.tsx?$/,oT=/\.json$/,iT=/\.(?:tsx?|json)$/,sT=/(?:^|\/)(?:layout|provider|globals?|[^/]+\.config)\.tsx?$/i,Ld=new Set(["document","eval","fetch","Function","globalThis","localStorage","location","module","navigator","process","require","sessionStorage","window","__dirname","__filename","exports"]),Dd=ZA,aT=typeof Dd=="function"?Dd:Dd.default;function cT(e){let t=Array.isArray(e.manifest.files)?e.manifest.files:[];if(t.length>qy)return{ok:!1,error:{code:"MATERIALIZATION_LIMIT_EXCEEDED",message:"Static prefab file count exceeds the reusable limit."}};let n=IT(t);if(n)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Static prefab resolves duplicate target path: ${n}`,path:n}};let r=eT.safeParse(e.manifest);if(!r.success)return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab manifest failed schema validation."}};let o=ET(e.generatedRoot);if(!o)return{ok:!1,error:{code:"MATERIALIZATION_PATH_INVALID",message:`Generated root must be ${ob}.`,path:e.generatedRoot}};if(!ib(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=nb(r.data.files),s=nb(e.controlledFiles);if(!kT(i,s))return{ok:!1,error:{code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Controlled file list must exactly match the manifest file templates."}};if(i.size>qy)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>qA)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>QA?{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 lT(e){let t=cT(e);if(!t.ok)return t;let n=t.data.generatedRoot,r=ib(e.manifest.instanceBaseName),o=Math.max(1,Math.min(lc,e.maxAttempts??lc));for(let i=0;i<o;i+=1){let s=ST(e.instanceNameGenerator?.()??GA(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=ab(n,a),l=uT({manifest:e.manifest,generatedRoot:n,instanceName:a,instanceRoot:c,hostCapabilities:e.hostCapabilities??null,availableHostDependencies:e.availableHostDependencies});if(!l.ok)return l;if(!await fT(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 Md(e){let t=Math.max(1,Math.min(lc,e.maxAttempts??lc));for(let n=0;n<t;n+=1){let r=await lT({...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 uT(e){let t=dT(e);if(t)return{ok:!1,error:t};let n=[],r=new Set;for(let s of e.manifest.files){let a=es({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=es({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=Bd({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 dT(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 fT(e,t,n){if(await e(t))return!0;for(let r of n)if(await e(r.path))return!0;return!1}function es(e){if(e.pathTemplate.split(Qy).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(Qy,e.instanceName),n=vT(t);return n?ab(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||!iT.test(n)||sT.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 Bd(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(oT.test(g.path)){if(g.path.endsWith(cc)){let b=tT(g.content);if(!b.success)return pr("MATERIALIZATION_DATA_UNSUPPORTED",b.error.message,g.path);u.set(g.path,new Set)}else try{JSON.parse(g.content)}catch{return pr("MATERIALIZATION_DATA_UNSUPPORTED","Static prefab JSON file must contain valid JSON.",g.path)}continue}let m;try{m=YA(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 p=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=mT(p.violations,g.path);if(y)return{ok:!1,error:y};c.set(g.path,m)}for(let g of t){if(!eb.test(g.path))continue;let m=c.get(g.path),p=null;if(aT(m,{ImportDeclaration(y){let b=tb({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});if(!b.allowed)p??={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&&!gT(y.node.source.value,i,s))p??={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(cc))){let E=yT({importer:g.path,imported:b.internalPath,source:y.node.source.value,ast:m});E.ok?u.get(b.internalPath).add(g.path):(p??=E.error,y.stop())}},ExportAllDeclaration(y){p??={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=tb({importer:g.path,source:y.node.source.value,instanceRoot:n,filePaths:a});!b.allowed||!b.internalPath&&!e.trustedManagedImports?.includes(y.node.source.value)?(p??={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"){p??={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"&&(p??={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"&&(p??={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"&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Static prefab files cannot use import.meta.",file:g.path},y.stop())},MemberExpression(y){let b=rb(y.node);b&&Ld.has(b)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:g.path},y.stop())},OptionalMemberExpression(y){let b=rb(y.node);b&&Ld.has(b)&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:`Static prefab files cannot depend on ${b}.`,file:g.path},y.stop())},Identifier(y){y.isReferencedIdentifier()&&Ld.has(y.node.name)&&(p??={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"||pT(y.node.value)||(p??={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"&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Static prefab source cannot declare style elements.",file:g.path},y.stop())},StringLiteral(y){e.preserveCapturedStyles&&uc(y.node.value)&&(p??={code:"MATERIALIZATION_STYLE_FORBIDDEN",message:"Captured styles cannot load URLs or execute CSS expressions.",file:g.path},y.stop())},TemplateElement(y){e.preserveCapturedStyles&&uc(y.node.value.cooked??y.node.value.raw)&&(p??={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())&&(p??={code:"MATERIALIZATION_DATA_UNSUPPORTED",message:"Captured components cannot embed executable external documents.",file:g.path},y.stop())}}),p)return{ok:!1,error:p}}if(r.length===0)return pr("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 pr("MATERIALIZATION_PATH_INVALID",`Static prefab contains duplicate source entries: ${g.path}`,g.path);if(d.add(g.path),!eb.test(g.path))return pr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must be a .ts/.tsx source module.",g.path);let m=c.get(g.path);if(!m)return pr("MATERIALIZATION_ENTRY_INVALID","Static prefab entry must resolve to a controlled source file.",g.path);if(!bT(m,g.export))return pr("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 pr("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 m of xT(g.path,l))f.add(m);return f.size!==t.length?pr("MATERIALIZATION_ENTRY_INVALID","Every controlled source file must be reachable from the entry module.",r[0]?.path):{ok:!0}}function uc(e){return/(?:url|expression)\s*\(|@import|javascript:|-moz-binding|\\/iu.test(e)}function pT(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"||uc(n))return!1;let r=t.value;return r.type==="StringLiteral"&&!uc(r.value)||r.type==="NumericLiteral"||r.type==="NullLiteral"||r.type==="UnaryExpression"&&["-","+"].includes(r.operator)&&r.argument.type==="NumericLiteral"})}function mT(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 tb(e){if(!e.source.startsWith("./")&&!e.source.startsWith("../"))return{allowed:!0};if(e.source.includes("\\")||e.source.includes("\0"))return{allowed:!1};let t=mr.posix.normalize(mr.posix.join(mr.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 gT(e,t,n){if(n===null)return!0;let r=hT(e);return r===null||t.has(r)&&n.has(r)}function hT(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 yT(e){let t=mr.posix.dirname(e.importer),n=mr.posix.dirname(e.imported),r=mr.posix.basename(e.importer).replace(/\.tsx?$/,""),o=mr.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 bT(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 xT(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 pr(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{file:n}:{}}}}function ET(e){let t=sb(e);return t===ob?t:null}function ST(e){let t=e.trim().toLowerCase();return rT.test(t)?t:null}function ib(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 nT.test(t)?t:null}function sb(e){if(!e||e.startsWith("/")||e.includes("\\"))return null;let t=mr.posix.normalize(e);return t==="."||t.startsWith("../")||t.includes("/../")||t.includes("//")?null:t}function vT(e){let t=sb(e);return!t||t!==e?null:t}function ab(...e){return mr.posix.join(...e)}function nb(e){return new Set(e.map(t=>t.pathTemplate))}function IT(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 kT(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function rb(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 df}from"node:crypto";import rf from"@babel/traverse";function jd(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 dc(e){if(e.node.alternate||!_T(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 _T(e){let t=cb(e);return e.traverse({enter(n){cb(n)||(t=!1,n.stop())}}),t}function cb(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 GT}from"node:crypto";import xb from"node:path";import*as Go from"@babel/parser";import Wd from"@babel/traverse";import Gd from"@babel/generator";import*as me from"@babel/types";import Jd from"@babel/generator";import{parse as DT}from"@babel/parser";import Xd from"@babel/traverse";import*as Te from"@babel/types";import{PortableInvocationBindingSchema as MT}from"@vcp-dev/contracts";import $d from"@babel/traverse";import*as Fe from"@babel/types";var lb=typeof $d=="function"?$d:$d.default;function jt(e){let t=db(e.module,e.exportName,e.parsedModules??new Map([[e.module.file,e.module]]),new Set);return t?ub(t,e.allowNonRenderingGuards):Tr("component-export-unresolved","The requested local component export is not a statically resolvable function.",e.module.file)}function vn(e){let t=RT(e.module,e.componentName,e.callSourceRange);return t.kind==="local"?ub(t.definition):t.kind==="imported"?!e.imported?.module&&!pt(t.specifier)?Tr("component-external-module-opaque","External package components are opaque to the local source graph.",t.specifier):e.imported?e.imported.module?jt({module:e.imported.module,exportName:e.imported.exportName,parsedModules:e.imported.parsedModules}):Tr("component-module-unavailable","The component source module is unavailable in the parsed graph.",e.imported.file):Tr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file):Tr("component-local-binding-unresolved","The JSX call does not resolve to a statically declared local component function.",e.module.file)}function ub(e,t=!1){let n=TT(e.module.ast,e.node);if(!n)return Tr("component-function-unresolved","The component function has no source AST path.",e.module.file);let r=fb(n,t);if(!r){let s=OT(n);return s?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:!1,roots:[s[0]],returnAlternatives:s}:Tr("component-control-flow-unsupported","Component roots require an expression body or one direct return.",e.module.file)}let o=[],i=pb(r);return pc(r,o)?{ok:!0,componentName:e.name,sourceFile:e.module.file,metadataOnly:i,roots:o}:Tr("component-root-dynamic","Component return contains an unsupported dynamic or spread root.",e.module.file)}function RT(e,t,n){let r={kind:"unresolved"};return lb(e.ast,{JSXElement(o){if(!NT(o.node.loc,n))return;let i=o.node.openingElement.name;if(!Fe.isJSXIdentifier(i)||i.name!==t)return;let s=o.scope.getBinding(t);if(!s||s.constantViolations.length>0){o.stop();return}if(CT(s.path)){let c=s.path.parentPath;c?.isImportDeclaration()&&(r={kind:"imported",specifier:c.node.source.value}),o.stop();return}let a=PT(s.path);a&&(r={kind:"local",definition:{node:a,name:t,module:e}}),o.stop()}}),r}function CT(e){return e.isImportSpecifier()||e.isImportDefaultSpecifier()||e.isImportNamespaceSpecifier()}function PT(e){if(e.isFunctionDeclaration())return e.node;if(!e.isVariableDeclarator())return null;let t=e.get("init");return!Array.isArray(t)&&Kd(t.node)?t.node:null}function NT(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 db(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=Ir(e.file,u,n),g=f?n.get(f):void 0;return g?db(g,d,n,i):null},a=u=>{let d=AT(e,u);if(d)return{...d,module:e};for(let f of e.ast.program.body)if(!(!Fe.isImportDeclaration(f)||f.importKind==="type")){for(let g of f.specifiers)if(g.local.name===u){if(Fe.isImportDefaultSpecifier(g))return s(f.source.value,"default");if(Fe.isImportSpecifier(g)&&g.importKind!=="type")return s(f.source.value,fc(g.imported))}}return null};for(let u of e.ast.program.body){if(Fe.isExportDefaultDeclaration(u)&&t==="default"){let d=u.declaration;if(Kd(d))return{node:d,name:LT(d)??"default",module:e};if(Fe.isIdentifier(d))return a(d.name)}if(!(!Fe.isExportNamedDeclaration(u)||u.exportKind==="type")){if(u.declaration){let d=FT(u.declaration,t);if(d)return a(d)}for(let d of u.specifiers)if(Fe.isExportSpecifier(d)&&d.exportKind!=="type"&&fc(d.exported)===t)return u.source?s(u.source.value,fc(d.local)):a(fc(d.local))}}let c=e.ast.program.body.flatMap(u=>{if(!Fe.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 AT(e,t){for(let n of e.ast.program.body){let r=Fe.isExportNamedDeclaration(n)?n.declaration:n;if(Fe.isFunctionDeclaration(r)&&r.id?.name===t)return{node:r,name:t};if(Fe.isVariableDeclaration(r)){for(let o of r.declarations)if(Fe.isIdentifier(o.id)&&o.id.name===t&&Kd(o.init))return{node:o.init,name:t}}}return null}function TT(e,t){let n=null;return lb(e,{Function(r){r.node===t&&(n=r,r.stop())}}),n}function fb(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()||wT(i)||t&&i.isIfStatement()&&dc(i))?null:o.get("argument")}function wT(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(!Fe.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 OT(e){let t=e.get("body");if(!t.isBlockStatement())return null;let n=Ud(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(!Fe.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=>!Fe.isJSXText(c)||c.value.trim()!=="")||i.node.openingElement.attributes.some(c=>Fe.isJSXSpreadAttribute(c)||Fe.isJSXAttribute(c)&&Fe.isJSXIdentifier(c.name,{name:"children"}))))return null;r.push(i)}return r}function Ud(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=>Ud(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:Ud(e.slice(t+1));return o&&s?[...o,...s]:null}return null}function pc(e,t){if(pb(e))return!0;if(e.isJSXFragment()||e.isJSXElement()&&it(e)){let n=e.get("children");for(let r of Array.isArray(n)?n:[n])if(!r.isJSXText()&&(r.isJSXSpreadChild()||!pc(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()||pc(n,t)}return e.isParenthesizedExpression()||e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTypeCastExpression()?pc(e.get("expression"),t):e.isNullLiteral()||e.isStringLiteral()||e.isNumericLiteral()||e.isBooleanLiteral()}function Vd(e){return["base","link","meta","script","style","title"].includes(e)}function pb(e){let t=!1,n=r=>{if(r.isJSXElement()){let o=r.node.openingElement.name;return Fe.isJSXIdentifier(o)&&Vd(o.name)?(t=!0,!0):it(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||!Fe.isIdentifier(o.node.property,{name:"map"})||i.length!==1)return!1;let s=i[0];if(!s.isArrowFunctionExpression()&&!s.isFunctionExpression())return!1;let a=fb(s);return a!==null&&n(a)}return!1};return n(e)&&t}function FT(e,t){return Fe.isFunctionDeclaration(e)?e.id?.name===t?t:null:Fe.isVariableDeclaration(e)&&e.declarations.some(n=>Fe.isIdentifier(n.id)&&n.id.name===t)?t:null}function Kd(e){return Fe.isFunctionDeclaration(e)||Fe.isFunctionExpression(e)||Fe.isArrowFunctionExpression(e)}function LT(e){return"id"in e&&e.id&&Fe.isIdentifier(e.id)?e.id.name:null}function fc(e){return Fe.isIdentifier(e)?e.name:e.value}function Tr(e,t,n){return{ok:!1,diagnostic:{code:e,message:t,file:n}}}var zd=typeof Jd=="function"?Jd:Jd.default,mb=typeof Xd=="function"?Xd:Xd.default,hb=new Set(["sourceBlockId","source_block_id","originalBlockId","original_block_id"]),BT=new Set(["sourceOrder","source_order","originalOrder","original_order"]),jT=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"]),$T=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,UT=/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/u;function Or(e){if(!bb(e)||!Array.isArray(e.bindings))return wr("INVOCATION_INPUT_INVALID","bindings must be an array in a portable invocation.","bindings");let t=XT(e);if(!t||!UT.test(t))return wr("INVOCATION_COMPONENT_INVALID","Portable invocation requires a safe JSX component local name.","component");let n=yb(e.targetBlockId);if(!n.ok)return n;let r=zT(e.targetOrder);if(!r.ok)return r;let o=e.searchParamsIdentifier??"searchParams";if(!$T.test(o))return wr("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[f,g]of e.bindings.entries()){let m=MT.safeParse(g);if(!m.success)return wr("INVOCATION_VALUE_UNRESOLVED","Portable invocation values must use the closed JSON/server/identity contract.",`bindings.${f}`);let p=m.data;if(a.has(p.propName))return wr("INVOCATION_DUPLICATE_PROP",`Portable invocation contains duplicate prop ${p.propName}.`,`bindings.${f}.propName`);if(a.add(p.propName),BT.has(p.propName))return wr("INVOCATION_SOURCE_METADATA","Source block order cannot be copied or rebound as a component prop.",`bindings.${f}`);if(hb.has(p.propName)&&p.value.kind!=="target-block-id")return wr("INVOCATION_SOURCE_METADATA","Source block identity/order cannot be copied as a business prop.",`bindings.${f}`);if(p.value.kind==="target-block-id"&&(u+=1,u>1))return wr("INVOCATION_DUPLICATE_PROP","A portable invocation may bind the target block identity only once.",`bindings.${f}`);p.value.kind==="route-search-params"&&(c=!0),p.value.kind==="route-params"&&(l=!0),s.push(p),i.push(Te.jsxAttribute(Te.jsxIdentifier(p.propName),Te.jsxExpressionContainer(KT(p.value,n.value,o))))}let d=Te.jsxElement(Te.jsxOpeningElement(JT(t),i,!0),null,[],!0);return{ok:!0,plan:{kind:"portable-invocation",component:t,jsx:zd(d,{jsescOption:{minimal:!0}}).code,bindings:s,targetBlockId:n.value,targetOrder:r.value,requiresRouteSearchParams:c,requiresRouteParams:l,searchParamsIdentifier:c?o:null}}}function VT(e){if(!bb(e)||e.jsx===void 0==(e.source===void 0))return Ho("BLOCK_METADATA_INPUT_INVALID","Provide exactly one JSX expression or full source module.","input");let t=yb(e.targetBlockId);if(!t.ok)return Ho("BLOCK_METADATA_TARGET_INVALID",t.error.message,"targetBlockId");if(!Number.isSafeInteger(e.targetOrder)||e.targetOrder<0)return Ho("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=_e("portable-entry.tsx",e.source);if(!g.ok)throw new Error(g.diagnostic.message);o=g.module,r=o.ast}else r=DT(n?e.jsx:e.source,{sourceType:"module",plugins:["jsx","typescript"]})}catch(g){return Ho("BLOCK_METADATA_PARSE_FAILED",g instanceof Error?g.message:String(g),n?"jsx":"source")}let i=[],s;if(o&&e.entryExport){let g=jt({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 mb(r,{JSXElement(g){gb(g)||i.push(g.node)},JSXFragment(g){gb(g)||i.push(g.node)}});if(i.length!==1)return Ho("BLOCK_METADATA_ROOT_AMBIGUOUS","Portable block metadata requires exactly one JSX root.",n?"jsx":"source");let a=i[0],c=HT(a);if(!c)return Ho("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=WT(g.node.name);!m||!jT.has(m)||(m==="data-site-block-id"||m==="data-vcp-block-id"||hb.has(m)?l+=1:u+=1,g.remove())};s?s.traverse({JSXAttribute:d}):mb(r,{JSXAttribute:d}),c.openingElement.attributes.push(Te.jsxAttribute(Te.jsxIdentifier("data-site-block-id"),Te.stringLiteral(t.value)),Te.jsxAttribute(Te.jsxIdentifier("data-site-block-order"),Te.jsxExpressionContainer(Te.numericLiteral(e.targetOrder))));let f=n?zd(a,{jsescOption:{minimal:!0}}).code:zd(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 KT(e,t,n){return e.kind==="route-params"?Te.identifier("params"):e.kind==="route-search-params"?Te.identifier(n):e.kind==="target-block-id"?Te.stringLiteral(t):Hd(e.value)}function Hd(e){return e===null?Te.nullLiteral():typeof e=="string"?Te.stringLiteral(e):typeof e=="number"?Te.numericLiteral(e):typeof e=="boolean"?Te.booleanLiteral(e):Array.isArray(e)?Te.arrayExpression(e.map(t=>Hd(t))):Te.objectExpression(Object.entries(e).map(([t,n])=>Te.objectProperty(Te.stringLiteral(t),Hd(n))))}function JT(e){let t=e.split("."),n=Te.jsxIdentifier(t[0]);for(let r of t.slice(1))n=Te.jsxMemberExpression(n,Te.jsxIdentifier(r));return n}function XT(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 yb(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 zT(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 HT(e){if(Te.isJSXElement(e))return e;let t=e.children.filter(Te.isJSXElement),n=e.children.some(r=>Te.isJSXText(r)&&r.value.trim().length>0);return t.length===1&&!n?t[0]??null:null}function gb(e){let t=e.parentPath;for(;t;){if(t.isJSXElement()||t.isJSXFragment())return!0;t=t.parentPath}return!1}function WT(e){return Te.isJSXIdentifier(e)?e.name:null}function bb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wr(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}function Ho(e,t,n){return{ok:!1,error:{code:e,path:n,message:t}}}var Yd=typeof Gd=="function"?Gd:Gd.default,YT=typeof Wd=="function"?Wd:Wd.default;function os(e){let t=_b(e);if(t)return{ok:!1,error:t};let n=e.projection,r=nf(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=QT(n,o),s=lw(e);if(!s.ok)return s;let a={jsx:s.invocation?.jsx??`<${e.component.localName} />`},c=ZT(e);if(i){let m=Zd(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??(gc(l,n.container.sourceRange)?n.container.sourceHash:null);if(!l||!u)return ts("Route page composition does not expose a verifiable container boundary.");let d=rs(l),f=Sb(e.source,d,u,"Route page composition container");if(!f.ok)return f.result;let g=o.anchorSourceRange?rs(o.anchorSourceRange):void 0;if(g){if(!o.anchorSourceHash)return ts("Route page composition placement does not expose a verifiable anchor boundary.");let m=Sb(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 ef(e){let t=_e(e.entryFile,e.source);if(!t.ok)return Fr("PORTABLE_ROUTE_SOURCE_INVALID",t.diagnostic.message);let n=Tn({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 Fr("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&&gc(l.anchorSourceRange,e.anchor.sourceRange)?[{placement:l,matchCount:1}]:[];let u=l.members.reduce((d,f)=>d+Ib(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 Fr("PORTABLE_ROUTE_ANCHOR_MISSING","Portable route anchor was not found in the canonical page composition.");if(o!==1||r.length!==1)return Fr("PORTABLE_ROUTE_ANCHOR_AMBIGUOUS","Portable route anchor does not identify exactly one page-composition gap.");let i=os({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 Fr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}else{let l=bn({source:s,locator:a.parentLocator,node:a.node,placement:a.placement,...a.anchorLocator?{anchorLocator:a.anchorLocator}:{}});if(!l.ok)return Fr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}if(i.plan.serverParamsStep){let l=Rb({source:s,step:i.plan.serverParamsStep});if(!l.ok)return Fr("PORTABLE_ROUTE_PATCH_FAILED",l.diagnostic.message);s=l.source}let c=xn({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}}:Fr("PORTABLE_ROUTE_PATCH_FAILED",c.diagnostic.message)}function Ib(e,t){return(e.label===t?1:0)+e.children.reduce((n,r)=>n+Ib(r,t),0)}function Fr(e,t,n=[]){return{ok:!1,error:{code:e,message:t,diagnostics:n}}}function ZT(e){let t=rw(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 go(e.source,"Root expression rewrite requires an exact expression locator.");let t=Ti(e.source,"value");if(!t.ok)return go(e.source,t.diagnostic.message);let n=Pe(t.ast,e.locator);if(!n.ok)return go(e.source,n.diagnostic.message);let r=n.match.path;if(!r.isExpression())return go(e.source,"Resolved value locator does not point to an expression.");let o=Wo(e.source,r.node.start??null,r.node.end??null);if(!o||o!==e.expectedSourceHash)return go(e.source,"Root expression hash no longer matches the current source.");if(e.action.kind==="remove")return r.replaceWith(me.nullLiteral()),{ok:!0,source:Yd(t.ast,{}).code};let i;try{i=Go.parseExpression(e.action.jsx,{plugins:["jsx","typescript"]})}catch(s){return go(e.source,s instanceof Error?s.message:String(s))}return!me.isJSXElement(i)&&!me.isJSXFragment(i)?go(e.source,"Root expression rewrite requires a JSX insertion expression."):(e.action.kind==="replace"?r.replaceWith(i):r.replaceWith(qT(r.node,i,e.action.placement,e.action.replaceOriginal)),{ok:!0,source:Yd(t.ast,{}).code})}function qT(e,t,n,r){if(me.isNullLiteral(e)||r)return t;let o=me.isJSXFragment(e)?[...e.children]:[me.isJSXElement(e)?e:me.jsxExpressionContainer(e)],s=n==="before"||n==="prepend"?[t,...o]:[...o,t];return me.jsxFragment(me.jsxOpeningFragment(),me.jsxClosingFragment(),s)}function go(e,t){return{ok:!1,source:e,diagnostic:{message:t}}}function tf(e){let t=_b(e);if(t)return{ok:!1,error:t};let n=e.projection,r=wb(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(ew(n,o)){let p=Zd(e);return p.ok?e.operation==="remove-node"&&!Eb(n,o.placementUnitKey)?ts("The last editable page unit cannot be deleted."):e.operation==="move-node"?ts("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:p.sourceHash,rewriteStep:{kind:e.operation==="remove-node"?"remove-root-expression":"replace-root-expression",locator:p.locator,sourceHash:p.sourceHash}}}:p.result}let s=rs(o.sourceRange),a=Kn(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?[]:[ns(a.diagnostic)]}};if(Wo(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 p=Zd(e);return p.ok?Eb(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}}}:ts("The last editable page unit cannot be deleted."):p.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||!nw(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=nf(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=rs(d),g=Kn(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?[]:[ns(g.diagnostic)]}};if(Wo(e.source,g.match.node.start??null,g.match.node.end??null)!==u.containerSourceHash)return vb("Route page composition target container hash no longer matches the current source.");if(u.relation==="before"||u.relation==="after"){let p=u.anchorSourceRange,y=u.anchorSourceHash;if(!p||!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=rs(p),E=Kn(e.source,b);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?[]:[ns(E.diagnostic)]}}:Wo(e.source,E.match.node.start??null,E.match.node.end??null)!==y?vb("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 Eb(e,t){for(let n of e.placementUnitByKey.values())if(n.placementUnitKey!==t&&n.members.length>0)return!0;return!1}function QT(e,t){let n=e.placementUnitByKey.get(t.placementUnitKey);return n&&e.container.kind!=="jsx-container"&&gc(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 ew(e,t){return e.container.kind!=="jsx-container"&&gc(t.sourceRange,e.mutationTarget.sourceRange)&&t.sourceHash===e.mutationTarget.sourceHash}function Zd(e){let t=e.projection.mutationTarget,n={kind:"value",root:{kind:"expression",sourceRange:t.sourceRange}},r=Kn(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?[]:[ns(r.diagnostic)]}}}:Wo(e.source,r.match.node.start??null,r.match.node.end??null)!==t.sourceHash?{ok:!1,result:kb("Route mutation target hash no longer matches the current source.")}:{ok:!0,locator:n,sourceHash:t.sourceHash}}function Sb(e,t,n,r){let o=Kn(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?[]:[ns(o.diagnostic)]}}}:Wo(e,o.match.node.start??null,o.match.node.end??null)!==n?{ok:!1,result:kb(`${r} hash no longer matches the current source.`)}:{ok:!0}}function kb(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ts(e){return{ok:!1,error:{code:"NO_SAFE_PAGE_PLACEMENT",message:e,diagnostics:[]}}}function vb(e){return{ok:!1,error:{code:"VERSION_STALE",message:e,diagnostics:[{code:"DOCUMENT_VERSION_STALE",message:e}]}}}function ns(e){return{code:"UNSUPPORTED_PAGE_SHAPE",message:e.message,details:{astCode:e.code}}}function _b(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&&!tw(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 tw(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function nw(e,t){return e.routeId===t.routeId&&e.templateId===t.effectiveTemplateId}function rw(e,t){let n=xb.posix.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=xb.posix.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function rs(e){return{kind:"jsx-node",strategy:"source-range",sourceRange:e}}function Wo(e,t,n){return t==null||n==null?null:`sha256:${GT("sha256").update(e.slice(t,n)).digest("hex")}`}function gc(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 Rb(e){let t;try{t=Go.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=ow(t,e.step);return n.ok?{ok:!0,source:Yd(t,{}).code}:{ok:!1,source:e.source,diagnostic:{message:n.message}}}function ow(e,t){let n=Ab(e);if(!n)return{ok:!1,message:"Route default function could not be resolved for searchParams wiring."};let r=Qd(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."}:Pb(r)!==t.identifier?{ok:!1,message:"Existing route searchParams binding no longer matches the plan."}:{ok:!0};let o=Cb(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?qd():iw()),{ok:!0};let i=n.node.params[0],s=Qd(i);return s?(sw(s,t.typescript),{ok:!0}):{ok:!1,message:"Route page parameter is not a supported object pattern."}}function iw(){return me.objectPattern([me.objectProperty(me.identifier("searchParams"),me.identifier("searchParams"),!1,!0)])}function qd(){let t=Go.parse("function __PortablePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {}",{sourceType:"module",plugins:["typescript"]}).program.body[0];if(!me.isFunctionDeclaration(t))throw new Error("Failed to construct the canonical searchParams type.");let n=t.params[0];if(!me.isObjectPattern(n))throw new Error("Failed to construct the canonical searchParams pattern.");return me.cloneNode(n,!0)}function sw(e,t){let n=me.objectProperty(me.identifier("searchParams"),me.identifier("searchParams"),!1,!0),r=e.properties.findIndex(me.isRestElement);if(r<0?e.properties.push(n):e.properties.splice(r,0,n),!t)return;let o=Nb(e);if(!o){e.typeAnnotation=qd().typeAnnotation;return}if(!me.isTSTypeLiteral(o.typeAnnotation))return;let i=qd().typeAnnotation;if(!i||!me.isTSTypeAnnotation(i)||!me.isTSTypeLiteral(i.typeAnnotation))return;let s=i.typeAnnotation.members[0];s&&!aw(o.typeAnnotation)&&o.typeAnnotation.members.push(me.cloneNode(s,!0))}function aw(e){return e.members.some(t=>!("key"in t)||!t.key?!1:Tb(t.key)==="searchParams")}function cw(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 lw(e){if(!e.invocation)return{ok:!0};let t=Or({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!t.ok)return mc(t.error.message);if(t.plan.requiresRouteParams)return mc("A captured native detail parameter has no independently proven target route binding.","UNSUPPORTED_ROUTE_PARAMS");let n;if(t.plan.requiresRouteSearchParams){let r=uw(e.source,e.entryFile);if(!r.ok)return mc(r.message,"UNSUPPORTED_ROUTE_PARAMS");if(n=r.step,r.step.identifier!==t.plan.searchParamsIdentifier&&(t=Or({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder,searchParamsIdentifier:r.step.identifier}),!t.ok))return mc(t.error.message)}return{ok:!0,invocation:t.plan,...n?{serverParamsStep:n}:{}}}function mc(e,t="PORTABLE_INVOCATION_INVALID"){return{ok:!1,error:{code:t,message:e,diagnostics:[]}}}function uw(e,t){let n;try{n=Go.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=Ab(n);if(!r)return{ok:!1,message:"Portable route searchParams wiring requires a default server function."};let o=/\.(?:ts|tsx)$/iu.test(t),i=Cb(r.node.params,o);return i.ok?{ok:!0,step:{kind:"ensure-search-params",action:i.action,identifier:i.identifier,typescript:o}}:i}function Cb(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=Qd(e[0]);if(!n)return{ok:!1,message:"Portable route searchParams wiring requires an object page parameter or an empty signature."};let r=Pb(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&&!dw(n)?{ok:!1,message:"Portable route searchParams wiring cannot safely extend this typed page signature."}:{ok:!0,action:"add",identifier:"searchParams"}}function Qd(e){return!e||me.isTSParameterProperty(e)?null:me.isObjectPattern(e)?e:me.isAssignmentPattern(e)&&me.isObjectPattern(e.left)?e.left:null}function Pb(e){for(let t of e.properties)if(!(!me.isObjectProperty(t)||t.computed||Tb(t.key)!=="searchParams"))return me.isIdentifier(t.value)?t.value.name:me.isAssignmentPattern(t.value)&&me.isIdentifier(t.value.left)?t.value.left.name:"unsupported";return null}function dw(e){let t=Nb(e);return t?me.isTSTypeLiteral(t.typeAnnotation):e.properties.length===0}function Nb(e){return e.typeAnnotation&&me.isTSTypeAnnotation(e.typeAnnotation)?e.typeAnnotation:null}function Ab(e){let t=null;return YT(e,{ExportDefaultDeclaration(n){if(t)return;let r=cw(n,n.get("declaration"));r&&(t=r)}}),t}function Tb(e){return me.isIdentifier(e)?e.name:me.isStringLiteral(e)?e.value:null}var fw=typeof rf=="function"?rf:rf.default;function Tn(e){if(!e.ast)return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","SourceGraph entry AST is required",{reason:"parsed-ast-required"})]);let t=Ew(e.ast);if(!t)return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export must resolve to a local function component",{reason:"default-export-unresolved"})]);let n=vw(t);if(!n.ok)return wn(e,[n.diagnostic]);let r=n.expression;if(r.isIdentifier()){let o=kw(r,t);if(o.status==="resolved")r=o.expression;else if(o.status==="invalid")return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export local binding is not a supported JSX root")])}if(Rw(r,t))return wn(e,[Rt("INDIRECT_RETURN_ONLY","Route default export only returns through an indirect function boundary")]);if(r.isNullLiteral())return sf(e,t,"virtual-route-root",r);if(_w(r)){let o=Aw({input:e,source:e.source,expression:r});return of(e,t,o,{kind:"virtual-route-root",sourceKind:"atomic-expression"},r)}if(r.isConditionalExpression())return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route conditional root contains an unsupported branch shape",{reason:"ambiguous-placement"})]);if(r.isJSXElement()&&!it(r)&&!as(r)){let o=lf(r),i=Lb({input:e,containerKind:"virtual-route-root",sourceKind:"jsx-element",source:e.source,containerPath:r,members:[o]});return of(e,t,i,{kind:"virtual-route-root",sourceKind:"jsx-element"},r)}if(r.isJSXElement()||r.isJSXFragment()){let o=Pw(r);if(!o.ok)return wn(e,[o.diagnostic]);let i=Yo(o.path);if(i.unsupported)return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")]);if(Cw(e.source,r,i.members))return sf(e,t,"starter-placeholder",r);let s=r.isJSXFragment()||it(r);if(i.members.length===0&&s)return sf(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=Lb({input:e,containerKind:a,sourceKind:c,source:e.source,containerPath:o.path,members:i.members});return of(e,t,l,{kind:a,sourceKind:c},r)}return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export contains an unsupported JSX shape")])}function nf(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Rt("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:Rt("PLACEMENT_KEY_NOT_FOUND","Placement key was not found in the projected page composition",{placementKey:t})}}function wb(e,t,n){if(e.documentVersion!==n)return{ok:!1,diagnostic:Rt("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:Rt("PLACEMENT_KEY_NOT_FOUND","Placement unit key was not found in the projected page composition",{placementUnitKey:t})}}function Db(e){return e.ok?pw(e.projection):mw(e.projection)}function pw(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((p,y)=>Mb(e,u,p,y,e.container.placementKey)),f=d.filter(({member:p})=>p.isBusinessMember).map(({sourceMember:p})=>hw(l,p,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:p})=>p)),o.set(l,f);let m=g[0]?.sourceMember.key??l;n.push({key:l,containerKey:m,businessMemberKeys:f.map(p=>p.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:gw(e,a),sourceMembers:i,businessMembers:s,placementUnits:n,placements:c}}function mw(e){let t=e.diagnostics.map(yw);return{status:"unsupported",version:e.version,composition:e.composition,reason:bw(e.diagnostics),diagnostics:t}}function gw(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 Mb(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)=>Mb(e,t,a,c,i))]}function hw(e,t,n){return{key:`business:${e}:${t.key}`,sourceMemberKey:t.key,containerKey:e,label:t.label,isIndependent:n}}function yw(e){return{code:xw(e),message:e.message}}function bw(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 xw(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 Ew(e){let t=null;return fw(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=Sw(o.path);i&&(t=i,n.stop())}}),t}function Sw(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 vw(e){let t=e.get("body");if(!t.isBlockStatement()){let s=ss(t);return s?{ok:!0,expression:s}:{ok:!1,diagnostic:Rt("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:Rt("ROUTE_RETURN_NOT_FOUND","Route default export does not contain a proven return boundary")};if(!r.isReturnStatement())return{ok:!1,diagnostic:Rt("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(!Iw(s)&&!dc(s))return{ok:!1,diagnostic:Rt("UNSUPPORTED_PAGE_SHAPE","Route guard return shape is not statically safe",{reason:"guard-shape"})};continue}if(Bb(s)||jb(s))return{ok:!1,diagnostic:Rt("UNSUPPORTED_PAGE_SHAPE","Route default export contains unsupported control flow before the terminal return",{reason:"control-flow-return"})}}let o=r.get("argument"),i=ss(o);return i?{ok:!0,expression:i}:{ok:!1,diagnostic:Rt("ROUTE_RETURN_NOT_FOUND","Route default export returns without a boundary expression",{reason:"bare-return"})}}function Iw(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(Bb(o)||jb(o))return null;return r}function Bb(e){return e.isForStatement()||e.isForInStatement()||e.isForOfStatement()||e.isWhileStatement()||e.isDoWhileStatement()||e.isSwitchStatement()||e.isTryStatement()||e.isWithStatement()}function jb(e){let t=!1;return e.traverse({Function(n){n.skip()},ReturnStatement(){t=!0}}),t}function kw(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=ss(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 _w(e){return e.isConditionalExpression()?Ob(ss(e.get("consequent")))&&Ob(ss(e.get("alternate"))):!1}function Ob(e){return!!(e&&(e.isJSXElement()||e.isJSXFragment()||e.isNullLiteral()))}function ss(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 Rw(e,t){if(e.isIdentifier())return Fb(e.node.name,t);if(e.isCallExpression()){let n=e.get("callee");if(n.isIdentifier())return Fb(n.node.name,t)}return!1}function Fb(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 Cw(e,t,n){return e.includes("DESIGN_PLAN_REPLACE_ME")&&t.isJSXElement()&&n.length>0&&cf(t)}function cf(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(!cf(t))return!1;continue}if(t.isJSXElement()&&!cf(t))return!1}return!0}function Pw(e){return{ok:!0,path:e}}function Yo(e){let t=[],n=!1;for(let r of e.get("children")){if(r.isJSXText()){if(!r.node.value.trim())continue;t.push({memberKey:uf(r.node.type,r.node.start,r.node.end),kind:"text",nodeType:r.node.type,sourceRange:In(r.node.loc),businessMemberCount:0,parentSourceRange:In(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=Yo(o);n||=i.unsupported,t.push(...i.members);continue}if(o.isJSXElement()){let i=as(o)?Yo(o):null;n||=i?.unsupported??!1,t.push({...lf(o,i?.members),sourceRange:In(r.node.loc),parentSourceRange:In(e.node.loc)});continue}if(o.isJSXSpreadChild()){n=!0;continue}t.push({memberKey:uf(o.node.type,o.node.start,o.node.end),kind:"atomic-expression",nodeType:o.node.type,sourceRange:In(r.node.loc),businessMemberCount:1,parentSourceRange:In(e.node.loc),children:[],isBusinessMember:!0,label:"atomic-expression"});continue}if(r.isJSXFragment()||r.isJSXElement()&&it(r)){let o=Yo(r);n||=o.unsupported,t.push(...o.members);continue}if(r.isJSXElement()){let o=as(r)?Yo(r):null;n||=o?.unsupported??!1,t.push({...lf(r,o?.members),parentSourceRange:In(e.node.loc)})}}return{members:t,unsupported:n}}function lf(e,t){let n=e.isJSXElement()&&as(e)?t??Yo(e).members:[],r=e.isJSXElement()&&!as(e)&&!it(e);return{memberKey:uf(e.node.type,e.node.start,e.node.end),kind:"jsx-element",nodeType:e.node.type,sourceRange:In(e.node.loc),businessMemberCount:r?1:$b(n),parentSourceRange:In(e.parentPath?.node.loc),children:n,isBusinessMember:r,label:Nw(e)}}function as(e){let t=e.node.openingElement.name;return t.type==="JSXIdentifier"&&t.name[0]===t.name[0]?.toLowerCase()}function Nw(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 $b(e){return e.reduce((t,n)=>t+n.businessMemberCount,0)}function hc(e){return e.length===0?0:Math.max(1,$b(e))}function Lb(e){let t=In(e.containerPath.node.loc),n=ff(e.source,e.containerPath.node.start,e.containerPath.node.end),r=kn(e.input,e.containerKind,e.sourceKind,t),o=kn(e.input,e.containerKind,"placement-unit",t);return{placementKey:r,placementUnitKey:o,version:e.input.version,containerKey:r,independent:hc(e.members)<=1,memberCount:hc(e.members),sourceRange:t,sourceHash:n,relation:"append",containerSourceRange:t,containerSourceHash:n,anchorSourceRange:null,anchorSourceHash:null,members:e.members}}function Aw(e){let t=In(e.expression.node.loc),n=ff(e.source,e.expression.node.start,e.expression.node.end),r=kn(e.input,"virtual-route-root","atomic-expression",t),o=kn(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:kn(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 Ub(e,t){let n=In(t.node.loc),r=ff(e.source,t.node.start,t.node.end);return!n||!r?null:{kind:"expression",documentVersion:e.version,sourceRange:n,sourceHash:r}}function of(e,t,n,r,o){let i=Ub(e,o);if(!i)return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let s=n.containerSourceRange??n.sourceRange,a=Tw(e,n,s),c=jd(a),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Kb(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 Tw(e,t,n){if(t.members.length===0)return[t];let r=[],o=(l,u,d,f,g,m,p=n)=>({...t,placementKey:u,placementUnitKey:d,containerKey:t.placementKey,independent:hc(m)<=1,memberCount:hc(m),sourceRange:f,sourceHash:f?af(e.source,f):null,relation:l,containerSourceRange:p,containerSourceHash:p?af(e.source,p):null,anchorSourceRange:g,anchorSourceHash:g?af(e.source,g):null,members:m}),i=t.placementKey,s=t.members.map(l=>kn(e,i,"placement-unit",l.sourceRange)),a=s[0]??t.placementUnitKey,c=s.at(-1)??t.placementUnitKey;r.push(o("prepend",kn(e,i,"prepend",n),a,n,null,[]));for(let l of t.members){let u=l.parentSourceRange??n,d=kn(e,i,"placement-unit",l.sourceRange);r.push(o("before",kn(e,d,"before",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u)),r.push(o("after",kn(e,d,"after",l.sourceRange),d,l.sourceRange,l.sourceRange,[l],u))}return r.push(o("append",i,c,n,null,[])),r}function sf(e,t,n,r){let o=Ub(e,r);if(!o)return wn(e,[Rt("UNSUPPORTED_PAGE_SHAPE","Route default export does not provide an exact mutation target",{reason:"mutation-target-unavailable"})]);let i=kn(e,n,"empty-container",void 0),s=kn(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=jd([a]),l={status:"supported",composition:e.composition,route:e.route,entryFile:e.entryFile,version:e.version,documentVersion:e.version,defaultExportName:Kb(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 wn(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 Rt(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,details:n}}function kn(e,t,n,r){return Vb([e.route,e.entryFile,String(e.version),t,n,r?`${r.startLine}:${r.startColumn}-${r.endLine}:${r.endColumn}`:"no-range"])}function uf(e,t,n){return Vb(["member",e,String(t??-1),String(n??-1)])}function Vb(e){return`pc_${df("sha256").update(e.join("\0")).digest("hex").slice(0,24)}`}function ff(e,t,n){return t==null||n==null?null:`sha256:${df("sha256").update(e.slice(t,n)).digest("hex")}`}function af(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:${df("sha256").update(e.slice(r+t.startColumn,o+t.endColumn)).digest("hex")}`}function In(e){return e?{startLine:e.start.line,startColumn:e.start.column,endLine:e.end.line,endColumn:e.end.column}:null}function Kb(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 Kw}from"node:crypto";import*as On from"@babel/types";function Jb(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 pf from"@babel/traverse";import*as Zo from"@babel/types";var Ow=typeof pf=="function"?pf:pf.default,Fw=32;function ho(e,t,n,r=new Set){if(r.has(e.ast)||r.size>=Fw)return null;let o=new Set(r).add(e.ast),i;if(Ow(e.ast,{Program(d){i=d,d.stop()}}),!i)return null;let s=(d,f)=>{let g=Ir(e.file,d,n),m=g?n.get(g):void 0;return m?ho(m,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,yc(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(Zo.getBindingIdentifiers(f.node),t)&&c.push(a(t));for(let g of d.node.specifiers)Zo.isExportSpecifier(g)&&g.exportKind!=="type"&&yc(g.exported)===t&&c.push(d.node.source?s(d.node.source.value,yc(g.local)):a(yc(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 yc(e){return Zo.isIdentifier(e)?e.name:e.value}import*as Ie from"@babel/types";var Lw=32;function on(e,t=new Map,n=new Set){if(n.has(e.node)||n.size>=Lw)return null;let r=new Set(n).add(e.node),o=t.get(e.node);if(o)return cs(o,t,r);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return on(e.get("expression"),t,r);if(e.isIdentifier()){let i=e.scope.getBinding(e.node.name);return!i||i.constantViolations.length?null:gf(i,t,r)}if(e.isMemberExpression()||e.isOptionalMemberExpression()){let i=sn(e.node.property,e.node.computed),s=e.get("object"),a=on(s,t,r);return i!==null&&a?Ec(a,i,t,r):null}if(e.isConditionalExpression())return cs([e.get("consequent"),e.get("alternate")],t,r);if(e.isLogicalExpression())return cs([e.get("left"),e.get("right")],t,r);if(e.isSequenceExpression()){let i=e.get("expressions").at(-1);return i?on(i,t,r):null}if(e.isCallExpression()&&Ie.isIdentifier(e.node.callee)){let i=e.scope.getBinding(e.node.callee.name);if(!i||!qo(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 p=l[g];if(!p?.isExpression())return null;let y=on(p,t,r);if(!y)return null;let b=m.scope.getBinding(m.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?on(f,c,r):null}return[e]}function gf(e,t=new Map,n=new Set){if(e.constantViolations.length)return null;let r=t.get(e.identifier);if(r)return cs(r,t,n);if(!e.path.isVariableDeclarator())return null;let o=e.path.get("init");if(!o.node)return null;let i=on(o,t,n);if(!i)return null;let s=mf(e.path.node.id,e.identifier.name);return s?s.reduce((a,c)=>a&&Ec(a,c,t,n),i):null}function bc(e){if(!e.params.every(n=>Ie.isIdentifier(n)||Ie.isAssignmentPattern(n)&&Ie.isIdentifier(n.left)&&gr(n.right)))return!1;if(!Ie.isBlockStatement(e.body))return gr(e.body);if(e.body.body.length!==1)return!1;let t=e.body.body[0];return Ie.isReturnStatement(t)&&!!t.argument&&gr(t.argument)}function qo(e){if(e.constantViolations.length>0)return!1;if(e.path.isFunctionDeclaration())return bc(e.path.node);let t=e.path.isVariableDeclarator()?e.path:e.path.findParent(r=>r.isVariableDeclarator()),n=t?.isVariableDeclarator()?t.node.init:null;return Ie.isArrowFunctionExpression(n)||Ie.isFunctionExpression(n)?bc(n):!1}function gr(e){let t=!0;return Ie.traverseFast(e,n=>{(Ie.isCallExpression(n)&&!xc(n)||Ie.isOptionalCallExpression(n)||Ie.isNewExpression(n)||Ie.isAwaitExpression(n)||Ie.isAssignmentExpression(n)||Ie.isUpdateExpression(n)||Ie.isUnaryExpression(n,{operator:"delete"})||Ie.isYieldExpression(n)||Ie.isTaggedTemplateExpression(n))&&(t=!1)}),t}function xc(e){return Ie.isIdentifier(e.callee,{name:"useTranslations"})&&e.arguments.length===1&&Ie.isStringLiteral(e.arguments[0])}function cs(e,t,n){let r=[];for(let o of e){let i=on(o,t,n);if(!i)return null;r.push(...i)}return r.length?r:null}function Ec(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()&&sn(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=>Ie.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 cs(o,n,r)}function hf(e,t){let n=on(e,t);return!!(n?.length&&n.every(r=>Ie.isLiteral(r.node)&&!r.isRegExpLiteral()||r.isTemplateLiteral()||r.isBinaryExpression()||r.isUnaryExpression()))}function sn(e,t){return!t&&Ie.isIdentifier(e)?e.name:Ie.isStringLiteral(e)||Ie.isNumericLiteral(e)?String(e.value):null}function mf(e,t){if(Ie.isIdentifier(e))return e.name===t?[]:null;if(Ie.isObjectPattern(e))for(let n of e.properties){if(!Ie.isObjectProperty(n)||n.computed)continue;let r=sn(n.key,!1),o=mf(n.value,t);if(r!==null&&o)return[r,...o]}if(Ie.isArrayPattern(e))for(let[n,r]of e.elements.entries()){if(!r)continue;let o=mf(r,t);if(o)return[String(n),...o]}return null}function Xb(e,t=new Set,n){return zb(e.get("callee"),t,n)}function zb(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&&Ir(d.file,l,n),g=f?n.get(f):void 0,m=r.path.isImportDefaultSpecifier()?"default":r.path.isImportSpecifier()&&r.path.node.importKind!=="type"?sn(r.path.node.imported,!1):null,p=g&&m&&i.node.importKind!=="type"?ho(g,m,n):null;return p?Qo(p,o,n):{kind:"guard"}}let s=r.path.isVariableDeclarator()?r.path.get("init"):r.path;if(!s.node)return{kind:"unknown"};let a=Qo(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=Qo(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=sn(e.node.property,e.node.computed),o=e.get("object"),i=on(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()&&sn(d.node.key,d.node.computed)===r);if(l.length!==1||!l[0].isObjectProperty())return{kind:"guard"};let u=Qo(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 Qo(e,new Set(t).add(e.node),n)}function Qo(e,t,n){if(e.isIdentifier())return zb(e,t,n);if(e.isTSAsExpression()||e.isTSTypeAssertion()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Qo(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 vc(e,t){return JSON.stringify([t,e])}var Mw=new Set;function Zb(e,t){let n=new Map,r=[],o=new Map,i=(m,p)=>JSON.stringify([m,p.loc?.start.line,p.loc?.start.column,p.loc?.end.line,p.loc?.end.column]);for(let m of e.graph.elements.values()){let p=m.sourceRange;o.set(JSON.stringify([m.sourceFile,p.startLine,p.startColumn,p.endLine,p.endColumn]),m)}let s=m=>r.push({code:"render-occurrence-unproven",message:"A block render occurrence cannot be proven statically.",file:m}),a=(m,p)=>!Yb(p)&&[...t].some(y=>e.graph.elements.get(y)?.sourceFile===m);function c(m,p,y,b,E,x=Mw){if(m.isIdentifier())return b&&Sc(m,b)?b.children.some(v=>c(v.path,v.file,y,v.substitution,E,x)):u({path:m,file:p,active:y,substitution:b,unknownIsRelevant:E,aliases:x});if(m.isCallExpression()||m.isOptionalCallExpression()){let v=m,N=Xb(v,x,e.parsedModules);return N.kind==="guard"||N.kind==="sources"&&N.sources.some(R=>c(R,[...e.parsedModules.values()].find(A=>A.ast.program===R.scope.getProgramParent().path.node)?.file??p,y,b,E,N.aliases))?!0:v.get("arguments").some(R=>c(R,p,y,b,E,x))||N.kind==="unknown"&&E}if(m.isJSXElement()){if(it(m))return m.get("children").some(M=>c(M,p,y,b,E,x));let v=o.get(i(p,m.node));if(v){if(t.has(v.identity.key))return!0;if(v.boundaryKind==="component-boundary"&&!v.isPublicUiComponent){let M=e.parsedModules.get(v.sourceFile);if(!M)return!1;let D=vn({module:M,componentName:v.tag,callSourceRange:v.sourceRange,...v.importedFrom?{imported:{file:v.importedFrom,module:e.parsedModules.get(v.importedFrom),exportName:v.exportName??v.tag,parsedModules:e.parsedModules}}:{}});return D.ok?D.metadataOnly?!1:l(D,m,v.sourceFile,y,b,x):D.diagnostic.code==="component-external-module-opaque"?ls(m).some(U=>c(U,p,y,b,!1,x)):a(M.file,D.diagnostic.code)}return m.get("children").some(M=>c(M,p,y,b,E,x))}let N=m.node.openingElement.name;if(!On.isJSXIdentifier(N))return!1;if(/^[a-z]/.test(N.name))return m.get("children").some(M=>c(M,p,y,b,E,x));let R=e.parsedModules.get(p),A=m.node.loc;if(!R||!A)return!1;let C=Vw({path:m,file:p,componentName:N.name,parsedModules:e.parsedModules}),w=vn({module:R,componentName:N.name,callSourceRange:{startLine:A.start.line,startColumn:A.start.column,endLine:A.end.line,endColumn:A.end.column},...C?{imported:C}:{}});return w.ok?w.metadataOnly?!1:l(w,m,p,y,b,x):w.diagnostic.code==="component-external-module-opaque"?ls(m).some(M=>c(M,p,y,b,!1,x)):a(R.file,w.diagnostic.code)}if(m.isJSXFragment())return m.get("children").some(v=>c(v,p,y,b,E,x));if(m.isJSXExpressionContainer()||m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion())return c(m.get("expression"),p,y,b,E,x);let S=!1;return m.traverse({"CallExpression|OptionalCallExpression"(v){c(v,p,y,b,E,x)&&(S=!0),v.skip(),S&&v.stop()},ReferencedIdentifier(v){c(v,p,y,b,E,x)&&(S=!0),S&&v.stop()},JSXElement(v){c(v,p,y,b,E,x)&&(S=!0),v.skip(),S&&v.stop()},JSXFragment(v){c(v,p,y,b,E,x)&&(S=!0),v.skip(),S&&v.stop()}}),S?!0:E&&!yo(m)}function l(m,p,y,b,E,x){let S=`${m.sourceFile}#${m.componentName}`;if(b.has(S))return!1;let v=new Set(b).add(S);return m.returnAlternatives?.some(N=>ls(N).some(R=>c(R,m.sourceFile,v,null,!1,x)))||m.roots.some(N=>c(N,m.sourceFile,v,null,!1,x))?!0:Hb(m.roots).kind==="none"?!1:Gb(p).some(N=>c(N,y,v,E,!0,x))}function u(m){if(!m.path.isIdentifier())return m.unknownIsRelevant;let p=Jb({path:m.path,aliases:m.aliases});return p.kind==="unbound"?m.unknownIsRelevant&&m.path.node.name!=="undefined":p.kind==="guard"||p.kind==="reassigned"?!0:p.kind==="not-alias"?m.unknownIsRelevant:c(p.initializer,m.file,m.active,m.substitution,m.unknownIsRelevant,p.aliases)?!0:yf(p.initializer).isIdentifier()?!1:m.unknownIsRelevant&&!yo(p.initializer)}let d=(m,p,y,b,E,x)=>{if(m.isIdentifier()){c(m,p,b,x,!1)&&s(p);return}if(m.isJSXElement()){if(it(m)){for(let N of m.get("children"))d(N,p,y,b,E,x);return}let S=o.get(i(p,m.node));if(!S)return;let v=S.identity.key;if(t.has(v)){E||s(p);let N=n.get(v)??[];N.push(vc(v,y)),n.set(v,N)}if(S.boundaryKind==="component-boundary"&&!S.isPublicUiComponent){let N=e.parsedModules.get(S.sourceFile);if(!N)return;let R=vn({module:N,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(!R.ok){if(R.diagnostic.code==="component-external-module-opaque"){ls(m).some(U=>c(U,p,b,x,!1))&&s(p);return}[...t].some(U=>e.graph.elements.get(U)?.sourceFile===N.file)&&!Yb(R.diagnostic.code)&&s(N.file);return}if(R.metadataOnly)return;let A=`${R.sourceFile}#${R.componentName}`;if(b.has(A)){s(N.file);return}let C=new Set(b).add(A);R.returnAlternatives?.some(U=>ls(U).some(B=>c(B,R.sourceFile,C,x,!1)))&&s(R.sourceFile);let w=Hb(R.roots),M=Uw(m);if(w.kind==="unproven"||w.kind==="supported"&&M){for(let U of Gb(m))if(c(U,p,C,x,!0)){s(p);break}}let D=w.kind==="supported"&&!M?{bindingNode:w.bindingNode,children:m.get("children").map(U=>({path:U,file:p,substitution:x}))}:null;for(let U of R.roots)d(U,R.sourceFile,[...y,v],C,E,D);return}for(let N of m.get("children"))d(N,p,y,b,E,x);return}if(m.isJSXFragment()){for(let S of m.get("children"))d(S,p,y,b,E,x);return}if(m.isJSXExpressionContainer()){let S=m.get("expression");if(x&&!S.isJSXEmptyExpression()){let v=yf(S);if(Sc(v,x)){for(let N of x.children)d(N.path,N.file,y,b,E,N.substitution);return}if(Bw(S,x))for(let N of x.children)d(N.path,N.file,y,b,!1,N.substitution)}d(S,p,y,b,E,x);return}if(m.isParenthesizedExpression()||m.isTSAsExpression()||m.isTSNonNullExpression()||m.isTSTypeAssertion()){d(m.get("expression"),p,y,b,E,x);return}c(m,p,b,x,!1)&&s(p),m.traverse({JSXElement(S){d(S,p,y,b,!1,x),S.skip()}})},f=e.parsedModules.get(e.entryFile);if(!f)return{occurrences:n,diagnostics:r};let g=jt({module:f,exportName:"default",allowNonRenderingGuards:!0});if(!g.ok)return s(e.entryFile),{occurrences:n,diagnostics:r};for(let m of g.roots)d(m,f.file,[],new Set,!0,null);return{occurrences:n,diagnostics:r}}function yf(e){let t=e;for(;t.isParenthesizedExpression()||t.isTSAsExpression()||t.isTSNonNullExpression()||t.isTSTypeAssertion();)t=t.get("expression");return t}function yo(e){let t=yf(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||yo(n)):t.isConditionalExpression()?yo(t.get("consequent"))&&yo(t.get("alternate")):t.isLogicalExpression()?yo(t.get("left"))&&yo(t.get("right")):!1}function Sc(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 Bw(e,t){if(Sc(e,t))return!0;let n=!1;return e.traverse({Identifier(r){Sc(r,t)&&(n=!0,r.stop())}}),n}function Hb(e){let t=e[0]?.getFunctionParent();if(!t)return{kind:"none"};let n=t.get("params")[0];return n?n.isAssignmentPattern()?Wb(n.get("left"),!0):Wb(n,!1):{kind:"none"}}function Wb(e,t){if(e.isObjectPattern()){let n=[],r=!1;for(let i of e.get("properties")){if(i.isObjectProperty()){if(i.node.computed){zn(i.get("value"))&&(r=!0);continue}let s=i.node.key;(On.isIdentifier(s)?s.name:On.isStringLiteral(s)?s.value:null)==="children"&&n.push(i);continue}i.isRestElement()&&zn(i.get("argument"))&&(r=!0)}if(n.length>1)return r||n.some(i=>zn(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=>jw(s))?t?{kind:"unproven"}:{kind:"supported",bindingNode:o.node}:{kind:"unproven"}}return zn(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=>$w(r))?{kind:"none"}:{kind:"unproven"}}return zn(e)?{kind:"unproven"}:{kind:"none"}}function zn(e){if(e.isIdentifier()){let t=e.scope.getBinding(e.node.name);return!!(t&&t.referencePaths.length>0)}return e.isAssignmentPattern()?zn(e.get("left")):e.isRestElement()?zn(e.get("argument")):e.isObjectPattern()?e.get("properties").some(t=>t.isObjectProperty()?zn(t.get("value")):t.isRestElement()?zn(t.get("argument")):!0):e.isArrayPattern()?e.get("elements").some(t=>t.node?zn(t):!1):!0}function jw(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 $w(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?On.isStringLiteral(n)&&n.value!=="children":On.isIdentifier(n)&&n.name!=="children"}function Uw(e){for(let t of e.get("openingElement").get("attributes")){if(t.isJSXAttribute()){let n=t.node.name;if(On.isJSXIdentifier(n)&&n.name==="children")return!0;continue}if(t.isJSXSpreadAttribute()&&qb(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(!On.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");qb(r)&&t.push(r)}}return t}function ls(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 qb(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 Vw(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=Ir(e.file,r.node.source.value,e.parsedModules);if(!o)return;let i=n.isImportDefaultSpecifier()?"default":On.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 Yb(e){return e==="component-export-unresolved"||e==="component-local-binding-unresolved"}function tx(e){let t=[],n=[];return nx(e.element,e,[],e.ownerNode,e.element,[],new Set,t,n),{roots:t,diagnostics:n}}function nx(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(Vd(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=vn({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 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}))}:{}}],p=d.roots.length>1?{kind:"component-definition",key:g}:r,y=new Set(s);y.add(g);let b=[];for(let E of d.returnAlternatives??[]){let x=ex(E),S=x?Qb(t.graph,f,x):[];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:f});return}b.push(S[0])}for(let E of d.roots){let x=ex(E),S=x?Qb(t.graph,f,x):[];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:f,structuralPath:e.identity.structuralPath});continue}nx(S[0],t,m,p,d.roots.length>1?S[0]:o,d.roots.length>1?m:i,y,a,c,b)}}function Qb(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 ex(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||!ox(e.projection.composition,e.composition)||e.graph.composition&&!ox(e.graph.composition,e.composition))return{roots:[],diagnostics:[us("composition-mismatch",e.entryFile)]};if(!e.parsedModules.has(e.entryFile))return{roots:[],diagnostics:[us("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(us("route-member-not-addressable",e.entryFile));continue}let s=Xw(e.graph,e.entryFile,i.sourceRange);if(s.length!==1){t.push(us(s.length?"route-root-ambiguous":"route-root-unresolved",e.entryFile));continue}let a=s[0],c=tx({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=Zb(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=vc(s,i.callChain.map(c=>c.callLocator.key));o.occurrences.get(s)?.filter(c=>c===a).length!==1&&t.push(us("render-occurrence-unproven",i.element.sourceFile))}return{roots:Jw(n,e.composition,o.occurrences),diagnostics:t}}function Jw(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:Kw("sha256").update(JSON.stringify([t,c,s.identity.key])).digest("hex"),rootRef:{key:s.identity.key,...a.length>1?{instanceIndex:a.indexOf(vc(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=rx(i);o.set(s,[...o.get(s)??[],i])}return r.map(i=>{let s=o.get(rx(i))??[i];return{...i,siblingIndex:s.indexOf(i),siblingRootKeys:s.filter(a=>a!==i).map(a=>a.rootKey)}})}function rx(e){return JSON.stringify([e.ownerNode.kind,e.ownerNode.key,e.parentStructuralPath,e.ownerCallKeys])}function Xw(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 ox(e,t){return e.routeId===t.routeId&&e.effectiveTemplateId===t.effectiveTemplateId}function us(e,t){return{code:e,message:"Page block roots could not be proven from the current source graph.",file:t}}import{SiteEditPageBlockDirectorySchema as zw,SiteEditPageBlockDescriptorSchema as Hw,SiteEditSourcePathSchema as sx}from"@vcp-dev/contracts";function kc(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}),ix(i,r,o,t,e)}}return{nodes:t,rootKeys:[...e.rootKeys]}}function ix(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}),ix(s,t,n,r,o))}}function ds(e){let t=[],n={...e.graph,composition:e.composition},r=Ma(kc(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=Yw(a,e.graph),f=d?e.parsedModules.get(d):void 0;if(!c||!l||l.sourceFile!==d||!u||!sx.safeParse(a.sourceFile).success||!d||!f||!sx.safeParse(d).success){t.push(bf("root-source-unavailable",a.sourceFile));continue}if(i.has(a.rootKey)){t.push(bf("block-key-ambiguous",a.sourceFile));continue}let g=Ae(u.source),m=Hw.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:Zw(a,e),capabilities:Ww(c,r),...Gw(c,r)});if(!m.success){t.push(bf("page-block-descriptor-invalid",a.sourceFile));continue}let p=m.data;o.push(p),i.set(a.rootKey,{blockKey:a.rootKey,composition:e.composition,documentVersion:e.documentVersion,descriptor:p,root:a,ownerFile:d,ownerSourceHash:Ae(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=zw.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 Ww(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 Gw(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 Yw(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 Zw(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 bf(e,t){return{code:e,message:"The page block source binding could not be proven.",file:t}}import xf from"@babel/traverse";import{BlockRenderRefSchema as qw,SiteEditPageBlockPositionSchema as Qw,SiteEditPageBlockTargetSchema as eO}from"@vcp-dev/contracts";var tO=typeof xf=="function"?xf:xf.default;function ei(e,t,n,r){if(!eO.safeParse(t).success)return Yt("INVALID_PARAMS","Invalid page block target.");if(n!==e.documentVersion)return Yt("VERSION_STALE","The page block index is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Yt("INVALID_TARGET","The target belongs to another composition.");let o=e.bindings.get(t.blockKey);return o?r&&(!qw.safeParse(r).success||r.key!==o.descriptor.rootRef.key||r.instanceIndex!==o.descriptor.rootRef.instanceIndex||r.instanceCount!==o.descriptor.rootRef.instanceCount)?Yt("INVALID_TARGET","The render occurrence does not match the target."):{ok:!0,binding:o}:Yt("INVALID_TARGET","The page block target was not found.")}function _c(e,t){if(!Qw.safeParse(t).success)return Yt("INVALID_PARAMS","Invalid page block boundary.");if(t.documentVersion!==e.documentVersion)return Yt("VERSION_STALE","The page block boundary is stale.");if(t.composition.routeId!==e.composition.routeId||t.composition.templateId!==e.composition.effectiveTemplateId)return Yt("INVALID_TARGET","The boundary belongs to another composition.");let n=e.bindings.get(t.anchorBlockKey);if(!n)return Yt("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 Yt("INVALID_TARGET","A verified sibling binding is unavailable.");let o=r.sort((u,d)=>u.root.siblingIndex-d.root.siblingIndex),i=ax(n);if(!i)return Yt("INVALID_TARGET","The operation owner call site is unavailable.");let s=cx(n,i);if(s===void 0)return Yt("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||!nO(cx(u,ax(u)),s))return Yt("INVALID_TARGET","Siblings do not share one proven source boundary.");let a=o.findIndex(u=>u.blockKey===n.blockKey);if(a<0)return Yt("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 ax(e){return e.ownerLocator.file===e.ownerFile?e.ownerLocator:null}function cx(e,t){if(!t)return;let n=_e(t.file,e.ownerSourceContent);if(!n.ok)return;let r=[];if(tO(n.module.ast,{JSXElement(i){let s=Ef(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=Ef(o.node);return i?{kind:"jsx-fragment",file:t.file,sourceRange:i}:void 0}if(o.isJSXElement()){let i=Ef(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 nO(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 Ef(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 Yt(e,t){return{ok:!1,code:e,message:t}}import dx from"node:path";import{SiteEditSourcePathSchema as pO}from"@vcp-dev/contracts";import Rc from"node:path";import Sf from"@babel/traverse";import*as Lr from"@babel/types";import{SiteEditSourcePathSchema as lx,SiteEditPageBlockTargetSchema as rO}from"@vcp-dev/contracts";var oO=typeof Sf=="function"?Sf:Sf.default;function ux(e){if(!e.operationId)return xt("INVALID_PARAMS","An operationId is required.");if(!rO.safeParse(e.target).success)return xt("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 xt("INVALID_TARGET","The request target does not match its resolved block binding.");if(e.documentVersion!==e.binding.documentVersion)return xt("VERSION_STALE","The resolved block belongs to a stale document version.");if(e.operation==="move-node"||e.operation==="remove-node")return xt("UNSUPPORTED_OPERATION","Move and remove are planned by the structural operation task.");if(!e.node)return xt("INVALID_PARAMS","An insert/replacement node is required.");let t=e.operation==="insert-child"?e.boundary?.ownerFile:e.binding.ownerFile;if(!t||!lx.safeParse(t).success)return xt("INVALID_TARGET","The exact owner source file is unavailable.");let n=e.files.get(t);if(n===void 0)return xt("INVALID_TARGET","The exact owner source is absent from the fixed file map.");if(Ae(n)!==e.binding.ownerSourceHash)return xt("VERSION_STALE","The owner source hash changed after target resolution.");let r=e.files.get(e.binding.descriptor.source.file);if(r===void 0||Ae(r)!==e.binding.descriptor.source.contentHash)return xt("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 xt("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 xt("INVALID_TARGET","The boundary anchor is not a verified same-owner sibling.");if(!o.parentLocator)return xt("UNSUPPORTED_OPERATION","A root without a source parent has no safe sibling insertion boundary.")}let i=sO(e.node,t,n,e.files);if(!i.ok)return i;let s=e.operation==="replace-node"?Bo({source:n,locator:iO(e.binding),node:{jsx:i.value.jsx}}):bn({source:n,locator:vf(o.parentLocator),anchorLocator:vf(o.anchorLocator),placement:o.placement,node:{jsx:i.value.jsx}});if(!s.ok)return xt("UNSUPPORTED_OPERATION",s.diagnostic.message);let a=s.source;if(i.value.import){let l=xn({source:a,moduleSpecifier:i.value.import.moduleSpecifier,imports:i.value.import.specifiers});if(!l.ok)return xt("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 iO(e){return vf(e.ownerLocator)}function vf(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 sO(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}>`}}:xt("INVALID_PARAMS","The native JSX tag is invalid.");if(!e.component)return xt("UNSUPPORTED_OPERATION","A materialized component entry is resolved by the materialization task.");let o=aO(t,e.component.source,r);if(!o)return xt("INVALID_TARGET","The component source is not in the safe fixed file map.");let i=_e(t,n);if(!i.ok)return xt("UNSUPPORTED_OPERATION",i.diagnostic.message);let s=cO(i.module.ast.program.body,e.component.source,e.component.exportName),a=s??uO(dO(e.component.exportName,o),lO(i.module.ast)),c=fO(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 aO(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Rc.posix.normalize(Rc.posix.join(Rc.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=>lx.safeParse(i).success&&n.has(i))??null:null}function cO(e,t,n){for(let r of e)if(!(!Lr.isImportDeclaration(r)||r.source.value!==t)){for(let o of r.specifiers)if(n==="default"&&Lr.isImportDefaultSpecifier(o)||n!=="default"&&Lr.isImportSpecifier(o)&&(Lr.isIdentifier(o.imported)?o.imported.name:o.imported.value)===n)return o.local.name}return null}function lO(e){let t=new Set;return oO(e,{Program(n){n.scope.crawl(),t=new Set(Object.keys(n.scope.bindings)),n.stop()}}),t}function uO(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function dO(e,t){let r=(e==="default"?Rc.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 fO(e){let t=[];for(let[n,r]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_:.-]*$/.test(n))return xt("INVALID_PARAMS","A component prop name is invalid.");let o;try{o=JSON.stringify(r)}catch{return xt("INVALID_PARAMS","Component props must be JSON serializable.")}if(o===void 0)return xt("INVALID_PARAMS","Component props must be JSON serializable.");t.push(`${n}={${o}}`)}return{ok:!0,value:t.join(" ")}}function xt(e,t){return{ok:!1,code:e,message:t}}function fx(e){if(e.materialization.kind!=="static-prefab-materialization"||!e.materialization.files.some(i=>i.path===e.materialization.entry.path))return Cc("MATERIALIZATION_ENTRY_INVALID","The materialization entry must identify one controlled create-only file.");if(!e.materialization.files.every(i=>i.kind==="create-only"&&pO.safeParse(i.path).success))return Cc("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 Cc("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 Cc("INVALID_TARGET","The exact page-block owner source is missing from the fixed file map.");let n=gO(t,e.materialization.entry.path),r=ux({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:mO(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 mO(e,t){let n=new Map(e);for(let r of t.files)n.set(r.path,r.content);return n}function gO(e,t){let n=dx.posix.relative(dx.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Cc(e,t){return{ok:!1,code:e,message:t}}import{PageTemplateIdSchema as RO}from"@vcp-dev/contracts";import Sz from"node:fs";import Iz from"node:path";var hO=/^page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function fs(e){let t=e.map(r=>_O(r.path)),n=yO(t);return n?t.filter(r=>xO(n,r)).map(r=>({routeId:EO(n,r),entryFile:r})).sort((r,o)=>r.routeId.localeCompare(o.routeId)):[]}function If(e,t=""){let r=((e??"/").trim()||"/").split(/[?#]/,1)[0]||"/",o=r.startsWith("/")?r:`/${r}`,i=kO(t),s=i&&(o===i||o.startsWith(`${i}/`))?o.slice(i.length)||"/":o,a=s.startsWith("/")?s:`/${s}`;return a==="/"?"/":a.replace(/\/+$/,"")}function yO(e){return e.some(r=>r.startsWith("app/")&&!bO(r))?"app":e.some(r=>r.startsWith("src/app/"))?"src/app":null}function bO(e){return/^(?:src\/)?app\/(?:_vcp|\.vcp)/.test(e)}function xO(e,t){if(!t.startsWith(`${e}/`))return!1;let n=t.slice(t.lastIndexOf("/")+1);return hO.test(n)?t.slice(e.length+1,-n.length-1).split("/").filter(Boolean).every(r=>!r.startsWith("_")&&!r.startsWith(".")):!1}function EO(e,t){let n=t.slice(e.length+1).split("/").slice(0,-1).map(vO).filter(r=>!!r);return n.length===0?"/":`/${n.join("/")}`}function SO(e){return e.startsWith("(")&&e.endsWith(")")}function vO(e){return!e||e.startsWith("@")||e.startsWith("_")||SO(e)?null:IO(e)}function IO(e){return e.replace(/^\((?:\.|\.\.|\.\.\.)\)/,"")}function kO(e){let t=e.trim();return!t||t==="/"?"":(t.startsWith("/")?t:`/${t}`).replace(/\/+$/,"")}function _O(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}var ps=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="PageTemplateManagedSourceError"}};function Zt(e,t={}){throw new ps("PAGE_TEMPLATE_MANAGED_SOURCE_INVALID",`Invalid page-template source (${e}): ${t.path??t.routeId??t.templateId??""}`,{reason:e,...t})}function kf(e){return RO.safeParse(e).success||Zt("invalid-template-id",{templateId:e}),Buffer.from(e,"utf8").toString("base64url")}function px(e){/^[A-Za-z0-9_-]{1,255}$/.test(e)||Zt("invalid-template-key",{path:e});let t;try{t=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.from(e,"base64url"))}catch{return Zt("invalid-template-key",{path:e})}return kf(t)!==e&&Zt("noncanonical-template-key",{path:e}),t}function CO(e){let t=If(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("(")||PO(r)&&!mx(r)))&&Zt("invalid-public-route",{routeId:e}),t}function PO(e){return e.includes("[")||e.includes("]")}function mx(e){return/^\[\[\.\.\.[^\[\]]+\]\]$|^\[[^\[\]]+\]$/.test(e)}function gx(e){return e.some(mx)}function hx(e,t,n="app"){n!=="app"&&n!=="src/app"&&Zt("invalid-app-root");let r=CO(e),o=kf(t),i=gx(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))&&Zt("path-too-long",{path:a}),{appRoot:n,routeRoot:s,templateKey:o,templateEntryFile:a}}function yx(e){return/^(?:src\/)?app\/\.vcp\/page-templates\//.test(e)}function bx(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===".")&&Zt("invalid-file-path",{path:i}),n.has(i)&&Zt("duplicate-file-path",{path:i}),n.set(i,o)}return n}function Nc(e){let t=bx(e.files),n=fs([...t.keys()].map(i=>({path:i}))),r=new Map;for(let i of n){if(r.has(i.routeId))throw new ps("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(!yx(i))continue;let s=/^(app|src\/app)\/\.vcp\/page-templates\/(.+)\/page\.tsx$/.exec(i);s||Zt("candidate-must-be-single-page",{path:i});let a=s[1],c=s[2].split("/"),l=gx(c),u=l?c[0]:c.pop(),d=l?c.slice(1):c,f=px(u),g=d.length?`/${d.join("/")}`:"/";hx(g,f,a).templateEntryFile!==i&&Zt("candidate-path-mismatch",{path:i,routeId:g});let p=r.get(g);(!p||!p.startsWith(`${a}/`))&&Zt("canonical-entry-missing",{path:i,routeId:g}),o.push({routeId:g,templateId:f,entryFile:i,canonicalEntryFile:p,appRoot:a})}return o.sort((i,s)=>Pc(i.routeId,s.routeId)||Pc(i.templateId,s.templateId))}function Ac(e){let t=bx(e.files),n=Nc({files:t}),r=fs([...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)=>Pc(o.context.routeId,i.context.routeId)||(o.context.effectiveTemplateId===void 0?-1:i.context.effectiveTemplateId===void 0?1:Pc(o.context.effectiveTemplateId,i.context.effectiveTemplateId)))}function NO(e){let t=If(e.selector.routeId),n=Ac({files:e.files}),r=n.find(i=>i.context.routeId===t&&i.context.effectiveTemplateId===void 0);(!r||r.entryFile!==e.canonicalEntryFile)&&Zt("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||Zt("template-selection-not-found",{routeId:t,templateId:e.selector.templateId}),{...o,mode:e.selector.templateId===void 0?"direct":"candidate",effectiveEntryFile:o.entryFile}}function Pc(e,t){return e<t?-1:e>t?1:0}import{HOME_PAGE_URL_PATH as ZO}from"@vcp-dev/contracts";import{parse as KO}from"@babel/parser";import{parse as jz}from"@babel/parser";import{FormBlockIdSchema as Uz,FormSpecV1Schema as Vz}from"@vcp-dev/contracts";import{posix as wz}from"node:path";import AO from"@babel/traverse";var _f=AO,Fz=typeof _f=="function"?_f:_f.default,Lz=Symbol("unknown-member");var ms="components/site/generated/forms",Jz=`${ms}/vcp-form-runtime.tsx`,Tc="[A-Za-z0-9][A-Za-z0-9_-]{0,127}",Xz=new RegExp(`^${ms}/form-(${Tc})\\.spec\\.ts$`),zz=new RegExp(`^${ms}/form-(${Tc})\\.tsx$`),Hz=new RegExp(`^@/${ms}/form-(${Tc})$`),Wz=new RegExp(`(?:^|/)${ms}/form-(${Tc})(?:\\.tsx?)?$`);var Gz=Symbol("invalid-literal");import{createHash as qz}from"node:crypto";import{posix as eH}from"node:path";import{parse as nH}from"@babel/parser";import{FormSpecV1Schema as oH}from"@vcp-dev/contracts";var iH=Symbol("dynamic");import{parse as TO}from"@babel/parser";function wc(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.type=="string"):[]}var wO=/^(?:src\/)?app\/(.*)page\.(?:tsx|ts|jsx|js|mjs|cjs)$/;function xx(e){let t=wO.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 OO(e){let t=e;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function Ex(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function FO(e){let t=e;for(;t&&(t.type==="TSAsExpression"||t.type==="TSSatisfiesExpression"||t.type==="ParenthesizedExpression");)t=t.expression??null;return t}function Rf(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(Rf);if(t?.type==="ObjectExpression"){let n={};for(let r of wc(t.properties)){if(r.type!=="ObjectProperty"||r.computed)throw new Error("dynamic object property");let o=Ex(r.key);if(!o)throw new Error("unsupported object key");n[o]=Rf(r.value)}return n}throw new Error(`unsupported static value: ${t?.type??"unknown"}`)}function Cf(e,t){let n=[],r=xx(t);if(r===null)return{found:!1,seo:null,diagnostics:n};let o;try{o=TO(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 wc(o.program.body)){let u=l.type==="ExportNamedDeclaration"?l.declaration:l;if(u?.type==="VariableDeclaration")for(let d of wc(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=FO(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 wc(s.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=Ex(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=OO(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=Rf(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 LO}from"@babel/parser";var Sx=["page","anchor","external","email","phone","group","file"],DO=["link","cta"],Ix=["description","badge","iconKey"],Pf=["label","targetType","href","role","openInNewTab","nofollow","children",...Ix],MO=new Set(Pf);function hs(e){return Array.isArray(e)?e:[]}function gs(e){let t=e;return t?.type==="StringLiteral"&&typeof t.value=="string"?t.value:void 0}function BO(e){let t=e;if(t?.type==="Identifier")return t.name;if(t?.type==="StringLiteral"&&typeof t.value=="string")return t.value}function vx(e){let t=e;return t?.type==="BooleanLiteral"&&typeof t.value=="boolean"?t.value:void 0}function Nf(e){let t=[],n;try{n=LO(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 hs(n.program.body)){let s=i.type==="ExportNamedDeclaration"?i.declaration:i;if(s?.type==="VariableDeclaration")for(let a of hs(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 hs(r.elements).forEach((i,s)=>{let a=kx(i,`NAV_ITEMS[${s}]`,t);a&&o.push(a)}),{items:o,diagnostics:t}}function kx(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 hs(e.properties)){if(l.type!=="ObjectProperty"||l.computed)continue;let u=BO(l.key);u&&(r[u]=l.value)}let o=gs(r.label),i=gs(r.targetType);if(!o)return n.push({severity:"fatal",path:`${t}.label`,message:"label must be a static string"}),null;if(!i||!Sx.includes(i))return n.push({severity:"fatal",path:`${t}.targetType`,message:`targetType must be one of ${Sx.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 Ix){if(r[l]===void 0)continue;let u=gs(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))MO.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 ${Pf.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=[];hs(r.children.elements).forEach((u,d)=>{let f=kx(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=gs(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=gs(r.role);if(c!==void 0&&(DO.includes(c)?s.role=c:n.push({severity:"warning",path:`${t}.role`,message:"role ignored: not link/cta"})),r.openInNewTab!==void 0){let l=vx(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=vx(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 jO}from"@babel/parser";function ys(e){return Array.isArray(e)?e:[]}function _x(e){let t=e;for(;t?.type==="TSAsExpression"||t?.type==="TSSatisfiesExpression";)t=t.expression;return t?.type==="ArrayExpression"?t:void 0}function $O(e){let t;try{t=jO(e,{sourceType:"module",plugins:["typescript","jsx"],tokens:!0})}catch{return{status:"unsupported"}}let n=[];for(let o of ys(t.program.body)){let i=o.type==="ExportNamedDeclaration"?o.declaration:o;if(i?.type==="VariableDeclaration")for(let s of ys(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=_x(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 Af(e,t){let n=Rx(t);if(!n)return{status:"unsupported",source:e};let r=$O(e);if(r.status!=="ok")return{status:r.status,source:e};let o=r.array;if(Nf(e).diagnostics.some(({severity:l})=>l==="fatal"))return{status:"unsupported",source:e};let s=[],a=l=>{let u=ys(l.elements);for(let[d,f]of u.entries()){if(VO(f,n)){let m=u[d+1],p=u[d-1],y=f.start,b=f.end;if(typeof y!="number"||typeof b!="number")continue;if(m&&typeof m.start=="number")s.push({start:y,end:m.start});else if(p&&typeof p.end=="number")s.push({start:p.end,end:b});else{let E=/^\s*,/.exec(e.slice(b));s.push({start:y,end:E?b+E[0].length:b})}continue}let g=UO(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 UO(e){if(e.type==="ObjectExpression")for(let t of ys(e.properties)){if(t.type!=="ObjectProperty")continue;let n=t.key;if((n?.name??n?.value)==="children")return _x(t.value)}}function Rx(e){let t=e.trim();return t.startsWith("/")?t==="/"?t:t.replace(/\/+$/,""):null}function VO(e,t){if(e.type!=="ObjectExpression")return!1;let n,r;for(let o of ys(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"&&Rx(n??"")===t}import{estimateNavLabelWidth as gH}from"@vcp-dev/contracts";import{parse as bH}from"@babel/parser";function _n(e,t){let n;try{n=KO(e,{sourceType:"module",sourceFilename:t.filePath,plugins:["jsx","typescript"]})}catch(A){let C=A.loc;return{form_codes:[],components:[],uncertain_components:[],rendered_component_openings:[],renders_native_form:!1,diagnostics:[{code:"rendered-module.parse-failed",message:A instanceof Error?A.message:"Rendered module failed Babel parsing.",file_path:t.filePath??"",line:C?.line??1}]}}let r=n.program,o=an(r?.body),i=new Map,s=new Map,a=new Map,c=new Map,l=A=>{if(A?.type==="FunctionDeclaration"){let C=A.id;C?.type==="Identifier"&&typeof C.name=="string"&&s.set(C.name,A);return}if(A?.type==="VariableDeclaration")for(let C of an(A.declarations)){let w=C.id,M=C.init;w?.type==="Identifier"&&typeof w.name=="string"&&M&&(Dr(M)?s.set(w.name,M):M.type==="Identifier"&&typeof M.name=="string"&&a.set(w.name,M.name))}};for(let A of o){if(A.type==="ImportDeclaration"){let C=A.source?.value;if(typeof C!="string")continue;for(let w of an(A.specifiers)){let M=w.local;if(!(M?.type!=="Identifier"||typeof M.name!="string")){if(w.type==="ImportDefaultSpecifier")i.set(M.name,{source:C,exportName:"default"});else if(w.type==="ImportNamespaceSpecifier")i.set(M.name,{source:C,exportName:"*"});else if(w.type==="ImportSpecifier"){let D=w.imported,U=D?.type==="Identifier"&&typeof D.name=="string"?D.name:D?.type==="StringLiteral"&&typeof D.value=="string"?D.value:"";U&&i.set(M.name,{source:C,exportName:U})}}}continue}A.type==="ExportNamedDeclaration"?l(A.declaration):l(A)}for(let A of o){if(A.type==="ExportDefaultDeclaration"){let M=A.declaration;M&&Dr(M)?c.set("default",M):M?.type==="Identifier"&&typeof M.name=="string"&&c.set("default",M.name);continue}if(A.type!=="ExportNamedDeclaration")continue;let C=A.declaration;if(C?.type==="FunctionDeclaration"){let M=C.id;M?.type==="Identifier"&&typeof M.name=="string"&&c.set(M.name,M.name)}else if(C?.type==="VariableDeclaration")for(let M of an(C.declarations)){let D=M.id;D?.type==="Identifier"&&typeof D.name=="string"&&c.set(D.name,D.name)}let w=A.source?.value;for(let M of an(A.specifiers)){let D=Nx(M.local),U=Nx(M.exported);if(!(!D||!U))if(typeof w=="string"){let B=`#re-export:${U}`;i.set(B,{source:w,exportName:D}),c.set(U,B)}else c.set(U,D)}}let u=new Set,d=[],f=new Set,g=[],m=new Set,p=[],y=new Map,b=!1,E=[],x=new Map,S=new Map,v=(A,C="rendered")=>{let w=Px(A,i);if(!w)return!1;let M=`${w.source}\0${w.exportName}`;if(C==="uncertain")return!f.has(M)&&!m.has(M)&&(m.add(M),g.push({source:w.source,export_name:w.exportName})),!0;if(!f.has(M)&&(f.add(M),d.push({source:w.source,export_name:w.exportName}),m.delete(M))){let D=g.findIndex(U=>U.source===w.source&&U.export_name===w.exportName);D>=0&&g.splice(D,1)}return!0},N=(A,C="rendered",w=[])=>{let M=`${C}\0${wf(w)}`,D=x.get(A)??new Set,U=S.get(A)??new Set;if(D.has(M)||U.has(C))return;D.add(M),x.set(A,D),U.add(C),S.set(A,U);let B=new Map(s),G=new Map,K=[],ge=(be,st=!1)=>{if(Oc(be)){if(!st&&Dr(be)){if(be.type==="FunctionDeclaration"){let Ke=be.id;Ke?.type==="Identifier"&&typeof Ke.name=="string"&&B.set(Ke.name,be)}return}if(be.type==="VariableDeclarator"){let Ke=be.id,F=be.init;Ke?.type==="Identifier"&&typeof Ke.name=="string"&&F&&(Dr(F)?B.set(Ke.name,F):G.set(Ke.name,F))}else if(be.type==="ReturnStatement"){let Ke=be.argument;Ke&&K.push(Ke)}if(be.type==="CallExpression"){let Ke=be.callee;if(Ke?.type==="Import"&&E.push({code:"rendered-module.dynamic-import",message:"Rendered component graph must use static imports.",file_path:t.filePath??"",line:be.loc?.start.line??1}),bs(Ke)==="cms.forms.getConfig"){let F=an(be.arguments)[0];F?.type==="StringLiteral"&&typeof F.value=="string"&&F.value.trim()?C==="rendered"?u.add(F.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:be.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:be.loc?.start.line??1})}}for(let[Ke,F]of Object.entries(be))if(Ke!=="loc")if(Array.isArray(F))for(let Z of F)ge(Z);else ge(F)}};ge(A,!0);let oe=new Set,Le=new Set,Je=(be,st=C,Ke=w)=>{if(!(!Oc(be)||Dr(be))){if(be.type==="Identifier"&&typeof be.name=="string"){let F=G.get(be.name),Z=`${st}\0${be.name}\0${wf(Ke)}`;F&&!oe.has(Z)&&!Le.has(be.name)?(oe.add(Z),Le.add(be.name),Je(F,st,Ke),Le.delete(be.name)):v(be.name,st);return}if(be.type==="CallExpression"){let F=be.callee,Z=an(be.arguments),ue=bs(F),Ue=F?.type==="Identifier"&&typeof F.name=="string"?i.get(F.name):void 0;if(st==="rendered"&&(ue==="createElement"||ue.endsWith(".createElement")||Ue?.source==="react"&&Ue.exportName==="createElement")&&Z[0]?.type==="StringLiteral"&&Z[0].value==="form"&&(b=!0),F?.type==="Identifier"&&typeof F.name=="string"){let Ge=B.get(F.name);if(Ge){N(Ge,st,Ke);return}}if(F&&Dr(F)){N(F,st,Ke);return}if(zO(F)){for(let Ge of Z)if(Dr(Ge))N(Ge,st,Ke);else if(Ge.type==="Identifier"&&typeof Ge.name=="string"){let Pn=B.get(Ge.name);Pn&&N(Pn,st,Ke)}return}for(let Ge of Z)HO(Ge)&&E.push({code:"rendered-module.unresolved-export",message:"Unable to prove whether a JSX-producing call argument is rendered.",file_path:t.filePath??"",line:Ge.loc?.start.line??1});return}if(be.type==="JSXElement"){let F=be.openingElement,Z=F?Cx(Ke,JO(F)):Ke;Je(F,st,Z);for(let ue of an(be.children))Je(ue,st,Z);return}if(be.type==="JSXOpeningElement"){let F=Fc(be.name);st==="rendered"&&F==="form"&&(b=!0);let Z=F?Px(F,i):void 0;if(st==="rendered"&&Z&&typeof be.start=="number"){let ue=`${Z.source}\0${Z.exportName}\0${be.start}`,Ue=y.get(ue);if(!Ue){let Ge=WO(be).get("formBlockId");Ue={source:Z.source,export_name:Z.exportName,start_offset:be.start,...typeof Ge=="string"?{static_form_block_id:Ge}:{}},y.set(ue,Ue),p.push(Ue)}Ke.length>0&&(Ue.static_render_blockers=Cx(Ue.static_render_blockers??[],Ke))}if(F&&!v(F,st)){let ue=B.get(F);ue?N(ue,st,Ke):G.has(F)?Je(G.get(F),st,Ke):XO(F)||/^[A-Z]/.test(F)&&E.push({code:"rendered-module.dynamic-import",message:`Unable to resolve rendered component ${F} from a static import.`,file_path:t.filePath??"",line:be.loc?.start.line??1})}for(let ue of an(be.attributes))Je(ue,"uncertain",Ke);return}if(be.type==="JSXAttribute"){let F=be.value,Z=F?.type==="JSXExpressionContainer"?F.expression:F;Z&&Dr(Z)?N(Z,"uncertain",Ke):Je(Z,"uncertain",Ke);return}for(let[F,Z]of Object.entries(be))if(!(F==="loc"||F==="closingElement"))if(Array.isArray(Z))for(let ue of Z)Je(ue,st,Ke);else Je(Z,st,Ke)}},mt=A.body;mt&&mt.type!=="BlockStatement"&&K.push(mt);for(let be of K)Je(be);U.delete(C)},R=c.get(t.exportName);if(typeof R=="string"){let A=R,C=new Set;for(;a.has(A)&&!C.has(A);)C.add(A),A=a.get(A);if(!v(A)){let w=s.get(A);w?N(w):E.push(Ax(t))}}else R?N(R):E.push(Ax(t));return{form_codes:[...u],components:d,uncertain_components:g,rendered_component_openings:p,renders_native_form:b,diagnostics:E}}function wf(e){return e.map(t=>`${t.start_offset}:${t.reason}`).join("|")}function Cx(e,t){return[...new Map([...e,...t].map(r=>[wf([r]),r])).values()]}function JO(e){let t=new Map;for(let a of an(e.attributes)){if(a.type==="JSXSpreadAttribute"){t.clear();continue}let c=Tx(a.name);if(!c)continue;let l=a.value;t.set(c,l?.type==="JSXExpressionContainer"?l.expression:l)}let n=Fc(e.name)??"unknown",r=[],o=a=>{r.push({element_name:n,line:e.loc?.start.line??1,start_offset:YO(e.start),reason:a})};for(let a of["hidden","inert","aria-hidden","disabled"]){if(!t.has(a)||a==="disabled"&&n!=="fieldset")continue;let c=Tf(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 an(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,Tf(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=Tf(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 Tf(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"&&an(e.expressions).length===0)return an(e.quasis)[0]?.value?.cooked}}function Px(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 XO(e){return e.endsWith(".Provider")||e.endsWith(".Consumer")}function Dr(e){return e?.type==="FunctionDeclaration"||e?.type==="FunctionExpression"||e?.type==="ArrowFunctionExpression"}function zO(e){let t=bs(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 HO(e){let t=!1;return Of(e,n=>{if(!t){if(n.type==="JSXOpeningElement"){t=!0;return}n.type==="CallExpression"&&bs(n.callee)==="cms.forms.getConfig"&&(t=!0)}}),t}function Nx(e){return e?.type==="Identifier"&&typeof e.name=="string"?e.name:e?.type==="StringLiteral"&&typeof e.value=="string"?e.value:""}function Ax(e){return{code:"rendered-module.unresolved-export",message:`Unable to resolve rendered export ${e.exportName}.`,file_path:e.filePath??"",line:1}}function bs(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=bs(e.object),n=e.property;return!t||n?.type!=="Identifier"||typeof n.name!="string"?"":`${t}.${n.name}`}function WO(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=Tx(o.name);i&&t.set(i,GO(o.value))}return t}function GO(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 Tx(e){let t=e;if(t?.type==="JSXIdentifier")return typeof t.name=="string"?t.name:void 0}function YO(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function Of(e,t){if(Oc(e)){t(e);for(let[n,r]of Object.entries(e))if(n!=="loc"){if(Array.isArray(r)){for(let o of r)Of(o,t);continue}Of(r,t)}}}function Oc(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Fc(e){let t=e;if(!t)return"";if(t.type==="JSXIdentifier")return typeof t.name=="string"?t.name:"";if(t.type==="JSXMemberExpression"){let n=Fc(t.object),r=Fc(t.property);return n&&r?`${n}.${r}`:r||n}return""}function an(e){return Array.isArray(e)?e.filter(t=>Oc(t)):[]}var qO="components/site/generated/",xs=[".tsx",".ts",".jsx",".js"];function wx(e){if(e.expectedUrlPath===ZO)return{ok:!1,code:"HOME_PAGE_LOCKED",message:"The homepage source is protected from deletion."};let t=new Set(fs(Object.keys(e.files).map(p=>({path:p}))).map(p=>p.entryFile)),n=Object.entries(e.files).filter(([p,y])=>{let b=p.replace(/\\/g,"/");if(!t.has(b))return!1;let E=Cf(y,b);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 p=Nc({files:new Map(Object.entries(e.files))});for(let y of p)y.canonicalEntryFile===r&&o.add(y.entryFile)}catch(p){return{ok:!1,code:"SOURCE_DEPENDENCY_UNSAFE",message:p instanceof Error?p.message:"Invalid page template source."}}let i=QO(e.files);if(!i.ok)return i.error;let s=i.graph,a=rF(o,s),c=oF(o,a,s),l=[...a].filter(p=>!c.has(p)).sort((p,y)=>p.localeCompare(y)),u=[...o,...[...c].sort((p,y)=>p.localeCompare(y))],d=new Set(u),f=u.map(p=>({operation:"delete",file:p})),g=[],m=[];for(let[p,y]of Object.entries(e.files))if(!d.has(p)){if(y.includes("NAV_ITEMS")){let b=Af(y,e.expectedUrlPath);b.status==="removed"?(f.push({operation:"upsert",file:p,content:b.source}),g.push(p)):b.status==="unsupported"&&m.push(`unsupported_navigation:${p}`)}y.includes(e.expectedUrlPath)&&!y.includes("NAV_ITEMS")&&m.push(`preserved_link:${p}`)}return{ok:!0,edits:f,deletedFiles:u,updatedFiles:g,preservedSharedFiles:l,warnings:m}}function QO(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")||!eF(r))continue;let s=_e(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(tF(c))continue;let l=$n(r,c),u=nF(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 eF(e){let t=e.toLowerCase();return xs.some(n=>t.endsWith(n))}function tF(e){return!!(/\.([a-z0-9]+)$/i.exec(e)&&!xs.some(n=>e.endsWith(n)))}function nF(e,t){let n=e.replace(/\\/g,"/");return(xs.some(o=>n.endsWith(o))?[n]:[...xs.map(o=>`${n}${o}`),...xs.map(o=>`${n}/index${o}`)]).find(o=>t.has(o))??null}function rF(e,t){let n=new Set,r=[...e].flatMap(o=>[...t.get(o)??[]]);for(;r.length>0;){let o=r.pop();!o.startsWith(qO)||n.has(o)||(n.add(o),r.push(...t.get(o)??[]))}return n}function oF(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 OE from"@babel/parser";import*as je from"@babel/types";import*as qc from"node:path";import*as Ye from"@babel/types";function Ox(e){if(e.path.isVariableDeclarator()){let n=e.path.get("init");return n?.isExpression()?{expressionPath:n}:null}if(!e.path.isIdentifier()||!e.path.parentPath?.isVariableDeclarator())return null;let t=e.path.parentPath.get("init");return t?.isExpression()?{expressionPath:t}:null}function Hn(e){if(e.path.isObjectPattern()||e.path.isArrayPattern())return bo(e.path.node,e.identifier.name);if(e.path.isVariableDeclarator()){let n=e.path.node.id;if(Ye.isObjectPattern(n)||Ye.isArrayPattern(n))return bo(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(sF(e.path,n))return!0}if(t.isFunction()||t.isVariableDeclarator())return!1;t=t.parentPath}return!1}function bo(e,t,n=!1){return Ye.isIdentifier(e)?e.name===t&&n:Ye.isObjectPattern(e)?e.properties.some(r=>Ye.isObjectProperty(r)?bo(r.value,t,n):bo(r.argument,t,n)):Ye.isArrayPattern(e)?e.elements.some(r=>{if(!r)return!1;let o=Ye.isRestElement(r)?r.argument:r;return bo(o,t,n)}):Ye.isAssignmentPattern(e)?bo(e.left,t,!0):Ye.isRestElement(e)?bo(e.argument,t,n):!1}function ti(e,t){if(e.path.isObjectPattern()){if(t){let r=Fn(e.path.node,t.base),[o,...i]=r??[];if(o?.kind==="property")return{propName:o.name,remainingPath:[...i,...t.path],hasDefault:Hn(e)}}return t?{propName:t.base,remainingPath:t.path,hasDefault:Hn(e)}:null}if(e.path.isVariableDeclarator()){let r=e.path.get("init");if(r?.isExpression()){let o=Fx(r),i=!1,s=o?o.initBinding&&Ff(o.initBinding)?(i=Hn(o.initBinding),[...o.initPathPrefix]):o.initBinding?(()=>{let c=ti(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=Fn(e.path.node.id,e.identifier.name);if(s&&a){let c=[...s,...a],[l,...u]=c;return!l||l.kind!=="property"?null:{propName:l.name,remainingPath:[...u,...t?.path??[]],hasDefault:i||Hn(e)}}}}let n=lF(e);if(n){let r=iF(n,e);if(r){let[s,...a]=r.path;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:r.hasDefault||Hn(e)}}if(n.findParent(s=>s.isVariableDeclarator()))return null;let o=aF(e);if(o){let[s,...a]=o;return!s||s.kind!=="property"?null:{propName:s.name,remainingPath:[...a,...t?.path??[]],hasDefault:Hn(e)}}let i=Es(n.node);return i?{propName:i,remainingPath:t?.path??[],hasDefault:Hn(e)}:null}if(Ff(e)){let[r,...o]=t?.path??[];return!r||r.kind!=="property"?null:{propName:r.name,remainingPath:o,hasDefault:Hn(e)}}return null}function iF(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=Fx(r);if(!o)return null;let{initBinding:i,initPathPrefix:s}=o;if(!i)return null;let a=!1,c=Ff(i)?(a=Hn(i),[...s]):(()=>{let u=ti(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=Fn(n.node.id,t.identifier.name);return l?{path:[...c,...l],hasDefault:a||Hn(t)}:null}function Fx(e){if(e.isIdentifier())return{initBinding:e.scope.getBinding(e.node.name),initPathPrefix:[]};if(!e.isMemberExpression())return null;let t=uF(e.node);return t?{initBinding:e.scope.getBinding(t.base),initPathPrefix:t.path}:null}function Ff(e){return e.path.isIdentifier()&&e.path.key===0&&Array.isArray(e.path.container)&&e.path.parentPath?.isFunction()===!0}function sF(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function aF(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=Fn(i.node,t);if(a)return a}return null}function Lx(e,t,n){if(e.path.isVariableDeclarator()){let a=e.path.get("id");if(!Array.isArray(a)&&(a.isObjectPattern()||a.isArrayPattern())){let c=Lc(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=Es(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=cF(e);if(!r)return null;let o=r.parentPath;if(!o?.isObjectProperty())return null;let i=Es(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 Lc(e,t){if(e.isObjectPattern()){for(let n of e.get("properties"))if(n.isObjectProperty()){let r=Es(n.node),o=n.get("value");if(o.isAssignmentPattern()){let i=o.get("left"),s=o.get("right");if(r&&!Array.isArray(i)&&Fn(i.node,t)&&!Array.isArray(s)&&s.isExpression())return{propName:r,expressionPath:s}}if(!Array.isArray(o)&&(o.isObjectPattern()||o.isArrayPattern())){let i=Lc(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=Lc(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=Lc(r,t);if(o)return o}}return null}function Fn(e,t,n=[]){if(Ye.isIdentifier(e))return e.name===t?n:null;if(Ye.isObjectPattern(e)){for(let r of e.properties)if(Ye.isObjectProperty(r)){let o=Es(r);if(!o)continue;let i=Fn(r.value,t,[...n,{kind:"property",name:o}]);if(i)return i}else if(Ye.isRestElement(r)){let o=Fn(r.argument,t,n);if(o)return o}}if(Ye.isArrayPattern(e))for(let r=0;r<e.elements.length;r+=1){let o=e.elements[r];if(!o)continue;let i=Ye.isRestElement(o)?o.argument:o,s=Fn(i,t,[...n,{kind:"index",index:r}]);if(s)return s}return Ye.isAssignmentPattern(e)?Fn(e.left,t,n):null}function cF(e){if(!e.path.isIdentifier())return null;let t=e.path.parentPath;return t?.isAssignmentPattern()&&t.node.left===e.path.node?t:null}function lF(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 Es(e){return e.computed?null:Ye.isIdentifier(e.key)?e.key.name:Ye.isStringLiteral(e.key)?e.key.value:null}function uF(e){let t=[],n=e;for(;Ye.isMemberExpression(n);){if(n.computed)if(Ye.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Ye.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(Ye.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return Ye.isIdentifier(n)?{base:n.name,path:t}:null}import*as Ux from"@babel/parser";import Mf from"@babel/traverse";import*as ni from"@babel/types";import*as we from"@babel/types";var Dx=new WeakMap;function Bc(e,t=[]){if(e.isIdentifier()){let n=e.scope.getBinding(e.node.name);return n?Dc(n,t):null}if(e.isMemberExpression()){let n=hF(e.node),r=dF(e.node);if(!n||r===null)return null;let o=e.scope.getBinding(n);return o?Dc(o,[...r,...t]):null}return e.isAwaitExpression()||Df(e.node)?Mr(bF(e.node),t,"awaited or fetched expression"):null}function dF(e){let t=[],n=e;for(;we.isMemberExpression(n);){if(n.computed)if(we.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(we.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else if(we.isIdentifier(n.property))t.unshift({kind:"property",name:n.property.name});else return null;n=n.object}return we.isIdentifier(n)?t:null}function Dc(e,t=[],n){let r=fF(e,t);if(r)return r;let o=pF(e,t,n);if(o)return o;let i=mF(e,t,n);return i||null}function vs(e){return e?.kind==="api-source"}function fF(e,t){if(e.path.isVariableDeclarator()&&we.isIdentifier(e.path.node.id)){let s=e.path.get("init");if(s?.isCallExpression()&&Lf(s.node)&&t[0]?.kind==="property"&&t[0].name==="data")return Mr(e.identifier.name,t,"query hook result.data binding")}if(e.path.isVariableDeclarator()&&we.isObjectPattern(e.path.node.id)){let s=e.path.node.id.properties.find(c=>we.isObjectProperty(c)&&jx(c)==="data"&&Ss(c.value,e.identifier.name)),a=e.path.get("init");if(s&&a?.isCallExpression()&&Lf(a.node))return Mr(e.identifier.name,t,"query hook data binding")}let n=gF(e);if(!n||jx(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()||!Lf(i.node)?null:Mr(e.identifier.name,t,"query hook data binding")}function pF(e,t,n){if(e.path.isVariableDeclarator()&&we.isArrayPattern(e.path.node.id)){let c=e.path.get("init");if(!c?.isCallExpression()||!Bx(c.node))return null;let[l,u]=e.path.node.id.elements;return!we.isIdentifier(l)||l.name!==e.identifier.name||!we.isIdentifier(u)?null:Mx(e,u.name,n)?Mr(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()||!Bx(i.node)||r.node.elements.findIndex(c=>c===e.path.node)!==0)return null;let a=r.node.elements[1];return we.isIdentifier(a)&&Mx(e,a.name,n)?Mr(e.identifier.name,t,"state setter is updated by API data"):null}function mF(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()?Mr(e.identifier.name,t,"awaited binding result"):Df(o.node,n)?Mr(e.identifier.name,t,"fetch-backed binding result"):null:null}function gF(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 Ss(e,t){return we.isIdentifier(e)?e.name===t:we.isAssignmentPattern(e)?Ss(e.left,t):we.isObjectPattern(e)?e.properties.some(n=>we.isObjectProperty(n)?Ss(n.value,t):Ss(n.argument,t)):we.isArrayPattern(e)?e.elements.some(n=>!!n&&Ss(we.isRestElement(n)?n.argument:n,t)):!1}function Mx(e,t,n){let r=!1,o=!1,i=e.scope.path,s;if(n){let c=Dx.get(n);c||(c=new WeakMap,Dx.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){Df(c.node)&&(r=!0),(yF(c.node.callee,t)||c.node.arguments.some(l=>we.isIdentifier(l)&&l.name===t))&&(o=!0)}});let a=r&&o;return s?.set(t,a),a}function Lf(e){let t=jc(e.callee);return t==="useQuery"||t==="useSWR"||t==="useSuspenseQuery"}function Bx(e){return jc(e.callee)==="useState"}function Df(e,t){let n=t?.get(e);if(n!==void 0)return n;let r=Mc(e,o=>we.isCallExpression(o)&&jc(o.callee)==="fetch");return t?.set(e,r),r}function hF(e){let t=e;for(;we.isMemberExpression(t);)t=t.object;return we.isIdentifier(t)?t.name:null}function jx(e){return e.computed?null:we.isIdentifier(e.key)?e.key.name:we.isStringLiteral(e.key)?e.key.value:null}function jc(e){return we.isIdentifier(e)?e.name:we.isMemberExpression(e)&&we.isIdentifier(e.property)?e.property.name:null}function yF(e,t){return Mc(e,n=>we.isIdentifier(n)&&n.name===t)}function Mc(e,t){if(t(e))return!0;let n=we.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(we.isNode(i)&&Mc(i,t))return!0;continue}if(we.isNode(o)&&Mc(o,t))return!0}return!1}function bF(e){return we.isIdentifier(e)?e.name:we.isCallExpression(e)?jc(e.callee)??"api":we.isAwaitExpression(e)?"awaited-api":"api"}function Mr(e,t,n){return{kind:"api-source",readonly:!0,sourceId:e,displayPath:xF(e,t),reason:n}}function xF(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}var Vx=typeof Mf=="function"?Mf:Mf.default;function Kx(e,t){let n=Xx(e);if(!n)return{allowed:!0};let r=!1;return Vx(n,{CallExpression(o){if(!zx(o.node,t.sourceRange)||!EF(o.node))return;let i=o.get("callee");if(!i.isMemberExpression())return;let s=i.get("object");Array.isArray(s)||!s.isExpression()||vs(Bc(s))&&(r=!0,o.stop())}}),r?{allowed:!1,reason:"Cannot add data-backed items to a dynamic API list"}:{allowed:!0}}function Jx(e,t){let n=Xx(e);if(!n)return{allowed:!0};let r=!1;return Vx(n,{JSXExpressionContainer(o){zx(o.node,t.sourceRange)&&(ni.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 Xx(e){try{return Ux.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function EF(e){let t=e.callee;return ni.isMemberExpression(t)&&ni.isIdentifier(t.property)&&t.property.name==="map"}function zx(e,t){let n=e.loc;return n?$x({line:n.start.line,column:n.start.column},{line:t.startLine,column:t.startColumn})>=0&&$x({line:n.end.line,column:n.end.column},{line:t.endLine,column:t.endColumn})<=0:!1}function $x(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 re from"@babel/types";import*as Hx from"@babel/parser";import Bf from"@babel/traverse";import*as lt from"@babel/types";import*as ri from"node:path";var Ln=typeof Bf=="function"?Bf:Bf.default;function At(e){try{return Hx.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function jf(e){return e.computed?lt.isStringLiteral(e.key)||lt.isNumericLiteral(e.key)?String(e.key.value):null:SF(e.key)}function SF(e){return lt.isIdentifier(e)?e.name:lt.isStringLiteral(e)||lt.isNumericLiteral(e)?String(e.value):null}function xo(e){return lt.isParenthesizedExpression(e)||lt.isTSAsExpression(e)||lt.isTSSatisfiesExpression(e)||lt.isTSNonNullExpression(e)||lt.isTSTypeAssertion(e)?xo(e.expression):lt.isExpression(e)?e:null}function $f(e){if(lt.isIdentifier(e))return[e.name];if((lt.isMemberExpression(e)||lt.isOptionalMemberExpression(e))&&!e.computed&&lt.isIdentifier(e.property)){let t=xo(e.object),n=t?$f(t):null;return n?[...n,e.property.name]:null}return null}function Eo(e,t){return t.startsWith("@/")?t.slice(2).replace(/\\/g,"/"):t.startsWith(".")?ri.normalize(ri.join(ri.dirname(e),t)).replace(/\\/g,"/"):t}function cn(e,t){return $c(e)===$c(t)}function $c(e){let t=oi(e);return t.endsWith("/index")?t.slice(0,-6):t}function oi(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"")}function Yx(e,t,n){let r=eE(e,t);if(tE(e,r),nE(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 Ln(e,{JSXElement(s){sE(s,r)&&o.push(s)}}),o.length!==1?{ok:!1,reason:"Cannot move prop-backed repeat child without a single unambiguous component call site"}:Uc(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 Zx(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 vF(i,n))o=r(s)||o}return[...n.values()]}function vF(e,t){let n=[],r=IF(e,t);for(let o of e.ast.program.body){if(re.isExportDefaultDeclaration(o)&&re.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=Is(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(re.isExportNamedDeclaration(o)&&o.source&&typeof o.source.value=="string"){let i=Eo(e.file,o.source.value);for(let s of o.specifiers){if(re.isExportNamespaceSpecifier(s)){let l=Br(s.exported);for(let u of t.values())cn(u.file,i)&&n.push({file:e.file,namespace:Uf(l,u.namespace),exportName:u.exportName});continue}if(!re.isExportSpecifier(s))continue;let a=Br(s.local),c=[...t.values()].filter(l=>cn(l.file,i)&&So(l.namespace,a));if(c.length>0){let l=Br(s.exported);for(let u of c){let d=Is(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:Br(s.exported)})}continue}if(re.isExportNamedDeclaration(o)&&!o.source){for(let i of o.specifiers){if(!re.isExportSpecifier(i))continue;let s=Br(i.local),a=r.get(s)??[];if(a.length>0){let c=Br(i.exported);n.push({file:e.file,exportName:c});for(let l of a){let u=Is(l.namespace,s,c);u&&n.push({file:e.file,namespace:u,exportName:l.exportName})}}}continue}if(re.isExportAllDeclaration(o)&&typeof o.source.value=="string"){let i=Eo(e.file,o.source.value),s=o.exported;if(s){let a=Br(s);for(let c of t.values())cn(c.file,i)&&n.push({file:e.file,namespace:Uf(a,c.namespace),exportName:c.exportName});continue}for(let a of t.values())cn(a.file,i)&&(a.namespace||a.exportName!=="default")&&n.push({file:e.file,namespace:a.namespace,exportName:a.exportName})}}return n}function Uf(e,t){return t?`${e}.${t}`:e}function So(e,t){return e===t||e?.startsWith(`${t}.`)===!0}function Is(e,t,n){return!So(e,t)||!e?null:e===t?n:`${n}${e.slice(t.length)}`}function IF(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(!re.isImportDeclaration(i)||typeof i.source.value!="string")continue;let s=Eo(e.file,i.source.value);for(let a of i.specifiers){if(re.isImportDefaultSpecifier(a)){let c=t.get(ii({file:s,exportName:"default"}));c&&r(a.local.name,c);let l=[...t.values()].filter(u=>cn(u.file,s)&&So(u.namespace,"default"));for(let u of l){let d=Is(u.namespace,"default",a.local.name);d&&r(a.local.name,{...u,namespace:d})}continue}if(re.isImportSpecifier(a)){let c=Br(a.imported),l=[...t.values()].filter(d=>cn(d.file,s)&&So(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(re.isImportNamespaceSpecifier(a))for(let c of t.values())cn(c.file,s)&&r(a.local.name,{...c,namespace:Uf(a.local.name,c.namespace)})}}let o=!0;for(;o;){o=!1;for(let i of e.ast.program.body)if(re.isVariableDeclaration(i))for(let s of i.declarations){if(!re.isIdentifier(s.id)||!s.init)continue;let a=xo(s.init);if(!a||!re.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 f=Is(d.namespace,a.name,s.id.name),g=f?{...d,namespace:f}: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`${$c(e.file)}#${t}`}function Br(e){return re.isIdentifier(e)?e.name:e.value}function qx(e,t){for(let n of e.program.body){if(re.isExportDefaultDeclaration(n)){let o=n.declaration;if((re.isFunctionDeclaration(o)||re.isClassDeclaration(o))&&o.id?.name===t)return{exportName:"default"};if(re.isIdentifier(o)&&o.name===t)return{exportName:"default"}}if(!re.isExportNamedDeclaration(n))continue;let r=n.declaration;if((re.isFunctionDeclaration(r)||re.isClassDeclaration(r))&&r.id?.name===t)return{exportName:t};if(re.isVariableDeclaration(r)){for(let o of r.declarations)if(re.isIdentifier(o.id,{name:t}))return{exportName:t}}for(let o of n.specifiers){if(!re.isExportSpecifier(o)||o.local.name!==t)continue;return{exportName:re.isIdentifier(o.exported)?o.exported.name:o.exported.value}}}return null}function Kf(e){let t=kF(e),n=[],r=nE(e.ast,t);return Ln(e.ast,{JSXElement(o){cn(e.file,e.sourceFile)&&Uc(o)===e.sourceComponent||sE(o,t)&&n.push({file:e.file,path:o})}}),{callSites:n,hasUnsafeReference:r}}function Qx(){return{localBindings:new Set,namespaceMembers:new Map,hasUnsupportedAlias:!1}}function eE(e,t){let n=Qx();return Ln(e,{Program(r){let o=r.scope.getBinding(t);o&&n.localBindings.add(o),r.stop()}}),n}function kF(e){let t=Qx();return cn(e.file,e.sourceFile)&&_F(t,eE(e.ast,e.sourceComponent)),Ln(e.ast,{ImportDeclaration(n){let r=n.node,o=r.source.value;if(typeof o!="string")return;let i=Eo(e.file,o),s=e.componentIdentities.filter(a=>cn(a.file,i));if(s.length!==0)for(let a of r.specifiers){let c=n.scope.getBinding(a.local.name);if(c){if(re.isImportDefaultSpecifier(a)&&s.some(l=>l.exportName==="default")&&t.localBindings.add(c),re.isImportDefaultSpecifier(a)){let l=s.filter(u=>So(u.namespace,"default"));if(l.length>0){let u=t.namespaceMembers.get(c)??new Set;for(let d of l){let f=Gx(d,"default");f&&u.add(f)}t.namespaceMembers.set(c,u)}continue}if(re.isImportSpecifier(a)){let l=re.isIdentifier(a.imported)?a.imported.name:a.imported.value,u=s.filter(d=>So(d.namespace,l));if(u.length>0){let d=t.namespaceMembers.get(c)??new Set;for(let f of u){let g=Gx(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(re.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)}}}}}),tE(e.ast,t),t}function _F(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 tE(e,t){Ln(e,{VariableDeclarator(n){if(!n.node.init)return;let r=xo(n.node.init);if(r){if(re.isIdentifier(n.node.id)){let o=vo(r,t,n),i=n.scope.getBinding(n.node.id.name);o&&i&&Vf(t,i,o);return}if(re.isObjectPattern(n.node.id)){let o=vo(r,t,n);o?.unsupported||o?.local?t.hasUnsupportedAlias=!0:o&&o.namespaceMembers.size>0&&iE(n.node.id,o.namespaceMembers,t,n)}}}})}function nE(e,t){if(t.hasUnsupportedAlias)return!0;let n=!1;return Ln(e,{ReferencedIdentifier(r){if(n){r.stop();return}RF(r)||!r.isIdentifier()||!rE(r,t)||CF(r,t)||PF(r)||(n=!0,r.stop())}}),n}function RF(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 rE(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)&&vo(r.node,t,r)?r:null}function CF(e,t){let n=e.findParent(c=>c.isVariableDeclarator());if(!n?.isVariableDeclarator())return!1;let r=n.get("init");if(!r?.isExpression()||!Wx(e,r))return!1;let o=rE(e,t);if(!o)return!1;if(xo(r.node)===o.node)return!!vo(r.node,t,r);let s=e.findParent(c=>c.isObjectProperty());if(!s?.isObjectProperty())return!1;let a=s.get("value");return a.isExpression()&&Wx(e,a)&&!!vo(a.node,t,a)}function PF(e){let t=e.parentPath;return t?.isExportDefaultDeclaration()&&t.node.declaration===e.node?!0:!!(t?.isExportSpecifier()&&t.node.local===e.node)}function Wx(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.parentPath}return!1}function vo(e,t,n){let r=xo(e);if(!r)return null;if(re.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(re.isObjectExpression(r))return NF(r,t,n);let o=$f(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?oE(s,o.slice(1).join(".")):null}function NF(e,t,n){let r=new Set,o=!1;for(let i of e.properties){if(!re.isObjectProperty(i))continue;let s=jf(i);if(!s||!re.isExpression(i.value)){re.isExpression(i.value)&&(o||=vo(i.value,t,n)!==null);continue}let a=vo(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 oE(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 Vf(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 iE(e,t,n,r){for(let o of e.properties){if(re.isRestElement(o)){if(re.isIdentifier(o.argument)){let c=r.scope.getBinding(o.argument.name);c&&Vf(n,c,{local:!1,namespaceMembers:new Set(t),unsupported:!1})}else n.hasUnsupportedAlias=!0;continue}if(!re.isObjectProperty(o))continue;let i=jf(o);if(!i){n.hasUnsupportedAlias=!0;continue}let s=oE(t,i);if(!s)continue;n.hasUnsupportedAlias||=s.unsupported;let a=re.isAssignmentPattern(o.value)?o.value.left:o.value;if(re.isIdentifier(a)){let c=r.scope.getBinding(a.name);c&&Vf(n,c,s);continue}if(re.isObjectPattern(a)&&s.namespaceMembers.size>0){iE(a,s.namespaceMembers,n,r);continue}n.hasUnsupportedAlias=!0}}function Gx(e,t){if(!So(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 sE(e,t){let n=e.node.openingElement.name;if(re.isJSXIdentifier(n)){let o=e.scope.getBinding(n.name);return!!(o&&t.localBindings.has(o))}let r=aE(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 aE(e){if(re.isJSXIdentifier(e))return[e.name];if(re.isJSXMemberExpression(e)){let t=aE(e.object);return t?[...t,e.property.name]:null}return null}function Uc(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()&&re.isIdentifier(n.node.id))return n.node.id.name}return null}function cE(e,t){let n=At(e);if(!n||!t.tag||!t.importedFrom||!t.exportName)return Number.POSITIVE_INFINITY;let r=Kf({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 We(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 ze(e){return typeof e.start=="number"&&typeof e.end=="number"?{start:e.start,end:e.end}:null}function Wn(e,t){let n=ze(e);return!!(n&&ln(t,n))}function ln(e,t){return t.start>=e.start&&t.end<=e.end}function Rn(e,t){let n=Pe(e,We(t));return n.ok&&n.match.path.isJSXElement()?n.match.path:Vc(e,t)}function si(e,t){let n=ze(t);return n?e.slice(n.start,n.end):""}function lE(e,t){return e.start===t.start&&e.end===t.end}function Vc(e,t){let n=null;return Ln(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 Kc(e,t){return Jf(e,t).length>0}function Jc(e,t){let n=ze(e.node),r=ze(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()&&!AF(o,n,r)))return!0;o=o.parentPath}return!1}function AF(e,t,n){let r=ze(e.node.consequent);if(r&&ln(r,t)&&!ln(r,n))return!1;let o=e.node.alternate?ze(e.node.alternate):null;return!(o&&ln(o,t)&&!ln(o,n))}function Jf(e,t){let n=ze(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=ze(o.node.consequent),a=ze(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()&&Xf(o.node.operator)){let s=ze(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 Xf(e){return e==="&&"||e==="||"||e==="??"}function uE(e,t){let n=ze(e.consequent);if(n&&ln(n,t))return n;let r=ze(e.alternate);return r&&ln(r,t)?r:null}function dE(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=>oi(a.file)));if(!t.has(oi(e.sourceFile))||!t.has(oi(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(oi(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=qx(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=At(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=Zx(r,{file:e.sourceFile,exportName:n.exportName}),i=[];for(let a of r){let c=Kf({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!cn(s.file,e.targetFile)||Uc(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 DF}from"@vcp-dev/contracts";function Xc(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 ks();let a=s.target,c=a.locator;if(a.sourceKind==="repeat-template"){let l=o?.instanceIndex;if(l===void 0)return ks();let u=TF(a,l,o?.instanceCount);if(!u)return ks();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"?ks():{ok:!0,target:{kind:"jsx-attribute"}}}function ks(){return{ok:!1,code:"unsupported-binding",reason:"Property does not have a safe typed binding write target for this scope and operation"}}function TF(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 Gn from"@babel/types";import{SiteEditSetPropsParamsSchema as wF}from"@vcp-dev/contracts";function fE(e){let t=e.changes??(e.change?[e.change]:[]);if(!wF.safeParse({kind:"set-props",scope:"selection",changes:t}).success)return _s("invalid-change","Repeat property changes are invalid");if(t.length!==1||t[0].name!==e.target.propertyName)return _s("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=nt(e.source,"value");if(!o.ok)return _s("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=Pe(o.ast,a);if(!c.ok||!c.match.path.isObjectExpression())return _s("unsupported-object",`Repeat item ${s} is not a writable object expression`);let l=s===e.target.sourceItemIndex?OF(r):FF(c.match.path.node,r.name);if(!l)return _s("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 OF(e){return e.operation==="set"?{kind:"value",value:e.value}:{kind:"undefined"}}function FF(e,t){let n=e.properties.filter(i=>Gn.isObjectProperty(i)&&LF(i.key)===t);if(n.length>1)return null;let r=n[0];if(!r)return{kind:"undefined"};if(!Gn.isExpression(r.value))return null;let o=Xn(r.value);return o.status==="undefined"?{kind:"undefined"}:o.status!=="resolved"?null:{kind:"value",value:o.value}}function LF(e){return Gn.isIdentifier(e)?e.name:Gn.isStringLiteral(e)?e.value:Gn.isNumericLiteral(e)?String(e.value):null}function _s(e,t){return{ok:!1,errorCode:e,reason:t}}function pE(e){if(e.change.name!=="className"&&e.change.name!=="class")return Rs("unsupported-owner",`No specialized property owner is available for '${e.change.name}'`);let t=e.classNameSource;if(!t||t.filePath!==e.node.file)return Rs("owner-source-unavailable","className source details are unavailable for the selected node");if(e.change.name==="class"&&t.sourceKind==="missing")return Rs("owner-source-unavailable","The class alias requires an existing className source");if(t.sourceKind==="expression")return Rs("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 Rs("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 Rs(e,t){return{ok:!1,errorCode:e,reason:t}}async function gE(e){let t=DF.safeParse({kind:"set-props",scope:e.scope,changes:e.changes});if(!t.success)return jr("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 jr("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 MF(e,r);if(o){if(!o.ok)return jr("owner-plan-failed",o.reason);mE(n,o.steps);continue}let i=await e.getPropertyState(e.node.key,r.name,e.selectionRef);if(!i)return jr("missing-property-state",`No authoritative property state is available for '${r.name}'`);if(i.status==="blocked")return jr("readonly-property",i.diagnostic?.message??`Property '${r.name}' is not writable`);if($F(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=Xc({state:i,scope:e.scope,operation:r.operation,selectionRef:e.selectionRef,repeatTarget:s});if(!a.ok)return jr(a.code,a.reason);let c=a.target;if(c.kind==="value-binding"&&r.operation==="set"){zf(n,{type:"update-value",order:n.length,file:c.file,locator:c.locator,value:r.value});continue}if(c.kind==="repeat-property"){let l=fE({source:e.getFileContent(c.target.sourceFile),target:c.target,changes:[r]});if(!l.ok)return jr("repeat-target-failed",l.reason);mE(n,l.steps);continue}zf(n,{type:"set-property-changes",order:n.length,file:e.node.file,locator:BF(e.node),scope:e.scope,changes:[r]})}return n.forEach((r,o)=>{r.order=o}),jF(n)?jr("step-conflict","Property changes resolve to conflicting write steps"):{ok:!0,steps:n}}async function MF(e,t){return t.name!=="className"&&t.name!=="class"?null:pE({node:e.node,change:t,classNameSource:e.classNameSource})}function BF(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 jF(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 mE(e,t){for(let n of t)zf(e,{...n,order:e.length})}function zf(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 $F(e,t){if(t.operation!=="set"||e.status!=="direct")return!1;let n=e.attribute?.resolution;return n?.status==="resolved"?Hf(n.value,t.value):e.attribute?.source===null&&e.attribute.value===t.value}function Hf(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)=>Hf(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=>Hf(n[i],r[i]))}return!1}function jr(e,t){return{ok:!1,errorCode:e,reason:t}}import*as ci from"@babel/types";import*as de from"@babel/types";function Wf(e,t,n){let r=Rn(t,n);return r?Yn(e,r):null}function Yn(e,t){let n=t.findParent(p=>p.isArrowFunctionExpression()||p.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(p=>p===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(!de.isIdentifier(l)||l.name!=="map"||c.computed)return null;let u=a.get("object"),d=si(e,u.node),f=r.node.params.map(p=>si(e,p)),g=ze(i.node),m=ze(r.node);return!d||f.some(p=>p.length===0)||!g||!m?null:{callStart:g.start,callEnd:g.end,callbackStart:m.start,callbackEnd:m.end,collectionExpression:d,callbackParams:f,mapOperator:de.isOptionalMemberExpression(c)&&c.optional?"?.map":".map",collectionNeedsParens:zc(u.node),callbackPath:r,collectionPath:u}}function Cs(e,t){return!!(e&&t&&e.callStart===t.callStart&&e.callEnd===t.callEnd&&e.callbackStart===t.callbackStart&&e.callbackEnd===t.callbackEnd)}function UF(e,t){let n=ze(e.node);return n?VF(t).some(r=>{let o=ze(r);return r===e.node||!!(o&&o.start===n.start&&o.end===n.end)}):!1}function VF(e){let t=e.callbackPath.node.body;return de.isBlockStatement(t)?$r(t.body):Ur(t)}function $r(e){let t=[];for(let n of e){if(de.isReturnStatement(n)){n.argument&&t.push(...Ur(n.argument));continue}if(de.isBlockStatement(n)){t.push(...$r(n.body));continue}if(de.isIfStatement(n)){let r=de.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent];if(t.push(...$r(r)),n.alternate){let o=de.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];t.push(...$r(o))}continue}if(de.isSwitchStatement(n)){for(let r of n.cases)t.push(...$r(r.consequent));continue}de.isTryStatement(n)&&(t.push(...$r(n.block.body)),n.handler&&t.push(...$r(n.handler.body.body)),n.finalizer&&t.push(...$r(n.finalizer.body)))}return t}function Ur(e){return de.isJSXElement(e)?KF(e)?hE(e.children):[e]:de.isJSXFragment(e)?hE(e.children):de.isParenthesizedExpression(e)||de.isTSAsExpression(e)||de.isTSSatisfiesExpression(e)||de.isTSNonNullExpression(e)||de.isTSTypeAssertion(e)?Ur(e.expression):de.isConditionalExpression(e)?[...Ur(e.consequent),...Ur(e.alternate)]:de.isLogicalExpression(e)&&Xf(e.operator)?Ur(e.right):[]}function hE(e){return e.flatMap(t=>de.isJSXElement(t)||de.isJSXFragment(t)?Ur(t):de.isJSXExpressionContainer(t)&&(de.isJSXElement(t.expression)||de.isJSXFragment(t.expression)||de.isConditionalExpression(t.expression)||de.isLogicalExpression(t.expression))?Ur(t.expression):[])}function KF(e){let t=e.openingElement.name;return de.isJSXIdentifier(t)?t.name==="Fragment":de.isJSXMemberExpression(t)&&t.property.name==="Fragment"}function yE(e,t){return!!(e&&t&&e.callbackStart<t.callbackStart&&e.callbackEnd>t.callbackEnd)}function zc(e){return!(de.isIdentifier(e)||de.isThisExpression(e)||de.isMemberExpression(e)||de.isOptionalMemberExpression(e)||de.isCallExpression(e)||de.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(de.isMemberExpression(n)||de.isOptionalMemberExpression(n))&&de.isIdentifier(n.property)&&n.property.name==="map"&&!n.computed}function ai(e,t){let n=At(e);if(!n)return t.isRepeatItemRoot===!0;let r=Pe(n,We(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Vc(n,t);if(!o)return t.isRepeatItemRoot===!0;let i=Yn(e,o);return i?UF(o,i):t.isRepeatItemRoot===!0}function xE(e,t){let n=At(e);if(!n)return!1;let r=Pe(n,We(t)),o=r.ok&&r.match.path.isJSXElement()?r.match.path:Vc(n,t);return o?!!o.findParent(i=>{if(!i.isCallExpression()&&!i.isOptionalCallExpression())return!1;let s=i.node.callee;return(de.isMemberExpression(s)||de.isOptionalMemberExpression(s))&&de.isIdentifier(s.property)&&s.property.name==="map"}):!1}import*as Qe from"@babel/types";function Gf(e){if(Qe.isJSXIdentifier(e))return/^[A-Z]/.test(e.name)?e.name:null;if(Qe.isJSXMemberExpression(e)){let t=e;for(;Qe.isJSXMemberExpression(t);)t=t.object;return t.name}return null}function JF(e,t){let n=ze(e.node);if(!n)return[];let r=new Set,o=(i,s)=>{let a=s.scope.getBinding(i);!a||Wn(a.path.node,n)||Vr(a,i,t)||r.add(i)};return e.traverse({ReferencedIdentifier(i){o(i.node.name,i)},JSXOpeningElement(i){let s=Gf(i.node.name);s&&o(s,i)}}),[...r].sort()}function Yf(e,t,n){let r=At(e);if(!r)return{ok:!0};let o=Pe(r,We(t));if(!o.ok||!o.match.path.isJSXElement())return{ok:!0};let i=Pe(r,We(n));if(!i.ok||!i.match.path.isJSXElement())return{ok:!0};let s=$i(o.match.path,i.match.path);if(Kc(s,i.match.path))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let a=JF(s,i.match.path);return a.length>0?{ok:!1,bindingNames:a}:{ok:!0}}function SE(e){let t=e;for(;Qe.isTSQualifiedName(t);)t=t.left;return Qe.isIdentifier(t)?t.name:null}function Ps(e,t){e.isIdentifier()&&e.isReferencedIdentifier()&&t(e),e.traverse({ReferencedIdentifier(n){n.isIdentifier()&&t(n)}})}function Hc(e){let t=[],n=r=>{if(r){if(Qe.isIdentifier(r)){t.push(r.name);return}if(Qe.isObjectPattern(r)){for(let o of r.properties){if(Qe.isRestElement(o)){n(o.argument);continue}Qe.isObjectProperty(o)&&n(o.value)}return}if(Qe.isArrayPattern(r)){for(let o of r.elements)n(o);return}if(Qe.isAssignmentPattern(r)){n(r.left);return}if(Qe.isRestElement(r)){n(r.argument);return}Qe.isTSParameterProperty(r)&&n(r.parameter)}};return n(e),t}function Zf(e,t){let n=ze(e.node),r=ze(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=EE(e),i=EE(t);if(!o||!i||!lE(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=uE(s.node,n);if(a&&!ln(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=ze(s.node.right);if(a&&ln(a,n)&&!ln(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=ze(s.node.body)??ze(s.node);if(a&&!ln(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 EE(e){let t=e;for(;t;){if(t.isReturnStatement())return t.node.argument?ze(t.node.argument):null;if(t.isArrowFunctionExpression()&&(Qe.isJSXElement(t.node.body)||Qe.isJSXFragment(t.node.body)||Qe.isConditionalExpression(t.node.body)||Qe.isLogicalExpression(t.node.body)))return ze(t.node.body);t=t.parentPath}return null}function Vr(e,t,n){return n.scope.getBinding(t)===e}function qf(e,t,n,r={}){if(!r.preserveConditionalBoundary&&Kc(e,t))return{ok:!1,bindingNames:[],reason:"Cannot move node out of its conditional branch"};let o=ze(e.node);if(!o)return{ok:!0};let i=new Set(n.callbackPath.node.params.flatMap(c=>Hc(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||Wn(u.path.node,o)||i.has(u.path.node)||Vr(u,c,t)||s.add(c)};return e.traverse({ReferencedIdentifier(c){a(c.node.name,c)},JSXOpeningElement(c){let l=Gf(c.node.name);l&&a(l,c)}}),s.size>0?{ok:!1,bindingNames:[...s].sort()}:{ok:!0}}function Qf(e,t,n){let r=ze(e.node);if(!r)return{ok:!0};let o=new Set(n.callbackPath.node.params.flatMap(s=>Hc(s)).map(s=>n.callbackPath.scope.getBinding(s)?.path.node).filter(Boolean)),i=new Set;return Ps(e,s=>{let a=s.scope.getBinding(s.node.name);!a||Wn(a.path.node,r)||o.has(a.path.node)||Vr(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=>Hc(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)||Vr(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(ci.isIdentifier(l))o(l.name,c);else{let u=SE(l);u&&o(u,c)}}});return r.size>0?{ok:!1,bindingNames:[...r].sort()}:{ok:!0}}function ep(e,t){let n=ze(e.node),r=new Set;return Ps(e,o=>{let i=o.scope.getBinding(o.node.name);i&&(n&&Wn(i.path.node,n)||Vr(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 IE(e){let t=[];for(let n of e.callbackPath.node.params){if(ci.isIdentifier(n)){t.push(n.name);continue}if(ci.isRestElement(n)&&ci.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 tp(e,t){return`${e.collectionNeedsParens?`(${e.collectionExpression})`:e.collectionExpression}${e.mapOperator}((${e.callbackParams.join(", ")}) => ${t})`}function Ns(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 _E(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 Io(e){return{file:e.file,component:e.component}}function XF(e){return e.target.kind==="node"?e.target.key:null}function zF(e){return"kind"in e&&e.kind==="page-composition"}function Yc(e){return typeof e=="object"&&e!==null&&"kind"in e&&e.kind==="block-boundary"}function Wc(e){return!zF(e)&&!Yc(e)}function sp(e,t){let n=qc.dirname(e),r=t.replace(/\.(tsx|ts|jsx|js)$/,""),o=qc.relative(n,r);return o=o.replace(/\\/g,"/"),o.startsWith(".")||(o=`./${o}`),o}function np(e,t){let n=e.getFileContent(t.file);if(!n)return;let r=Kn(n,We(t));if(r.ok)return n.slice(r.match.start,r.match.end)}function cp(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 HF(e){if(e.isNumericLiteral())return!0;if(!e.isUnaryExpression({operator:"-"}))return!1;let t=e.get("argument");return!Array.isArray(t)&&t.isNumericLiteral()}function WF(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 rp(e){return e==="Cannot edit repeat-backed child node structure with a generic node operation"}function GF(e){let t=Yx(e.ast,e.sourceNode.component,e.targetParent.component);if(!t.ok)return{ok:!1,reason:t.reason};let n=Zf(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=FE(r.collectionExpression);return{ok:!0,context:{...e.sourceContext,collectionExpression:r.collectionExpression,collectionNeedsParens:o?zc(o):!0}}}function YF(e){let t=ze(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||Wn(a.path.node,t))return;let c=QF(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=tL(e.callSitePath,c.propName,e.source);if(!l.ok){o=l.reason;return}let u=ZF(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=ep(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}Vr(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:nL(e.source,t,[...n.values()])}}function ZF(e,t){if(t.length===0)return e;let n=FE(e);if(!n)return null;let r=zc(n)?`(${e})`:e;for(let o of t){if(o.kind==="property"){r=qF(o.name)?`${r}.${o.name}`:`${r}[${JSON.stringify(o.name)}]`;continue}r=`${r}[${o.index}]`}return r}function qF(e){return/^[$A-Z_a-z][$\w]*$/.test(e)}function QF(e,t,n){let r=eL(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=ti(t,o);if(!i)return null;let s=r?.range??ze(e.node);return s?{propName:i.propName,remainingPath:i.remainingPath,hasDefault:i.hasDefault,range:s}:null}function eL(e,t){let n=e.parentPath;if(!n||!n.isMemberExpression()&&!n.isOptionalMemberExpression()||n.node.object!==e.node||!Wn(n.node,t)||n.node.computed||!je.isIdentifier(n.node.property))return null;let r=ze(n.node);return r?{propertyName:n.node.property.name,range:r}:null}function tL(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()&&je.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=si(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 nL(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 FE(e){try{let n=OE.parse(`const __VD_EXPR__ = (${e});`,{sourceType:"module",plugins:["jsx","typescript"]}).program.body[0],r=je.isVariableDeclaration(n)?n.declarations[0]?.init:null;return r&&je.isExpression(r)?r:null}catch{return null}}function rL(e){let t=ze(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||Wn(s.path.node,t))return;let a=RE(s,e.sourceFile,e.targetFile);if(a){let c=e.targetParentPath.scope.getBinding(a.localName);if(c){let u=RE(c,e.targetFile,e.targetFile);(!u||u.moduleFile!==a.moduleFile||!oL(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 Ps(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 oL(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 RE(e,t,n){let r=iL(e),o=r?.parentPath;if(!r||!o?.isImportDeclaration())return null;let i=o.node.source.value;if(typeof i!="string")return null;let s=Eo(t,i),a=i.startsWith(".")?sp(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=je.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 iL(e){let t=e.path;for(;t&&!t.isImportDeclaration();){if(t.isImportSpecifier()||t.isImportDefaultSpecifier()||t.isImportNamespaceSpecifier())return t;t=t.parentPath}return null}function CE(e,t,n,r){let o=Jf(t,n);if(o.length===0)return{sourceJsx:r,conditionPaths:[]};let i=r,s=[];for(let a of o){let c=si(e,a.conditionPath.node);if(!c)return{sourceJsx:r,conditionPaths:[]};let l=sL(a.conditionPath,c);if(s.push(a.conditionPath),a.kind==="logical"){i=`${l} ${a.operator} ${cL(i)}`;continue}i=a.branch==="consequent"?`${l} ? ${i} : null`:`${l} ? null : ${i}`}return{sourceJsx:i,conditionPaths:s}}function sL(e,t){return aL(e.node)?t:`(${t})`}function aL(e){return je.isIdentifier(e)||je.isThisExpression(e)||je.isSuper(e)||je.isMemberExpression(e)||je.isOptionalMemberExpression(e)||je.isCallExpression(e)||je.isOptionalCallExpression(e)||je.isBooleanLiteral(e)||je.isNumericLiteral(e)||je.isStringLiteral(e)||je.isNullLiteral(e)||je.isUnaryExpression(e)}function cL(e){return e.trim().startsWith("<")?e:`(${e})`}var lL={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 Gc(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=lL[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 uL(e,t){for(let n of e.program.body){if(!je.isImportDeclaration(n)||n.source.value!==t)continue;let r=n.specifiers.find(o=>je.isImportDefaultSpecifier(o));if(r&&je.isImportDefaultSpecifier(r))return r.local.name}return null}function dL(e,t,n){for(let r of e.program.body){if(!je.isImportDeclaration(r)||r.source.value!==t)continue;let o=r.specifiers.find(i=>je.isImportSpecifier(i)&&(je.isIdentifier(i.imported)?i.imported.name:i.imported.value)===n);if(o&&je.isImportSpecifier(o))return o.local.name}return null}function PE(e){let t=new Set;return Ln(e,{Program(n){for(let r of Object.keys(n.scope.bindings))t.add(r);n.stop()}}),t}function NE(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n+=1;return`${e}${n}`}function fL(e,t){if(!e.component)return{localName:"Component"};let n=e.component,r=cp(e),o=At(t);if(n.exportName!=="default"){let a=o?dL(o,n.source,n.exportName):null;if(a)return{localName:a};let c=o?NE(r,PE(o)):r;return{localName:c,importStep:op(e,c)}}if(!o)return{localName:r,importStep:op(e,r)};let i=uL(o,n.source);if(i)return{localName:i};let s=NE(r,PE(o));return{localName:s,importStep:op(e,s)}}function pL(e,t){if(e.kind==="native-tag")return e.text?`<${e.tag}>${e.text}</${e.tag}>`:`<${e.tag} />`;let n=t??cp(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 mL(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?gL(e.props):void 0;return{kind:e.kind,component:{source:e.component.source,exportName:e.component.exportName},...t?{props:t}:{}}}function gL(e){return Object.fromEntries(Object.entries(e).filter(t=>ap(t[1])))}function ap(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ap):typeof e=="object"?Object.values(e).every(ap):!1}function op(e,t=cp(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 AE(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 hL(e,t,n){let r=e;for(;r;){if(r===t)return!0;r=n.getNode(r)?.parentKey}return!1}function li(e,t){return`Operation kind '${e}' does not match params.kind '${t}'`}function lp(e,t=e.path){return{kind:"value",root:e.root,path:t&&t.length>0?t:void 0,expectedRange:e.expectedRange}}function As(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:lp(e,t.slice(0,n)),index:r.index}}return null}function ip(e,t){return e.locator?e.collectionPathMap?.[t]?lp(e.locator,e.collectionPathMap[t]):As(e.locator)?bL(e.locator,xL(t,e.collectionIndexMap)):null:null}function yL(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:LE(o,t)}function LE(e,t){let[n,...r]=e;if(!n)return t;if(n.kind!=="property")return;let o=LE(r,t);return o===void 0?void 0:{[n.name]:o}}function bL(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},lp(e,i)}return null}function xL(e,t){return t?.[e]??e}function TE(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 EL(e,t){return SL(e.root,t.root)&&IL(e.path??[],t.path??[])}function SL(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&&vL(e.sourceRange,t.sourceRange)}}function vL(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function IL(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 Zc=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:li(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:li(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:li(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:li(t.kind,t.params.kind)};let r=t;if(Yc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page-block boundaries require the page-block resolver"};if(!Wc(r.params.position))return{ok:!1,errorCode:"unsupported-operation",reason:"Page composition insert-child requires the page composition transaction planner"};let o=AE(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:li(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:li(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=XF(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):wE(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 wE(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:We(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?gE({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=ip(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:We(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=ip(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:We(t),segmentIndex:n,newText:r}]}}coerceTextValueForValueTarget(t,n,r,o="update-text"){let i=this.graph.getFileContent(t),s=At(i);if(!s)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not inspect the value source`};let a=Pe(s,n);if(!a.ok)return{ok:!1,errorCode:"invalid-params",reason:`${o} could not resolve the value source`};if(!HF(a.match.path))return{ok:!0,value:r};let c=WF(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=ip(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=At(this.graph.getFileContent(t));if(!o)return!1;let i=Pe(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=As(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=Ns(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:We(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||cE(n,t)>1)return null;let r=sp(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(!Wc(n.params.position))return Yc(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=Ns(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=Kx(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=Gc(r,n.params.node);if(m)return{ok:!1,errorCode:"unsupported-operation",reason:m};let p=[],y=0,b=n.params.node.kind==="component-call"?fL(n.params.node,this.graph.getFileContent(r.file)):void 0,E=b?.importStep;return E&&p.push({order:y++,file:r.file,type:"add-import",moduleSpecifier:E.moduleSpecifier,imports:E.imports}),p.push({order:y++,file:r.file,type:"insert-child",parentLocator:We(r),node:{jsx:pL(n.params.node,b?.localName)},placement:n.params.position.relation,anchorLocator:i?We(i):void 0}),this.buildPlan(t,n,p,o)}async planExternalBackedInsertChild(t,n,r,o,i,s){if(!Wc(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:mL(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(!Wc(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=As(a.locator);if(!c)return{ok:!1,errorCode:"unsupported-operation",reason:"Repeat-backed insert-child requires an array-backed target"};let l=yL(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"?TE(0,a.collectionIndexMap):TE(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=Ns(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 ai(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:")||xE(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&&ai(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=At(c);if(!l)return null;let u=Rn(l,r),d=Rn(l,o);if(!u||!d)return null;let f=Yn(c,u),g=Yn(c,d);if(!Cs(f,g))return null;if(a&&(s==="before"||s==="after")){let p=Rn(l,a),y=p?Yn(c,p):null;if(!Cs(f,y))return null}if(Jc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child across statement-level conditional branches"};let m=Yf(c,r,o);return m.ok?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:We(r),targetParentLocator:We(o),placement:s,anchorLocator:a?We(a):void 0,selectionContext:Io(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&&ai(this.graph.getFileContent(r.file),r)||r.file!==o.file)return null;let c=this.graph.getFileContent(r.file),l=At(c);if(!l)return null;let u=Rn(l,r),d=Rn(l,o);if(!u||!d)return null;let f=Yn(c,u);if(!f)return null;let g=Yn(c,d);if(Cs(f,g))return null;if(g&&!yE(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=Wf(c,l,a);if(g&&!Cs(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=Gc(o,{kind:"native-tag",tag:r.tag});if(x)return{ok:!1,errorCode:"unsupported-operation",reason:x}}let m=np(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(Jc(u,d))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let p=CE(c,u,d,m);for(let x of p.conditionPaths){let S=Qf(x,d,f);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=qf(u,d,f,{preserveConditionalBoundary:p.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=vE(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 E=f;if(r.component!==o.component){let x=GF({source:c,ast:l,sourceContext:f,sourceNode:r,targetParent:o,targetParentPath:d});if(!x.ok)return{ok:!1,errorCode:"unsupported-operation",reason:x.reason};E=x.context}else{let x=ep(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:We(r),targetParentLocator:We(o),placement:s,anchorLocator:a?We(a):void 0,repeatExpression:tp(E,p.sourceJsx),selectionContext:Io(o)}],i)}planCrossFileRepeatTemplateHoistMove(t,n,r,o,i,s,a){if(r.isRepeatItemRoot&&ai(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=At(c),d=At(l);if(!u||!d)return null;let f=dE({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=Rn(u,r),m=Rn(d,o);if(!g||!m)return null;let p=Zf(f.callSitePath,m);if(!p.ok)return{ok:!1,errorCode:"unsupported-operation",reason:p.reason};let y=Yn(c,g);if(!y)return null;if(Yn(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")&&Wf(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 C=Gc(o,{kind:"native-tag",tag:r.tag});if(C)return{ok:!1,errorCode:"unsupported-operation",reason:C}}let E=np(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(Jc(g,m))return{ok:!1,errorCode:"unsupported-operation",reason:"Cannot move repeat-backed child out of a statement-level conditional branch"};let x=CE(c,g,m,E);for(let C of x.conditionPaths){let w=Qf(C,m,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 S=qf(g,m,y,{preserveConditionalBoundary:x.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 v=rL({sourceFile:r.file,targetFile:o.file,sourceContext:y,targetParentPath:m});if(!v.ok)return{ok:!1,errorCode:"unsupported-operation",reason:v.reason};let N=IE(y);if(!N.ok)return{ok:!1,errorCode:"unsupported-operation",reason:N.reason};let R=kE(y,N.callbackParams),A=[{order:0,file:r.file,type:"remove-node",locator:We(r),removeWhitespace:!0}];for(let C of v.imports)A.push({order:A.length,file:o.file,type:"add-import",moduleSpecifier:C.moduleSpecifier,imports:C.imports});return A.push({order:A.length,file:o.file,type:"insert-jsx-expression-child",parentLocator:We(o),expression:tp(R,x.sourceJsx),placement:s,anchorLocator:a?We(a):void 0,selectionContext:Io(o)}),this.buildPlan(t,n,A,i)}async planMoveNode(t,n,r,o){if(!o.canMove)return{ok:!1,errorCode:"capability-denied",reason:"Cannot move this node"};if(Yc(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,S=this.graph.getNode(x.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 v=this.graph.getFileVersion(r.file);if(n.documentVersion!==v)return{ok:!1,errorCode:"stale-version",reason:`Document version ${n.documentVersion} is stale or otherwise does not match source sibling file version (current: ${v})`};let N=this.graph.getFileContent(r.file),R=At(N),A=R?Rn(R,r):null,C=R?Rn(R,S):null,w=A?.parentPath,M=C?.parentPath;if(!A||!C||!w||!M||w.node!==M.node||!w.isJSXFragment()&&!(w.isJSXElement()&&it(w)))return{ok:!1,errorCode:"unsupported-operation",reason:"Source sibling move requires two direct children of the same transparent Fragment"};let D=w.node.loc;return D?this.buildPlan(t,n,[{order:0,file:r.file,type:"move-node",locator:We(r),targetParentLocator:{kind:"jsx-node",strategy:"source-range",sourceRange:{startLine:D.start.line,startColumn:D.start.column,endLine:D.end.line,endColumn:D.end.column}},placement:x.relation,anchorLocator:We(S),selectionContext:Io(r)}],o):{ok:!1,errorCode:"locator-miss",reason:"Source Fragment has no stable source range"}}let i=AE(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(hL(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,S=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: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,f=this.graph.getTextProvenance?.(r.key,0)??null,g=Ns(r,c,f);if(g&&!rp(g)&&!_E(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,S=await this.graph.getTextWriteTarget(d.key,0);if(x?.kind==="value-binding"&&S?.kind==="value-binding"&&x.locator&&S.locator){let v=As(x.locator),N=As(S.locator);if(v&&N&&x.file===S.file&&EL(v.locator,N.locator)){let R=v.index,A=N.index,C=u==="before"?A-(R<A?1:0):A+(R<A?0:1);return this.buildPlan(t,n,[{order:0,file:x.file,type:"move-array-item",locator:v.locator,fromIndex:R,toIndex:C}],o)}}}if(r.isRepeatItemRoot&&ai(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),p=rp(g)?g:m;if(p&&rp(p)){let x=this.planRepeatTemplateInternalMove(t,n,r,s,o,u,d);if(x)return x;let S=this.planRepeatTemplateHoistMove(t,n,r,s,o,u,d);if(S)return S;let v=this.planCrossFileRepeatTemplateHoistMove(t,n,r,s,o,u,d);return v||{ok:!1,errorCode:"unsupported-operation",reason:p}}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 x=Gc(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=Yf(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 E=[{order:0,file:r.file,type:"move-node",locator:We(r),targetParentLocator:We(s),placement:u,anchorLocator:d?We(d):void 0,selectionContext:Io(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=np(this.graph,r)??`<${r.component} />`,f=Jx(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:We(r),removeWhitespace:!0}),r.importedFrom&&r.exportName){let m=r.tag??r.component,y={moduleSpecifier:sp(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:We(o),node:{jsx:d},placement:s,anchorLocator:a?We(a):void 0,selectionContext:Io(o)})}else c.push({order:l++,file:o.file,type:"insert-child",parentLocator:We(o),node:{jsx:d},placement:s,anchorLocator:a?We(a):void 0,selectionContext:Io(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:Ae(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 wE(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 hp from"@babel/generator";import{parse as ML,parseExpression as BL}from"@babel/parser";import*as k from"@babel/types";import*as Zn from"@babel/types";import up from"@babel/generator";import*as Ze from"@babel/types";var kL=typeof up=="function"?up:up.default,_L=/(?:token|secret|key|password|authorization|cookie|signature|credential)/i,RL=/^((?:https?:)?\/\/)[^/@\s]+@/i,CL=/(\/(?:token|secret|api[-_]?key|password|credential|signature)\/)[^/?#]+/gi;function ME(e,t){let n=un(e.callee);if(!n)return null;if(n==="fetch")return dp(e.arguments[0],"GET",t,["fetch call"]);if(n.startsWith("axios.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(DE(r))return dp(e.arguments[0],r,t,["axios client contract"])}if(n.startsWith("ky.")){let r=n.split(".").at(-1)?.toUpperCase()??"GET";if(DE(r))return dp(e.arguments[0],r,t,["ky client contract"])}return null}function dp(e,t,n,r){if(!e||Ze.isSpreadElement(e)||Ze.isJSXNamespacedName(e))return TL(t,n,r,"missing url argument");let o=Ts(e);return{sourceKind:AL(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 Ts(e){if(Ze.isStringLiteral(e))return ko(e.value);if(Ze.isTemplateLiteral(e))return ko(PL(e));if(Ze.isBinaryExpression(e)&&e.operator==="+"){let t=Ts(e.left),n=Ts(e.right);return!t&&!n?void 0:ko(`${t??fp(e.left)}${n??fp(e.right)}`)}if(Ze.isMemberExpression(e)){let t=BE(e);if(t)return`env:${t}`}if(!(Ze.isCallExpression(e)&&un(e.callee)==="new URL")){if(Ze.isNewExpression(e)&&Ze.isIdentifier(e.callee,{name:"URL"})){let[t,n]=e.arguments,r=t&&!Ze.isSpreadElement(t)?Ts(t):void 0,o=n&&!Ze.isSpreadElement(n)?Ts(n):void 0;return o&&r?ko(`${o} + ${r}`):r??o}if(Ze.isIdentifier(e))return`:${e.name}`}}function PL(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+=fp(r))}return t}function fp(e){if(Ze.isIdentifier(e))return`:${e.name}`;if(Ze.isMemberExpression(e)){let t=BE(e);if(t)return`env:${t}`}return`:${NL(e)}`}function NL(e){return kL(e,{comments:!1}).code.replace(/[^a-zA-Z0-9_$]+/g,"_").replace(/^_+|_+$/g,"")||"param"}function ko(e){let[t]=e.split("#"),[n,r]=t.split("?"),o=n.replace(RL,"$1<redacted>@").replace(CL,"$1<redacted>");if(!r)return o;let i=r.split("&").map(s=>{let[a]=s.split("=");return a?_L.test(a)?`${a}=<redacted>`:`${a}=:${a}`:""}).filter(Boolean).join("&");return i?`${o}?${i}`:o}function AL(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 TL(e,t,n,r){return{sourceKind:"unknown-api",method:e,confidence:"partial",evidence:[{file:t.file,reason:[...n,r].join("; ")}]}}function DE(e){return["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)}function BE(e){return!Ze.isMemberExpression(e.object)||!Ze.isIdentifier(e.object.object,{name:"process"})||!wL(e.object.property,"env")?null:Ze.isIdentifier(e.property)?e.property.name:Ze.isStringLiteral(e.property)?e.property.value:null}function wL(e,t){return Ze.isIdentifier(e)&&e.name===t}function un(e){if(Ze.isIdentifier(e))return e.name;if(Ze.isMemberExpression(e)){let t=un(e.object),n=Ze.isIdentifier(e.property)?e.property.name:Ze.isStringLiteral(e.property)?e.property.value:null;if(t&&n)return`${t}.${n}`}return null}var OL=new Set(["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"]),FL=new Set(["getConfig","submit"]);function hr(e,t){let n=jE(un(e.callee),t);if(!n)return null;let r="cms.collections.";if(n.startsWith(r)){let i=n.slice(r.length);if(!OL.has(i))return null;let s=pp(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(!FL.has(i))return null;let s=pp(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=pp(e,0)??LL(e,0,"path")??"/cms/:path",s=DL(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 jE(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 $E(e,t){let n=un(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 Qc(e,t){let n=un(e.callee),r=t?jE(n,t):n;return typeof r=="string"&&r.startsWith("cms.field.")}function pp(e,t){let n=e.arguments[t];return Zn.isStringLiteral(n)?n.value:null}function LL(e,t,n){let r=e.arguments[t];if(!Zn.isObjectExpression(r))return null;for(let o of r.properties)if(Zn.isObjectProperty(o)&&!o.computed&&(Zn.isIdentifier(o.key)&&o.key.name===n||Zn.isStringLiteral(o.key)&&o.key.value===n)&&Zn.isStringLiteral(o.value))return o.value.value;return null}function DL(e){let t=/^\/collections\/([^/]+)(?:\/|$)/.exec(e)?.[1];return t&&/^[a-z0-9][a-z0-9_-]*$/i.test(t)?t:null}function el(e){return e.match(/^\/([a-z0-9][a-z0-9_-]*)\/[^/?#]+(?:[?#].*)?$/i)?.[1]??null}import*as It from"@babel/types";var mp=new WeakMap;function qn(e,t){let n=mp.get(e)?.get(t);if(n!==void 0)return n;let r=new Set([t]),o=l=>{let u=l;for(;It.isMemberExpression(u)||It.isOptionalMemberExpression(u);)u=u.object;return It.isIdentifier(u)?u.name:null},i=!0;for(;i;)i=!1,It.traverseFast(e,l=>{if(!It.isVariableDeclarator(l)||!l.init)return;let u=o(l.init);if(!(!u||!r.has(u)))for(let d of Object.keys(It.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(It.getBindingIdentifiers(l)).some(d=>r.has(d))},a=!1;It.traverseFast(e,l=>{(It.isAssignmentExpression(l)&&s(l.left)||It.isUpdateExpression(l)&&s(l.argument)||It.isUnaryExpression(l,{operator:"delete"})&&s(l.argument))&&(a=!0)});let c=mp.get(e)??new Map;return c.set(t,a),mp.set(e,c),a}function UE(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,m=g.get(a)??new Map,p=m.get(c)??new Map;return p.set(l,f),m.set(c,p),g.set(a,m),t.set(s,g),n.add(f),d.catch(()=>{r(f)}),d}}}import*as $t from"@babel/types";import{posix as gp}from"node:path";function ui(e,t,n=new Set){if(n.has(e))return;let r=new Set(n).add(e);if($t.isBooleanLiteral(e))return e.value;if($t.isUnaryExpression(e,{operator:"!"})){let l=ui(e.argument,t,r);return l===void 0?void 0:!l}if($t.isLogicalExpression(e)){let l=ui(e.left,t,r),u=ui(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(!$t.isCallExpression(e)||!$t.isIdentifier(e.callee))return;let o=t.imports.get(e.callee.name),i=o?.source.startsWith(".")&&t.file?gp.normalize(gp.join(gp.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=$t.isExpression(s.body)?s.body:s.body.body.length===1&&$t.isReturnStatement(s.body.body[0])?s.body.body[0].argument:null;if(!a||!$t.isExpression(a))return;let c=s.params.flatMap(l=>$t.isIdentifier(l)?[l.name]:[]);return ui(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 I2=typeof hp=="function"?hp:hp.default,ZE=new WeakMap;function qE(e){let t=new Map;return ZE.set(t,new Map([...e].map(n=>[n.file,n]))),t}var jL={maxFunctionDepth:8,maxImportDepth:6},$L=new Set(["src","href","alt","poster","content","title","aria-label"]),VE=new WeakMap;function UL(e,t,n){let r=VE.get(t.fileCache);r||(r=new WeakMap,VE.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 m=g.get(d.tag)??[];m.push(f),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 ul(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")&&JE(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=vp(e.file,e.source,t),r={file:e.file,analysis:n,readFile:e.readFile,exists:e.exists,fileCache:t,options:{...jL,...e.options},variableCache:new Map,functionDepth:0,importDepth:0,paramSources:new Map,paramArguments:new Map,resolvingVariables:new Set,resolvingComponentProps:new Set,scopeVariables:pS(n,e.element.componentName),scopeFunction:Ip(n,e.element.componentName)};await QE(e.element.componentName,e.graph,r);let o=[];o.push(...await XL(e.element,e.graph,r),...await zL(e.element,e.graph,r));for(let s of e.element.textSegments){let a=await HL(s,e.element,e.graph,r);a&&o.push(cl(a,"text","children"))}for(let s of e.element.attributes??[]){let a=JE(s,e.element);if(!a)continue;let c=await nS(s.source,e.element,e.graph,r);if(!c&&s.syntaxKind==="expression"&&!(s.source&&Ro(s.source.base,e.element,e.graph))){let u=n.jsxElementsByRange.get(dl(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)&&!oS(u.value.expression,e.element,e.graph)&&(c=await at(u.value.expression,r))}c&&o.push(cl(c,a,s.name))}let i=iD(o).sort(dS);return{hasDynamicData:i.length>0,bindings:i}}async function QE(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 UL(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 VL(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 tS(l.sourceFile,n);if(!d)continue;let f=zr(d,n,{importDepth:n.importDepth+1});f.paramSources.clear(),f.scopeVariables=pS(d,l.componentName),f.scopeFunction=Ip(d,l.componentName),f.lexicalContext=void 0,await QE(l.componentName,t,f);let g=await KL(l,t,f);for(let[m,p]of g){if(!p)continue;let y=a.get(m)??[];y.push(p),a.set(m,y)}}finally{n.resolvingComponentProps.delete(u)}}}let c=new Map;for(let[l,u]of a){let d=Sp(u);d.length===1&&c.set(l,d[0])}JL(o,c,n)}var KE=new WeakMap;function VL(e,t,n,r){let o=KE.get(r.fileCache);return o||(o=UE(),KE.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 tS(e,r))?.imports.get(t);if(!s||!pt(s.source))return!1;let a=await _p(e,s.source,r.exists);return a?a===n?!0:eS(a,s.importedName,n,r,o):!1}async function KL(e,t,n){let r=new Map,o=n.analysis.jsxElementsByRange.get(dl(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?Ro(c.base,e,t):null)?await fl(c,e,t,n):oS(a,e,t)?null:await at(a,n);u&&i.set(s,u)}return i}function dl(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}async function tS(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 vp(e,r,t.fileCache)}function JL(e,t,n){if(k.isIdentifier(e)){t.size>0&&n.paramSources.set(e.name,al(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,Ft(o))}}function JE(e,t){return e.name==="dangerouslySetInnerHTML"?"richtext":$L.has(e.name)?"attribute":t.importedFrom||/^[A-Z]/.test(t.tag)?"component-prop":null}async function XL(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 pl(i.collectionSource,n);s&&r.push(cl(Kr(s),"repeat-region",i.collectionExpression))}return r}async function zL(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 pl(i.conditionSource,n);s&&r.push(cl(Kr(s),"conditional-region",i.conditionExpression))}return r}async function HL(e,t,n,r){if(!e.source){let i=r.analysis.jsxElementsByRange.get(dl(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)&&Qc(i.expression)?rS(i.expression,t,n,r):null}return nS(e.source,t,n,r)}async function nS(e,t,n,r){return e&&Ro(e.base,t,n)?fl(e,t,n,r):pl(e,r)}async function fl(e,t,n,r,o){if(!e)return null;let i=Ro(e.base,t,n,o);if(!i||i.candidate.itemParamName!==e.base)return null;let s=i.candidate.collectionSource,c=(s?Ro(s.base,t,n,i.region):null)?await fl(s,t,n,r,i.region):s?await pl(s,r):await WL(i.candidate.collectionExpression,t,n,r,i.region);return c?ws(c,e.path,!0):null}async function WL(e,t,n,r,o){let i;try{i=BL(e,{plugins:["typescript","jsx"]})}catch{return null}return rS(i,t,n,r,o)}async function rS(e,t,n,r,o){let i=zr(r.analysis,r),s=new Set;k.traverseFast(e,a=>{k.isIdentifier(a)&&s.add(a.name)});for(let a of s){let c=Ro(a,t,n,o);if(!c)continue;if(c.candidate.itemParamName!==a)return null;let l=await fl({kind:"identifier",expression:a,base:a,path:[]},t,n,r,o);if(!l)return null;i.paramSources.set(a,l)}return at(e,i)}function Ro(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&&!XE(s.sourceRange,r.sourceRange))continue;let a=s.sourceCandidates?.find(c=>c.kind==="repeat-template"&&(c.itemParamName===e||c.indexParamName===e));a&&(!i||XE(i.region.sourceRange,s.sourceRange))&&(i={candidate:a,region:s})}o=n.elements.get(o)?.parentKey??null}return i}function XE(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 oS(e,t,n){let r=!1;return k.traverseFast(e,o=>{!r&&k.isIdentifier(o)&&Ro(o.name,t,n)&&(r=!0)}),r}async function pl(e,t){if(!e)return null;let n=await xp(e.base,t);return n?ws(n,e.path,!1):null}async function xp(e,t){let n=t.paramSources.get(e);if(n)return Ft(n);if(t.variableCache.has(e))return sD(t.variableCache.get(e)??null);let r=Xr(e,t);if(r&&r!==t)return xp(e,r);if(t.resolvingVariables.has(e))return null;t.resolvingVariables.add(e);let o=await YL(e,t);if(o)return t.variableCache.set(e,Ft(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 GL(e,t):await at(s,t);return t.variableCache.set(e,c?Ft(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 kp(a,t);if(c){let l=zr(c,t,{importDepth:t.importDepth+1}),u=mS(a,c);if(u){let g=(await _o(u,[],l)).returnSource;return t.variableCache.set(e,g?Ft(g):null),t.resolvingVariables.delete(e),g}let d=c.variables.get(a.importedName);if(d){let f=await at(d,l);return t.variableCache.set(e,f?Ft(f):null),t.resolvingVariables.delete(e),f}}}return t.variableCache.set(e,null),t.resolvingVariables.delete(e),null}function Xr(e,t){return t.scopeVariables?.has(e)||t.scopeFunction?.params.some(n=>Jr(n).includes(e))?t:t.lexicalContext?Xr(e,t.lexicalContext):void 0}function tl(e,t,n=new Set){if(k.isIdentifier(e)){let s=Xr(e.name,t);if(s&&s!==t)return tl(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=Xr(e.name,t),o=t.paramArguments.get(e.name);if(o)return tl(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?tl(i,t,n):null}function Qn(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=Xr(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?Qn(s.expression,s.context,r):a?Qn(a,i,r):null)??`:${e.name}`}if(k.isBinaryExpression(e,{operator:"+"})){let o=Qn(e.left,t,r),i=Qn(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+=(Qn(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=Qn(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)?Qn(e.expression,t,r):null}async function GL(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,f=>{k.isIdentifier(f,{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)&&(Jr(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 f of u.arguments){let g=k.isSpreadElement(f)?f.argument:f,m=k.isExpression(g)?await at(g,d):null;m?r.push(bp(m)):o=!0}return}if(u.arguments.some(f=>s(f))){o=!0;return}}if(k.isForOfStatement(u)){let f=await at(u.right,d),g=zr(d.analysis,d),m=k.isVariableDeclaration(u.left)?u.left.declarations[0]?.id:u.left;f&&m&&il(m,bp(f),g),await c(u.body,g);return}for(let f of k.VISITOR_KEYS[u.type]??[]){let g=u[f];for(let m of Array.isArray(g)?g:[g])k.isNode(m)&&await c(m,d)}}};await c(n.body,t);let l=Sp(r);return!o&&i===1&&l.length===1?Kr(l[0]):null}async function YL(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 at(o,t);if(i)return i}return null}async function at(e,t){if(k.isIdentifier(e))return xp(e.name,t);if(k.isMemberExpression(e)||k.isOptionalMemberExpression(e)){let n=k.isMemberExpression(e)?$E(e,{file:t.file}):null;if(n)return lS(n);let r=await ZL(e,t);if(!r)return null;let o=oD(e);return ws(r,o,!1)}if(k.isAwaitExpression(e))return k.isExpression(e.argument)?at(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 fi(await at(e.callee.object,t));if(k.isCallExpression(e))return sS(e,t);if(k.isObjectExpression(e)){let n=await cS(e,t);return Object.keys(n).length>0?al(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 at(o,t);i&&(n[String(r)]=i)}return Object.keys(n).length?al(n,t.file):null}if(k.isConditionalExpression(e)){let n=await at(e.consequent,t),r=await at(e.alternate,t);return fi(WE(n,r))}if(k.isLogicalExpression(e)){let n=await at(e.left,t),r=await at(e.right,t);return fi(WE(n,r))}return k.isTSAsExpression(e)||k.isTSSatisfiesExpression(e)||k.isTSNonNullExpression(e)||k.isTypeCastExpression(e)||k.isParenthesizedExpression(e)?at(e.expression,t):null}async function ZL(e,t){let n=e;for(;k.isMemberExpression(n)||k.isOptionalMemberExpression(n);)n=n.object;return k.isExpression(n)?at(n,t):null}async function iS(e,t,n=0){if(n>=t.options.maxFunctionDepth)return null;let r=Xr(e,t);if(r){if(r.scopeFunction&&qn(r.scopeFunction,e))return null;let s=r.paramArguments.get(e);return s&&k.isIdentifier(s.expression)?iS(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)||qn(t.analysis.ast,e))return null;let i=await _p(t.file,o.source,t.exists);return i?{...o,source:i}:null}async function sS(e,t){let n=e.arguments[0],r=k.isExpression(n)?tl(n,t):null,i=un(e.callee)?.split(".")[0],s=i?await iS(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 b=aS(n,"path"),E=b&&Qn(b,t);E?.startsWith("/")&&(a={...e,arguments:[{...n,properties:n.properties.map(x=>k.isObjectProperty(x)&&mi(x)==="path"?{...x,value:k.stringLiteral(ko(E))}:x)},...e.arguments.slice(1)]})}let c=hr(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 b=zE(n,"query"),E=k.isObjectExpression(b)?zE(b,"path"):null,x=E&&Qn(E,t),S=x&&el(x);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 b=await yr(e.callee,t);if(b&&!nl(b.node))return null;if(b&&nl(b.node)){let E=await yp(e,t,{node:b.node,context:b.context});return E&&{...E,...E.sourceKind===c.sourceKind?{operation:c.operation}:{}}}}if((c.operation==="getByUrl"||c.operation==="getByUrlStrict")&&k.isExpression(n)){let b=Qn(n,t);b?.startsWith("/")&&(c.endpointPattern=ko(b))}return lS(c)}if(un(e.callee)==="Promise.all"&&k.isArrayExpression(n))return at(n,t);if(Qc(e)){if(!Qc(e,{file:t.file,imports:i&&s?new Map([[i,s]]):new Map})||!k.isExpression(e.callee))return null;let b=await yr(e.callee,t);if(b)return nl(b.node)?yp(e,t,{node:b.node,context:b.context}):null;let E=e.arguments[0];if(E&&k.isExpression(E))return fi(await at(E,t))}let l=await qL(e,t);if(l)return l;let u=ME(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 eD(e,t);if(d)return d;let f=await tD(e,t);if(f)return f;let g=await nD(e,t);if(g)return g;let m=await yp(e,t);if(m)return m;let p=[];for(let b of e.arguments)if(k.isExpression(b)){let E=await at(b,t);E&&p.push(E)}let y=Sp(p);return y.length===1?fi(y[0]):null}async function qL(e,t){let n=un(e.callee);if(n!=="useQuery"&&n!=="useSuspenseQuery"&&n!=="useInfiniteQuery"&&n!=="useSWR")return null;if(n==="useSWR"){let i=QL(e.arguments[0],t.file,"SWR key"),s=e.arguments[1];if(k.isIdentifier(s)){let a=await pi(s.name,t);if(a)return(await _o(a.node,i?[i]:[],a.context)).returnSource??i}return i}let r=e.arguments[0];if(!k.isObjectExpression(r))return rl(t.file,`${n} without static options`);let o=aS(r,"queryFn");if(!o)return rl(t.file,`${n} without queryFn`);if(k.isIdentifier(o)){let i=await pi(o.name,t);return i?(await _o(i.node,[],i.context)).returnSource:rl(t.file,`${n} queryFn unresolved`)}return k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)?(await _o(o,[],t)).returnSource:k.isCallExpression(o)?sS(o,t):null}function aS(e,t){for(let n of e.properties){if(!k.isObjectProperty(n)||!k.isExpression(n.value))continue;if(mi(n)===t)return n.value}return null}function zE(e,t){let n=new Set;for(let i of e.properties){if(!k.isObjectProperty(i)||i.computed)return null;let s=mi(i);if(!s||n.has(s))return null;n.add(s)}let r=e.properties.filter(i=>k.isObjectProperty(i)&&mi(i)===t);if(r.length!==1)return null;let o=r[0];return k.isObjectProperty(o)&&k.isExpression(o.value)?o.value:null}function QL(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 eD(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 at(e.callee.object,t):null;if(!r)return null;if(n!=="map")return Kr(r);let o=e.arguments[0];if(k.isIdentifier(o)){let i=await pi(o.name,t);if(!i)return Kr(r);let s=await _o(i.node,[r],i.context);return{...Kr(r),...s.objectReturnMap??s.returnSource?.fieldMap?{fieldMap:s.objectReturnMap??s.returnSource.fieldMap}:{}}}if(k.isArrowFunctionExpression(o)||k.isFunctionExpression(o)){let i=await _o(o,[r],t);return{...Kr(r),...i.objectReturnMap??i.returnSource?.fieldMap?{fieldMap:i.objectReturnMap??i.returnSource.fieldMap}:{}}}return Kr(r)}async function tD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"json"})||!k.isExpression(e.callee.object)?null:at(e.callee.object,t)}async function nD(e,t){return!k.isMemberExpression(e.callee)||!k.isIdentifier(e.callee.property,{name:"then"})||!k.isExpression(e.callee.object)?null:fi(await at(e.callee.object,t))}async function yp(e,t,n){let r=n;if(!r&&k.isIdentifier(e.callee))r=await pi(e.callee.name,t)??void 0;else if(!r&&k.isMemberExpression(e.callee)){let s=await yr(e.callee,t);s&&nl(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(rl(t.file,`unsupported argument for ${un(e.callee)??"call"}`));continue}let a=await at(s,t);o.push(a)}return(await _o(r.node,o,r.context,{arguments:e.arguments,context:t})).returnSource}function nl(e){return k.isFunctionDeclaration(e)||ll(e)||k.isObjectMethod(e)&&e.kind==="method"}async function yr(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 yr(e.expression,t,o);if(k.isIdentifier(e)){let i=Xr(e.name,t),s=i??t;if(qn(i?.scopeFunction??t.analysis.ast,e.name))return r;let a=s.paramArguments.get(e.name);if(a)return yr(a.expression,a.context,o);let c=i?i.scopeVariables?.get(e.name):s.analysis.variables.get(e.name);if(c)return yr(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 kp(u,s);return d?yr(k.identifier(u.importedName),zr(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 yr(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)?yr(c.value,s.context,o):null}return{node:e,context:t}}async function pi(e,t,n=new Set){let r=t.paramArguments.get(e);if(r&&!n.has(r.expression)){if(n.add(r.expression),ll(r.expression))return{node:r.expression,context:r.context};if(k.isIdentifier(r.expression))return pi(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 kp(i,t);if(!s)return null;let a=zr(s,t,{importDepth:t.importDepth+1}),c=mS(i,s);return c?{node:c,context:a}:pi(i.importedName,a)}async function _o(e,t,n,r){if(n.functionDepth>=n.options.maxFunctionDepth)return{returnSource:null};let o=zr(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 Jr(d))o.paramSources.delete(y),o.paramArguments.delete(y);let g=k.isAssignmentPattern(d)?d.left:d,m=r?.arguments[f];k.isIdentifier(g)&&k.isExpression(m)&&r&&o.paramArguments.set(g.name,{expression:m,context:r.context});let p=t[f];p&&il(d,bp(p),o)});let a=rD(e,o),c=null,l,u=!1;for(let d of a){let f=zr(n.analysis,o);if(k.isObjectExpression(d)){l={...l??{},...await cS(d,f)},c=c??al(l,n.file);continue}let g=await at(d,f);if(g){if(!c){c=g;continue}let m=Ep(c,g);if(!m){u=!0,c=null;continue}c=m}}return{returnSource:u?null:c,...l?{objectReturnMap:l}:{}}}function il(e,t,n){if(k.isIdentifier(e)){n.paramSources.set(e.name,Ft(t));return}if(k.isAssignmentPattern(e)){il(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=ws(t,[{kind:"property",name:r.key.name}],!0),i=k.isAssignmentPattern(r.value)?r.value.left:r.value;o&&il(i,o,n)}}function rD(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=ui(i.test,{file:t.file,imports:new Map([...t.analysis.imports].filter(([c])=>!Xr(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 cS(e,t){let n={};for(let r of e.properties){if(!k.isObjectProperty(r))continue;let o=mi(r);if(!o||!k.isExpression(r.value))continue;let i=await at(r.value,t);i&&(n[o]=i)}return n}function mi(e){return k.isIdentifier(e.key)&&!e.computed?e.key.name:k.isStringLiteral(e.key)?e.key.value:null}function oD(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 ws(e,t,n){if(t.length===0)return Ft(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?ws(s,t.slice(1),n):null}let i=Ft(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=di(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=di(i.valuePath,"data")),i.fieldPath=di(i.fieldPath,s.slice(a+1).join(".")),i.cmsFieldRoot=!0,i):i.cmsFieldRoot||n||i.fieldMap?(i.fieldPath=di(i.fieldPath,s.join(".")),i):(i.valuePath=di(i.valuePath,HE(t)),i)}return i.valuePath=di(i.valuePath,HE(t)),i}function HE(e){return e.map(t=>t.kind==="property"?t.name:`[${t.index}]`).join(".").replace(/\.\[/g,"[")}function di(e,t){return t?e?t.startsWith("[")?`${e}${t}`:`${e}.${t}`:t:e}function lS(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 Kr(e){let t=Ft(e);return t.sourceType==="cms-field"&&!t.valuePath&&(t.valuePath="items[]"),t}function bp(e){let t=Ft(e);return t.valuePath=void 0,t.sourceType==="cms-field"&&!t.fieldPath&&(t.cmsFieldRoot=!1),t}function fi(e){return e?{...Ft(e),confidence:e.confidence==="unknown"?"unknown":"safe-derived",evidence:[...e.evidence,{file:e.evidence[0]?.file??"unknown",reason:"safe derived expression"}]}:null}function WE(e,t){return e?t?Ep(e,t):Ft(e):t?Ft(t):null}function Ep(e,t){if(sl(e)!==sl(t))return null;let n=fS(e.confidence,t.confidence)<=0?e.confidence:t.confidence;return{...e,confidence:n,evidence:[...e.evidence,...t.evidence]}}function Sp(e){let t=new Map;for(let n of e){let r=sl(n),o=t.get(r);t.set(r,o?Ep(o,n):Ft(n))}return[...t.values()]}function sl(e){let t=e.fieldMap?Object.fromEntries(Object.entries(e.fieldMap).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,sl(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 al(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 rl(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 uS(e){let t=[...e].sort(dS),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 iD(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 dS(e,t){return GE(e.targetKind)-GE(t.targetKind)||fS(e.confidence,t.confidence)||YE(e.sourceKind)-YE(t.sourceKind)||e.targetName.localeCompare(t.targetName)}function GE(e){return{"repeat-region":0,"conditional-region":1,text:2,richtext:3,attribute:4,"component-prop":5}[e]}function YE(e){return e.startsWith("vcp-cms-")?0:e==="site-api-route"?1:e==="external-api"?2:3}function fS(e,t){let n={exact:0,"safe-derived":1,partial:2,unknown:3};return n[e]-n[t]}function vp(e,t,n){let r=n.get(e);if(r?.source===t)return r;let o=ZE.get(n)?.get(e),i=o?.source===t?o.ast:ML(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 f=d.loc;if(!f)return;let g=dl({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)k.isImportSpecifier(g)&&k.isIdentifier(g.local)?s.imports.set(g.local.name,{source:f,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: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&&(k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f)||k.isObjectMethod(f))?f:null,m=g?s.functionVariables.get(g)??new Map:s.variables;g&&!s.functionVariables.has(g)&&s.functionVariables.set(g,m);for(let[p,y]of ol(d.id,k.isExpression(d.init)?d.init:null))m.set(p,y);if(k.isArrayPattern(d.id)&&k.isCallExpression(d.init)&&un(d.init.callee)==="useState"){let[p,y]=d.id.elements;k.isIdentifier(p)&&k.isIdentifier(y)&&s.stateSetters.set(p.name,y.name)}k.isIdentifier(d.id)&&ll(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 m of d.specifiers){if(!k.isExportSpecifier(m))continue;let p=k.isIdentifier(m.exported)?m.exported.name:m.exported.value,y=m.local.name;s.imports.set(p,{source:g,importedName:y,localName:p,isDefault:y==="default"})}if(k.isFunctionDeclaration(f)&&f.id?.name&&s.functions.set(f.id.name,f),k.isVariableDeclaration(f))for(let m of f.declarations)k.isIdentifier(m.id)&&ll(m.init)&&s.functions.set(m.id.name,m.init);break}case"ExportDefaultDeclaration":{let f=d.declaration;if((k.isFunctionDeclaration(f)||k.isFunctionExpression(f)||k.isArrowFunctionExpression(f))&&s.functions.set("default",f),k.isIdentifier(f)){let g=s.functions.get(f.name);g&&s.functions.set("default",g)}break}}},exit(d){k.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=k.isIdentifier(d.callee)?d.callee.name:null;f&&l.has(f)&&k.isExpression(d.arguments[0])&&u(f,d.arguments[0]);let g=new Set;for(let m of d.arguments)k.isIdentifier(m)&&m.name!==f&&l.has(m.name)&&g.add(m.name);for(let m of g)u(m,d)}return n.set(e,s),s}function ol(e,t){return k.isIdentifier(e)?[[e.name,t]]:k.isAssignmentPattern(e)?ol(e.left,t):k.isArrayPattern(e)?e.elements.flatMap((n,r)=>n&&!k.isRestElement(n)?ol(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=mi(n);return r?ol(n.value,t?k.memberExpression(t,k.stringLiteral(r),!0):null):[]}):[]}function Jr(e){return!e||k.isVoidPattern(e)?[]:k.isIdentifier(e)?[e.name]:k.isObjectPattern(e)?e.properties.flatMap(t=>k.isObjectProperty(t)?Jr(t.value):Jr(t.argument)):k.isArrayPattern(e)?e.elements.flatMap(t=>t?Jr(k.isRestElement(t)?t.argument:t):[]):k.isAssignmentPattern(e)?Jr(e.left):k.isRestElement(e)?Jr(e.argument):[]}function ll(e){return k.isFunctionExpression(e)||k.isArrowFunctionExpression(e)}function pS(e,t){let n=Ip(e,t);return n?e.functionVariables.get(n):void 0}function Ip(e,t){return e.functions.get(t)??e.functions.get("default")}async function kp(e,t){let n=await _p(t.file,e.source,t.exists);if(!n)return null;let r=await t.readFile(n);return vp(n,r,t.fileCache)}function mS(e,t){return e.isDefault?t.functions.get("default")??t.functions.get(e.localName)??null:t.functions.get(e.importedName)??null}async function _p(e,t,n){return pt(t)?no(e,t,n):null}function zr(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 sD(e){return e?Ft(e):null}function Ft(e){return{...e,evidence:e.evidence.map(t=>({...t})),...e.fieldMap?{fieldMap:Object.fromEntries(Object.entries(e.fieldMap).map(([t,n])=>[t,Ft(n)]))}:{}}}import*as Cp from"@babel/parser";import Rp from"@babel/traverse";import*as fe from"@babel/types";import{classifySiteEditPropertyName as aD}from"@vcp-dev/contracts";var Pp=typeof Rp=="function"?Rp:Rp.default;function Np(e){let t=aD(e.propertyName);if(t.owner!=="generic")return dn("invalid-property",t.diagnostic?.message??`Property '${e.propertyName}' is not a generic property`);let n=e.selectionRef;if(!n)return dn("missing-selection-ref","A repeat property target requires a complete selection reference");if(n.key!==e.element.identity.key)return dn("selection-mismatch","Selection reference does not identify the requested element");if(n.instanceIndex===void 0)return dn("missing-instance-index","A repeat property target requires an instance index");let r;try{r=Cp.parse(e.source,{sourceType:"module",plugins:["typescript","jsx"]})}catch(y){return dn("repeat-not-found",`Unable to parse repeat source: ${y instanceof Error?y.message:String(y)}`)}let o=cD(r,e.element.sourceRange);if(!o)return dn("repeat-not-found","The selected element is not inside a supported map repeat");if(!fe.isIdentifier(o.callback.params[0]))return dn("unsupported-callback","Repeat property materialization requires an identifier callback item");let i=lD(r,o.collection,e.file,e.sources);if(!i)return dn("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||!fe.isObjectExpression(b)||!ES(b))return dn("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 dn("count-mismatch",`Selection reports ${n.instanceCount} instances but the source collection has ${d}`);let f=n.instanceIndex;if(f>=d)return dn("index-out-of-range",`Selected repeat instance ${f} is outside the source collection`);let g=s.elements[f];if(!g||!fe.isObjectExpression(g))return dn("unsafe-collection","Selected repeat item is not an object");let m=gD(e.element,e.propertyName),p=pD(g,e.propertyName);return p?{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:p,selectedResolution:mD(g,e.propertyName),...m?{property:m}:{},selectionRef:n}:dn("unsafe-property-source",`Property '${e.propertyName}' has a dynamic or unsupported source in the repeat item`)}function cD(e,t){let n=[];return Pp(e,{CallExpression(r){let o=gS(r.node);o&&yS(o.callback,t)&&n.push({...o,span:hS(r.node)})},OptionalCallExpression(r){let o=gS(r.node);o&&yS(o.callback,t)&&n.push({...o,span:hS(r.node)})}}),n.sort((r,o)=>r.span-o.span),n[0]??null}function gS(e){let t=e.callee;if(!fe.isMemberExpression(t)&&!fe.isOptionalMemberExpression(t)||t.computed||!fe.isIdentifier(t.property)||t.property.name!=="map"||!fe.isExpression(t.object))return null;let n=e.arguments[0];return!n||!fe.isExpression(n)||!fe.isArrowFunctionExpression(n)&&!fe.isFunctionExpression(n)?null:{collection:t.object,callback:n}}function lD(e,t,n,r){let o=Os(t);if(o&&fe.isArrayExpression(o))return{array:o,locator:{kind:"value",root:{kind:"expression",sourceRange:vS(o)}},sourceFile:n};if(!fe.isIdentifier(t))return null;let i=[];if(Pp(e,{VariableDeclarator(s){fe.isIdentifier(s.node.id)&&s.node.id.name===t.name&&s.node.init&&i.push(s.node)}}),i.length===1){let s=Os(i[0].init);return!s||!fe.isArrayExpression(s)?null:{array:s,locator:{kind:"value",root:{kind:"binding",name:t.name}},sourceFile:n}}return uD(e,t.name,n,r)}function uD(e,t,n,r){if(!r)return null;for(let o of e.program.body){if(!fe.isImportDeclaration(o))continue;let i=o.specifiers.find(f=>f.local.name===t);if(!i||!fe.isStringLiteral(o.source)||!fe.isImportSpecifier(i))continue;let s=fD(n,o.source.value,r);if(!s)return null;let a=fe.isIdentifier(i.imported)?i.imported.name:i.imported.value,c=r.get(s);if(c===void 0)return null;let l;try{l=Cp.parse(c,{sourceType:"module",plugins:["typescript","jsx"]})}catch{return null}let u=dD(l,a),d=u?Os(u):null;return!d||!fe.isArrayExpression(d)?null:{array:d,locator:{kind:"value",root:{kind:"binding",name:a}},sourceFile:s}}return null}function dD(e,t){let n=null;return Pp(e,{VariableDeclarator(r){n||!fe.isIdentifier(r.node.id)||r.node.id.name!==t||!r.node.init||!fe.isExpression(r.node.init)||(n=r.node.init)}}),n}function fD(e,t,n){let r=$n(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 Os(e){return fe.isParenthesizedExpression(e)?Os(e.expression):fe.isTSAsExpression(e)?xS(e.typeAnnotation)?Os(e.expression):null:fe.isTSSatisfiesExpression(e)?null:e}function xS(e){return fe.isTSTypeReference(e)&&fe.isIdentifier(e.typeName)&&e.typeName.name==="const"}function ES(e){return e.properties.every(t=>!fe.isObjectProperty(t)||t.computed||!fe.isExpression(t.value)?!1:ml(t.value))}function ml(e){if(fe.isTSAsExpression(e)&&xS(e.typeAnnotation))return ml(e.expression);if(fe.isTSSatisfiesExpression(e))return!1;if(fe.isArrayExpression(e))return e.elements.every(n=>!n||fe.isSpreadElement(n)||!fe.isExpression(n)?!1:ml(n));if(fe.isObjectExpression(e))return ES(e);let t=Xn(e);return t.status==="resolved"||t.status==="undefined"}function pD(e,t){let n=e.properties.filter(o=>fe.isObjectProperty(o)&&SS(o.key)===t);if(n.length>1)return null;let r=n[0];return r?fe.isExpression(r.value)?ml(r.value)?"static":fe.isIdentifier(r.value)||fe.isMemberExpression(r.value)?"binding":null:null:"missing"}function mD(e,t){let n=e.properties.filter(o=>fe.isObjectProperty(o)&&SS(o.key)===t);if(n.length>1)return{status:"unresolved"};let r=n[0];return!r||!fe.isExpression(r.value)?{status:"undefined"}:Xn(r.value)}function gD(e,t){let n=e.attributes?.filter(r=>r.name===t)??[];return n.length===1?n[0]:void 0}function SS(e){return fe.isIdentifier(e)?e.name:fe.isStringLiteral(e)?e.value:fe.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 hS(e){return e.start==null||e.end==null?Number.MAX_SAFE_INTEGER:e.end-e.start}function yS(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 dn(e,t){return{ok:!1,errorCode:e,reason:t}}import{classifySiteEditPropertyName as QD}from"@vcp-dev/contracts";import*as he from"@babel/types";import Bs from"node:path";import*as Q from"@babel/types";import*as PS from"@babel/parser";import Ap from"@babel/traverse";import*as Se from"@babel/types";function hl(e,t){let n=[],r=e;for(;Se.isMemberExpression(r);){if(r.computed)if(Se.isNumericLiteral(r.property))n.unshift({kind:"index",index:r.property.value});else if(Se.isStringLiteral(r.property))n.unshift({kind:"property",name:r.property.value});else return null;else{if(!Se.isIdentifier(r.property))return null;n.unshift({kind:"property",name:r.property.name})}r=r.object}return!Se.isIdentifier(r)||r.name!==t?null:n}function IS(e){if(Se.isIdentifier(e))return{base:e.name,path:[]};if(!Se.isMemberExpression(e))return null;let t=[],n=e;for(;Se.isMemberExpression(n);){if(n.computed)if(Se.isNumericLiteral(n.property))t.unshift({kind:"index",index:n.property.value});else if(Se.isStringLiteral(n.property))t.unshift({kind:"property",name:n.property.value});else return null;else{if(!Se.isIdentifier(n.property))return null;t.unshift({kind:"property",name:n.property.name})}n=n.object}return Se.isIdentifier(n)?{base:n.name,path:t}:null}function Ut(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 er=Symbol("not-closed-literal");function gl(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:er;case"TSAsExpression":case"TSSatisfiesExpression":case"TSNonNullExpression":return gl(e.expression);case"ArrayExpression":{let t=[];for(let n of e.elements){if(!n||Se.isSpreadElement(n))return er;let r=gl(n);if(r===er)return er;t.push(r)}return t}case"ObjectExpression":{let t={};for(let n of e.properties){if(!Se.isObjectProperty(n)||n.computed||n.shorthand||!Se.isExpression(n.value))return er;let r=Se.isIdentifier(n.key)?n.key.name:Se.isStringLiteral(n.key)?n.key.value:null;if(!r)return er;let o=gl(n.value);if(o===er)return er;t[r]=o}return t}default:return er}}function kS(e){let{resolveBindingTarget:t}=e;async function n(i,s,a,c,l,u,d){let f=gl(i);if(f!==er)return f;if(!Se.isTemplateLiteral(i)){if(Se.isTSAsExpression(i)||Se.isTSSatisfiesExpression(i)||Se.isTSNonNullExpression(i))return await n(i.expression,s,a,c,l,u,d);if(Se.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(Se.isArrayExpression(i)){let g=[];for(let m of i.elements){if(!m||Se.isSpreadElement(m))return;let p=await r(m,s,a,c,l,u,d);if(p===void 0)return;g.push(p)}return g}if(Se.isObjectExpression(i)){let g={};for(let m of i.properties){if(!Se.isObjectProperty(m)||m.computed)return;let p=null;if(Se.isIdentifier(m.key)?p=m.key.name:Se.isStringLiteral(m.key)&&(p=m.key.value),!p)return;if(m.shorthand){if(!Se.isIdentifier(m.value))return;let b=await r(m.value,s,a,c,l,u,d);if(b===void 0)return;g[p]=b;continue}if(!Se.isExpression(m.value))return;let y=await r(m.value,s,a,c,l,u,d);y!==void 0&&(g[p]=y)}return g}if(Se.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 p=await t({currentFile:a,binding:m,readFile:c,exists:l,fileCache:u,visited:d});return!p||p.kind!=="static"?void 0:Ut(p.value,g.path)}}}async function r(i,s,a,c,l,u,d){if(!Se.isSpreadElement(i))return await n(i,s,a,c,l,u,d)}async function o(i,s,a,c,l,u,d){if(Se.isIdentifier(i))return{base:i.name,path:[]};if(!Se.isMemberExpression(i))return null;let f=[],g=i;for(;Se.isMemberExpression(g);){if(g.computed){let m=g.property;if(Se.isNumericLiteral(m))f.unshift({kind:"index",index:m.value});else if(Se.isStringLiteral(m))f.unshift({kind:"property",name:m.value});else{let p=Se.isExpression(m)?await n(m,s,a,c,l,u,d):void 0;if(typeof p=="string")f.unshift({kind:"property",name:p});else if(Number.isInteger(p))f.unshift({kind:"index",index:p});else return null}}else{if(!Se.isIdentifier(g.property))return null;f.unshift({kind:"property",name:g.property.name})}g=g.object}return Se.isIdentifier(g)?{base:g.name,path:f}:null}return{normalizeExpressionWithScope:o,evaluateStaticExpression:n}}var NS=typeof Ap=="function"?Ap:Ap.default,_S=new WeakMap;function AS(e){try{return PS.parse(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return null}}function yl(e,t,n){let r=e.get(t);if(r?.source===n)return r.ast;let o=AS(n);return e.set(t,{source:n,ast:o}),o}function bl(e,t){return Tp(Fs(e).expressionRanges,t,!1)}function TS(e,t){return Fs(e).exactExpressions.get(wS(t))??null}function xl(e,t){return Tp(Fs(e).jsxRanges,t,!0)}function Fs(e){let t=_S.get(e);if(t)return t;let n={expressions:[],expressionRanges:[],jsxRanges:[],exactExpressions:new Map};return NS(e,{Expression(r){let o=r;n.expressions.push(o);let i=RS(o,n.expressions.length-1);if(!i)return;n.expressionRanges.push(i);let s=wS(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=RS(r,n.jsxRanges.length);o&&n.jsxRanges.push(o)}}),n.expressionRanges.sort(CS),n.jsxRanges.sort(CS),_S.set(e,n),n}function RS(e,t){let n=Ls(e.node);return n?{path:e,range:n,traversalIndex:t,span:(e.node.end??0)-(e.node.start??0)}:null}function wS(e){return`${e.startLine}:${e.startColumn}:${e.endLine}:${e.endColumn}`}function CS(e,t){return e.range.startLine-t.range.startLine||e.range.startColumn-t.range.startColumn||e.traversalIndex-t.traversalIndex}function Tp(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 Ls(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 gi(e,t){if(t)return wp(e,t);let n=IS(e);return n?n.path.reduce((r,o)=>o.kind==="property"?`${r}.${o.name}`:`${r}[${o.index}]`,n.base):""}function wp(e,t){return e.start==null||e.end==null?"":t.slice(e.start,e.end)}function Ds(e,t,n){let r=null,o=Number.POSITIVE_INFINITY;for(let i of Fs(e).expressions){if(wp(i.node,t)!==n)continue;let s=(i.node.end??0)-(i.node.start??0);s<=o&&(r=i,o=s)}return r}function OS(e,t,n,r){return Tp(Fs(e).expressionRanges,r,!0,o=>wp(o.node,t)===n)}function hi(e,t){return t.reduce((n,r)=>r.kind==="property"?`${n}.${r.name}`:`${n}[${r.index}]`,e)}function Ms(e){let t=null;if(NS(e,{Program(n){t=n.scope,n.stop()}}),!t)throw new Error("Unable to determine program scope");return t}async function Dn(e,t,n){let r=n.get(e);if(r)return r;let o=await t(e),i=AS(o),s={source:o,ast:i};return n.set(e,s),s}function hD(e){return Q.isIdentifier(e.callee)&&(e.callee.name==="useState"||e.callee.name==="useReducer")?e.callee.name:Q.isMemberExpression(e.callee)&&Q.isIdentifier(e.callee.property)&&(e.callee.property.name==="useState"||e.callee.property.name==="useReducer")?e.callee.property.name:null}function yD(e){if(!Q.isNewExpression(e)||!Q.isIdentifier(e.callee,{name:"Proxy"})||e.arguments.length!==2||!Q.isIdentifier(e.arguments[0])||!Q.isObjectExpression(e.arguments[1])||e.arguments[1].properties.length!==1)return null;let[t]=e.arguments[1].properties;if(!Q.isObjectMethod(t)||t.kind!=="method"||t.computed||t.async||t.generator||!Q.isIdentifier(t.key,{name:"get"})||t.params.length!==3||!t.params.every(Q.isIdentifier)||t.body.body.length!==2)return null;let[n,r,o]=t.params,[i,s]=t.body.body;if(Q.isIfStatement(i)&&Q.isBlockStatement(i.consequent)&&i.consequent.body.length!==1)return null;let a=Q.isIfStatement(i)?i.test:null,c=a&&Q.isLogicalExpression(a,{operator:"&&"})?a.right:null,l=Q.isIfStatement(i)?Q.isBlockStatement(i.consequent)?i.consequent.body[0]:i.consequent:null,u=Q.isReturnStatement(s)?s.argument:null;return!a||!Q.isLogicalExpression(a,{operator:"&&"})||!Q.isBinaryExpression(a.left,{operator:"==="})||!Q.isUnaryExpression(a.left.left,{operator:"typeof"})||!Q.isIdentifier(a.left.left.argument,{name:r.name})||!Q.isStringLiteral(a.left.right,{value:"string"})||!Q.isUnaryExpression(c,{operator:"!"})||!Q.isBinaryExpression(c.argument,{operator:"in"})||!Q.isIdentifier(c.argument.left,{name:r.name})||!Q.isIdentifier(c.argument.right,{name:n.name})||!Q.isReturnStatement(l)||!Q.isIfStatement(i)||i.alternate||!Q.isCallExpression(u)||!Q.isMemberExpression(u.callee)||!Q.isIdentifier(u.callee.object,{name:"Reflect"})||!Q.isIdentifier(u.callee.property,{name:"get"})||u.arguments.length!==3||!Q.isIdentifier(u.arguments[0],{name:n.name})||!Q.isIdentifier(u.arguments[1],{name:r.name})||!Q.isIdentifier(u.arguments[2],{name:o.name})?null:e.arguments[0].name}function bD(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()||!Q.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 FS(e,t){let n=bD(e.path);if(!n)return null;let r=ti(e,t);return r?{...n,...r}:null}function LS(e,t,n,r){return e.importedFrom===t?r?e.exportName===r:!0:e.sourceFile===t&&e.tag===n}function Op(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 Fp(e,t){for(let n of e.program.body){if(t==="default"&&Q.isExportDefaultDeclaration(n))return Q.isExpression(n.declaration)?{kind:"default-expression",expression:n.declaration}:(Q.isFunctionDeclaration(n.declaration)||Q.isClassDeclaration(n.declaration))&&n.declaration.id?{kind:"default-binding",name:n.declaration.id.name}:null;if(Q.isExportNamedDeclaration(n)){if(n.declaration){if(Q.isVariableDeclaration(n.declaration)){for(let r of n.declaration.declarations)if(Q.isIdentifier(r.id)&&r.id.name===t)return{kind:"local-binding",name:r.id.name}}if((Q.isFunctionDeclaration(n.declaration)||Q.isClassDeclaration(n.declaration))&&n.declaration.id&&n.declaration.id.name===t)return{kind:"local-binding",name:t}}for(let r of n.specifiers)if((Q.isIdentifier(r.exported)?r.exported.name:r.exported.value)===t&&Q.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 DS(e){let{resolveExternalExpression:t,resolveCollectionCallTarget:n,evaluateStaticExpression:r,resolveSourceInfoProvenance:o,buildExpressionSourceInfo:i}=e;async function s(p){let{currentFile:y,binding:b,readFile:E,exists:x,fileCache:S,visited:v}=p,N=`${y}::${b.kind}::${b.identifier.name}`;if(v.has(N))return null;v.add(N);try{let R=await a({currentFile:y,binding:b,readFile:E,exists:x,fileCache:S,visited:v});if(R)return R;if(b.path.isImportSpecifier()||b.path.isImportDefaultSpecifier())return await g({currentFile:y,binding:b,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,fileCache:S,visited:v});if(b.kind==="param")return null;if(b.path.isVariableDeclarator()){let A=b.path.node.init;if(!A||!Q.isExpression(A))return null;let C=yD(A);if(C&&!b.path.scope.getBinding("Proxy")&&!b.path.scope.getBinding("Reflect")){let D=b.path.scope.getBinding(C),U=D?await s({...p,binding:D}):null;if(U?.kind==="static"&&U.value!==null&&!Array.isArray(U.value)&&typeof U.value=="object")return U}let w=b.path.get("init");if(w&&!Array.isArray(w)&&w.isExpression()){let D=await t({currentFile:y,expressionPath:w,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});if(D)return D;if(w.isCallExpression()){let U=await n({currentFile:y,callPath:w,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});if(U)return U}}let M=await r(A,b.path.scope,y,E,x,S,v);return M===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:M,sourceKind:"binding"}}if(b.path.isIdentifier()&&b.path.parentPath?.isExportDefaultDeclaration()){let A=b.path.parentPath.node.declaration;if(!Q.isExpression(A))return null;let C=await r(A,b.path.scope,y,E,x,S,v);return C===void 0?null:{kind:"static",file:y,root:{kind:"binding",name:b.identifier.name},value:C,sourceKind:"binding"}}return null}finally{v.delete(N)}}async function a(p){let{currentFile:y,binding:b,readFile:E,exists:x,fileCache:S,visited:v}=p;if(!b.path.isVariableDeclarator()||!b.path.get("id").isArrayPattern())return null;let N=b.path,R=N.node.init;if(!R||!Q.isCallExpression(R))return null;let A=hD(R);if(!A||!Q.isArrayPattern(N.node.id)||N.node.id.elements.findIndex(U=>Q.isIdentifier(U)&&U.name===b.identifier.name)!==0)return null;let w=A==="useReducer"?1:0,M=R.arguments[w];if(!M||!Q.isExpression(M))return null;let D=await r(M,N.scope,y,E,x,S,v);return D===void 0?null:{kind:"static",file:y,root:{kind:"hook-state",name:b.identifier.name,hook:A},value:D,sourceKind:"binding"}}async function c(p){let y=p.expressionPath.scope.getBinding(p.sourceInfo.base);if(!y||!y.constant||y.kind!=="param"||!p.graph)return null;let b=FS(y,p.sourceInfo);if(!b)return null;let E=[...p.graph.elements.values()].filter(S=>LS(S,p.currentFile,b.componentName,b.exportName));if(!E.length)return null;let x=[];for(let S of E){if(S.sourceFile!==E[0].sourceFile||S.componentName!==E[0].componentName||S.attributeSpreads?.length)return null;let v=await Dn(S.sourceFile,p.readFile,p.fileCache),N=v.ast?xl(v.ast,S.sourceRange):null;if(!N)return null;let R=N.parentPath;for(;R&&!R.isFunction();){if(R.isJSXElement()){let B=R.node.openingElement.name;if(!Q.isJSXIdentifier(B)||!/^[a-z]/.test(B.name))return null}else if(!R.isJSXFragment()&&!R.isReturnStatement()&&!R.isBlockStatement())return null;R=R.parentPath}if(!R)return null;let A=N.get("openingElement").get("attributes").filter(B=>B.isJSXAttribute()&&Q.isJSXIdentifier(B.node.name,{name:b.propName}));if(A.length!==1)return null;let C=A[0];if(!C?.isJSXAttribute())return null;let w=C.get("value"),M=w.isJSXExpressionContainer()?w.get("expression"):w;if(!M.isExpression())return null;let D=await r(M.node,M.scope,S.sourceFile,p.readFile,p.exists,p.fileCache,p.visited),U=D===void 0?void 0:Ut(D,b.remainingPath);if(U===void 0)return null;x.push(U)}return x}async function l(p){let y=FS(p.binding,p.sourceInfo);if(!y||!p.graph)return null;let b=["component-prop",p.currentFile,p.binding.identifier.start??p.binding.path.node.start??-1,y.componentName,y.propName].join(":");if(p.visited.has(b))return null;p.visited.add(b);try{return await u(p,y,p.graph)}finally{p.visited.delete(b)}}async function u(p,y,b){let E=[...b.elements.values()].filter(C=>LS(C,p.currentFile,y.componentName,y.exportName));if(E.length!==1)return null;let x=E[0],S=x.attributes?.find(C=>C.name===y.propName);if(S&&!S.source){let C=await d({caller:x,propName:y.propName,remainingPath:y.remainingPath,readFile:p.readFile,fileCache:p.fileCache});if(C)return Op(C,{componentName:y.componentName,propName:y.propName,file:x.sourceFile})}if(!S?.source){let C=await f({caller:x,propName:y.propName,remainingPath:y.remainingPath,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});if(C)return Op(C,{componentName:y.componentName,propName:y.propName,file:x.sourceFile});let w=Lx(p.binding,y.componentName,y.propName);if(!w||w.propName!==y.propName)return null;let M=await r(w.expressionPath.node,w.expressionPath.scope,p.currentFile,p.readFile,p.exists,p.fileCache,p.visited);if(M===void 0)return null;let D=y.remainingPath;return D.length>0&&Ut(M,D)===void 0?null:{kind:"value",file:p.currentFile,root:{kind:"binding",name:y.propName},path:D,sourceKind:"binding",semanticKind:"component-prop",displayExpression:w.displayPath,chainPrefix:[{kind:"component-prop",file:p.currentFile,displayName:w.displayPath,canEditHere:!0}],editMode:"upstream",diagnostics:[]}}let v=await Dn(x.sourceFile,p.readFile,p.fileCache);if(!v.ast)return null;let N=OS(v.ast,v.source,S.source.expression,S.sourceRange)??Ds(v.ast,v.source,S.source.expression);if(!N)return null;let R={...S.source,expression:hi(S.source.expression,y.remainingPath),path:[...S.source.path,...y.remainingPath]},A=await o({currentFile:x.sourceFile,expressionPath:N,sourceInfo:R,readFile:p.readFile,exists:p.exists,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:p.fileCache,visited:p.visited});return A?Op(A.kind==="external"?A:{...A,displayExpression:R.expression},{componentName:y.componentName,propName:y.propName,file:x.sourceFile}):null}async function d(p){let y=await Dn(p.caller.sourceFile,p.readFile,p.fileCache);if(!y.ast)return null;let b=xl(y.ast,p.caller.sourceRange);if(!b)return null;let E=b.get("openingElement").get("attributes").find(N=>N.isJSXAttribute()&&N.node.name.type==="JSXIdentifier"&&N.node.name.name===p.propName);if(!E?.isJSXAttribute())return null;let x=E.get("value"),S=x.isStringLiteral()?x:x.isJSXExpressionContainer()?x.get("expression"):null;if(!S?.isExpression())return null;let v=Ls(S.node);return v?{kind:"value",file:p.caller.sourceFile,root:{kind:"expression",sourceRange:v},path:p.remainingPath,sourceKind:"binding",semanticKind:"component-prop",displayExpression:p.propName,editMode:"upstream",diagnostics:[]}:null}async function f(p){let y=await Dn(p.caller.sourceFile,p.readFile,p.fileCache);if(!y.ast)return null;let b=xl(y.ast,p.caller.sourceRange);if(!b)return null;let E=b.get("openingElement");for(let x of E.get("attributes")){if(!x.isJSXSpreadAttribute())continue;let S=x.get("argument");if(!S.isExpression())continue;let v=await i({expression:S.node,scope:S.scope,source:y.source,currentFile:p.caller.sourceFile,readFile:p.readFile,exists:p.exists,fileCache:p.fileCache,visited:p.visited});if(!v)continue;let N=[{kind:"property",name:p.propName},...p.remainingPath],R={...v,expression:hi(v.expression,N),path:[...v.path,...N]},A=await o({currentFile:p.caller.sourceFile,expressionPath:S,sourceInfo:R,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(A)return A.kind==="external"?A:{...A,displayExpression:R.expression}}return null}async function g(p){let{currentFile:y,binding:b,readFile:E,exists:x,fileCache:S,visited:v}=p,N=b.path.parentPath;if(!N||!N.isImportDeclaration())return null;let R=N.node.source.value;if(typeof R!="string")return null;let A=await no(y,R,x);if(!A)return null;if(b.path.isImportDefaultSpecifier()){let B=await Dn(A,E,S),G=B.ast?Fp(B.ast,"default"):null,K=await m({file:A,exportName:"default",readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});return!K||K.kind!=="static"?null:{kind:"static",file:G?.kind==="default-expression"?K.file:A,root:G?.kind==="default-expression"?K.root:{kind:"default-export"},value:K.value,sourceKind:"imported-binding"}}if(!b.path.isImportSpecifier())return null;let C=b.path.node.imported,w=Q.isIdentifier(C)?C.name:C.value,M=await Dn(A,E,S),D=M.ast?Fp(M.ast,w):null,U=await m({file:A,exportName:w,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v});return U?U.kind==="external"?U:{kind:"static",file:D?.kind==="re-export"?U.file:A,root:D?.kind==="re-export"||U.root.kind==="binding"&&U.root.name!==D?.name?U.root:{kind:"named-export",name:w},value:U.value,sourceKind:"imported-binding"}:null}async function m(p){let{file:y,exportName:b,readFile:E,exists:x,fileCache:S,visited:v}=p,N=`export::${y}::${b}`;if(!v.has(N)){v.add(N);try{let R=await Dn(y,E,S);if(!R.ast)return;let A=Fp(R.ast,b);if(!A)return;if(A.kind==="default-expression"){let D=A.expression;if(!D||!Q.isIdentifier(D))return;let U=Ms(R.ast).getBinding(D.name);return U?await s({currentFile:y,binding:U,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}if(A.kind==="re-export"){if(!A.source||!A.name)return;let D=await no(y,A.source,x);return D?m({...p,file:D,exportName:A.name}):void 0}let C=A.name;if(!C)return;let w=Ms(R.ast).getBinding(C);return w?await s({currentFile:y,binding:w,readFile:E,exists:x,graph:p.graph,externalSourceResolvers:p.externalSourceResolvers,externalAdapters:p.externalAdapters,functionCallContracts:p.functionCallContracts,fileCache:S,visited:v})??void 0:void 0}finally{v.delete(N)}}}return{resolveExportValue:m,resolveComponentPropBinding:l,resolveComponentPropValues:c,resolveBindingTarget:s}}import*as le from"@babel/types";function Dp(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=Fn(o,t);if(!i)return null;let s=r.parentPath;return!s||!s.isCallExpression()||!xD(s,r)?null:{callPath:s,basePath:i}}function xD(e,t){let n=e.node.callee;return!le.isMemberExpression(n)||!le.isIdentifier(n.property)||n.property.name!=="map"?!1:e.node.arguments.some(r=>r===t.node)}function $S(e,t){let n=e.get("callee");if(!n.isMemberExpression())return null;let r=n.get("object");return Array.isArray(r)||!r.isExpression()?null:Bc(r,t)}function MS(e,t){return e?le.isNumericLiteral(e)&&Number.isInteger(e.value)?e.value:null:t}function BS(e,t,n,r,o){let i=le.isExpression(e.body)?e.body:e.body.body.find(a=>le.isReturnStatement(a))?.argument;if(!i||!le.isExpression(i))return;let s=Lp(i,t,n,r,o);return typeof s=="number"?s:void 0}function Lp(e,t,n,r,o){if(le.isNumericLiteral(e)||le.isStringLiteral(e)||le.isBooleanLiteral(e))return e.value;if(le.isIdentifier(e))return e.name===t?r:e.name===n?o:void 0;if(le.isMemberExpression(e)){let i=hl(e,t);if(i)return Ut(r,i);let s=hl(e,n);return s?Ut(o,s):void 0}if(le.isBinaryExpression(e)&&e.operator==="-"){let i=le.isExpression(e.left)?Lp(e.left,t,n,r,o):void 0,s=le.isExpression(e.right)?Lp(e.right,t,n,r,o):void 0;return typeof i=="number"&&typeof s=="number"?i-s:void 0}}function ED(e){if(le.isExpression(e.body))return e.body;for(let t of e.body.body)if(le.isReturnStatement(t)&&t.argument&&le.isExpression(t.argument))return t.argument;return null}function SD(e,t,n){let r=Co(e,t,n);return typeof r=="boolean"?r:void 0}function Co(e,t,n){if(le.isStringLiteral(e)||le.isNumericLiteral(e)||le.isBooleanLiteral(e))return e.value;if(le.isNullLiteral(e))return null;if(le.isIdentifier(e))return e.name===t?n:void 0;if(le.isMemberExpression(e)){let r=hl(e,t);return r?Ut(n,r):void 0}if(le.isUnaryExpression(e)&&e.operator==="!"){let r=Co(e.argument,t,n);return r===void 0?void 0:!r}if(le.isLogicalExpression(e)){let r=Co(e.left,t,n);if(r===void 0)return;if(e.operator==="&&")return r&&Co(e.right,t,n);if(e.operator==="||")return r||Co(e.right,t,n)}if(le.isBinaryExpression(e)){let r=le.isExpression(e.left)?Co(e.left,t,n):void 0,o=le.isExpression(e.right)?Co(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 US(e){let t=[],n=e;for(;le.isMemberExpression(n)||le.isOptionalMemberExpression(n);){let r=n.property;if(n.computed)if(le.isNumericLiteral(r))t.unshift({kind:"index",index:r.value});else if(le.isStringLiteral(r))t.unshift({kind:"property",name:r.value});else if(le.isExpression(r))t.unshift({kind:"dynamic",expression:r});else return null;else if(le.isIdentifier(r))t.unshift({kind:"property",name:r.name});else return null;n=n.object}return le.isIdentifier(n)?{base:n.name,segments:t}:null}function VS(e){return e.some(t=>t.kind==="dynamic")}function jS(e){return typeof e=="string"?{kind:"property",name:e}:Number.isInteger(e)?{kind:"index",index:e}:null}function KS(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 vD(e,t){let n=[],r=[];for(let o of t){let i=Ut(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 JS(e){let{resolveBindingTarget:t,evaluateStaticExpression:n,buildExpressionSourceInfo:r,resolveSourceInfoProvenance:o,resolveComponentPropValues:i}=e;async function s(m){let{currentFile:p,callPath:y,readFile:b,exists:E,fileCache:x,visited:S}=m,v=y.node.callee;if(!le.isMemberExpression(v)||!le.isIdentifier(v.property)||v.property.name!=="map")return null;let N=y.get("callee");if(!N.isMemberExpression())return null;let R=N.get("object");if(Array.isArray(R)||!R.isExpression())return null;let A=await a({currentFile:p,expressionPath:R,readFile:b,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:x,visited:S});return!A||!Array.isArray(A.value)||A.value.length===0?null:A}async function a(m){let{currentFile:p,expressionPath:y,readFile:b,exists:E,fileCache:x,visited:S}=m;if(y.isIdentifier()){let v=y.scope.getBinding(y.node.name);if(!v)return null;let N=await t({currentFile:p,binding:v,readFile:b,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:x,visited:S});return N?.kind==="static"?N:null}if(y.isCallExpression())return l({currentFile:p,callPath:y,readFile:b,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:x,visited:S});if(y.isTSAsExpression()||y.isTSSatisfiesExpression()||y.isTSNonNullExpression()){let v=y.get("expression");if(!Array.isArray(v)&&v.isExpression())return a({...m,expressionPath:v})}if(y.isArrayExpression()){let v=Ls(y.node);if(!v)return null;let N=await n(y.node,y.scope,p,b,E,x,S);return Array.isArray(N)?{kind:"static",file:p,root:{kind:"expression",sourceRange:v},value:N,sourceKind:"binding"}:null}if(y.isMemberExpression()){let v=await r({expression:y.node,scope:y.scope,currentFile:p,readFile:b,exists:E,fileCache:x,visited:S});if(!v)return null;let N=await o({currentFile:p,expressionPath:y,sourceInfo:v,readFile:b,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:x,visited:S});if(!N||N.kind==="external")return null;let R=await c({currentFile:p,expressionPath:y,provenance:N,readFile:b,exists:E,graph:m.graph,externalSourceResolvers:m.externalSourceResolvers,externalAdapters:m.externalAdapters,functionCallContracts:m.functionCallContracts,fileCache:x,visited:S});if(!R||R.kind!=="static")return null;if(N.collectionPathMap?.length){let C=vD(R.value,N.collectionPathMap);if(C)return{kind:"static",file:N.file,root:N.root,value:C.value,sourceKind:N.sourceKind,collectionPathMap:C.collectionPathMap}}let A=Ut(R.value,N.path);return Array.isArray(A)?{kind:"static",file:N.file,root:N.root,value:A,sourceKind:N.sourceKind,pathPrefix:N.path,collectionIndexMap:N.collectionIndexMap,collectionPathMap:N.collectionPathMap}:null}return null}async function c(m){let{provenance:p}=m;if(p.root.kind==="binding"){let x=m.expressionPath.scope.getBinding(p.root.name);if(!x&&p.file!==m.currentFile){let S=await Dn(p.file,m.readFile,m.fileCache);x=S.ast?Ms(S.ast).getBinding(p.root.name):void 0}return x?await t({currentFile:p.file,binding:x,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(p.root.kind!=="expression")return null;let y=await Dn(p.file,m.readFile,m.fileCache);if(!y.ast)return null;let b=TS(y.ast,p.root.sourceRange);if(!b)return null;let E=await n(b.node,b.scope,p.file,m.readFile,m.exists,m.fileCache,m.visited);return E===void 0?null:{kind:"static",file:p.file,root:p.root,value:E,sourceKind:p.sourceKind}}async function l(m){return await u(m)??await d(m)??await f(m)}async function u(m){let{callPath:p}=m,y=p.node.callee;if(!le.isMemberExpression(y)||!le.isIdentifier(y.property)||y.property.name!=="filter")return null;let b=p.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let x=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(!x||!Array.isArray(x.value))return null;let[S]=p.node.arguments;if(!le.isArrowFunctionExpression(S)&&!le.isFunctionExpression(S))return null;let v=S.params[0];if(!le.isIdentifier(v))return null;let N=ED(S);if(!N)return null;let R=[],A=[],C=[];for(let[w,M]of x.value.entries()){let D=SD(N,v.name,M);if(typeof D!="boolean")return null;if(D){R.push(M),A.push(x.collectionIndexMap?.[w]??w);let U=x.collectionPathMap?.[w];U&&C.push(U)}}return{...x,value:R,pathPrefix:x.pathPrefix,collectionIndexMap:A,...C.length>0?{collectionPathMap:C}:{}}}async function d(m){let{callPath:p}=m,y=p.node.callee;if(!le.isMemberExpression(y)||!le.isIdentifier(y.property)||y.property.name!=="slice")return null;let b=p.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let x=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(!x||!Array.isArray(x.value))return null;let[S,v]=p.node.arguments,N=MS(S,0),R=MS(v,x.value.length);if(N===null||R===null)return null;let A=Math.max(0,N<0?x.value.length+N:N),C=Math.max(0,R<0?x.value.length+R:R),w=x.value.map((D,U)=>x.collectionIndexMap?.[U]??U).slice(A,C),M=x.collectionPathMap?.slice(A,C);return{...x,value:x.value.slice(A,C),pathPrefix:x.pathPrefix,collectionIndexMap:w,...M?{collectionPathMap:M}:{}}}async function f(m){let{callPath:p}=m,y=p.node.callee;if(!le.isMemberExpression(y)||!le.isIdentifier(y.property)||y.property.name!=="sort"&&y.property.name!=="toSorted")return null;let b=p.get("callee");if(!b.isMemberExpression())return null;let E=b.get("object");if(Array.isArray(E)||!E.isExpression())return null;let x=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(!x||!Array.isArray(x.value))return null;let[S]=p.node.arguments;if(!le.isArrowFunctionExpression(S)&&!le.isFunctionExpression(S))return null;let[v,N]=S.params;if(!le.isIdentifier(v)||!le.isIdentifier(N))return null;let R=x.value.map((C,w)=>({value:C,sourceIndex:x.collectionIndexMap?.[w]??w,originalIndex:w})),A=[...R];for(let C of R)for(let w of R)if(BS(S,v.name,N.name,C.value,w.value)===void 0)return null;return A.sort((C,w)=>{let M=BS(S,v.name,N.name,C.value,w.value)??0;return M===0?C.originalIndex-w.originalIndex:M}),{...x,value:A.map(C=>C.value),pathPrefix:x.pathPrefix,collectionIndexMap:A.map(C=>C.sourceIndex),...x.collectionPathMap?{collectionPathMap:A.map(C=>x.collectionPathMap?.[C.originalIndex]).filter(C=>!!C)}:{}}}async function g(m){let p=null,y=!1,b,E=[];for(let S of m.segments){if(S.kind!=="dynamic")continue;let v=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(!v)return null;let N=Dp(m.expressionPath,v.base),R;if(N){y=!0;let A=await s({currentFile:m.currentFile,callPath:N.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(!A||!Array.isArray(A.value))return null;R=A.value.map((C,w)=>{let M=Ut(A.value,[{kind:"index",index:w},...N.basePath,...v.path]);return jS(M)}),b??=A.collectionIndexMap}else{let A=await i({...m,sourceInfo:v});if(!A)return null;R=A.map(jS)}if(R.some(A=>A===null)||p!==null&&p!==R.length)return null;p=R.length,E.push(R)}if(p===null||p===0)return null;let x=[];for(let S=0;S<p;S+=1){let v=[...m.rootPath],N=0;for(let R of m.segments){if(R.kind==="dynamic"){let A=E[N]?.[S];if(!A)return null;v.push(A),N+=1;continue}v.push({...R})}x.push(v)}return{sourceKind:y||p>1?"repeat-template":"binding",...b?{collectionIndexMap:b}:{},collectionPathMap:x}}return{resolveRepeatCollectionTarget:s,resolveCollectionCallTarget:l,resolveDynamicMemberPathMap:g}}var{normalizeExpressionWithScope:ID,evaluateStaticExpression:El}=kS({resolveBindingTarget:e=>Sl(e)}),{resolveRepeatCollectionTarget:kD,resolveCollectionCallTarget:_D,resolveDynamicMemberPathMap:RD}=JS({resolveBindingTarget:e=>Sl(e),evaluateStaticExpression:El,buildExpressionSourceInfo:tr,resolveSourceInfoProvenance:Cn,resolveComponentPropValues:e=>ND(e)}),{resolveExportValue:CD,resolveComponentPropBinding:PD,resolveComponentPropValues:ND,resolveBindingTarget:Sl}=DS({resolveExternalExpression:Kp,resolveCollectionCallTarget:_D,evaluateStaticExpression:El,resolveSourceInfoProvenance:Cn,buildExpressionSourceInfo:tr});function QS(e){return new Map([...e].map(t=>[t.file,{source:t.source,ast:t.ast}]))}var XS=new WeakMap;function AD(e){let t=XS.get(e);return t||(t=new WeakMap,XS.set(e,t)),t}function zS(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 ev(e){let{file:t,source:n,segment:r,readFile:o,exists:i}=e,s=e.fileCache??new Map,a=yl(s,t,n);if(!a)return null;let c=bl(a,r.sourceRange);if(!c)return null;let l=await tr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:o,exists:i,fileCache:s,visited:new Set});if(!l){let f=await Hp({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?jp(f,gi(c.node,n)):null}let u=new Set,d=await qD({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?jp(d,l.expression):null}async function yi(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=yl(i,t,n);if(!s)return null;let a=e.sourceRange?bl(s,e.sourceRange):e.expression!==void 0?Ds(s,n,e.expression):null;if(!a)return null;let c=vl(a);if(!c.isIdentifier()&&!c.isMemberExpression())return null;let l=new Set,u=await tr({expression:c.node,scope:c.scope,source:n,currentFile:t,readFile:r,exists:o,fileCache:i,visited:l}),d=u?await Cn({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 cv({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 jp(d,e.expression??gi(c.node,n))}async function Vp(e){let{file:t,source:n,readFile:r,exists:o}=e,i=e.fileCache??new Map,s=yl(i,t,n);if(!s)return fn("unsupported-expression","Unable to parse source for provenance resolution");let a=new Set;return e.target.kind==="text-segment"?TD({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}):wD({file:t,source:n,ast:s,candidate:e.target.candidate,readFile:r,exists:o,graph:e.graph,fileCache:i,visited:a})}async function tr(e){if(he.isIdentifier(e.expression))return{kind:"identifier",expression:e.expression.name,base:e.expression.name,path:[]};if(!he.isMemberExpression(e.expression))return null;let t=await ID(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:gi(e.expression,e.source),base:t.base,path:t.path}:null}function jp(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 TD(e){let{file:t,source:n,ast:r,segment:o,readFile:i,exists:s,fileCache:a,visited:c}=e,l=bl(r,o.sourceRange),u=l?await tr({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 HS(t,o.value);let f=await Hp({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"?qS(t,f):Up(t,gi(l.node,n),f):OD({expression:l.node,scope:l.scope,currentFile:t,source:n,readFile:i,exists:s,fileCache:a,visited:c,functionCallContracts:e.functionCallContracts})}if(!l)return fn("unsupported-expression","Unable to locate text expression for provenance resolution");let d=await Cn({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=$p(l.node);if(f)return fn(f.code,f.message);let g=l.scope.getBinding(u.base);if(g?.path.isVariableDeclarator()){let m=$p(g.path.node.init);if(m)return fn(m.code,m.message)}return g?.path.isVariableDeclarator()&&he.isCallExpression(g.path.node.init)?FD("unsupported-expression",iv(g.path.node.init,e.functionCallContracts)):fn("unsupported-expression",`Unable to resolve provenance for expression "${u.expression}"`)}return d.kind==="external"?qS(t,d):Up(t,u.expression,d)}async function wD(e){let{file:t,source:n,ast:r,candidate:o,readFile:i,exists:s,fileCache:a,visited:c}=e;if(!o.conditionSource)return fn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let l=Ds(r,n,o.conditionExpression);if(!l)return fn("conditional-branch-unresolved",`Unable to locate conditional expression "${o.conditionExpression}"`);let u=await Cn({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 fn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);if(u.kind==="external")return fn("conditional-branch-unresolved",`Unable to resolve conditional branch source for "${o.conditionExpression}"`);let d=Up(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 HS(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 OD(e){let t=await nv(e);if(t.length===0)return fn("unsupported-expression",`Unsupported expression type: ${e.expression.type}`);if(LD(e.expression))return tv(t);if(ov(e.expression))return fn("unsupported-expression","i18n helpers require a static message id string");if(he.isMemberExpression(e.expression)&&e.expression.computed&&!he.isNumericLiteral(e.expression.property)&&!he.isStringLiteral(e.expression.property))return fn("dynamic-key","Computed member expressions are not supported for provenance resolution");let[n]=t;return fn(n.code,n.message)}function fn(e,t){return{finalSource:null,chain:[],confidence:"unknown",editMode:"unsupported",diagnostics:[{code:e,message:t}]}}function FD(e,t){return tv([{code:e,message:t}])}function tv(e){return{finalSource:null,chain:[],confidence:"partial",editMode:"readonly",diagnostics:e}}function LD(e){return he.isCallExpression(e)||he.isConditionalExpression(e)||he.isLogicalExpression(e)||he.isBinaryExpression(e)}function js(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 nv(e){let{expression:t,scope:n,currentFile:r,readFile:o,exists:i,fileCache:s,visited:a,functionCallContracts:c}=e,l=$p(t);if(l)return[l];if(he.isCallExpression(t))return[{code:"unsupported-expression",message:iv(t,c)}];if(he.isMemberExpression(t)&&t.computed){let u=t.property;if(!he.isNumericLiteral(u)&&!he.isStringLiteral(u)){if(!he.isExpression(u))return[{code:"dynamic-key",message:"Computed member expressions are not supported for provenance resolution"}];let f=await El(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 he.isBinaryExpression(t)?js([...await Mp(t.left,t.right,e),{code:"unsupported-expression",message:"Mixed expressions are recognized but remain readonly until a safer composition editing strategy is available"}]):he.isLogicalExpression(t)?js([...await Mp(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"}]):he.isConditionalExpression(t)?js([...await Mp(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 $p(e){return ov(e)?WS("i18n helpers require a static message id string"):$D(e)?WS("CMS helpers require static entry id and field path string arguments"):null}async function Mp(...e){let t=e[e.length-1],n=e.slice(0,-1),r=[];for(let o of n)r.push(...await nv({...t,expression:o}));return r}function DD(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:[MD(e.sourceType)]}}async function Kp(e){for(let n of JD){if(!GS(e.expressionPath,n.helperNames))continue;let r=await n.resolve(e);if(r)return ZS(YS(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 ZS(YS(r),e.externalAdapters)}return null}function MD(e){return{code:"missing-adapter",message:`No external adapter is registered for ${e}`}}function BD(e){return{code:"external-source-readonly",message:e}}function WS(e){return{code:"unsupported-expression",message:e}}function Jp(e){return!e||!he.isCallExpression(e)?null:he.isIdentifier(e.callee)?e.callee.name:he.isMemberExpression(e.callee)&&!e.callee.computed&&he.isIdentifier(e.callee.object)&&he.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=Jp(e.node);return n?t.includes(n):!1}function YS(e){return"match"in e?{match:e.match,editMode:e.editMode,diagnostics:js(e.diagnostics??[])}:{match:e,diagnostics:[]}}function ZS(e,t){let n=DD(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:js([...e.diagnostics,...e.editMode==="readonly"||n.editMode==="readonly"?n.diagnostics:[]])}}function jD(e){if(!e.isCallExpression())return null;let t=e.node.callee;if(!he.isIdentifier(t)||t.name!=="getCmsField")return null;let[n,r]=e.node.arguments;if(!n||!r||!he.isStringLiteral(n)||!he.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 $D(e){return!!e&&he.isCallExpression(e)&&he.isIdentifier(e.callee)&&e.callee.name==="getCmsField"&&(e.arguments.length<2||!he.isStringLiteral(e.arguments[0])||!he.isStringLiteral(e.arguments[1]))}function rv(e){if(!(!e||!he.isCallExpression(e))){if(he.isIdentifier(e.callee)&&e.callee.name==="t"){let[t]=e.arguments;return t&&he.isStringLiteral(t)?t.value:null}if(he.isMemberExpression(e.callee)&&!e.callee.computed&&he.isIdentifier(e.callee.object)&&e.callee.object.name==="intl"&&he.isIdentifier(e.callee.property)&&e.callee.property.name==="formatMessage"){let[t]=e.arguments;if(!t||!he.isObjectExpression(t))return null;for(let n of t.properties)if(he.isObjectProperty(n)&&!n.computed&&(he.isIdentifier(n.key)&&n.key.name==="id"||he.isStringLiteral(n.key)&&n.key.value==="id")&&he.isStringLiteral(n.value))return n.value.value;return null}}}function ov(e){return rv(e)===null}async function UD(e,t,n){let r=new Set,o=Bs.posix.dirname(e);for(;r.add(o),!(o==="."||o==="/");){let i=Bs.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"]:[Bs.posix.join(i,"locales"),Bs.posix.join(i,"messages")];for(let a of s){let c=Bs.posix.join(a,`${t}.json`);if(await n(c))return c}}return null}async function VD(e){let t=rv(e.expressionPath.node);if(typeof t!="string"||t.length===0)return null;let n="en",r=await UD(e.currentFile,n,e.exists);return r?{sourceType:"i18n-message",sourceId:`${n}:${t}`,file:r,displayPath:t}:null}async function KD(e){if(!e.expressionPath.isCallExpression())return null;let t=e.expressionPath.node.callee;if(!he.isIdentifier(t)||t.name!=="apiField")return null;let[n,r]=e.expressionPath.node.arguments;if(!n||!he.isExpression(n))return null;let o=await El(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:[BD("API mapping transforms must stay readonly until a reversible mapping strategy is registered")]}:i}var JD=[{helperNames:["getCmsField"],resolve:({expressionPath:e})=>jD(e)},{helperNames:["apiField"],resolve:e=>KD(e)},{helperNames:["t","intl.formatMessage"],resolve:({currentFile:e,expressionPath:t,exists:n})=>VD({currentFile:e,expressionPath:t,exists:n})}];function Xp(e){return{...e,editMode:"readonly",diagnostics:[{code:"unsupported-expression",message:"Derived display values are readonly because no identity-preserving write target exists"}]}}function qS(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 Up(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=ZD(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 XD=[{helperName:"formatPrice",purity:"pure",sourceArgIndex:0},{helperName:"formatDate",purity:"pure",sourceArgIndex:0},{helperName:"pickLabel",purity:"pure",sourceArgIndex:0}];function zp(e,t){let n=[...XD,...t??[]];for(let r=n.length-1;r>=0;r-=1){let o=n[r];if(o?.helperName===e)return o}return null}function iv(e,t){let n=e.callee;return he.isIdentifier(n)&&zp(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 Hp(e){let t=await Kp(e);if(t)return t;let n=await sv({...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 tr({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 Cn({...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 GD(e)}async function sv(e){let t=await Mn({...e,allowComposed:!1});if(t?.kind!=="source")return null;let n=vl(e.expressionPath);return n.isIdentifier()||n.isMemberExpression()?t.provenance:Xp(t.provenance)}async function Mn(e){let t=vl(e.expressionPath),n=WD(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 tr({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 Cn({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 tr({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 Cn({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 Mn({...e,expressionPath:r,allowComposed:!0}),a=await Mn({...e,expressionPath:o,allowComposed:!1}),c=await Mn({...e,expressionPath:i,allowComposed:!1});return Bp(s,a,c)}if(t.isCallExpression())return zD({...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 Mn({...e,expressionPath:r,allowComposed:!0}),s=await Mn({...e,expressionPath:o,allowComposed:!0});return Bp(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 Mn({...e,expressionPath:r,allowComposed:!0}),s=await Mn({...e,expressionPath:o,allowComposed:!0});return Bp(i,s)}if(t.isUnaryExpression()){let r=t.get("argument");return Array.isArray(r)||!r.isExpression()?null:Mn({...e,expressionPath:r,allowComposed:!0})}return null}finally{n&&e.visited.delete(n)}}function vl(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 zD(e){let t=Jp(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:Mn({...e,expressionPath:r,allowComposed:!1})}let n=e.expressionPath.get("callee");if(n.isMemberExpression()&&!n.node.computed){let r=n.node.property;if(he.isIdentifier(r)&&(r.name==="toFixed"||r.name==="toString")){let o=n.get("object");return Array.isArray(o)||!o.isExpression()?null:Mn({...e,expressionPath:o,allowComposed:!1})}}return null}function Bp(...e){let t=null;for(let n of e){if(!n)return null;if(n.kind!=="none"){if(!t){t=n.provenance;continue}if(!HD(t,n.provenance))return null}}return t?{kind:"source",provenance:t}:{kind:"none"}}function HD(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 WD(e,t){return t.start==null||t.end==null?null:`safe-derived:${e}:${t.start}:${t.end}`}async function GD(e){if(!e.expressionPath.isCallExpression())return null;let t=Jp(e.expressionPath.node);if(!t)return null;let n=zp(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 av({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?Xp(i):null}async function av(e){let t=await Kp({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 tr({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 Cn({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 Hp({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 YD(e){if(!e.binding.path.isVariableDeclarator())return null;let t=e.binding.path.node.init;if(!t||!he.isCallExpression(t))return null;let n=t.callee;if(!he.isIdentifier(n))return null;let r=zp(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 av({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?Xp(a):null}function ZD(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=hi(t,e.path);return{sourceId:o,displayPath:o}}async function qD(e){let t=e.segment.source;return t?Cn({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 Cn(e){let t=e.sourceInfo,n=Dp(e.expressionPath,t.base);if(n){let l=await kD({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 p=$S(n.callPath,[...n.basePath,...t.path]);return vs(p)?zS(e.currentFile,p.sourceId,p.displayPath):null}let u=KS(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 Ut(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 no(e.currentFile,u.node.source.value,e.exists);if(!d)return null;let f=await CD({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 Ut(f.value,g)===void 0?null:{kind:"value",file:f.file,root:f.root,path:g,sourceKind:"imported-binding",collectionIndexMap:f.collectionIndexMap}}let o=Ox(r);if(o){let l=o.expressionPath,u=await tr({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 Cn({...e,expressionPath:l,sourceInfo:{...u,expression:hi(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 cv({...e,expressionPath:vl(l),memberSuffix:t.path});if(f?.kind==="value")return f}finally{e.visited.delete(d)}}if(t.path.length===0){let d=await sv({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 PD({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 YD({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=Dc(r,t.path,AD(e.fileCache));if(vs(s))return zS(e.currentFile,s.sourceId,s.displayPath);let a=await Sl({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:Ut(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 cv(e){let t=US(e.expressionPath.node);if(!t||!VS(t.segments))return null;let n=await Cn({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 RD({...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 Sl({...e,binding:i}):null;if(s?.kind!=="static"||o.some(a=>Ut(s.value,a.slice(n.path.length))===void 0))return null}return{...n,path:o[0]??n.path,sourceKind:r.sourceKind,displayExpression:gi(e.expressionPath.node,e.fileCache.get(e.currentFile)?.source),...r.collectionIndexMap?{collectionIndexMap:r.collectionIndexMap}:{},collectionPathMap:o}}async function lv(e){let t=QD(e.propertyName);if(t.owner==="blocked")return Hr(t.owner,t.diagnostic);if(t.owner==="class-name-source"||t.owner==="style")return Hr(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 Hr("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 tM(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 Hr("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}:Hr("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?Hr("generic",{code:"remove-exposes-spread",message:`Removing '${e.propertyName}' would expose an earlier spread source`}):eM(e,s.attribute)}async function eM(e,t){if(t.resolution&&t.resolution.status!=="resolved"&&!t.source){let r=await yi({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}}:Hr("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 yi({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"?Hr("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 tM(e,t){let n=t.source?.expression;if(!n)return;let r=await yi({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:nM(r,e.propertyName)}}function nM(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 Hr(e,t){return{status:"blocked",owner:e,...t?{diagnostic:t}:{}}}function uv(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(Po(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=>sM(a,r.componentName)),s=i.length===1?i[0].identity.key:null;return o.keys.set(r.componentName,s),s};return r=>rM({...r,graph:e},n)}function rM(e,t){let{key:n,element:r,graph:o,provenances:i}=e,s=iM(n,r,o,t),a=s?.tag??(Po(r.tag)?r.tag:r.componentName),c=s?.identity.key??t(r,o)??n,l=cM(s),u=lM(n,r,o,i,s),d=oM(n,r,o,i,c);return{componentName:a,instanceKey:c,templateOwner:aM(s??r,a),...l.length>0?{variantKeys:l}:{},...u.length>0?{slotKeys:u}:{},editableStrategy:d,impactScope:uM(d),alternativeStrategies:dM(d)}}function oM(e,t,n,r,o){for(let i of r.values())if(i?.editMode==="upstream")return"upstream";return Wp(e,n)?"instance":!Po(t.tag)&&t.sourceFile!==n.routeId&&o!==e?"template":"instance"}function iM(e,t,n,r){if(Po(t.tag))return t;let o=Wp(e,n);if(o)return o;let i=r(t,n);return i?n.elements.get(i)??null:null}function sM(e,t){return e.exportName===t||e.tag===t||e.exportName==="default"}function aM(e,t){return Po(e.tag)&&e.importedFrom?`${e.importedFrom}#${t}`:`${e.sourceFile}#${t}`}function cM(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 lM(e,t,n,r,o){let i=new Set,s=Wp(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&&Po(t.tag)&&t.childKeys.length>0&&i.add("children"),[...i]}function Wp(e,t){let n=t.elements.get(e)?.parentKey??null;for(;n;){let r=t.elements.get(n);if(!r)break;if(Po(r.tag))return r;n=r.parentKey}return null}function Po(e){return/^[A-Z]/.test(e)}function uM(e){switch(e){case"template":return"component-template";case"upstream":return"upstream-source";default:return"current-instance"}}function dM(e){switch(e){case"template":return["instance"];case"upstream":return["template"];default:return["template"]}}function pv(e){let t=e.isRepeat??(e.graph?EM(e.element,e.graph):!1),n=e.propertyProvenance??new Map,r=e.repeatTargets??new Map,o=xM(e.element.attributes??[]),i=[...r.values()].some(u=>u.ok),s=o.map(u=>fM({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:SM(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 fM(e){let{attribute:t,provenance:n,repeatTarget:r}=e,o=e.selectionRef?.instanceIndex!==void 0&&r?.ok===!0?r:null,i=pM(t,n,e.isRepeat),s=["selection","template"].map(y=>({scope:y,result:Xc({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=mM(t,n,l,e.isRepeat),d=c?yM(c,e.element,t.name):void 0,f=s.filter(({result:y})=>y.ok).map(({scope:y})=>y),g=f.length>0?hM(n,o,e.element):"unsupported",m=o?"repeat-item":e.isRepeat?"repeat-template":"node",p=bM(t,n,r);if(f.length===0&&p.length===0){let y=s.find(({result:b})=>!b.ok)?.result;y&&!y.ok&&p.push({code:y.code,message:y.reason})}return{name:t.name,source:i,resolution:u,editMode:g,sourceScope:m,allowedWriteScopes:f,...d?{effectiveWriteTarget:d}:{},diagnostics:p}}function pM(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 mM(e,t,n,r){return n?dv(n.selectedResolution):t?.status==="blocked"?{status:"unresolved"}:r&&t?.status==="binding"?{status:"unresolved"}:dv(gM(e))}function gM(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 dv(e){return!e||e.status==="unresolved"?{status:"unresolved"}:e.status==="undefined"?{status:"undefined"}:{status:"resolved",value:e.value}}function hM(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 yM(e,t,n){return e.kind==="repeat-property"?{kind:"value-path",file:e.target.sourceFile,isProxy:e.target.sourceFile!==t.sourceFile,displayPath:fv({...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:fv(e.locator)}:{kind:"jsx-node",file:t.sourceFile,isProxy:!1,displayPath:t.componentName+" > "+n}}function bM(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 xM(e){let t=new Set;return e.filter(n=>t.has(n.name)?!1:(t.add(n.name),!0))}function EM(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 fv(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 SM(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 vM(e){return e==="api-field"||e==="cms-field"||e==="i18n-message"||e==="config-entry"}var IM=160;function mv(e,t,n,r={}){let o=Uo(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 gv(e,t,n,r,o,i,s,a,c,l,u){let d=Uo(t),f=t.elements.get(e),g=n.nodes.get(e),m=r.get(e);if(!f||!g||!m)throw new Error(`Node not found: ${e}`);let p=Ev(f.textSegments,s),y=Sv(e,t,f,m,p),b=p?CM(p):void 0,E=PM(i,p),x=f.textSegments.map(R=>({index:R.index,value:R.value,editable:vv(R,m,s?.get(R.index)??null),source:o.get(R.index)??null})),S=bv(f,t),v=f.childKeys.map(R=>{let A=t.elements.get(R);return A?{key:R,tag:A.tag,label:A.tag}:null}).filter(R=>R!==null),N=[];if(f.parentKey){let R=t.elements.get(f.parentKey);if(R)for(let A of R.childKeys){if(A===e)continue;let C=t.elements.get(A);C&&N.push({key:A,tag:C.tag,label:C.tag})}}return{composition:d,key:e,tag:f.tag,componentName:f.componentName,sourceFile:f.sourceFile,sourceLocator:yv(f),label:f.tag,capabilities:y,writeTarget:i,effectiveWriteTarget:E,provenanceChain:b,componentSemantic:c,styleSource:l,conditional:a,...u?{dynamicData:u}:{},textSegments:x,boundaryKind:f.boundaryKind,isOpaque:f.isOpaque,ancestors:S,children:v,siblings:N}}function hv(e,t,n,r,o,i,s,a){let c=Uo(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=Ev(l.textSegments,i),g=kM(l);return{composition:c,key:e,tag:l.tag,...g?{linkSourceKind:g}:{},componentName:l.componentName,sourceFile:l.sourceFile,sourceLocator:yv(l),label:l.tag,capabilities:Sv(e,t,l,d,f),provenanceChain:f?{editMode:f.editMode,diagnostics:f.diagnostics.map(m=>({code:m.code,message:m.message}))}:void 0,...s?{dynamicData:s}:{},...a?{properties:a}:{},textSegments:l.textSegments.map(m=>{let p=o.get(m.index);return{index:m.index,editable:vv(m,d,i?.get(m.index)??null),source:p?{kind:p.kind}:null}}),boundaryKind:l.boundaryKind,isOpaque:l.isOpaque,ancestors:bv(l,t)}}function kM(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 yv(e){return{sourceFile:e.sourceFile,componentName:e.componentName,openingElementRange:_M(e.sourceRange),structuralPath:e.identity.structuralPath,...RM(e.textSegments)}}function bv(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 _M(e){return{startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,endColumn:e.endColumn}}function RM(e){let t=e.map(n=>n.value.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();return t?{textPreview:t.slice(0,IM)}:{}}function xv(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 Ev(e,t){if(!t)return null;for(let n of e){let r=t.get(n.index);if(r)return r}return null}function Sv(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&&Iv(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 vv(e,t,n){return!e.editable||!t.canUpdateText?!1:n?Iv(n.editMode):!0}function Iv(e){return e==="direct"||e==="proxy"||e==="upstream"}function CM(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 PM(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}:vM(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 Gp=["set-class-name-source","apply-style-draft"];function kv(e){let t=e.attributes?.find(n=>n.name==="className");if(!t)return{kind:"class-name-source",className:"",sourceKind:"missing",editable:!0,operationBoundary:Gp,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:Gp,sourcePath:n}}return{kind:"class-name-source",className:t.value,sourceKind:t.resolvedValue===void 0?"static-attribute":"static-expression",editable:!0,operationBoundary:Gp}}import _v from"node:path";function Zp(){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 Cv(e,t,n){let r=[],o=new Set;for(let i of e.intents){let s=wM(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 Il(e){let t=()=>NM(e);return e.mutex?e.mutex.runExclusive(t):t()}async function NM(e){let t=await Cv(e.plan,e.overlay,e.exists);if(!t.ok)return{ok:!1,stage:"precheck",reason:t.reason,error:t,recoveryRequired:!1};let n=AM(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 Yp({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 Yp({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 Yp({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 Rv("swap",l,"Live state swap failed after durable publish.")}try{await e.finalizeCandidate?.(c)}catch(l){return Rv("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 AM(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 Yp(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:TM(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 Rv(e,t,n){return{ok:!1,stage:e,reason:n,error:t,recoveryRequired:!0}}function TM(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 wM(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)||_v.isAbsolute(e))return{ok:!1,code:"unsafe-path",path:e,reason:`Unsafe file path: ${e}`};let t=_v.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 OM=50,FM=8*1024*1024;function Tv(e,t={}){let n=[],r=[],o=t.externalAdapters??[],i=Math.max(0,t.maxUndoEntries??OM),s=Math.max(0,t.maxUndoBytes??FM);return{prepareRewritePlan:a,execute:c,executeFilePlan:l,undo:u,redo:d};async function a(R){let A=[...R.steps].sort((B,G)=>B.order-G.order),C=A.filter(B=>B.type!=="invoke-external-adapter");if(C.length!==A.length)return{ok:!1,errorCode:"unsupported-operation",reason:"External adapter writes require a transactional prepare/commit/rollback contract."};let w=new Set(C.map(B=>B.file)),M=await E(w),D=new Map(M.map(B=>[B.file,B.exists===!1?"":B.content])),U;for(let B of C){let G=Av(B,D.get(B.file)??"");if(!G.ok)return{ok:!1,errorCode:G.errorCode,reason:G.reason};D.set(B.file,G.source),U=G.selectionRef??U}return{ok:!0,filePlan:{operationId:R.operationId,kind:"source-edit",target:R.target,documentVersion:R.documentVersion,conflictPolicy:"compare-and-swap",edits:[...D].map(([B,G])=>({operation:"upsert",file:B,content:G,baseContentHash:M.find(K=>K.file===B)?.sha256??null}))},...U?{selectionRef:U}:{}}}async function c(R){let A=[...R.steps].sort((K,ge)=>K.order-ge.order),C=A.filter(K=>K.type!=="invoke-external-adapter"),w=A.filter(K=>K.type==="invoke-external-adapter"),M=new Set(C.map(K=>K.file));if(C.length>0&&w.length>0)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:"Mixed local file rewrites and external adapter writes require an explicit compensation contract.",rolledBack:!1};if(C.length===0)return y(R,w);let D=await E(M),U=new Map;for(let K of D)U.set(K.file,K.exists===!1?"":K.content);let B;for(let K of C){let ge=U.get(K.file)??"",oe=Av(K,ge);if(!oe.ok)return{ok:!1,operationId:R.operationId,errorCode:oe.errorCode,reason:oe.reason,rolledBack:!1};U.set(K.file,oe.source),oe.selectionRef&&(B=oe.selectionRef)}let G=await S([...U].map(([K,ge])=>({file:K,content:ge,exists:!0,version:0,sha256:Ae(ge)})),D);return G.ok===!1?{ok:!1,operationId:R.operationId,errorCode:G.rolledBack?"writeback-failed":"rollback-failed",reason:G.reason,rolledBack:G.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:D,postSnapshots:G.snapshots,plan:R}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...G.snapshots.map(K=>K.version)),affectedFiles:[...M],...B?{selectionRef:B}:{}})}async function l(R){let A=new Set(R.edits.map(G=>G.file)),C=await E(A),w=b(R,C);if(w)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:w.reason,affectedFiles:[w.file],rolledBack:!1};let M=new Map(C.map(G=>[G.file,G])),D=R.edits.find(G=>G.operation==="create-only"&&M.get(G.file)?.exists!==!1);if(D)return{ok:!1,operationId:R.operationId,errorCode:"stale-version",reason:`MATERIALIZATION_INSTANCE_CONFLICT: create-only target already exists: ${D.file}`,affectedFiles:[D.file],rolledBack:!1};let U=R.edits.map(G=>G.operation==="delete"?{file:G.file,content:"",exists:!1,version:0}:{file:G.file,content:G.content,exists:!0,version:0,sha256:Ae(G.content)}),B=await S(U,C,new Set(R.edits.filter(G=>G.operation==="create-only").map(G=>G.file)));return B.ok===!1?{ok:!1,operationId:R.operationId,errorCode:B.rolledBack?"writeback-failed":"rollback-failed",reason:B.reason,rolledBack:B.rolledBack}:(n.push({operationId:R.operationId,preSnapshots:C,postSnapshots:B.snapshots,plan:{operationId:R.operationId,kind:R.kind,target:R.target,documentVersion:R.documentVersion,steps:[],preSnapshots:C}}),f(),r.length=0,{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:Math.max(...B.snapshots.map(G=>G.version)),affectedFiles:[...A]})}async function u(){let R=n.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to undo"};let A=await S(R.preSnapshots,R.postSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(n.pop(),r.push(R),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(C=>C.version)),affectedFiles:R.preSnapshots.map(C=>C.file)})}async function d(){let R=r.at(-1);if(!R)return{ok:!1,operationId:"",errorCode:"unknown",reason:"Nothing to redo"};let A=await S(R.postSnapshots,R.preSnapshots);return A.ok===!1?{ok:!1,operationId:R.operationId,errorCode:A.rolledBack?"writeback-failed":"rollback-failed",reason:A.reason,rolledBack:A.rolledBack}:(r.pop(),n.push(R),f(),{ok:!0,operationId:R.operationId,kind:R.plan.kind,target:R.plan.target,resultVersion:Math.max(...A.snapshots.map(C=>C.version)),affectedFiles:R.postSnapshots.map(C=>C.file)})}function f(){for(;n.length>i;)n.shift();for(;n.length>0&&g()>s;)n.shift()}function g(){return n.reduce((R,A)=>R+m(A),0)}function m(R){return p(R.preSnapshots)+p(R.postSnapshots)}function p(R){return R.reduce((A,C)=>A+C.file.length+C.content.length,0)}async function y(R,A){let C=[];for(let w of A){let M=w.capability??"write-text",D=o.find(B=>B.sourceType===w.sourceType&&(w.adapterId===void 0||B.adapterId===w.adapterId)&&(B.capabilities===void 0||B.capabilities.includes(M)));if(!D)return{ok:!1,operationId:R.operationId,errorCode:"unsupported-operation",reason:`No external adapter registered for ${w.sourceType}`,rolledBack:!1};let U=await D.execute(w);if(!U.ok)return{ok:!1,operationId:R.operationId,errorCode:"writeback-failed",reason:U.reason??`External adapter failed for ${w.sourceType}`,rolledBack:!1};C.push(w.file)}return{ok:!0,operationId:R.operationId,kind:R.kind,target:R.target,resultVersion:0,affectedFiles:C}}function b(R,A){if(R.conflictPolicy!=="compare-and-swap")return null;let C=new Map(A.map(w=>[w.file,w]));for(let w of R.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 M=C.get(w.file),D=w.baseContentHash;if(D===null){if(M?.exists!==!1)return{file:w.file,reason:`Source file ${w.file} was created or changed before save.`};continue}if(!D)return{file:w.file,reason:`Source file ${w.file} is missing baseContentHash. Reopen the file before saving.`};if(M?.exists===!1||M?.sha256!==D)return{file:w.file,reason:`Source file ${w.file} changed before save. Reload or explicitly overwrite the newer version.`}}return null}async function E(R){let A=[];for(let C of R)A.push(await x(C));return A}async function x(R){if(!await e.exists(R))return{file:R,content:"",version:0,exists:!1};let C=Math.max(1,e.getVersion(R)),w=await e.readFile(R);return{file:R,content:w,version:C,exists:!0,sha256:Ae(w)}}async function S(R,A,C=new Set){let w=[];try{for(let M of R){if(C.has(M.file)){if(!e.createExclusive)throw new Error("Create-only write requires atomic exclusive-create support.");await e.createExclusive(M.file,M.content)}else await v(M);let D=e.bumpVersion(M.file);w.push(M.file),M.version=D}}catch(M){let D=await N(A.filter(B=>w.includes(B.file)));if(D.ok===!1)return{ok:!1,reason:`Writeback failed, then rollback failed for ${D.failedFiles.join(", ")}: ${Nv(M)}`,rolledBack:!1,instanceConflict:Pv(M)};let U=Pv(M);return{ok:!1,reason:`${U?"MATERIALIZATION_INSTANCE_CONFLICT: ":""}Writeback failed and committed files were restored: ${Nv(M)}`,rolledBack:!0,instanceConflict:U}}return{ok:!0,snapshots:R.map(LM)}}async function v(R){if(R.exists===!1){await e.deleteFile(R.file);return}await e.writeFile(R.file,R.content)}async function N(R){let A=[];for(let C of R)try{await v(C),e.bumpVersion(C.file)}catch{A.push(C.file)}return A.length===0?{ok:!0}:{ok:!1,failedFiles:A}}}function Pv(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function LM(e){let t=e.exists!==!1;return{file:e.file,content:t?e.content:"",version:e.version,exists:t,...t?{sha256:Ae(e.content)}:{}}}function Nv(e){return e instanceof Error?e.message:String(e)}function Av(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 Lt(xn({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-import":return Lt($o({source:t,moduleSpecifier:e.moduleSpecifier,imports:e.imports}));case"remove-node":return Lt(uo({source:t,locator:e.locator,removeWhitespace:e.removeWhitespace}));case"insert-child":return Lt(bn({source:t,locator:e.parentLocator,node:e.node,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"update-text":return Lt(Ra({source:t,locator:e.locator,segmentIndex:e.segmentIndex,newText:e.newText}));case"update-value":return Lt(Vi({source:t,locator:e.locator,next:e.value}));case"update-array-item":return Lt(Vi({source:t,locator:e.locator,next:e.value}));case"insert-bound-array-item":return Lt(wa({source:t,locator:e.locator,index:e.index,value:e.value}));case"insert-jsx-expression-child":return Lt(Ca({source:t,locator:e.parentLocator,expression:e.expression,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"remove-bound-array-item":return Lt(Oa({source:t,locator:e.locator,index:e.index}));case"move-array-item":return Lt(Fa({source:t,locator:e.locator,fromIndex:e.fromIndex,toIndex:e.toIndex}));case"move-node":return Lt(po({source:t,locator:e.locator,targetParentLocator:e.targetParentLocator,placement:e.placement,anchorLocator:e.anchorLocator,selectionContext:e.selectionContext}));case"move-repeat-template-child":return Lt(Pa({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 DM(e,t);case"set-property-changes":return Lt(Na({source:t,locator:e.locator,changes:e.changes}));case"set-link-target":return Lt(Aa({source:t,locator:e.locator,link:e.link,changes:e.changes}));case"set-property-binding":return Lt(Ta({source:t,locator:e.locator,name:e.name,object:e.object,property:e.property}));case"upsert-object-property":return Lt(Da({source:t,objectLocator:e.locator,name:e.name,value:e.value}));default:return{ok:!1,reason:`Unknown step type: ${e.type}`,errorCode:"unknown"}}}function DM(e,t){let{request:n}=e;if(n.newAttrRaw!==null&&!Jh(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!==Ae(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:Kh({source:t,oldAttrRange:n.oldAttrRange,openingElementRange:n.openingElementRange,newAttrRaw:n.newAttrRaw})}}function Lt(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 kl,SiteEditCompositionContextSchema as MM,SiteEditCompositionSelectorSchema as BM}from"@vcp-dev/contracts";var Vt=class extends Error{constructor(t,n,r){super(n),this.code=t,this.details=r,this.name="SiteEditCompositionError"}};function wv(e,t){throw new Vt("INVALID_COMPOSITION",e,{value:t})}function _l(e){let t=MM.safeParse(e);return t.success?t.data:wv("Invalid SiteEditCompositionContext.",e)}function Ov(e){let t=[],n=new Map,r=new Map;for(let l of e.compositions){let u=_l(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Vt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=kl(u);if(n.has(d))throw new Vt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u});let f=r.get(l.entryFile);if(f)throw new Vt("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 Vt("INVALID_COMPOSITION","At least one composition must be registered.");let o=new Map;for(let l of e.initialDocumentVersions??[]){let u=_l(l?.composition);if(!Number.isInteger(l?.version)||(l?.version??-1)<0)throw new Vt("INVALID_INITIAL_DOCUMENT_VERSION","Initial document version must be a non-negative integer.",{context:u,version:l?.version});let d=kl(u);if(!n.has(d))throw new Vt("UNKNOWN_COMPOSITION","Initial document version references an unregistered composition.",{context:u,key:d});if(o.has(d))throw new Vt("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=BM.safeParse(l);if(!u.success)return wv("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 Vt("AMBIGUOUS_COMPOSITION","The composition selector matches multiple registered contexts.",{selector:u.data}):new Vt("UNKNOWN_COMPOSITION","The composition selector is not registered.",{selector:u.data})}function s(l){let u=_l(l),d=kl(u),f=n.get(d);if(!f)throw new Vt("UNKNOWN_COMPOSITION","The composition context is not registered.",{context:u,key:d});return f}function a(l){let u=_l(l?.context);if(typeof l.entryFile!="string"||!l.entryFile)throw new Vt("INVALID_COMPOSITION","A registered composition must have a non-empty entryFile.");let d=kl(u),f=n.get(d);if(f){if(f.entryFile===l.entryFile)return f;throw new Vt("DUPLICATE_COMPOSITION",`Composition key ${d} is registered more than once.`,{key:d,context:u})}let g=[...n.values()].find(p=>p.entryFile===l.entryFile);if(g)throw new Vt("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(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 qp(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 Fv(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 jM,stripSiteEditRepeatInstanceKeys as Lv}from"@vcp-dev/contracts";function Dv(e){let t=new Map,n=new Map,r=new Map;for(let o of e.entries){t.set(o.key,o);let i=Lv(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 $M(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 Rl(e){return e?.map(t=>({...t}))}function Qp(e,t){if(t===null||e?.kind!=="value-binding"||e.sourceKind!=="repeat-template")return e;let n=e.collectionIndexMap?.[t]??t,r=Rl(e.collectionPathMap?.[t])??Rl(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:Rl(e.path),locator:e.locator?{...e.locator,path:r}:e.locator,collectionIndexMap:e.collectionIndexMap?[...e.collectionIndexMap]:void 0,collectionPathMap:e.collectionPathMap?.map(o=>Rl(o)??[])}}function Mv(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)=>jM(g,m),c=(g,m,p)=>{let y=o.get(g);if(!y)return a(g,p);let b=a(g,p),E={...y,key:b,parentKey:m,childKeys:[]};return i.push(E),E.childKeys=y.childKeys.flatMap(x=>l(x,p,b)),b},l=(g,m,p)=>{if(!r.has(g))return[c(g,p,m)];let y=d(g,m),b=[];for(let E=0;E<y;E+=1)b.push(c(g,p,[...m,E]));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 m=d(g,[]);for(let p=0;p<m;p+=1)c(g,null,[p])}return{...e,rootKeys:[...e.rootKeys],entries:i};function d(g,m){let p=new Set;for(let y of f(g)){let b=n.get(y);if(b){for(let E of[...b.textTargets.values(),...b.elementPropertyTargets.values()])if(!(E?.kind!=="value-binding"||E.sourceKind!=="repeat-template"))for(let x of UM(E))x.length<=m.length||VM(x,m)&&p.add(x[m.length])}}return p.size>0?p.size:$M(n.get(g))}function f(g){let m=s.get(g);if(m)return m;let p=[g],y=o.get(g);for(let b of y?.childKeys??[])p.push(...f(b));return s.set(g,p),p}}function Bv(e){let t=e.parts.at(-1);return typeof t?.repeatIndex=="number"?t.repeatIndex:null}function jv(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((Lv(s.key)??s.key)===n){if(s.key===t)return i;i+=1}return null}function UM(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 VM(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 $v(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 Uv(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 Vv(e){return{path:e.path,code:e.code,message:e.message,...e.details?{details:JSON.parse(JSON.stringify(e.details))}:{}}}function KM(e){return e.map(t=>`${t.code} (${t.path}): ${t.message}`).join("; ")}var $s=class extends Error{constructor(t){let n=t.map(Vv);super(KM(n)),this.name="RouteBuildDiagnosticsError",this.diagnostics=n}};function Kv(e,t){let n=t instanceof Error&&t.message?t.message:String(t);return t instanceof $s?{routeId:e,message:n,diagnostics:t.diagnostics.map(Vv)}:{routeId:e,message:n}}function em(e){return e.map(({routeId:t,message:n})=>`${t}: ${n}`).join("; ")}function tm(e,t){let n=new Map(e);for(let r of t)n.delete(r);return n}function Us(e,t){e.clear();for(let[n,r]of t)e.set(n,r)}function Jv(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 Xv(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 ZM=/^(?:src\/)?app\/.*\/?page\.[cm]?[jt]sx?$/,qM=["layout.tsx","layout.ts","layout.jsx","layout.js","layout.mjs","layout.cjs"],zv=32,Nl=256;function QM(e){return{expectedIndexDigest:e.digest,publishedIndexDigest:e.digest,publishedCursor:e.cursor,publishedCurrentId:e.currentId}}var Hv={maxEntries:50,maxBytes:8*1024*1024};function eB(){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 ja(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 Wv(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 tB(){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>Hv.maxEntries||nB(e)>Hv.maxBytes;)e.shift()}}function nB(e){return e.reduce((t,n)=>t+rB(n),0)}function rB(e){return Gv(e.preSnapshots)+Gv(e.postSnapshots)+oB(e.provenance)}function oB(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 Yv(e,t){return{key:XM(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 Al=class extends Error{constructor(t){super(t.reason),this.result=t}},No=class extends Error{constructor(t){super(em(t)),this.failedRoutes=t}};function Zv(e,t){if(!e)return;let n=[...t];if(n.some(o=>o?.entries.some(i=>i.key===e.key)))return e;let r=qt(e.key)??e.key;for(let o of n){let i=o?.entries.find(s=>(qt(s.key)??s.key)===r);if(i)return{...e,key:i.key}}return e}function iB(e,t,n){if(!n)return;let r=qt(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 sB=/\.(?:[cm]?[jt]sx?)$/i,aB=/\.json$/i,cB=/\.(?:css|scss|sass)$/i,lB=/\.mdx$/i,uB=/\.ya?ml$/i;function dB(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 fB(e){return{kind:e.isProxy?"component-proxy":"jsx-node",file:e.file,componentName:e.componentName,isProxy:e.isProxy}}function pB(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=rI(await e.listFiles(i)),a=new Map(s.files.map(l=>[l.path,l]));for(let[l,u]of n)if(mB(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 mB(e,t){return t.length===0?!0:t.some(n=>e===n||e.startsWith(`${n}/`))}function rI(e){return Array.isArray(e)?{files:e}:e}function gB(e){if(!HM(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!==GM||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=zM(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(sB.test(e.path)){let t=Un({source:e.content,profile:oo({filePath:e.path,source:e.content})});if(!t.ok)return{ok:!1,errorCode:"ast-error",message:t.diagnostic.message,details:{path:e.path}}}if(aB.test(e.path))try{JSON.parse(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`JSON parse failed: ${Xt(t)}`,details:{path:e.path}}}if(cB.test(e.path)){let t=qv({content:e.content,path:e.path,profile:"css"});if(!t.ok)return t}if(lB.test(e.path)){let t=qv({content:e.content,path:e.path,profile:"mdx"});if(!t.ok)return t}if(uB.test(e.path))try{YM(e.content)}catch(t){return{ok:!1,errorCode:"ast-error",message:`YAML parse failed: ${Xt(t)}`,details:{path:e.path}}}return{ok:!0}}function qv({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 m=e.indexOf(`
8
+ `,d);if(m===-1){l=!0;break}d=m,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 bi(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 m=f==="}"?"{":f===")"?"(":"[",p=r.pop();if(!p||p.char!==m)return bi(t,`Unexpected closing token "${f}" in ${t}.`);l=!1;continue}l=f===`
14
+ `||f==="\r"}if(s)return bi(t,`Unterminated block comment in ${t}.`);if(o)return bi(t,`Unterminated string literal in ${t}.`);if(c)return bi(t,`Unterminated MDX code fence in ${t}.`);let u=r.at(-1);return u?bi(t,`Unclosed token "${u.char}" in ${t}.`):{ok:!0}}function bi(e,t){return{ok:!1,errorCode:"ast-error",message:t,details:{path:e}}}function Tl(e){let t="idle",n=e.fileSystem??eB(),r=Xh(),o=Ov({compositions:e.compositions,initialDocumentVersions:e.initialDocumentVersions}),i=new Map,s=new Map,a=new Set,c=null,l=e.history??(e.historyStore?Fy(e.historyStore):tB()),u=Tv(n,{externalAdapters:e.externalAdapters}),d=new Map,f=ty(Nl),g=new Set,m=0,p=e.historyStore?.recoveryRequired??!1,y=Zp(),b=v();function E(h){return(Pl.isAbsolute(h)?Pl.relative(e.projectRoot,h):h).replace(/\\/g,"/").replace(/^\.\//,"")}function x(h,_){let I=Pl.posix.dirname(h),T=_.replace(/\.(?:tsx?|jsx?)$/i,""),j=Pl.posix.relative(I,T);return j.startsWith(".")?j:`./${j}`}function S(h,_){return h.startLine===_.startLine&&h.startColumn===_.startColumn&&h.endLine===_.endLine&&h.endColumn===_.endColumn}async function v(){let h=e.historyStore;if(h)try{let _=await h.readTransactionJournal();if(!_)return;let I=await h.readIndex(),T=await Promise.all(_.files.map(async $=>await n.exists($.path)?Ae(await n.readFile($.path)):null));if(Xv({journal:_,index:I,observedFileDigests:T})!=="ambiguous"){await h.clearTransactionJournal(_.transactionId);let $=await h.readStatus();$.recoveryRequired||(await h.cleanupTmp(),$=await h.readStatus()),p=$.recoveryRequired;return}await h.markRecoveryRequired(`Ambiguous transaction journal ${_.transactionId} at phase ${_.phase}`),p=!0}catch(_){p=!0,await h.markRecoveryRequired(`Transaction journal recovery failed: ${Xt(_)}`).catch(()=>{})}}function N(){return t==="disposed"}e.onEvent&&r.subscribe(e.onEvent);for(let h of o.entries){let _=Yv(h.context,h.entryFile);i.set(h.key,_),R(_,_.dependencyFiles)}function R(h,_){let I=new Set(_);A(h),h.dependencyFiles=I;for(let T of h.dependencyFiles){let j=s.get(T);j||(j=new Set,s.set(T,j)),j.add(h.key)}}function A(h){for(let _ of h.dependencyFiles){let I=s.get(_);I&&(I.delete(h.key),I.size===0&&s.delete(_))}h.dependencyFiles.clear()}function C(h){let _=new Set;for(let I of h)for(let T of s.get(I)??[])_.add(T);return _}function w(h){for(let _ of h)if(!s.has(_))return!1;return!0}async function M(h,_,I,T,j,$){let X=new Map,z=uv(h),te=QS(j.values()),W=qE(j.values()),H=typeof $.exists=="function"?ie=>$.exists(ie):async()=>!1;for(let[ie,pe]of h.elements){let Ne=_.nodes.get(ie);if(!Ne)continue;let ce=I.get(pe.sourceFile)??T.get(pe.sourceFile),De=new Map,Ce=new Map,V=new Map,ee=[];for(let ot of pe.textSegments){if(!ce){De.set(ot.index,null);continue}let Ai=await ev({file:pe.sourceFile,source:ce,segment:ot,readFile:nn=>$.readFile(nn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:nn,adapterId:to,capabilities:gu})=>({sourceType:nn,adapterId:to,capabilities:gu})),functionCallContracts:e.functionCallContracts,fileCache:te}),Jt=await Vp({file:pe.sourceFile,source:ce,target:{kind:"text-segment",segment:ot},readFile:nn=>$.readFile(nn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:nn,adapterId:to,capabilities:gu})=>({sourceType:nn,adapterId:to,capabilities:gu})),functionCallContracts:e.functionCallContracts,fileCache:te}),gn=dB(Ai);De.set(ot.index,gn),Ce.set(ot.index,Ai),V.set(ot.index,Jt),ee.push({editable:ot.editable,source:gn})}let xe=new Map,Oe=new Map;if(ce)for(let ot of pe.attributes??[]){let Ai=await yi({file:pe.sourceFile,source:ce,sourceRange:ot.sourceRange,expression:ot.source?.expression??ot.value,sourceInfo:ot.source,readFile:gn=>$.readFile(gn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gn,adapterId:nn,capabilities:to})=>({sourceType:gn,adapterId:nn,capabilities:to})),functionCallContracts:e.functionCallContracts,fileCache:te}),Jt=await lv({element:pe,file:pe.sourceFile,source:ce,propertyName:ot.name,readFile:gn=>$.readFile(gn),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:gn,adapterId:nn,capabilities:to})=>({sourceType:gn,adapterId:nn,capabilities:to})),functionCallContracts:e.functionCallContracts,fileCache:te});Oe.set(ot.name,Jt),xe.set(ot.name,Ai)}let Me=xv(fB(Ne.writeTarget),ee),ut=z({key:ie,element:pe,provenances:V}),Sr=kv(pe),jn=ce?await ul({element:pe,graph:h,file:pe.sourceFile,source:ce,readFile:ot=>$.readFile(ot),exists:H,fileCache:W}):void 0,eo=h.regions.find(ot=>ot.kind==="conditional-region"&&ot.childKeys.includes(ie)),wt,mn=eo?.sourceCandidates?.[0];if(ce&&eo&&mn?.kind==="conditional-branch"){let ot=await Vp({file:pe.sourceFile,source:ce,target:{kind:"conditional-branch",candidate:mn},readFile:Jt=>$.readFile(Jt),exists:H,graph:h,externalSourceResolvers:e.externalSourceResolvers,externalAdapters:e.externalAdapters?.map(({sourceType:Jt,adapterId:gn,capabilities:nn})=>({sourceType:Jt,adapterId:gn,capabilities:nn})),functionCallContracts:e.functionCallContracts,fileCache:te});wt={currentBranch:eo.childKeys.indexOf(ie)<=0?"then":"else",availableBranches:eo.childKeys.length>1?["then","else"]:["then"],conditionExpression:mn.conditionExpression,provenance:{finalSource:ot.finalSource?{kind:ot.finalSource.kind,file:ot.finalSource.file,displayPath:ot.finalSource.displayPath}:null,chain:ot.chain.map(Jt=>({kind:Jt.kind,file:Jt.file,displayName:Jt.displayName,canEditHere:Jt.canEditHere})),confidence:ot.confidence,editMode:ot.editMode,diagnostics:ot.diagnostics.map(Jt=>({code:Jt.code,message:Jt.message}))}}}X.set(ie,{textSources:De,textTargets:Ce,elementPropertyTargets:xe,propertyProvenances:Oe,isRepeat:TB(ie,h),provenances:V,writeTarget:Me,componentSemantic:ut,styleSource:Sr,conditional:wt,dynamicData:jn})}return X}function D(h){return typeof n.getVersion=="function"?n.getVersion(h):0}function U(h,_){let I=o.initialVersions.get(h.key)??0;for(let T of _.values())I=Math.max(I,T);return Math.max(I,h.graph?.version??0)}function B(h){return i.get(h)?.graph?.version??o.initialVersions.get(h)??0}function G(h){try{return B(o.resolveSelector(h.composition).key)}catch{return 0}}async function K(h,_,I=n,T={}){let j=await Jo(h,_,$=>I.readFile($),$=>I.exists($),{additionalEntries:await oe(h,I),...T});if(j.diagnostics.length>0)throw new $s(j.diagnostics);return T.validationOnly||f.remember(j.parsedModules.values()),j}async function ge(h,_,I={}){let T=i.get(h);if(!T)return null;let j=I.sourceCache??tm(d,[]),$=I.fileSystem??qp(n),{graph:X,allSources:z,parsedModules:te,entryModule:W}=await K(T.entryFile,_,$,{version:T.graph?.version??1}),H=new Map;for(let wt of z.keys())H.set(wt,D(wt));let ie=Math.max(U(T,H),I.minimumVersion??0);I.changed&&ie<=(T.graph?.version??0)&&(ie=(T.graph?.version??0)+1),X.version=ie;for(let[wt,mn]of z)Cl(j,wt,mn,Nl);let pe=await Le(T.composition,T.entryFile,z,j,$);X.routeId=T.routeId,X.composition=T.composition;let Ne=kc(X),ce=Ma(Ne,X),De=await M(X,Ne,z,j,te,$);st(ce,De);let Ce=be(X,ce,De),V=mt(De),ee=Mv(mv(X,Ne,ce,{canUpdateTextByKey:Ce,dynamicDataSummaryByKey:V}),X,De),xe=Tn({route:T.routeId,composition:T.composition,entryFile:T.entryFile,version:ie,source:_,ast:W?.ast}),Oe=Db(xe),Me=null,ut=[];if(xe.ok){yB(ee,X,xe.projection,te);let wt=Ic({composition:T.composition,entryFile:T.entryFile,graph:X,parsedModules:te,projection:xe.projection});if(wt.diagnostics.length===0){let mn=ds({composition:T.composition,entryFile:T.entryFile,graph:X,parsedModules:te,projection:xe.projection,documentVersion:ie,roots:wt.roots});mn.diagnostics.length===0&&(Me=mn,ut=mn.descriptors)}}let Sr={...ee,composition:T.composition,pageBlocks:ut,...pe?{styleContext:pe}:{},pageComposition:Oe},jn=new Set([T.entryFile,...z.keys()]);if(pe){jn.add(pe.entryCss.path);for(let wt of pe.stylesheets)jn.add(wt.path)}let eo={...T,dependencyFiles:jn,graph:X,topology:Ne,capabilities:ce,document:Sr,pageBlockIndex:Me,pageComposition:Oe,pageCompositionProjection:xe.projection,pagePlacementByKey:xe.ok?xe.projection.placementByKey:null,pagePlacementUnitByKey:xe.ok?xe.projection.placementUnitByKey:null,pageUnitByKey:xe.ok?xe.projection.unitByKey:null,pagePlacementsByUnitKey:xe.ok?xe.projection.placementsByUnitKey:null,documentIndex:Dv(Sr),detailProjections:De,fileVersions:H,styleContext:pe};if(I.publish===!1)return eo;for(let wt of jn){let mn=z.get(wt)??j.get(wt);mn!==void 0&&(Cl(d,wt,mn,Nl),g.delete(wt))}return R(T,jn),Object.assign(T,eo),T}async function oe(h,_=n){let I=[];for(let T of _B(h))typeof _.exists=="function"&&await _.exists(T)&&I.push({file:T,source:await _.readFile(T)});return I}async function Le(h,_,I,T,j){let $=[];for(let[H,ie]of I){if(nm(H)){$.push(H);continue}for(let pe of CB(ie)){let Ne=nI(H,pe);Ne&&$.push(Ne)}}if(!$.length){for(let H of RB(_))if(await j.exists(H)){$.push(H);break}}let X=new Map,z=AB($).slice(0,zv);for(;z.length>0&&X.size<zv;){let H=z.shift();if(X.has(H)||!nm(H))continue;let ie=await Je(H,T,j);if(ie!==null){X.set(H,{path:H,content:ie});for(let pe of PB(ie)){let Ne=nI(H,pe);Ne&&!X.has(Ne)&&!z.includes(Ne)&&z.push(Ne)}}}let te=[...X.values()].map(H=>({...H,hash:Ae(H.content)})),W=te[0];return W?{composition:h,revision:Ae(JSON.stringify(te.map(({path:H,hash:ie})=>({path:H,hash:ie})))),entryCss:W,stylesheets:te.slice(1)}:null}async function Je(h,_,I){let T=_.get(h);if(T!==void 0)return T;if(!await I.exists(h))return null;let j=await I.readFile(h);return Cl(_,h,j,Nl),j}function mt(h){let _=new Map;for(let[I,T]of h)T.dynamicData?.bindings.length&&_.set(I,uS(T.dynamicData.bindings));return _}function be(h,_,I){let T=new Map;for(let[j,$]of h.elements){if(!_.get(j)?.canUpdateText){T.set(j,!1);continue}let z=I.get(j),te=$.textSegments.some(W=>{if(!W.editable)return!1;let H=z?.provenances.get(W.index)??null;return!H||Ke(H)});T.set(j,te)}return T}function st(h,_){for(let[I,T]of _){let j=h.get(I);j?.canUpdateText&&T.dynamicData?.bindings.some($=>$.readonly&&($.targetKind==="text"||$.targetKind==="richtext"))&&h.set(I,{...j,canUpdateText:!1})}}function Ke(h){return h.editMode==="direct"||h.editMode==="proxy"||h.editMode==="upstream"}async function F(h,_={}){let I=[...new Set(h)],T=_.affectedCompositionKeys!==void 0,j=T?new Set(_.affectedCompositionKeys):C(I);if(!T&&(j.size===0||!w(I)))for(let W of i.values())yg(W,I)&&j.add(W.key);let $=!T&&j.size===0&&I.some(tI),X=_.publish===!1?tm(d,I):void 0,z={rebuiltRoutes:[],failedRoutes:[],..._.publish===!1?{candidateRouteStates:[],candidateSourceCache:X}:{}},te=qp(n);for(let W of i.values())if(!(_.excludedCompositionKeys?.has(W.key)||!(j.has(W.key)||$)))try{let ie=!!W.graph,pe=await te.readFile(W.entryFile),Ne=await ge(W.key,pe,{..._,fileSystem:te,...X?{sourceCache:X}:{}});Ne?.graph&&(z.rebuiltRoutes.push({documentChanged:ie,composition:W.composition,routeId:W.routeId,version:Ne.graph.version}),z.candidateRouteStates?.push({composition:W.composition,key:W.key,routeId:W.routeId,state:Ne}))}catch(ie){z.failedRoutes.push({...Kv(W.routeId,ie),composition:W.composition})}return z}function Z(h){let _=[...new Set(h)],I=C(_);if(I.size>0&&w(_))return[...I];for(let T of i.values())yg(T,_)&&I.add(T.key);return[...I]}function ue(h){let _=new Set(Z(h));return o.entries.filter(I=>_.has(I.key)).map(I=>I.context)}function Ue(h){return[...new Set(Z(h))].sort((I,T)=>I<T?-1:I>T?1:0).map(I=>o.getByKey(I)?.context).filter(I=>I!==void 0)}function Ge(h,_){let I=new Set(Z(_)),T=h.provenance?.affectedCompositions??[];if(T.length===0)return I;if([...new Set(T.map($=>o.resolveContext($).key))].some($=>!I.has($)))throw new Error("History provenance does not match the affected composition index.");return I}function Pn(h,_){let I=h.composition??h.provenance?.initiatingComposition;if(I){let $=o.resolveContext(I);return{context:$.context,key:$.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 j=o.getByKey(T[0]);if(!j)throw new Error("Legacy history entry references an unknown affected composition.");return{context:j.context,key:j.key}}function Ni(h,_){r.emit({type:"operation-completed",composition:h.composition,result:h});for(let{composition:I,version:T}of _.rebuiltRoutes)r.emit({type:"document-changed",composition:I,version:T});for(let{composition:I,message:T}of _.failedRoutes)r.emit({type:"graph-error",composition:I,message:T})}function yg(h,_){return _.some(I=>h.dependencyFiles.has(I)||h.entryFile===I||h.graph?.fileIndex.has(I))}function bg(h){for(let _ of h)a.add(_);c||N()||(c=(async()=>{t="building";let _=!1;try{for(;a.size>0;){if(N())return;await m_(),await y.runExclusive(async()=>{if(m>0||N())return;let I=[...a];a.clear();let T=await xg(I);if(T.length===0)return;let j=Z(T);for(let z of j){let te=i.get(z)?.composition;te&&r.emit({type:"graph-invalidated",composition:te})}let{rebuiltRoutes:$,failedRoutes:X}=await F(T,{changed:!0});for(let{documentChanged:z,composition:te,version:W}of $)r.emit({type:"graph-ready",composition:te,version:W}),z&&r.emit({type:"document-changed",composition:te,version:W});for(let{composition:z,message:te}of X)_=!0,r.emit({type:"graph-error",composition:z,message:te})})}}finally{c=null,t!=="disposed"&&(t=!_&&[...i.values()].some(I=>I.graph)?"ready":"idle"),a.size>0&&bg([])}})())}async function m_(){for(;m>0;)await new Promise(h=>setTimeout(h,0))}async function xg(h){let _=[];for(let I of new Set(h)){let T=d.get(I);if(T===void 0){if(g.has(I)&&!await n.exists(I))continue;g.delete(I),_.push(I);continue}try{await n.readFile(I)!==T&&(g.delete(I),_.push(I))}catch(j){if(!hB(j))try{if(await n.exists(I))continue}catch{continue}g.add(I),_.push(I)}}return _}function Eg(h){Jv(d,h);for(let _ of h)_.exists===!1?g.add(_.file):g.delete(_.file)}function Sg(h){g.clear();for(let _ of h)g.add(_)}async function vg(h){let _=await xg(h);if(_.length===0)return;let I=Z(_);for(let $ of I){let X=i.get($)?.composition;X&&r.emit({type:"graph-invalidated",composition:X})}let{rebuiltRoutes:T,failedRoutes:j}=await F(_,{changed:!0});for(let{documentChanged:$,composition:X,version:z}of T)r.emit({type:"graph-ready",composition:X,version:z}),$&&r.emit({type:"document-changed",composition:X,version:z});for(let{composition:$,message:X}of j)r.emit({type:"graph-error",composition:$,message:X})}async function g_(h,_){let I=Do(h,_);if(!I?.graph)return;let T=qt(h)??h,j=I.graph.elements.get(T);j&&await vg([j.sourceFile])}async function Ig(h){let _=new Set;if(h.target.kind==="node"){let I=Do(h.target.key,h.composition),T=qt(h.target.key)??h.target.key,j=I?.graph?.elements.get(T);j&&_.add(j.sourceFile)}else if(h.target.kind==="route"){let I=i.get(o.resolveSelector(h.target.composition).key);I&&_.add(I.entryFile)}else if(h.target.kind==="page-unit"){let I=i.get(o.resolveSelector(h.target.composition).key);I&&_.add(I.entryFile)}else if(h.target.kind==="page-block"){let I=i.get(o.resolveSelector(h.target.composition).key),T=I?.pageBlockIndex?.bindings.get(h.target.blockKey);if(T&&(_.add(T.ownerFile),_.add(T.descriptor.source.file)),I?.pageBlockIndex&&h.params.kind==="move-node"&&"kind"in h.params.target&&h.params.target.kind==="block-boundary"){let j=I.pageBlockIndex.bindings.get(h.params.target.anchorBlockKey);j&&(_.add(j.ownerFile),_.add(j.descriptor.source.file))}}else if(h.target.kind==="source-file")_.add(h.target.path);else if(h.target.kind==="source-batch")for(let I of h.target.paths)_.add(I);if(h.params.kind==="move-node"&&!("kind"in h.params.target)){let I=[h.params.target.parentKey,...h.params.target.relation==="before"||h.params.target.relation==="after"?[h.params.target.anchorKey]:[]];for(let T of I){let j=Do(T,h.composition),$=qt(T)??T,X=j?.graph?.elements.get($);X&&_.add(X.sourceFile)}}await vg(_)}async function h_(h){if(h.params.kind!=="source-edit")return du(h,"invalid-params","source-edit requires source-edit params");for(let _ of h.params.edits){let I=gB(_);if(!I.ok)return du(h,I.errorCode,I.message,I.details)}m+=1;try{let _=await __(h.params.edits);if(!_.ok)return du(h,_.errorCode,_.message,_.details);await Ig(h);let I={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 Er({request:h,filePlan:I})}catch(_){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:J.INTERNAL_ERROR,message:Xt(_)}}}finally{m-=1}}async function y_(h){if(h.target.kind!=="project"||h.params.kind!=="insert-page-resource")return q(h,J.INVALID_PARAMS,"insert-page-resource requires project target and matching params.");m+=1;try{let _=await wi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:[...h.params.artifact.components.flatMap(T=>T.materialization.files.map(j=>({path:j.pathTemplate,content:j.content}))),...h.params.artifact.pages.flatMap(T=>T.materialization.files.map(j=>({path:j.pathTemplate,content:j.content})))],exists:T=>n.exists(T),readFile:T=>n.readFile(T)});if(!_.ok)return q(h,J.MATERIALIZATION_REJECTED,_.message);let I=await Ad({artifact:h.params.artifact,exists:T=>n.exists(T)});return I.ok?await Er({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"overwrite",edits:I.files},output:{kind:"insert-page-resource",package_instance_id:I.packageInstanceId,pages:I.pages},historyPolicy:"none"}):q(h,I.code==="MATERIALIZATION_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,I.message,I.path?{path:I.path}:void 0)}catch(_){return q(h,J.INTERNAL_ERROR,Xt(_))}finally{m-=1}}async function b_(h){if(h.target.kind!=="project"||h.params.kind!=="delete-page-source")return q(h,J.INVALID_PARAMS,"delete-page-source requires project target and matching params.");if(!n.listFiles)return q(h,J.PLAN_FAILED,"Complete project file listing is required for page deletion.");m+=1;try{let _=rI(await n.listFiles({maxFiles:5e4,maxDepth:64}));if(_.truncated)return q(h,J.PLAN_FAILED,"Project file listing is incomplete; page deletion was refused.",{truncationReasons:_.truncated.reasons});let I=_.files.filter(({path:X})=>/\.(?:tsx?|jsx?)$/.test(X)),T=Object.fromEntries(await Promise.all(I.map(async({path:X})=>[X,await n.readFile(X)]))),j=wx({expectedUrlPath:h.params.expectedUrlPath,files:T});if(!j.ok)return q(h,j.code==="HOME_PAGE_LOCKED"?J.HOME_PAGE_LOCKED:j.code==="ROUTE_NOT_FOUND"?J.ROUTE_NOT_FOUND:J.PLAN_FAILED,j.message);let $=await Promise.all(j.edits.map(async X=>({...X,baseContentHash:Ae(await n.readFile(X.file))})));return Er({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:$},output:{kind:"delete-page-source",deleted_files:j.deletedFiles,updated_files:j.updatedFiles,preserved_shared_files:j.preservedSharedFiles,warnings:j.warnings},historyPolicy:"none"})}catch(_){return q(h,J.INTERNAL_ERROR,Xt(_))}finally{m-=1}}async function x_(h,_){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return q(h,J.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 q(h,J.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 q(h,J.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.");if(h.params.position.documentVersion!==h.documentVersion)return q(h,J.VERSION_STALE,"Page-unit insert-child placement belongs to a different document version.")}let I=_.document,T=_.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!T||T.status!=="supported")return q(h,J.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==I.version||T.documentVersion!==I.version)return q(h,J.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let j=h.params.node.kind==="component-call"?h.params.node.materialization:void 0;if(!j)return q(h,J.UNSUPPORTED_OPERATION,"Page-unit insertion currently requires a static materialization manifest.");let $=h.params.kind==="insert-child"?h.params.position:null,X=await wi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:j.files.map(W=>({path:W.pathTemplate,content:W.content})),exists:W=>n.exists(W),readFile:W=>n.readFile(W)});if(!X.ok)return q(h,J.MATERIALIZATION_REJECTED,X.message);let z=await Wv(n,Object.keys(j.projectDependencies??{})),te=await Md({manifest:j,generatedRoot:"components/site/generated",controlledFiles:j.files.map(W=>({pathTemplate:W.pathTemplate})),exists:W=>n.exists(W),availableHostDependencies:z,hostCapabilities:_d(),commit:async W=>{let H=await n.readFile(_.entryFile),ie=_.document,pe=_.pageCompositionProjection;if(!ie||ie.pageComposition?.status!=="supported"||ie.version!==h.documentVersion||!pe||pe.status!=="supported"||pe.documentVersion!==ie.version)return{ok:!0,data:q(h,J.VERSION_STALE,"The route changed before the page-unit insertion could commit.")};let Ne=W.entry.path,ce=w_(W.instanceName),De,Ce=[];if(h.params.kind==="insert-child"){if(!$||!("kind"in $)||$.kind!=="page-composition")return{ok:!0,data:q(h,J.INVALID_PARAMS,"Page-unit insert-child requires a page-composition placement.")};let Oe=os({routeId:_.routeId,entryFile:_.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:h.documentVersion,source:H,projection:pe,placementKey:$.placementKey,component:{source:Ne,exportName:W.entry.export.kind==="default"?"default":W.entry.export.name,localName:ce}});if(!Oe.ok)return{ok:!0,data:q(h,mu(Oe.error.code),Oe.error.message,{diagnostics:Oe.error.diagnostics})};let Me=Oe.plan.rewriteStep,ut;switch(Me.kind){case"insert-root-expression":ut=is({source:H,locator:Me.locator,expectedSourceHash:Me.sourceHash,action:{kind:"insert",jsx:Me.node.jsx,placement:Me.placement,replaceOriginal:Me.replaceOriginal}});break;case"insert-child":ut=bn({source:H,locator:Me.parentLocator,node:Me.node,placement:Me.placement,...Me.anchorLocator?{anchorLocator:Me.anchorLocator}:{}});break;default:ut={ok:!1,source:H,diagnostic:{code:"unsupported-syntax",message:`Unsupported route composition rewrite: ${String(Me)}`}}}if(!ut.ok)return{ok:!0,data:q(h,J.AST_PARSE_ERROR,ut.diagnostic.message)};De=ut.source}else{let Oe=tf({routeId:_.routeId,composition:_.composition,entryFile:_.entryFile,currentDocumentVersion:ie.version,expectedDocumentVersion:h.documentVersion,source:H,projection:pe,placementUnitKey:h.target.placementUnitKey,operation:"replace-node"});if(!Oe.ok)return{ok:!0,data:q(h,mu(Oe.error.code),Oe.error.message,{diagnostics:Oe.error.diagnostics})};let Me=Oe.plan.rewriteStep,ut;switch(Me.kind){case"replace-root-expression":ut=is({source:H,locator:Me.locator,expectedSourceHash:Me.sourceHash,action:{kind:"replace",jsx:`<${ce} />`}});break;case"replace-node":ut=Bo({source:H,locator:Me.locator,node:{jsx:`<${ce} />`}});break;default:ut={ok:!1,source:H,diagnostic:{message:`Unsupported page-unit replacement rewrite: ${Me.kind}`}}}if(!ut.ok)return{ok:!0,data:q(h,J.AST_PARSE_ERROR,ut.diagnostic.message)};let Sr=await uu({routeState:_,placementUnitKey:h.target.placementUnitKey,source:H,mutatedSource:ut.source});De=Sr.source,Ce=await Promise.all(Sr.files.map(async jn=>({operation:"delete",file:jn,baseContentHash:Ae(await n.readFile(jn))})))}let V=xn({source:De,moduleSpecifier:x(_.entryFile,Ne),imports:W.entry.export.kind==="default"?[{kind:"default",local:ce}]:[{kind:"named",imported:W.entry.export.name,local:ce}]});if(!V.ok)return{ok:!0,data:q(h,J.AST_PARSE_ERROR,V.diagnostic.message)};let ee=W.files.map(Oe=>({operation:"create-only",file:Oe.path,content:Oe.content})),xe=[{operation:"upsert",file:_.entryFile,content:V.source,baseContentHash:Ae(H)},...ee,...Ce];m+=1;try{let Oe=await Er({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:_.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:xe}});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{m-=1}}});return te.ok?te.data:q(h,te.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,te.error.message,{materializationCode:te.error.code})}async function E_(h,_){if(h.kind!=="insert-child"&&h.kind!=="replace-node")return q(h,J.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 q(h,J.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let I=_.document,T=_.pageBlockIndex;if(!I||!T||T.diagnostics.length>0)return q(h,J.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==I.version||T.documentVersion!==I.version)return q(h,J.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let j=ei(T,h.target,h.documentVersion,h.selectionRef);if(!j.ok)return q(h,oa(j.code),j.message);let $=j.binding;if(!(h.kind==="insert-child"?$.descriptor.capabilities.insert:$.descriptor.capabilities.replace)){let ce=$.descriptor.unavailableReasons?.[h.kind==="insert-child"?"insert":"replace"]?.reason??"The selected page block does not permit this operation.";return q(h,J.UNSUPPORTED_OPERATION,ce)}let z=(h.kind==="insert-child",h.params);if(z.kind!==h.kind)return q(h,J.INVALID_PARAMS,"Page-block materialization operation kind must match its params.");let te=z.node;if(te.kind!=="component-call"||!te.materialization)return q(h,J.UNSUPPORTED_OPERATION,"Page-block materialization requires a static component manifest.");let W;if(z.kind==="insert-child"){let ce=z.position;if(!("kind"in ce&&ce.kind==="block-boundary"))return q(h,J.INVALID_PARAMS,"Page-block insert-child requires a block-boundary position.");if(ce.documentVersion!==h.documentVersion)return q(h,J.VERSION_STALE,"The block insertion boundary belongs to a different document version.");let De=_c(T,ce);if(!De.ok)return q(h,oa(De.code),De.message);W=De.boundary}let H=te.materialization,ie=await wi({deferTargetLocale:!!e.resourceTranslationLocale,targetLocale:e.resourceTranslationLocale,files:H.files.map(ce=>({path:ce.pathTemplate,content:ce.content})),exists:ce=>n.exists(ce),readFile:ce=>n.readFile(ce)});if(!ie.ok)return q(h,J.MATERIALIZATION_REJECTED,ie.message);let pe=await Wv(n,Object.keys(H.projectDependencies??{})),Ne=await Md({manifest:H,generatedRoot:"components/site/generated",controlledFiles:H.files.map(ce=>({pathTemplate:ce.pathTemplate})),exists:ce=>n.exists(ce),availableHostDependencies:pe,hostCapabilities:_d(),commit:async ce=>{let De=_.document,Ce=_.pageBlockIndex;if(!De||!Ce||De.version!==h.documentVersion||Ce.documentVersion!==De.version||!Ce.bindings.has($.blockKey))return{ok:!0,data:q(h,J.VERSION_STALE,"The route or selected block changed before materialization could commit.")};let V=Ce.bindings.get($.blockKey);if(!V||V.ownerFile!==$.ownerFile||V.ownerSourceHash!==$.ownerSourceHash||V.sourceHash!==$.sourceHash)return{ok:!0,data:q(h,J.VERSION_STALE,"The selected block owner or source changed before materialization could commit.")};let ee=new Set([$.ownerFile,$.descriptor.source.file,...W?[W.ownerFile,W.anchorLocator.file,...W.parentLocator?[W.parentLocator.file]:[]]:[]]),xe=new Map;try{for(let Me of ee)xe.set(Me,await n.readFile(Me))}catch{return{ok:!0,data:q(h,J.VERSION_STALE,"A selected owner, root, or boundary file is no longer readable.")}}let Oe=fx({operationId:h.id,documentVersion:h.documentVersion,target:h.target,binding:$,...W?{boundary:W}:{},operation:z.kind,materialization:ce,files:xe});if(!Oe.ok){let Me=k_(Oe.code);return{ok:!0,data:q(h,Me,Oe.message,{materializationCode:Oe.code})}}m+=1;try{let Me=await Er({request:h,filePlan:Oe.plan});return!Me.ok&&Me.error?.message.includes("MATERIALIZATION_INSTANCE_CONFLICT")?{ok:!1,error:{code:"MATERIALIZATION_INSTANCE_CONFLICT",message:Me.error.message||"Static prefab instance conflicted during commit."}}:{ok:!0,data:Me}}finally{m-=1}}});return Ne.ok?Ne.data:q(h,Ne.error.code==="MATERIALIZATION_INSTANCE_CONFLICT"?J.MATERIALIZATION_CONFLICT:J.MATERIALIZATION_REJECTED,Ne.error.message,{materializationCode:Ne.error.code})}async function S_(h,_){if(h.kind!=="move-node"&&h.kind!=="remove-node")return q(h,J.UNSUPPORTED_OPERATION,"Only page-unit move-node and remove-node are currently supported by the page composition transaction.");let I=_.document,T=_.pageCompositionProjection;if(!I||I.pageComposition?.status!=="supported"||!T||T.status!=="supported")return q(h,J.UNSUPPORTED_OPERATION,"The current route has no supported page composition.");if(h.documentVersion!==I.version||T.documentVersion!==I.version)return q(h,J.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let j=await n.readFile(_.entryFile),$=tf({routeId:_.routeId,composition:_.composition,entryFile:_.entryFile,currentDocumentVersion:I.version,expectedDocumentVersion:h.documentVersion,source:j,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(!$.ok)return q(h,mu($.error.code),$.error.message,{diagnostics:$.error.diagnostics});let X=$.plan.rewriteStep,z;switch(X.kind){case"move-node":z=po({source:j,locator:X.locator,targetParentLocator:X.targetParentLocator,placement:X.placement,...X.anchorLocator?{anchorLocator:X.anchorLocator}:{}});break;case"remove-node":z=uo({source:j,locator:X.locator});break;case"remove-root-expression":z=is({source:j,locator:X.locator,expectedSourceHash:X.sourceHash,action:{kind:"remove"}});break;default:z={ok:!1,source:j,diagnostic:{message:`Unsupported page-unit mutation rewrite: ${X.kind}`}}}if(!z.ok)return q(h,J.AST_PARSE_ERROR,z.diagnostic.message);let te=z.source,W=[];if(h.kind==="remove-node"){let ie=await uu({routeState:_,placementUnitKey:h.target.placementUnitKey,source:j,mutatedSource:te});te=ie.source,W=await Promise.all(ie.files.map(async pe=>({operation:"delete",file:pe,baseContentHash:Ae(await n.readFile(pe))})))}let H=[{operation:"upsert",file:_.entryFile,content:te,baseContentHash:Ae(j)},...W];m+=1;try{return await Er({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:{kind:"source-file",path:_.entryFile},documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:H}})}finally{m-=1}}async function v_(h,_){if(h.kind!=="move-node"&&h.kind!=="remove-node")return q(h,J.UNSUPPORTED_OPERATION,"Only page-block move-node and remove-node use this source transaction.");let I=_.document,T=_.pageBlockIndex;if(!I||!T||T.diagnostics.length>0)return q(h,J.UNSUPPORTED_OPERATION,"The current route has no complete verified page-block index.");if(h.documentVersion!==I.version||T.documentVersion!==I.version)return q(h,J.VERSION_STALE,`Document version ${h.documentVersion} is stale (current: ${I.version}).`);let j=ei(T,h.target,h.documentVersion,h.selectionRef);if(!j.ok)return q(h,oa(j.code),j.message);let $=j.binding;if($.documentVersion!==I.version)return q(h,J.VERSION_STALE,"The resolved page-block binding is stale.");if(!(h.kind==="move-node"?$.descriptor.capabilities.move:$.descriptor.capabilities.remove)){let Ce=$.descriptor.unavailableReasons?.[h.kind==="move-node"?"move":"remove"]?.reason??"The selected block does not permit this operation.";return q(h,J.UNSUPPORTED_OPERATION,Ce)}if(h.kind==="remove-node"){let Ce=[...i.values()].filter(V=>V.dependencyFiles.has($.ownerFile));if(Ce.includes(_)||Ce.push(_),Ce.some(V=>!V.pageBlockIndex||V.pageBlockIndex.descriptors.length<=1))return q(h,J.UNSUPPORTED_OPERATION,"The selected source is the last editable page block in an affected composition.")}let z=null;if(h.kind==="move-node"){if(h.params.kind!=="move-node"||!("kind"in h.params.target)||h.params.target.kind!=="block-boundary")return q(h,J.INVALID_PARAMS,"Page-block move requires a block-boundary target.");if(h.params.target.anchorBlockKey===$.blockKey)return q(h,J.INVALID_TARGET,"A page block cannot be moved relative to itself.");let Ce=_c(T,h.params.target);if(!Ce.ok)return q(h,oa(Ce.code),Ce.message);let V=T.bindings.get(h.params.target.anchorBlockKey);if(!V||!$.descriptor.siblingBlockKeys.includes(V.blockKey)||!V.descriptor.siblingBlockKeys.includes($.blockKey)||V.ownerFile!==$.ownerFile||V.root.ownerNode.kind!==$.root.ownerNode.kind||V.root.ownerNode.key!==$.root.ownerNode.key||V.root.parentStructuralPath!==$.root.parentStructuralPath)return q(h,J.INVALID_TARGET,"The selected block and boundary anchor are not verified same-owner source siblings.");if(z=Ce.boundary,z.ownerFile!==$.ownerFile||z.sourceHash!==$.ownerSourceHash||!z.parentLocator)return q(h,J.INVALID_TARGET,"The move boundary does not belong to the selected block's source owner.")}let te=$.ownerFile,W=await n.readFile(te);if(Ae(W)!==$.ownerSourceHash)return q(h,J.VERSION_STALE,"The page-block owner source changed after resolution.");let H=$.descriptor.source.file===te?W:await n.readFile($.descriptor.source.file);if(Ae(H)!==$.descriptor.source.contentHash)return q(h,J.VERSION_STALE,"The selected page-block source changed after resolution.");let ie=I_($),pe=h.kind==="remove-node"?uo({source:W,locator:ie}):po({source:W,locator:ie,targetParentLocator:lu(z.parentLocator),anchorLocator:lu(z.anchorLocator),placement:z.placement});if(!pe.ok)return q(h,J.AST_PARSE_ERROR,pe.diagnostic.message);let Ne=pe.source,ce=[];if(h.kind==="remove-node"&&$.root.ownerNode.kind==="route-member"&&$.root.callChain.length>0&&$.descriptor.placementUnitKey){let Ce=await uu({routeState:_,placementUnitKey:$.descriptor.placementUnitKey,source:W,mutatedSource:Ne});Ne=Ce.source,ce=Ce.files}let De=[{operation:"upsert",file:te,content:Ne,baseContentHash:$.ownerSourceHash},...await Promise.all(ce.map(async Ce=>({operation:"delete",file:Ce,baseContentHash:Ae(await n.readFile(Ce))})))];m+=1;try{return await Er({request:h,filePlan:{operationId:h.id,kind:"source-edit",target:h.target,documentVersion:h.documentVersion,conflictPolicy:"compare-and-swap",edits:De}})}finally{m-=1}}function I_(h){return lu(h.ownerLocator)}function lu(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 oa(h){return h==="VERSION_STALE"?J.VERSION_STALE:h==="INVALID_PARAMS"?J.INVALID_PARAMS:J.INVALID_TARGET}function k_(h){return h==="VERSION_STALE"?J.VERSION_STALE:h==="INVALID_PARAMS"?J.INVALID_PARAMS:h==="INVALID_TARGET"?J.INVALID_TARGET:h.startsWith("MATERIALIZATION_")?J.MATERIALIZATION_REJECTED:J.UNSUPPORTED_OPERATION}async function uu(h){let _={source:h.mutatedSource,files:[]},I=h.routeState.graph,T=h.routeState.pageCompositionProjection;if(!I||!T||T.status!=="supported"||!n.listFiles)return _;let $=T.placementUnitByKey.get(h.placementUnitKey)?.sourceRange;if(!$)return _;let X=[...I.elements.values()].find(V=>V.sourceFile===h.routeState.entryFile&&V.importedFrom&&S(V.sourceRange,$));if(!X?.importedFrom||!X.exportName)return _;let z=E(X.importedFrom),te="components/site/generated/";if(!z.startsWith(te))return _;let W=z.slice(te.length).split("/")[0];if(!W||!/-[0-9a-f]{8}$/i.test(W))return _;let H=`${te}${W}`;if([...I.elements.values()].filter(V=>V.sourceFile===h.routeState.entryFile&&E(V.importedFrom??"")===z).length!==1)return _;let pe=await n.listFiles({maxFiles:5e3,maxDepth:32}),Ne=Array.isArray(pe)?pe:pe.files;if(!Array.isArray(pe)&&pe.truncated)return _;let ce=Ne.map(({path:V})=>V).filter(V=>V===H||V.startsWith(`${H}/`));if(ce.length===0||!ce.includes(z))return _;for(let{path:V}of Ne)if(!(V===h.routeState.entryFile||V===H||V.startsWith(`${H}/`)))try{if((await n.readFile(V)).includes(W))return _}catch{return _}let De=x(h.routeState.entryFile,z),Ce=$o({source:h.mutatedSource,moduleSpecifier:De,imports:X.exportName==="default"?[{kind:"default"}]:[{kind:"named",imported:X.exportName}]});return Ce.ok?Ce.source.includes(W)?{source:Ce.source,files:[]}:{source:Ce.source,files:ce.sort((V,ee)=>V.localeCompare(ee))}:_}async function __(h){if(n.getFileInfo){for(let X of h)if(await n.exists(X.path)&&await n.getFileInfo(X.path)===null)return{ok:!1,errorCode:"invalid-params",message:`Source edit path must resolve to a regular non-symbolic-link file: ${X.path}`,details:{path:X.path}}}for(let X of h){if(X.operation!=="upsert"||!/^(?:src\/)?app\/globals\.css$/i.test(X.path))continue;let z=await n.exists(X.path)?await Au(n,X.path):null;if(z?.ok){let te=JM(z.content,X.content);if(!te.ok)return{ok:!1,errorCode:"invalid-params",message:te.message,details:{path:X.path,code:te.code}}}}let _=R_(h);if(_.length===0)return{ok:!0};let I=pB(n,h),T=new Map,j=(X,z)=>{let te=T.get(X);if(te?.source===z)return te.result;let W=_e(X,z);return T.set(X,{source:z,result:W}),W},$;try{$=await Fv(_,async X=>{let z=i.get(X);return z?[...(await K(z.entryFile,await I.readFile(z.entryFile),I,{validationOnly:!0,parseModule:j,validatedImports:f.getImports})).parsedModules.values()]:[]})}catch(X){return{ok:!1,errorCode:"ast-error",message:`Source edit preflight failed: ${Xt(X)}`,details:{compositionKeys:_}}}for(let X of $)f.remember(X);return{ok:!0}}function R_(h){return h.map(I=>I.path).some(tI)?[...i.keys()]:[]}function du(h,_,I,T){let j=Vs(_);return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:j,message:I,...T?{details:T}:{}}}}async function fu(h){let _=[];for(let I of new Set(h))_.push(await C_(I));return _}async function C_(h){if(!(typeof n.exists=="function"?await n.exists(h):!0))return{file:h,content:"",version:Math.max(0,D(h)),exists:!1};let I=await n.readFile(h);return{file:h,content:I,version:Math.max(1,D(h)),exists:!0,sha256:Ae(I)}}async function kg(h,_,I,T){if(!e.historyStore)return null;let j=new Map(_.map(z=>[z.file,z])),$=new Map(I.map(z=>[z.file,z])),X=[...new Set([...j.keys(),...$.keys()])].sort().map(z=>{let te=j.get(z),W=$.get(z);return{path:z,preDigest:te?.exists===!1||!te?null:Ae(te.content),postDigest:W?.exists===!1||!W?null:Ae(W.content)}});return{schemaVersion:2,transactionId:`${h}:${T.expectedIndexDigest}`,operationId:h,phase:"prepared",historyTransition:T,files:X}}async function _g(h){return!h||!e.historyStore||await e.historyStore.writeTransactionJournal(h),h}async function Lo(h){h&&e.historyStore&&await e.historyStore.clearTransactionJournal(h.transactionId)}async function pu(h,_){let I=[];try{for(let T of h)await Rg(T),typeof n.bumpVersion=="function"&&n.bumpVersion(T.file),I.push(T.file)}catch(T){let j=await P_(_.filter($=>I.includes($.file)));return j.ok?{ok:!1,reason:`Writeback failed and committed files were restored: ${Xt(T)}`,rolledBack:!0}:{ok:!1,reason:`Writeback failed, then rollback failed for ${j.failedFiles.join(", ")}: ${Xt(T)}`,rolledBack:!1}}return{ok:!0,snapshots:h.map(N_)}}async function Rg(h){if(h.exists===!1){await n.deleteFile(h.file);return}await n.writeFile(h.file,h.content)}async function P_(h){let _=[];for(let I of h)try{await Rg(I),typeof n.bumpVersion=="function"&&n.bumpVersion(I.file)}catch{_.push(I.file)}return _.length===0?{ok:!0}:{ok:!1,failedFiles:_}}function N_(h){let _=h.exists!==!1;return{file:h.file,content:_?h.content:"",version:h.version,exists:_,..._?{sha256:Ae(h.content)}:{}}}async function Er(h){return y.runExclusive(()=>A_(h))}async function A_(h){let _=h.filePlan.edits.map(V=>V.file),I=o.resolveSelector(h.request.composition),T=I.context,j=h.historyPolicy==="none"?void 0:{initiatingComposition:T,affectedCompositions:Ue(_)},$=await fu(_),X=new Map($.filter(V=>V.exists!==!1).map(V=>[V.file,V.content])),z=Pg(),te=new Map(d),W=new Set(g),H=new Set([...i.values()].filter(V=>h.filePlan.edits.some(ee=>ee.operation==="delete"&&ee.file===V.entryFile)).map(V=>V.key)),ie=h.filePlan.edits.map(V=>V.operation==="delete"?{file:V.file,content:"",version:0,exists:!1}:{file:V.file,content:V.content,version:0,exists:!0,sha256:Ae(V.content)}),pe={operationId:h.filePlan.operationId,intents:h.filePlan.edits.map(V=>V.operation==="delete"?{kind:"delete",path:V.file}:{kind:V.operation==="create-only"?"create-only":"upsert",path:V.file,content:V.content})},Ne=null,ce=!1,De=await Il({overlay:X,exists:V=>n.exists(V),plan:pe,buildCandidate:async({plan:V})=>({plan:V}),prepareHistory:async()=>{let V=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:$,postSnapshots:ie,...h.selectionRef?{selectionRef:h.selectionRef}:{},...h.output?{output:h.output}:{},...j?{provenance:j}:{}}),ee=V?.historyTransition?V.historyTransition:e.historyStore?QM(await e.historyStore.readIndex()):null;if(e.historyStore&&!ee)throw new Error("Durable history did not provide an exact index transition.");return Ne=await kg(h.request.id,$,ie,ee),Ne=await _g(Ne),{history:V,historyTransition:ee}},reverify:async()=>{},writeCandidate:async()=>{let V=await u.executeFilePlan(h.filePlan);if(!V.ok)throw new Al(V);return{postSnapshots:await fu(V.affectedFiles),affectedFiles:V.affectedFiles,internalResultVersion:V.resultVersion}},validateCandidate:async({candidate:V,receipt:ee})=>{let xe=await F(ee.affectedFiles,{changed:!0,minimumVersion:ee.internalResultVersion,publish:!1,excludedCompositionKeys:H});if(xe.failedRoutes.length>0)throw new No(xe.failedRoutes);let Oe=Ag(z,xe.candidateRouteStates??[]),Me=Ng(Oe,I.key);return{...V,rebuild:xe,routeSnapshots:Oe,resultVersion:Me,...Zv(h.selectionRef,Oe.map(ut=>ut.state.document))?{selectionRef:Zv(h.selectionRef,Oe.map(ut=>ut.state.document))}:{}}},publishCandidate:async({candidate:V,history:ee,receipt:xe})=>{ee?.history&&(await l.publishPrepared(ee.history),ce=!0);let Oe=V.resultVersion??xe.internalResultVersion;return{composition:T,requestId:h.request.id,kind:h.request.kind,target:h.request.target,ok:!0,resultVersion:Oe,affectedFiles:xe.affectedFiles,fileChanges:xe.postSnapshots.map(Me=>({path:Me.file,operation:Me.exists===!1?"delete":"upsert"})),...h.output?{output:h.output}:{},...V.selectionRef?{selectionRef:V.selectionRef}:{}}},swapCandidate:({candidate:V,receipt:ee})=>{V.routeSnapshots&&ia(V.routeSnapshots),V.rebuild?.candidateSourceCache&&Us(d,V.rebuild.candidateSourceCache),Eg(ee.postSnapshots)},finalizeCandidate:async()=>{await Lo(Ne);for(let V of H)i.delete(V)},emitCommitted:({candidate:V,published:ee})=>{Ni(ee,V.rebuild??{rebuiltRoutes:[],failedRoutes:[]})},rollbackCandidate:async({history:V,receipt:ee})=>{if(ce)throw new Error("history was published before transaction finalization failed");if(ee){let xe=await pu($,ee.postSnapshots);if(!xe.ok)throw new Error(xe.reason)}ia(z),Us(d,te),Sg(W),V?.history&&await l.discardPrepared?.(V.history),await Lo(Ne)}});if(De.ok)return De.published;if(De.stage==="precheck"||De.stage==="build")try{await Lo(Ne)}catch(V){let ee=await aa(Xt(V));return q(h.request,ee,"Unable to clear an uncommitted transaction journal.")}if(De.recoveryRequired){let V=await aa(De.reason);return q(h.request,V===J.RECOVERY_PERSIST_FAILED?V:J.ROLLBACK_FAILED,De.reason)}let Ce=De.error;return Ce instanceof Al?{...q(h.request,Vs(Ce.result.errorCode),Ce.result.reason),...Ce.result.affectedFiles?{affectedFiles:Ce.result.affectedFiles}:{}}:Ce instanceof No?q(h.request,J.ROUTE_REBUILD_FAILED,`Route rebuild failed and source was rolled back: ${em(Ce.failedRoutes)}`,{failedRoutes:Ce.failedRoutes}):q(h.request,wg(De.stage),Xt(Ce))}async function Cg(h){return y.runExclusive(async()=>{let _=h==="undo"?await l.prepareUndo():await l.prepareRedo();return _?T_(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:J.INTERNAL_ERROR,message:h==="undo"?"Nothing to undo":"Nothing to redo"}}})}async function T_(h,_){let I=_.entry,T=h==="undo"?I.preSnapshots:I.postSnapshots,j=h==="undo"?I.postSnapshots:I.preSnapshots,$=T.map(ee=>ee.file),{context:X,key:z}=Pn(I,$),te=await fu($),W=new Map(te.filter(ee=>ee.exists!==!1).map(ee=>[ee.file,ee.content])),H=B(z),ie=Pg(),pe=new Map(d),Ne=new Set(g),ce=null,De=!1,Ce,V=await Il({overlay:W,plan:{operationId:`${h}:${I.operationId}`,intents:T.map(ee=>ee.exists===!1?{kind:"delete",path:ee.file}:{kind:"upsert",path:ee.file,content:ee.content})},buildCandidate:async()=>({}),prepareHistory:async()=>(ce=await kg(`${h}:${I.operationId}`,te,T,_.historyTransition),ce=await _g(ce),_),reverify:async()=>{},writeCandidate:async()=>{let ee=await pu(T,j);if(!ee.ok)throw new Error(ee.reason);return{snapshots:ee.snapshots}},validateCandidate:async({candidate:ee})=>{Ce=Ge(I,$);let xe=await F($,{changed:!0,minimumVersion:H+1,publish:!1,affectedCompositionKeys:Ce});if(xe.failedRoutes.length>0)throw new No(xe.failedRoutes);let Oe=Ag(ie,xe.candidateRouteStates??[]),Me=Ng(Oe,z);return{...ee,rebuild:xe,routeSnapshots:Oe,resultVersion:Me}},publishCandidate:async({candidate:ee,history:xe,receipt:Oe})=>{if(!xe)throw new Error("history cursor intent is missing");await l.publishPrepared(xe),De=!0;let Me=ee.resultVersion??H+1;return{composition:X,requestId:h,kind:I.kind,target:I.target,ok:!0,resultVersion:Me,affectedFiles:$,fileChanges:Oe.snapshots.map(ut=>({path:ut.file,operation:ut.exists===!1?"delete":"upsert"})),...I.output?{output:I.output}:{}}},swapCandidate:({candidate:ee,receipt:xe})=>{ee.routeSnapshots&&ia(ee.routeSnapshots),ee.rebuild?.candidateSourceCache&&Us(d,ee.rebuild.candidateSourceCache),Eg(xe.snapshots)},finalizeCandidate:async()=>{await Lo(ce)},emitCommitted:({candidate:ee,published:xe})=>Ni(xe,ee.rebuild??{rebuiltRoutes:[],failedRoutes:[]}),rollbackCandidate:async({history:ee,receipt:xe})=>{if(De)throw new Error("history cursor was published before transaction finalization failed");if(xe){let Oe=await pu(j,xe.snapshots);if(!Oe.ok)throw new Error(Oe.reason)}ia(ie),Us(d,pe),Sg(Ne),ee&&await l.discardPrepared?.(ee),await Lo(ce)}});if(V.ok)return V.published;if(V.stage==="precheck"||V.stage==="build")try{await Lo(ce)}catch(ee){let xe=await aa(Xt(ee));return{composition:X,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:H,error:{code:xe,message:"Unable to clear an uncommitted transaction journal."}}}if(V.recoveryRequired){let ee=await aa(V.reason);return{composition:X,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:H,affectedFiles:$,error:{code:ee===J.RECOVERY_PERSIST_FAILED?ee:J.ROLLBACK_FAILED,message:V.reason}}}return{composition:X,requestId:h,kind:I.kind,target:I.target,ok:!1,resultVersion:H,affectedFiles:$,error:{code:V.error instanceof No?J.ROUTE_REBUILD_FAILED:wg(V.stage),message:Xt(V.error),...V.error instanceof No?{details:{failedRoutes:V.error.failedRoutes}}:{}}}}function Pg(){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 Ng(h,_){return h.find(T=>T.key===_)?.state.graph?.version??o.initialVersions.get(_)??0}function Ag(h,_){let I=new Map(h.map(T=>[T.key,T]));for(let T of _)I.set(T.key,T);return[...I.values()]}function ia(h){for(let _ of i.values())A(_);for(let _ of h){let I={..._.state,dependencyFiles:new Set(_.state.dependencyFiles),fileVersions:new Map(_.state.fileVersions)};i.set(_.key,I),R(I,I.dependencyFiles)}}async function sa(h){let _=i.get(h);if(!_)throw new Error(`Composition not found: ${h}`);if(_.graph)return;let I=await n.readFile(_.entryFile);await ge(h,I)}function Do(h,_){let I=i.get(o.resolveSelector(_).key)??null;return!I||!Tg(I,h)?null:I}function Tg(h,_){if(h.documentIndex?.entriesByKey.has(_)||h.graph?.elements.has(_))return!0;let I=qt(_);return I&&I!==_?h.graph?.elements.has(I)===!0:!1}function q(h,_,I,T){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:_,message:I,...T?{details:T}:{}}}}function wg(h){return h==="validate"?J.ROUTE_REBUILD_FAILED:h==="publish"?J.HISTORY_COMMIT_FAILED:J.WRITE_IO_ERROR}async function aa(h){if(p=!0,!l.markRecoveryRequired)return J.RECOVERY_REQUIRED;try{return await l.markRecoveryRequired(h),J.RECOVERY_REQUIRED}catch{return J.RECOVERY_PERSIST_FAILED}}function w_(h){let I=h.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join("").replace(/^[^a-zA-Z_$]+/,"");return I?`Prefab${I}`:"GeneratedPrefab"}function mu(h){return h==="VERSION_STALE"?J.VERSION_STALE:h==="CROSS_PAGE_MOVE_UNSUPPORTED"?J.CROSS_PAGE_MOVE_UNSUPPORTED:J.UNSUPPORTED_OPERATION}async function Og(h){if(h.target.kind==="route"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await sa(I.key),I):q(h,J.ROUTE_NOT_FOUND,"Composition not found for route target.")}if(h.target.kind==="page-unit"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await sa(I.key),I):q(h,J.ROUTE_NOT_FOUND,"Composition not found for page-unit target.")}if(h.target.kind==="page-block"){let I=i.get(o.resolveSelector(h.target.composition).key)??null;return I?(I.graph||await sa(I.key),I):q(h,J.ROUTE_NOT_FOUND,"Composition not found for page-block target.")}if(h.target.kind!=="node")return q(h,J.UNSUPPORTED_OPERATION,`${h.kind} source target execution is not implemented yet.`);let _=i.get(o.resolveSelector(h.composition).key)??null;return _?(_.graph||await sa(_.key),Tg(_,h.target.key)?_:q(h,J.NODE_NOT_FOUND,`Target key not found: ${h.target.key}`)):q(h,J.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,_){let I=o.register({context:h,entryFile:_}),T=i.get(I.key);if(T?.entryFile===_)return;T&&A(T);let j=Yv(I.context,_);i.set(I.key,j),R(j,j.dependencyFiles),r.emit({type:"graph-invalidated",composition:I.context})},unregisterComposition(h){let _=o.resolveSelector(h),I=i.get(_.key);I&&(A(I),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),I=i.get(_.key);if(!I)throw new Error(`Composition not registered: ${_.key}`);if(I.graph)t="ready";else{t="building";try{let T=await n.readFile(I.entryFile);await ge(_.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:Xt(T)}),T}}},getDocument(h){let _=o.resolveSelector(h),I=i.get(_.key);if(!I)throw new Error(`Composition not registered: ${_.key}`);if(!I.document)throw new Error(`Composition not built: ${_.key}`);return I.document},async getHistoryStatus(){await b;let h=await l.getStatus?.();return h?{...h,recoveryRequired:p}:{canUndo:!1,canRedo:!1,undoDepth:0,redoDepth:0,recoveryRequired:p}},getObjectEditContext(h,_,I){let T=Do(h,_),j=qt(h)??h;if(T?.graph&&T.topology&&T.capabilities&&T.detailProjections){let $=T.detailProjections.get(j);if($){let X=T.graph.elements.get(j);if(!X)throw new Error(`Key not found: ${h}`);let z=iB(h,j,I),te=new Map;if($.isRepeat&&z?.instanceIndex!==void 0)for(let ie of X.attributes??[])te.set(ie.name,Np({file:X.sourceFile,source:d.get(X.sourceFile)??"",element:X,propertyName:ie.name,selectionRef:z,graph:T.graph,sources:d}));let W=pv({element:X,graph:T.graph,source:d.get(X.sourceFile),documentVersion:T.graph.version,selectionRef:I,isRepeat:$.isRepeat,propertyProvenance:$.propertyProvenances,repeatTargets:te}),H=hv(j,T.graph,T.topology,T.capabilities,$.textSources,$.provenances,$.dynamicData,W);return h===j?H:Uv(H,h,T.document??null,T.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getRenderDetail(h,_){let I=Do(h,_),T=qt(h)??h;if(I?.graph&&I.topology&&I.capabilities&&I.detailProjections){let j=I.detailProjections.get(T);if(j){let $=gv(T,I.graph,I.topology,I.capabilities,j.textSources,j.writeTarget,j.provenances,j.conditional,j.componentSemantic,j.styleSource,j.dynamicData);return h===T?$:$v($,h,I.document??null,I.documentIndex?.entriesByKey)}}throw new Error(`Key not found: ${h}`)},getClassNameSource(h,_){let I=Do(h,_),T=qt(h)??h;if(!I?.graph)throw new Error(`Key not found: ${h}`);let j=I.graph.elements.get(T);if(!j)throw new Error(`Key not found: ${h}`);let $=d.get(j.sourceFile);if($===void 0)throw new Error(`Source not loaded: ${j.sourceFile}`);return Gu({key:T,route:{composition:I.composition,routeId:I.routeId,graph:I.graph,source:$}})},refreshSourceForKey:g_,async execute(h){if(await b,p)return q(h,J.RECOVERY_REQUIRED,"The edit engine requires explicit recovery before accepting mutations.");if(h.kind==="source-edit")return h_(h);if(h.kind==="insert-page-resource")return y_(h);if(h.kind==="delete-page-source")return b_(h);let _=await Og(h);if("ok"in _)return _;await Ig(h);let I=await Og(h);if("ok"in I)return I;let T=I;if(h.target.kind==="page-unit"){let H=h;return h.kind==="insert-child"||h.kind==="replace-node"?x_(H,T):h.kind==="move-node"||h.kind==="remove-node"?S_(H,T):q(h,J.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 H=h;return h.kind==="insert-child"||h.kind==="replace-node"?E_(H,T):h.kind==="move-node"||h.kind==="remove-node"?v_(H,T):q(h,J.UNSUPPORTED_OPERATION,"Page-block operation is not supported by the current structural transaction.")}let $=h.params,X=h.target.kind==="node"?h.target.key:null;if($.kind==="move-node"&&"kind"in $.target&&$.target.kind==="source-sibling"){let H=$.target,ie=X?T.document?.entries.find(ee=>ee.key===X):null,pe=T.document?.entries.find(ee=>ee.key===H.anchorKey),Ne=ie?.pageCompositionActionScope,ce=Ne?.kind==="source-siblings"?Ne.siblingKeys:null,De=ce?.indexOf(ie?.key??"")??-1,Ce=ce?.indexOf(H.anchorKey)??-1,V=H.relation==="before"?De-1:De+1;if(!ie||!pe||!ce||De<0||Ce!==V||pe.pageCompositionActionScope?.kind!=="source-siblings"||pe.pageCompositionActionScope.siblingKeys.length!==ce.length||pe.pageCompositionActionScope.siblingKeys.some((ee,xe)=>ee!==ce[xe])||!ie.operationSummary.canMove)return q(h,J.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:G(h),error:{code:h.target.kind==="route"?J.ROUTE_NOT_FOUND:J.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 z=IB(T,T.graph,T.capabilities,d,i),te=await new Zc(z).plan(h);if(!te.ok)return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:Vs(te.errorCode),message:te.reason}};let W=te.plan;if(W.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:G(h),affectedFiles:[]}:{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:J.PLAN_FAILED,message:"Planner could not generate a valid execution plan"}};m+=1;try{if(W.steps.some(ie=>ie.type==="invoke-external-adapter")){let ie=await u.execute(W);if(!ie.ok)return q(h,Vs(ie.errorCode),ie.reason);let pe={composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!0,resultVersion:Math.max(G(h),ie.resultVersion),affectedFiles:ie.affectedFiles,...ie.selectionRef?{selectionRef:ie.selectionRef}:{}};return Ni(pe,{rebuiltRoutes:[],failedRoutes:[]}),pe}let H=await u.prepareRewritePlan(W);return H.ok?await Er({request:h,filePlan:H.filePlan,...H.selectionRef?{selectionRef:H.selectionRef}:{}}):q(h,Vs(H.errorCode),H.reason)}catch(H){return{composition:o.resolveSelector(h.composition).context,requestId:h.id,kind:h.kind,target:h.target,ok:!1,resultVersion:G(h),error:{code:J.INTERNAL_ERROR,message:Xt(H)}}}finally{m-=1}},async undo(h){if(await b,p)return{composition:o.entries[0].context,requestId:"undo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:B(o.entries[0].key),error:{code:J.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting undo."}};m+=1;try{return await Cg("undo")}finally{m-=1}},async redo(h){if(await b,p)return{composition:o.entries[0].context,requestId:"redo",kind:"update-text",target:{kind:"node",key:""},ok:!1,resultVersion:B(o.entries[0].key),error:{code:J.RECOVERY_REQUIRED,message:"The edit engine requires explicit recovery before accepting redo."}};m+=1;try{return await Cg("redo")}finally{m-=1}},notifyFileChanged(h){bg([h])},getAffectedCompositions(h){return ue(h)},subscribe(h){return r.subscribe(h)}}}function hB(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function yB(e,t,n,r){let o=new Map,i=new Map,s=(d,f,g)=>{let m=d.get(f)??new Set,p=m.size;return m.add(g),d.set(f,m),m.size!==p},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(m=>m.members.some(p=>p.sourceRange!==null&&Ks(d.sourceRange,p.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=qt(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&&Ks(g.sourceRange,n.container.sourceRange)&&u){d.pageCompositionUnitKey=u.placementUnitKey;continue}let y=n.placements.find(b=>b.members.some(E=>E.sourceRange!==null&&(Ks(g.sourceRange,E.sourceRange)||vB(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 p=i.get(g.sourceFile);p?.size===1&&(d.pageCompositionUnitKey=p.values().next().value)}bB(e,t,n,r)}function bB(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(m=>m.sourceRange!==null&&Ks(f.sourceRange,m.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 m of l){let p=s.get(m.owner)??s.get(m.ownerDefault)??0;if(!p)continue;let y=s.get(m.target)??0,b=Math.min(2,y+p);b!==y&&(s.set(m.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!==(qt(f.key)??f.key))continue;let m=r.get(g.sourceFile);if(!m)continue;let p=Pe(m.ast,{kind:"jsx-node",strategy:"source-range",sourceRange:g.sourceRange});if(!p.ok||!p.match.path.isJSXElement())continue;let y=p.match.path,b=y.parentPath;if(!b||!b.isJSXFragment()&&!(b.isJSXElement()&&it(b))){u(g)===1&&Qv(y)&&(f.pageCompositionActionScope={kind:"route-unit"});continue}if(!Qv(b))continue;let E=d.get(b.node)??[];E.push({entry:f,element:g,parentPath:b}),d.set(b.node,E)}for(let f of d.values()){let g=f[0];if(!g)continue;let m=g.entry.pageCompositionUnitKey,p=[],y=!!(m&&u(g.element)===1);for(let E of g.parentPath.node.children){if(xB(E))continue;if(!EB(E)){y=!1;break}let x=[...t.elements.values()].find(v=>v.sourceFile===g.element.sourceFile&&v.componentName===g.element.componentName&&Ks(v.sourceRange,SB(E))),S=x?o.get(x.identity.key):null;if(!x||!S||S.parentKey||S.pageCompositionUnitKey!==m||u(x)!==1){y=!1;break}p.push(S)}if(!y||p.length!==f.length||f.some(({entry:E})=>!p.some(x=>x.key===E.key)))continue;if(p.length===1){p[0].pageCompositionActionScope={kind:"route-unit"};continue}if(p.length<2)continue;let b=p.map(E=>E.key);for(let E of p)E.pageCompositionActionScope={kind:"source-siblings",siblingKeys:b}}}function Qv(e){let t=e.parentPath;return!!(t?.isReturnStatement?.()||t?.isArrowFunctionExpression?.()&&t.node.body===e.node)}function xB(e){return!!(e&&typeof e=="object"&&e.type==="JSXText"&&!(e.value??"").trim())}function EB(e){return!!(e&&typeof e=="object"&&e.type==="JSXElement")}function SB(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 Ks(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function vB(e,t){return eI(e.startLine,e.startColumn,t.startLine,t.startColumn)<=0&&eI(e.endLine,e.endColumn,t.endLine,t.endColumn)>=0}function eI(e,t,n,r){return e!==n?e-n:t-r}function IB(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(p=>{let y=qt(p)??p,b=t.elements.get(y);return b?l(p,b):null}).filter(p=>p!==null);let m=t.elements.get(d.baseKey);return m?m.childKeys.map(p=>{let y=t.elements.get(p);return y?l(p,y):null}).filter(p=>p!==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:Gu({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 Qp(e.detailProjections?.get(f.baseKey)?.textTargets.get(d)??null,f.repeatIndex)},async getElementPropertyWriteTarget(u,d){let f=c(u);return Qp(e.detailProjections?.get(f.baseKey)?.elementPropertyTargets.get(d)??null,f.repeatIndex)},getPropertyState(u,d,f){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 b=m.attributes?.find(E=>E.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:m.sourceFile,sourceRange:b.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,f){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 p=f?{...f,key:g.baseKey}:g.repeatIndex!==null?{key:g.baseKey,instanceIndex:g.repeatIndex}:void 0;return Np({file:m.sourceFile,source:r.get(m.sourceFile)??"",element:m,propertyName:d,selectionRef:p,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=WM(u);return d?{baseKey:d.baseKey,repeatIndex:jv(e.document??null,u,d.baseKey,e.documentIndex)??Bv(d)}:{baseKey:u,repeatIndex:null}}function l(u,d){let f=qt(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(m=>({name:m.name,value:m.value,source:m.source?{expression:m.source.expression,base:m.source.base,path:m.source.path.map(p=>({...p}))}:null,resolvedValue:m.resolvedValue}))}}}var kB={"stale-version":J.VERSION_STALE,"capability-denied":J.CAPABILITY_REJECTED,"invalid-params":J.INVALID_PARAMS,"locator-miss":J.LOCATOR_FAILED,"route-not-found":J.ROUTE_NOT_FOUND,"unsupported-operation":J.UNSUPPORTED_OPERATION,"invalid-target":J.INVALID_TARGET,"ast-error":J.AST_PARSE_ERROR,"writeback-failed":J.WRITE_IO_ERROR,"rollback-failed":J.RECOVERY_REQUIRED,unknown:J.INTERNAL_ERROR};function Vs(e){return kB[e]}function Xt(e){return e instanceof Error&&e.message?e.message:String(e)}function tI(e){return/\.(?:[cm]?[jt]sx?|css|scss|sass|mdx|json)$/i.test(e)}function _B(e){let t=Ao(e);if(!ZM.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=>qM.map(a=>`${s}/${a}`))}function RB(e){let n=Ao(e).startsWith("src/app/")?"src/app":"app";return[`${n}/globals.css`,`${n}/global.css`]}function CB(e){return oI(e,/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+\.css(?:\?[^"']*)?)["']/g)}function PB(e){return oI(e,/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)}function oI(e,t){let n=[];for(let r of e.matchAll(t)){let o=iI(r[1]??"");o&&n.push(o)}return n}function nI(e,t){let n=iI(t);return!n||n.startsWith("tailwindcss")||n.startsWith("http:")||n.startsWith("https:")?null:n.startsWith("@/")?Ao(`src/${n.slice(2)}`):n.startsWith("./")||n.startsWith("../")?Ao(`${NB(e)}/${n}`):n.startsWith("/")?Ao(n.slice(1)):nm(n)?Ao(n):null}function iI(e){return e.split(/[?#]/,1)[0]?.trim()??""}function nm(e){return/\.css$/i.test(e)}function NB(e){let t=Ao(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function AB(e){return Array.from(new Set(e))}function Ao(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 TB(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 wl=class{constructor(t){this.options=t,this.fileSystem=new Oi(t.files),this.engine=this.createEngine(this.fileSystem)}get status(){return this.engine.status}initializeComposition(t){return this.engine.initializeComposition(t)}getDocument(t){return ma(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 ga(r?this.engine.getObjectEditContext(t,n,r):this.engine.getObjectEditContext(t,n))}getClassNameSource(t,n){return this.engine.getClassNameSource(t,n)}getSourceTree(t){return ba(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}getSourceFile(t){return xa(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.options.compositions.map(n=>n.entryFile)})}resolveSourceLocation(t){return Ea(t,this.engine.getRenderDetail(t.key,t.composition))}async planOperation(t){let n=OB.safeParse(t);if(!n.success)return{result:pa(t,n.error.issues.map(i=>i.message))};let r=new Oi(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:ao(i)},a=r.getChangedFiles();if(a.length===0)return{result:s};let c=FB.parse({siteId:t.siteId,baseSnapshotId:t.baseSnapshotId,operationId:t.id,reason:`site-edit:${t.kind}`,patches:a.map(l=>LB(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 Tl({projectRoot:"/snapshot",fileSystem:t,compositions:this.options.compositions,onEvent:r&&this.options.onEvent?o=>{let i=ha(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 LB(e,t){return e.after===void 0?{path:e.path,operation:"delete",...t||e.before===void 0?{}:{expectedHash:Ae(e.before)}}:{path:e.path,operation:e.before===void 0?"create":"update",...t||e.before===void 0?{}:{expectedHash:Ae(e.before)},fullContent:e.after}}function DB(e){return new wl(e)}import{SiteEditOperationRequestSchema as jB}from"@vcp-dev/contracts";import Bn from"node:fs/promises";import zt from"node:path";import{SITE_EDIT_SOURCE_ALLOWED_DIRS as MB,SITE_EDIT_SOURCE_ALLOWED_ROOT_FILES as BB}from"@vcp-dev/contracts";var Ol=class{constructor(t){this.options=t,this.fileSystem=this.createFileSystem(),this.engine=Tl({...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 ba(this.fileSystem,{composition:this.engine.getCompositionContext(t),routeEntryFiles:this.engine.getCompositionEntryFiles()})}getSourceFile(t){return xa(this.fileSystem,t,{composition:this.engine.getCompositionContext(t.composition),routeEntryFiles:this.engine.getCompositionEntryFiles()})}resolveSourceLocation(t){return Ea(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 Bn.readFile(zt.join(n,r),"utf8")},async readFileBytes(r){return Bn.readFile(zt.join(n,r))},async getFileInfo(r){let o=zt.join(n,...r.split("/"));try{let i=await Bn.lstat(o);return!i.isFile()||i.isSymbolicLink()?null:{path:r,sizeBytes:i.size}}catch{return null}},async writeFile(r,o){await ja(zt.join(n,r),o)},async createExclusive(r,o){let i=zt.join(n,r);await Bn.mkdir(zt.dirname(i),{recursive:!0});let s=await Bn.open(i,"wx");try{await s.writeFile(o,"utf8")}catch(a){throw await s.close(),await Bn.rm(i,{force:!0}),a}await s.close()},async deleteFile(r){await Bn.rm(zt.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=zt.join(n,i),a=zt.dirname(zt.join(n,o));for(;a!==s&&a.startsWith(`${s}${zt.sep}`);){try{await Bn.rmdir(a)}catch(c){if(c instanceof Error&&"code"in c&&c.code==="ENOENT"){a=zt.dirname(a);continue}break}a=zt.dirname(a)}},async exists(r){try{return await Bn.access(zt.join(n,r)),!0}catch{return!1}},async listFiles(r={}){let o=r.roots??[...BB,...MB],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 m=zt.join(n,...d.split("/")),p;try{p=await Bn.lstat(m)}catch{return}if(p.isSymbolicLink())return;if(p.isFile()){let b=p.ino>0?`${String(p.dev)}:${String(p.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+p.size>r.maxTotalBytes){a.add("max-total-bytes");return}b&&s.add(b),f.push({path:d,sizeBytes:p.size}),c+=p.size;return}if(!p.isDirectory())return;if(r.maxFiles!==void 0&&f.length>=r.maxFiles){a.add("max-files");return}let y=await Bn.readdir(m,{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 rm(e){return new Ol(e)}var Fl=class{constructor(t){this.options=t,this.listeners=new Set,this.engine=rm({projectRoot:t.projectRoot,fileSystem:t.fileSystem,compositions:t.compositions,onEvent:n=>{let r=ha(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:ma(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:ga(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=jB.safeParse(r);if(!o.success)return pa(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:ao(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:ao(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:ao(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 $B(e){return new Fl(e)}import{GeneratedSiteCapabilitiesSchema as zB}from"@vcp-dev/contracts";import{GeneratedSiteCapabilitiesSchema as UB}from"@vcp-dev/contracts";function xi(e){let t=KB(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)?br(e.node,"platform-managed","controlled platform package"):t?JB(e.node.path,t)?br(e.node,"host-public","declared Starter runtime dependency"):br(e.node,"unsupported-external-private","external package is not declared by the trusted Starter contract"):br(e.node,"unknown","trusted host capability contract is invalid"):sI(e.node.path,n)?br(e.node,"platform-managed","controlled platform path"):t?cI(e.node.path,t.generated_sections_path)?br(e.node,"private","site-generated section path"):sI(e.node.path,t.public_paths)?br(e.node,"host-public","declared Starter public path"):br(e.node,"private","site-local file outside host public paths"):br(e.node,"unknown","trusted host capability contract is invalid")}function VB(e){return e.nodes.map(t=>xi({...e,node:t})).sort((t,n)=>t.path===n.path?t.ownership.localeCompare(n.ownership):t.path.localeCompare(n.path))}function br(e,t,n){return{path:e.path,kind:e.kind,ownership:t,reason:n}}function KB(e){let t=UB.safeParse(e);return t.success?t.data:null}function JB(e,t){return t.runtime_dependencies.some(({name:n})=>e===n||e.startsWith(`${n}/`))}function sI(e,t){return t.some(n=>cI(e,n))}function cI(e,t){let n=XB(t),r=lI(e);return n.endsWith("/*")?r.startsWith(n.slice(0,-1)):aI(r)===aI(n)}function XB(e){return lI(e.split("#",1)[0]??e)}function lI(e){return e.replace(/^@\//u,"").replace(/\\/g,"/").replace(/^\.\//u,"")}function aI(e){return e.replace(/\.(?:jsx?|tsx?|json)$/iu,"")}function Ll(e){let t=zB.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=xi({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=HB(n).sort(WB);return{complete:o.length===0,nodes:r.sort(GB),edges:[...e.closure.edges].sort(YB),errors:o}}function HB(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function WB(e,t){return pn(e.path,t.path)||pn(e.code,t.code)||pn(e.specifier??"",t.specifier??"")||pn(e.message,t.message)}function GB(e,t){return pn(e.path,t.path)||pn(e.kind,t.kind)||pn(e.ownership,t.ownership)||pn(e.status,t.status)}function YB(e,t){return pn(e.from,t.from)||pn(e.target??"",t.target??"")||pn(e.specifier??"",t.specifier??"")||pn(e.kind,t.kind)||pn(e.resolution,t.resolution)}function pn(e,t){return e<t?-1:e>t?1:0}var uI={helper:"text",tsType:"string"},om={helper:"images",tsType:"MediaItem[]",importName:"MediaItem"},dI={helper:"image",tsType:"MediaItem | null",importName:"MediaItem"},fI=/(gallery|galleries|images|photos|pics|pictures|album|attachments|files|media)$/i;function ZB(e,t,n){switch(e){case"text":case"date":return uI;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"||fI.test(n)?om:dI;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 im(e,t,n){if(n){let r=ZB(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{...fI.test(t)?om:dI};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{...uI}}}function sm(e,t,n={}){let r=`${QB(e)}View`,o=t.filter(l=>l.front_display!=="forbidden").map(l=>{let u={key:qB(l.name)?`${l.name}_field`:l.name,source:l.name,...im(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
15
  `)+`
16
16
  `:`import type { ${i.join(", ")} } from "@/lib/cms/field";
17
17
  `:"",a=o.map(l=>` ${l.key}: ${l.tsType};`).join(`
@@ -36,18 +36,18 @@ export function to${r}(rec: CollectionRecord): ${r} {
36
36
  ${c}
37
37
  };
38
38
  }
39
- `}function Cj(e){return e==="id"||e==="url"||e==="seo"}function Rj(e){return e.replace(/(^|[-_])([a-z0-9])/g,(t,n,r)=>r.toUpperCase())}import{createHash as Tu}from"node:crypto";import{BlockRenderRefSchema as xU,GeneratedSiteCapabilitiesSchema as bU,PORTABLE_AUDITED_PLACEHOLDER_SVG as $g,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Nk,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as EU,SiteEditPageBlockTargetSchema as SU,SiteEditPortableExportResultSchema as IU}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as Pj,SiteIdSchema as Nj,SnapshotIdSchema as Aj}from"@vcp-dev/contracts";async function Lm(e){if(!Nj.safeParse(e.site_id).success||!Aj.safeParse(e.base_snapshot_id).success||!Pj.safeParse(e.target).success)return yr("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!wj(e.composition,e.target.composition))return yr("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(!Om(u))return yr("INVALID_PARAMS","Snapshot contains an unsafe source path.");let p=typeof d=="string"?d:Tj(u,d);p!==null&&(n.set(u,p),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,p))}let r;try{r=Zc({files:n})}catch{return yr("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 yr("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return yr("INVALID_TARGET","The selected composition entry is unavailable.");let s=await ci(o.entryFile,i,async u=>{if(!Om(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=>Om(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return yr("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 yr("INVALID_TARGET","The selected snapshot page composition is unsupported.");let c=Kc({composition:s.graph.composition,entryFile:o.entryFile,graph:s.graph,parsedModules:s.parsedModules,projection:a.projection});if(c.diagnostics.length>0)return yr("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=Ts({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?{...yr("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...xi(l,e.target,e.document_version,e.selection_ref),index:l}}function Tj(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 Om(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function wj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function yr(e,t){return{ok:!1,code:e,message:t}}import{createHash as zj}from"node:crypto";import ua from"node:path";import Bm from"@babel/generator";import{parse as Hj}from"@babel/parser";import Wj from"@babel/traverse";import*as M from"@babel/types";import{SiteEditSourcePathSchema as Gj}from"@vcp-dev/contracts";import*as an from"@babel/types";var Bv=[".tsx",".ts",".jsx",".js"],Oj=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 br(e){let t=Dj(e.files),n=$v(e.max_depth??32,"max_depth"),r=$v(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(Jv).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(!ji(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 T=o.includes(f.path)?"SOURCE_ENTRY_UNRESOLVED":$i(f.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";po(i,{path:f.path,kind:$i(f.path)?"asset":"source",depth:f.depth,status:"unresolved"}),a.push({code:T,path:f.path,message:`Portable source closure could not read ${f.path}.`});continue}let x=$i(f.path)?"asset":"source";if(x==="asset"){let T=Mj(f.path,y);po(i,{path:f.path,kind:x,depth:f.depth,status:T?"parse-failed":"complete"}),T&&a.push(T);continue}let E=Dm(y),b=we(f.path,E);if(!b.ok){po(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=Fj(b.module.ast),I=!1;for(let T of S){let C=Lj({from:f.path,depth:f.depth,reference:T,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)}po(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(Jj),g=Uj(s).sort(Kj),m=Vj(a).sort(Xj);return{entry_files:o.sort(xr),nodes:p,edges:g,errors:m,complete:m.length===0,budget:{max_depth:n,max_nodes:r}}}function Lj(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=jj(t.specifier);return ji(o,e.discovered,e.maxNodes)?(po(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=Mm(e.from,t.specifier);if(Kv(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}.`}),ji(n,e.discovered,e.maxNodes)?po(e.nodes,{path:n,kind:$i(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=Vv(e.from,t.specifier,e.files);if(!r){let o=$i(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}.`}),ji(n,e.discovered,e.maxNodes)?po(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=$i(r)?"asset":"source";return ji(r,e.discovered,e.maxNodes)?po(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 ji(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 Fj(e){let t=[];for(let n of e.program.body)an.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):an.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):an.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return Fm(e.program,n=>{if(an.isCallExpression(n)&&an.isImport(n.callee)){let r=n.arguments[0];an.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}an.isTSImportType(n)&&t.push({specifier:an.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),$j(t)}function Fm(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)Uv(r)&&Fm(r,t);else Uv(n)&&Fm(n,t)}function wt(e,t,n){let r=Mm(e,t);return!mt(t)||Kv(e,t,r)?null:Vv(e,t,n)}function Vv(e,t,n){let r=Mm(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(Bj(o))return null;for(let i of Bv){let s=`${o}${i}`;if(n.has(s))return s}for(let i of Bv){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function Mm(e,t){let n=nr(e,t);return Jv(n)}function Jv(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 Dj(e){return e instanceof Map?e:new Map(Object.entries(e))}function Dm(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function Mj(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(Dm(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(Dm(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function po(e,t){let n=e.get(t.path);(!n||jv(t.status)>jv(n.status))&&e.set(t.path,t)}function ji(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function jv(e){return e==="complete"?1:0}function $i(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&Oj.has(n)}function Bj(e){return/\.[a-z0-9]+$/iu.test(e)}function jj(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function $j(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 Uj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Vj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Jj(e,t){return xr(e.path,t.path)||xr(e.kind,t.kind)}function Kj(e,t){return xr(e.from,t.from)||xr(e.target??"",t.target??"")||xr(e.specifier??"",t.specifier??"")||xr(e.kind,t.kind)}function Xj(e,t){return xr(e.path,t.path)||xr(e.code,t.code)||xr(e.specifier??"",t.specifier??"")}function xr(e,t){return e<t?-1:e>t?1:0}function $v(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function Uv(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Kv(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 jm=Wj,Km=typeof jm=="function"?jm:jm.default,Yj=typeof Bm=="function"?Bm:Bm.default,Xv=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),Yv=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),Zv=new Set(["Boolean","Number","String"]),Zj=new Set(["assign","values","entries"]);function Xm(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 Ht("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!Gj.safeParse(t.source_file).success)return Ht("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 Ht("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Ht("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 Ht("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=iu(n,t.source_file);return i===null||!Gv(t,i)?Ht("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):nu({entryFile:r,entryContent:i,files:n,selection:t})}let o=iu(n,t.source_file);if(o===null||!Gv(t,o))return Ht("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 nu({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 Ht("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=Zr({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Ht("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,"")}`)};
39
+ `}function qB(e){return e==="id"||e==="url"||e==="seo"}function QB(e){return e.replace(/(^|[-_])([a-z0-9])/g,(t,n,r)=>r.toUpperCase())}import{createHash as iu}from"node:crypto";import{BlockRenderRefSchema as D$,GeneratedSiteCapabilitiesSchema as M$,PORTABLE_AUDITED_PLACEHOLDER_SVG as ag,PORTABLE_BLOCK_LOCAL_ASSET_CHUNK_BYTES as Yk,PORTABLE_BLOCK_LOCAL_ASSET_MAX_BYTES as B$,SiteEditPageBlockTargetSchema as j$,SiteEditPortableExportResultSchema as $$}from"@vcp-dev/contracts";import{SiteEditPageBlockTargetSchema as ej,SiteIdSchema as tj,SnapshotIdSchema as nj}from"@vcp-dev/contracts";async function cm(e){if(!tj.safeParse(e.site_id).success||!nj.safeParse(e.base_snapshot_id).success||!ej.safeParse(e.target).success)return nr("INVALID_PARAMS","Invalid site, snapshot, or page block identity.");if(!oj(e.composition,e.target.composition))return nr("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(!am(u))return nr("INVALID_PARAMS","Snapshot contains an unsafe source path.");let f=typeof d=="string"?d:rj(u,d);f!==null&&(n.set(u,f),/\.(?:[cm]?[jt]sx?)$/i.test(u)&&t.set(u,f))}let r;try{r=Ac({files:n})}catch{return nr("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 nr("INVALID_TARGET","The requested route/template is absent from this snapshot.");let i=t.get(o.entryFile);if(i===void 0)return nr("INVALID_TARGET","The selected composition entry is unavailable.");let s=await Jo(o.entryFile,i,async u=>{if(!am(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=>am(u)&&t.has(u),{version:e.document_version});if(s.diagnostics.length>0||!s.entryModule)return nr("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=Tn({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 nr("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 nr("INVALID_TARGET","The selected snapshot has unproven page block roots.");let l=ds({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?{...nr("INVALID_TARGET","The selected snapshot block index is incomplete."),index:l}:{...ei(l,e.target,e.document_version,e.selection_ref),index:l}}function rj(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 am(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}function oj(e,t){return e.routeId===t.routeId&&e.templateId===t.templateId}function nr(e,t){return{ok:!1,code:e,message:t}}import{createHash as bj}from"node:crypto";import Js from"node:path";import fm from"@babel/generator";import{parse as xj}from"@babel/parser";import Ej from"@babel/traverse";import*as L from"@babel/types";import{SiteEditSourcePathSchema as Sj}from"@vcp-dev/contracts";import*as Ht from"@babel/types";var pI=[".tsx",".ts",".jsx",".js"],ij=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 or(e){let t=cj(e.files),n=gI(e.max_depth??32,"max_depth"),r=gI(e.max_nodes??512,"max_nodes"),o=[...new Set(e.entry_files.map(bI).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 p of o)if(!(!p||l.has(p))){if(!Ei(p,c,r)){a.push({code:"SOURCE_NODE_BUDGET_EXHAUSTED",path:p,message:"Portable source closure node budget was exhausted."});continue}l.add(p),d.push({path:p,depth:0})}for(;d.length>0;){let p=d.shift();if(u.has(p.path))continue;u.add(p.path);let y=t.get(p.path);if(y===void 0){let N=o.includes(p.path)?"SOURCE_ENTRY_UNRESOLVED":Si(p.path)?"SOURCE_ASSET_UNRESOLVED":"SOURCE_FILE_UNRESOLVED";Wr(i,{path:p.path,kind:Si(p.path)?"asset":"source",depth:p.depth,status:"unresolved"}),a.push({code:N,path:p.path,message:`Portable source closure could not read ${p.path}.`});continue}let b=Si(p.path)?"asset":"source";if(b==="asset"){let N=lj(p.path,y);Wr(i,{path:p.path,kind:b,depth:p.depth,status:N?"parse-failed":"complete"}),N&&a.push(N);continue}let E=um(y),x=_e(p.path,E);if(!x.ok){Wr(i,{path:p.path,kind:b,depth:p.depth,status:"parse-failed"}),a.push({code:"SOURCE_PARSE_FAILED",path:p.path,message:x.diagnostic.message});continue}let S=aj(x.module.ast),v=!1;for(let N of S){let R=sj({from:p.path,depth:p.depth,reference:N,files:t,nodes:i,errors:a,maxDepth:n,maxNodes:r,visited:u,queued:l,discovered:c});s.push(R.edge),R.next&&(R.next.depth>n?v=!0:!u.has(R.next.path)&&!l.has(R.next.path)&&(l.add(R.next.path),d.push(R.next))),R.depthExhausted&&(v=!0)}Wr(i,{path:p.path,kind:b,depth:p.depth,status:v?"depth-exhausted":"complete"}),v&&a.push({code:"SOURCE_DEPTH_EXHAUSTED",path:p.path,message:`Portable source closure reached max_depth=${n} before closing all dependencies.`})}let f=[...i.values()].sort(gj),g=pj(s).sort(hj),m=mj(a).sort(yj);return{entry_files:o.sort(rr),nodes:f,edges:g,errors:m,complete:m.length===0,budget:{max_depth:n,max_nodes:r}}}function sj(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(!pt(t.specifier)){let o=dj(t.specifier);return Ei(o,e.discovered,e.maxNodes)?(Wr(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=dm(e.from,t.specifier);if(xI(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}.`}),Ei(n,e.discovered,e.maxNodes)?Wr(e.nodes,{path:n,kind:Si(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=yI(e.from,t.specifier,e.files);if(!r){let o=Si(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}.`}),Ei(n,e.discovered,e.maxNodes)?Wr(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=Si(r)?"asset":"source";return Ei(r,e.discovered,e.maxNodes)?Wr(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 Ei(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 aj(e){let t=[];for(let n of e.program.body)Ht.isImportDeclaration(n)?t.push({specifier:n.source.value,kind:n.importKind==="type"?"type":"import"}):Ht.isExportNamedDeclaration(n)&&n.source?t.push({specifier:n.source.value,kind:"export"}):Ht.isExportAllDeclaration(n)&&t.push({specifier:n.source.value,kind:"export"});return lm(e.program,n=>{if(Ht.isCallExpression(n)&&Ht.isImport(n.callee)){let r=n.arguments[0];Ht.isStringLiteral(r)?t.push({specifier:r.value,kind:"dynamic"}):t.push({specifier:null,kind:"dynamic"})}Ht.isTSImportType(n)&&t.push({specifier:Ht.isStringLiteral(n.argument)?n.argument.value:null,kind:"type"})}),fj(t)}function lm(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let r of n)hI(r)&&lm(r,t);else hI(n)&&lm(n,t)}function Tt(e,t,n){let r=dm(e,t);return!pt(t)||xI(e,t,r)?null:yI(e,t,n)}function yI(e,t,n){let r=dm(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(uj(o))return null;for(let i of pI){let s=`${o}${i}`;if(n.has(s))return s}for(let i of pI){let s=`${o}/index${i}`;if(n.has(s))return s}return null}function dm(e,t){let n=$n(e,t);return bI(n)}function bI(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 cj(e){return e instanceof Map?e:new Map(Object.entries(e))}function um(e){return typeof e=="string"?e:Buffer.from(e).toString("utf8")}function lj(e,t){if(e.toLowerCase().endsWith(".css")&&/[@\\]|url\s*\(/iu.test(um(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(um(t))}catch{return{code:"SOURCE_ASSET_INVALID",path:e,message:`Portable source closure found invalid JSON asset: ${e}.`}}return null}function Wr(e,t){let n=e.get(t.path);(!n||mI(t.status)>mI(n.status))&&e.set(t.path,t)}function Ei(e,t,n){return t.has(e)?!0:t.size>=n?!1:(t.add(e),!0)}function mI(e){return e==="complete"?1:0}function Si(e){let n=e.replace(/[?#].*$/u,"").split(".").pop()?.toLowerCase();return n!==void 0&&ij.has(n)}function uj(e){return/\.[a-z0-9]+$/iu.test(e)}function dj(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]??e}function fj(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 pj(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}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 rr(e.path,t.path)||rr(e.kind,t.kind)}function hj(e,t){return rr(e.from,t.from)||rr(e.target??"",t.target??"")||rr(e.specifier??"",t.specifier??"")||rr(e.kind,t.kind)}function yj(e,t){return rr(e.path,t.path)||rr(e.code,t.code)||rr(e.specifier??"",t.specifier??"")}function rr(e,t){return e<t?-1:e>t?1:0}function gI(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Portable source closure ${t} must be a positive safe integer.`);return e}function hI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function xI(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 pm=Ej,bm=typeof pm=="function"?pm:pm.default,vj=typeof fm=="function"?fm:fm.default,EI=new Set(["Array","Boolean","Infinity","JSON","Math","NaN","Number","Object","String","undefined"]),_I=new Map([["JSON",new Set(["stringify"])],["Object",new Set(["keys","values","entries","getOwnPropertyNames"])],["Array",new Set(["isArray"])]]),RI=new Set(["Boolean","Number","String"]),Ij=new Set(["assign","values","entries"]);function xm(e){let{selection:t,files:n}=e,r=t.strategy==="extract-jsx"||t.strategy==="collection-container"?t.entry_file:t.source_file;if(!ym(r))return Dt("SOURCE_INPUT_INVALID",r,"The selected Portable entry path is not safe.");if(!Sj.safeParse(t.source_file).success)return Dt("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 Dt("SOURCE_NOT_PORTABLE",t.source_file,"Nested component invocation bindings are not yet a proven independent entry.");if(t.invocation&&!t.invocation.complete)return Dt("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 Dt("SOURCE_INPUT_INVALID",t.entry_file,"A reusable entry must point at the proven selected component source.");let i=jl(n,t.source_file);return i===null||!kI(t,i)?Dt("SOURCE_ENTRY_NOT_FOUND",t.source_file,"The reusable selected source is missing or does not match its pinned hash."):Dl({entryFile:r,entryContent:i,files:n,selection:t})}let o=jl(n,t.source_file);if(o===null||!kI(t,o))return Dt("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 Dl({entryFile:r,entryContent:o,files:n,selection:t,sourceMapping:i})}if(t.strategy==="collection-container"){let i=t.collection_container_file;if(!i||!ym(i)||!n.has(i)||n.has(r)||!t.invocation?.complete)return Dt("SOURCE_INPUT_INVALID",r,"The proven collection container or isolated entry is unavailable.");let s=Or({component:"PortableCollection",bindings:t.invocation.bindings,targetBlockId:"portable-captured-collection"});if(!s.ok)return Dt("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,"")}`)};
40
40
  export default function PortableCollectionEntry(${a}) { return ${s.plan.jsx}; }
41
- `;return nu({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)?Ht("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):qj(t,o,n)}function qj(e,t,n){let r;try{r=Hj(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(P){return Ht("SOURCE_PARSE_FAILED",e.source_file,P instanceof Error?P.message:String(P))}let o=Qj(r,e);if(o.length!==1)return Ht("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(P=>P.isFunction());if(!s||!i_(s.node))return Ht("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=y0(a);if(!c.ok)return Ht("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 P of r.program.body){if(!M.isImportDeclaration(P)||P.specifiers.length||P.importKind==="type")continue;let F=P.source.value,B=F.startsWith(".")||F.startsWith("@/")?su(e.source_file,F,n):null;if(!B?.endsWith(".css"))return Ht("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(B)||l.imports.add(P),u.add(B)}let d=e0(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(t0(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(P=>M.isVariableDeclaration(P)&&P.declarations.some(F=>M.isIdentifier(F.id,{name:c.translationBinding}))))return Ht("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let p=S0(r,"__vcpPortableProps"),g=M.cloneNode(i.node,!0),m=[];for(let P of[...l.imports].sort($m)){let F=g0(P,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($m).map(P=>M.cloneNode(P,!0)),y=[...l.functionDeclarations].sort($m).map(P=>M.cloneNode(P,!0)),x=M.returnStatement(g),E=[...l.props].filter(([P])=>!P.startsWith("@")).map(([P,F])=>M.variableDeclaration("const",[M.variableDeclarator(M.identifier(P),M.memberExpression(M.identifier(p),M.identifier(F)))]));l.propsObjectName&&E.push(M.variableDeclaration("const",[M.variableDeclarator(M.identifier(l.propsObjectName),M.identifier(p))]));let b=M.blockStatement([...E,...y,x]),S=l.props.size?[m0(p)]:[],I=M.functionDeclaration(M.identifier("PortableBlockEntry"),S,b),T=M.program([...m,...f,I,M.exportDefaultDeclaration(M.identifier("PortableBlockEntry"))]);T.directives=r.program.directives.map(P=>M.cloneNode(P,!0));let C=Yj(M.file(T),{jsescOption:{minimal:!0}}).code,A={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return nu({entryFile:e.entry_file,entryContent:C,files:n,selection:e,sourceMapping:A,invocationBindings:E0(e,l.props)})}function Qj(e,t){let n=[];return Km(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function e0(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:Pt("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(M.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!M.isObjectPattern(o))return{ok:!1,error:Pt("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!M.isObjectProperty(i)||i.computed||!(M.isIdentifier(i.key)||M.isStringLiteral(i.key))||!(M.isIdentifier(i.value)||M.isAssignmentPattern(i.value)&&M.isIdentifier(i.value.left)))return{ok:!1,error:Pt("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=M.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=M.isIdentifier(a)?a.name:M.isAssignmentPattern(a)&&M.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function t0(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=r0(n,r,m,o,a);return l.set(m,y),y||s.errors.push(Pt("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){Xv.has(f)||s.errors.push(Pt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${f}.`));return}if(!ou(y.path.node,t)){if(r.bindingByLocalName.has(f)&&y.scope===n.scope){let x=r.bindingByLocalName.get(f);Hv(o,x)?u(x)&&s.props.set(f,x):s.errors.push(Pt("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&&M.isIdentifier(x.property)?x.property.name:x.computed&&M.isStringLiteral(x.property)?x.property.value:null;E&&Hv(o,E)?u(E)&&(s.propsObjectName=f,s.props.set(`@${f}.${E}`,E)):s.errors.push(Pt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${f}.`));return}c.has(y)||(c.add(y),zv(y,n,o,s,d,p,a))}},p=(m,f)=>{let y=o_(m);if(!y||/^[a-z]/u.test(y.name))return;let x=f.scope.getBinding(y.name);if(!x){Xv.has(y.name)||s.errors.push(Pt("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(x)||ou(x.path.node,t)||(c.add(x),zv(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){r_(f,i)||s.errors.push(Pt("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(Pt("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),f.stop()},UpdateExpression(f){s.errors.push(Pt("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),f.stop()},NewExpression(f){s.errors.push(Pt("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),f.stop()}})})(e)}function zv(e,t,n,r,o,i,s){let a=e.path;if(b0(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(Pt("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(Pt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(a0(e)){r.errors.push(Pt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new ru(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=su(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"?bn(a.node.imported,!1):null,b=x&&E&&u.node.importKind!=="type"?Hn(x,E,c):null,S=b?xn(b):null;if(!S?.length){r.errors.push(Pt("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||n0(e))&&!fa(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(Pt("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||!wr(m.node.id)||!wr(x.node)&&!x0(x)){r.errors.push(Pt("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=M.variableDeclaration("const",[M.cloneNode(m.node,!0)]);Wv(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()&&jc(f.node)){let x=f.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;Wv(x,M.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(Pt("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function n0(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=p0(n.node);return M.isFunctionExpression(r)||M.isArrowFunctionExpression(r)||M.isCallExpression(r)&&$c(r)?!1:!Uf(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||Vf(i,new Map))}var ru=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=iu(this.files,t);if(r===null)return;let o=we(t,r);if(o.ok)return super.set(t,o.module),o.module}};function r0(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=M.file(M.program([M.expressionStatement(M.valueToNode(i.value.value))]));Km(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 ru(o)};if(t.propsParameter)return Um(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),!fa(d,c,!0)))return!1}return!0}function o0(e,t){if(Vf(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(M.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!M.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=i0(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=xn(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(!M.isObjectProperty(p)||p.computed)return!1;let g=bn(p.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let p=Uc(c,d,t.inputs);return p!==null&&Um(s,d,p,a)})}let l=r.isJSXAttribute()&&M.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return Um(s,l,c,a)}function i0(e,t){let n=e.node.name;if(!M.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=su(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()?bn(r.path.node.imported,!1):null;if(!l)return null;let u=qt({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function Um(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(bn(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=fa(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=bn(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),e_(c,{...r,inputs:i},!0))})}function fa(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=>e_(i,r,n));return o&&t.bindings.add(e),o}function zm(e,t,n){let r=e.node.id;if(M.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?fa(o,t,n):!1}if(M.isObjectPattern(r)||M.isArrayPattern(r)){let o=[];return Ui(r,o)?s0(o,e,t):!1}return!1}function Ui(e,t){if(M.isRestElement(e))return Ui(e.argument,t);if(M.isIdentifier(e))return t.push(e.name),!0;if(M.isAssignmentPattern(e))return Ui(e.left,t);if(M.isObjectPattern(e)){for(let n of e.properties){if(M.isRestElement(n)){if(!Ui(n.argument,t))return!1;continue}if(!M.isObjectProperty(n)||n.computed||!(M.isIdentifier(n.key)||M.isStringLiteral(n.key)||M.isNumericLiteral(n.key))||!Ui(n.value,t))return!1}return!0}if(M.isArrayPattern(e)){for(let n of e.elements)if(n&&!Ui(n,t))return!1;return!0}return!1}function s0(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?fa(o,n,!0):!1})}function a0(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=Qv(t);if(!r)return!1;let o=n.parentPath;return!!(qv(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function qv(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?ou(e.node,t.node.left):!1}function Qv(e){let t=Vm(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=Vm(t.parentPath);return{current:t,memberAccess:n}}function e_(e,t,n){if(!u0(e,t))return!1;let{current:r,memberAccess:o}=Qv(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:zm(i,t,o||n)}return qv(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:c0(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?o0(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?l0(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 c0(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(M.isIdentifier(r)){if(Zv.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!hi(i)?!1:da(e,n,new Set)}if(!M.isMemberExpression(r)&&!M.isOptionalMemberExpression(r)||!M.isIdentifier(r.property))return!1;let o=Hm(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:da(e,n,new Set):Yv.get(o.name)?.has(r.property.name)??!1?n_(e)?da(e,n,new Set):!0:!1}function l0(e,t,n,r){let o=t_(e);return o.kind==="declarator"?zm(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function t_(e){let t=Vm(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 da(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=t_(e);return r.kind==="declarator"?zm(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:n_(r.call)?da(r.call,t,n):f0(r.call):!0}function u0(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!i_(n.node))return!0;let r=d0(n);return!r||!hi(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:da(i,t,new Set)})}function d0(e){let t=e.node,n=null;if(M.isFunctionDeclaration(t)?n=t.id?.name??null:(M.isArrowFunctionExpression(t)||M.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&M.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 n_(e){let t=e.node.callee;if(M.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&hi(r))}if(!M.isMemberExpression(t)&&!M.isOptionalMemberExpression(t)||!M.isIdentifier(t.property))return!1;let n=Hm(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&Zj.has(t.property.name)}function f0(e){let t=e.node.callee;if(M.isIdentifier(t))return Zv.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!M.isMemberExpression(t)&&!M.isOptionalMemberExpression(t)||!M.isIdentifier(t.property))return!1;let n=Hm(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:Yv.get(n.name)?.has(t.property.name)??!1}function Vm(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 p0(e){let t=e;for(;t&&(M.isTSAsExpression(t)||M.isTSTypeAssertion(t)||M.isTSNonNullExpression(t)||M.isTSSatisfiesExpression(t)||M.isParenthesizedExpression(t));)t=t.expression;return t&&M.isExpression(t)?t:null}function Hm(e){return!e.computed&&M.isIdentifier(e.object)?e.object:null}function m0(e){let t=M.identifier(e);return t.typeAnnotation=M.tsTypeAnnotation(M.tsTypeReference(M.identifier("Record"),M.tsTypeParameterInstantiation([M.tsStringKeyword(),M.tsAnyKeyword()]))),t}function nu(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=br({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>Pt(I0(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=iu(t,i.path);if(s===null)return Ht("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 g0(e,t,n,r){let o=M.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=su(t,i,r);if(!s)return{ok:!1,error:Pt("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=h0(n,s)}return{ok:!0,node:o}}function su(e,t,n){let r=t.startsWith("@/")?t.slice(2):ua.posix.normalize(ua.posix.join(ua.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 h0(e,t){let n=ua.posix.relative(ua.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function y0(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!M.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!M.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"||!M.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!M.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 r_(e,t){let n=e.node.callee;if(M.isImport(n))return!1;if(t&&M.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>M.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!!(M.isCallExpression(s)&&$c(s))}if(!M.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?hi(r):!1}function x0(e){return e.isCallExpression()&&r_(e,null)&&M.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>M.isExpression(t)&&wr(t))}function o_(e){return M.isJSXIdentifier(e)?M.isValidIdentifier(e.name)?M.identifier(e.name):null:M.isJSXMemberExpression(e)?o_(e.object):null}function b0(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>M.isObjectPattern(n)&&n.properties.some(r=>M.isObjectProperty(r)&&M.isIdentifier(r.value,{name:e.node.name}))))}function ou(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 i_(e){return M.isFunction(e)}function Hv(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function E0(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function S0(e,t){let n=new Set;Km(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function Wv(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 $m(e,t){return(e.start??0)-(t.start??0)}function iu(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 Gv(e,t){let n=zj("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 I0(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 Ht(e,t,n){return{complete:!1,errors:[Pt(e,t,n)]}}function Pt(e,t,n){return{code:e,path:t,message:n}}import{createHash as l_}from"node:crypto";import Zm from"@babel/generator";import qm from"@babel/traverse";import*as qe from"@babel/types";function _t(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 a_ from"@babel/types";import{createHash as Wm}from"node:crypto";var v0="sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f",_0="sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5",k0=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]),C0=new Set(["sha256:64f26e7284e844de65cfeaf268974aeb4a612ae796638fe219587f1d3e46b429"]),R0=new Map([["sha256:3b952ddc14778008dac157346c997cdea06844d890f1e5280ea08d38fbf03776","sha256:061e4143d12a22f4256157df2824144ac8fb86744f456afa50ff963278ddb263"],["sha256:92f7425b0f1eb031ef47470adb2b777fe863234c268504287323ff06cd4f91cc","sha256:4b5aa33d4bbf4e895e0186ee7049a7f9606b5d85ee6e045b8eed084cee458646"]]);function au(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:${Wm("sha256").update(s).digest("hex")}`;return a&&t.get(i)===a?a:""},o=r(n);return!!o&&R0.get(o)===r(n.replace("jsonld.tsx","metadata-fields.ts"))}function cu(e){return e.index===v0&&e.client===_0&&k0.has(e.collections)}function Fr(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:${Wm("sha256").update(i).digest("hex")}`;return t.get(`${n}${o}.ts`)===s?s:""};return cu({index:r("index"),collections:r("collections"),client:r("client")})&&C0.has(r("field"))}function lu(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:${Wm("sha256").update(r).digest("hex")}`;return o==="sha256:6e1c0d0af2938dc4e74d4a35b185bec0ad1fd6d16fd2323ee0cd72eaa05c836f"&&t.get(n)===o&&Fr(e,t)}import*as pn from"@babel/types";var Qe={kind:"primitive"},Er={kind:"json"},Gm=new Set(["__proto__","prototype","constructor","then","toString","valueOf","toLocaleString"]),mo=e=>({kind:"object",properties:new Map(Object.entries(e))}),Sr=e=>({kind:"array",item:e});function du(e){let t=new Map;for(let n of e.split("/")){let r=/^\[(\[)?(\.\.\.)?([^\[\]/]+)\]\]?$/u.exec(n);r&&t.set(r[3],r[2]?Sr(Qe):Qe)}return{kind:"object",properties:t}}function xt(e){return!!e&&e.kind!=="promise"&&e.kind!=="jsx"}function fu(e,t){let n=mo({id:Qe,url:Qe,seo:Er,fields:t?{kind:"json",origin:{slug:t,field_path:""}}:Er}),r=["list","listStrict"].includes(e)?mo({items:Sr(n),total:Qe,page:Qe,pageSize:Qe}):["get","getStrict","getByUrl","getByUrlStrict"].includes(e)?n:e==="categories"?Sr(mo({id:Qe,label:Qe,children:Er})):e==="schema"?Er:null;return r?{kind:"promise",value:e.endsWith("Strict")?mo({kind:Qe,data:r,error:Er}):r}:null}function Ym(e){if(["text","selected","num","bool","url","phone"].includes(e))return Qe;if(e==="richtext")return mo({__html:Qe});if(["image","images"].includes(e)){let t=mo({url:Qe,name:Qe});return e==="images"?Sr(t):t}return e==="category"?Sr(mo({id:Qe,label:Qe})):e==="list"?Sr(Qe):e==="dateRange"?mo({start:Qe,end:Qe}):null}function s_(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=pn.isIdentifier(c)?c.name:pn.isStringLiteral(c)?c.value:null;l&&!Gm.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 pu(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=s_(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=pa(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:xt(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=pn.isIdentifier(f)?f.name:pn.isStringLiteral(f)?f.value:null,x=n(m.get("value"),i,a);if(!y||Gm.has(y)||g.has(y)||!xt(x))return null;g.set(y,x)}return{kind:"object",properties:g}}if(o.isArrayExpression()){if(!o.node.elements.length)return{kind:"array",item:Er,empty:!0};let g=pa(o.get("elements").map(m=>c(m)));return xt(g)?Sr(g):null}if(o.isMemberExpression()||o.isOptionalMemberExpression()){let g=P0(o);if(!g||Gm.has(g))return null;let m=c(o.get("object"));return m?.kind==="object"?uu(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}}:Er:m?.kind==="array"?g==="length"?Qe:/^\d+$/u.test(g)?uu(m.item,m.origin):null:m?.kind==="primitive"&&g==="length"?Qe:null}if(o.isConditionalExpression())return pa([c(o.get("consequent")),c(o.get("alternate"))]);if(o.isLogicalExpression())return pa([c(o.get("left")),c(o.get("right"))]);if(o.isUnaryExpression())return["typeof","!","void"].includes(o.node.operator)||xt(c(o.get("argument")))?Qe:null;if(o.isBinaryExpression())return["in","instanceof"].includes(o.node.operator)?null:["===","!=="].includes(o.node.operator)||xt(c(o.get("left")))&&xt(c(o.get("right")))?Qe:null;if(o.isTemplateLiteral())return o.get("expressions").every(g=>xt(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=>xt(c(g)))?Qe:null;let d=r(o,i,a);if(d)return d.result;if(u.isMemberExpression()&&!u.node.computed){if(pn.isIdentifier(u.node.object,{name:"Object"})&&!u.scope.getBinding("Object")&&pn.isIdentifier(u.node.property,{name:"keys"})&&o.node.arguments.length===1&&xt(c(o.get("arguments")[0])))return Sr(Qe);let g=c(u.get("object")),m=pn.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=>xt(c(f))))return m==="split"?Sr(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||!pn.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=[uu(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"?Sr(g):c==="filter"?l:c==="find"?l.item:Qe}:null}return{value:n,arrayCall:r,bind:s_}}function P0(e){let t=e.node.property;return!e.node.computed&&pn.isIdentifier(t)?t.name:pn.isStringLiteral(t)?t.value:pn.isNumericLiteral(t)?String(t.value):null}function pa(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:pa(n.map(r=>r?.kind==="array"?r.item:null))??Er}:{kind:"array",item:Er,empty:!0}}return e.every(n=>n?.kind==="primitive")?e.every(n=>JSON.stringify(n?.origin)===JSON.stringify(t.origin))?uu(Qe,t.origin):Qe:e.every(n=>n?.kind==="jsx")?t:e.every(xt)?Er:null}function uu(e,t){return e&&t?{...e,origin:e.origin??t}:e}function c_(e){if(!Fr(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=_t(e.files.get(d)),m=g===null?null:we(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=wt(g.file,p.node.source.value,e.files);if(!m)return null;let f=d.path.node.imported;return{module:g,file:m,name:a_.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?Hn(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&&au(e.files,e.trusted_host_file_hashes,m.file))},c=pu({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=>xt(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)||rn(m.module.ast,m.local))return null;let f=$n(u.node,{file:m.module.file,imports:new Map([[m.local,{source:m.file,importedName:m.name}]])})?.operation;return f?fu(f):null}}),l=c.bind(e.owner,[{kind:"object",properties:new Map([["params",{kind:"promise",value:du(e.route_id)}],["searchParams",{kind:"promise",value:{kind:"json"}}]])}]);return u=>{if(!u.node||!xt(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)||!xt(c.value(g,l)))&&(d=!1)}else g.isMemberExpression()||g.isOptionalMemberExpression()?xt(c.value(g,l))||(d=!1):!wr(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 N0=typeof qm=="function"?qm:qm.default,A0=typeof Zm=="function"?Zm:Zm.default;function u_(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=_t(n.get(o.sourceFile));if(i===null||`sha256:${l_("sha256").update(i).digest("hex")}`!==t.ownerSourceHash)return{complete:!1};let s=we(o.sourceFile,i);if(!s.ok)return{complete:!1};let a=null;N0(s.module.ast,{JSXElement(H){let he=o.callLocator.sourceRange;H.node.loc?.start.line===he.startLine&&H.node.loc.start.column===he.startColumn&&H.node.loc.end.line===he.endLine&&H.node.loc.end.column===he.endColumn&&(a=H)}});let c=a,l=c?.getFunctionParent();if(!c||!l?.isFunctionDeclaration()||!l.parentPath.isExportDefaultDeclaration()||!l.get("body").isBlockStatement())return{complete:!1};let u=c.findParent(H=>H.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=H=>{if(!H||d.has(H))return;if(d.add(H),!H.constant||H.constantViolations.length){y=!0;return}let he=H.path;if(he.isImportSpecifier()||he.isImportDefaultSpecifier()||he.isImportNamespaceSpecifier()){let je=he.parentPath;if(!je.isImportDeclaration()){y=!0;return}let He=p.get(je.node)??new Set;He.add(he.node),p.set(je.node,He);return}if(H.kind==="param"){let je=l.node.params[0];if(!qe.isObjectPattern(je)){y=!0;return}let He=je.properties.filter(L=>qe.isObjectProperty(L)&&!L.computed&&qe.isIdentifier(L.value,{name:H.identifier.name})),ht=He[0];if(He.length!==1||!qe.isObjectProperty(ht)){y=!0;return}let O=qe.isIdentifier(ht.key)?ht.key.name:qe.isStringLiteral(ht.key)?ht.key.value:"";if(!["params","searchParams"].includes(O)){y=!0;return}f.add(O);return}let ue=he.getStatementParent();if(!ue||ue.node===l.node){y=!0;return}if(he.isVariableDeclarator()){if(!ue.isVariableDeclaration({kind:"const"})||ue.node.declarations.length!==1){y=!0;return}}else if(!he.isFunctionDeclaration()&&!he.isTSTypeAliasDeclaration()&&!he.isTSInterfaceDeclaration()){y=!0;return}if(ue.parentPath===l.get("body"))m.add(ue.node);else if(ue.parentPath.isProgram())g.add(ue.node);else if(ue.parentPath.isExportNamedDeclaration()&&ue.parentPath.parentPath.isProgram())g.add(ue.node);else{y=!0;return}E(ue)},E=H=>{let he=ue=>x(ue.scope.getBinding(ue.node.name));H.isReferencedIdentifier()&&he(H),H.traverse({ReferencedIdentifier(ue){he(ue)},JSXOpeningElement(ue){qe.isJSXIdentifier(ue.node.name)&&!/^[a-z]/u.test(ue.node.name.name)&&x(ue.scope.getBinding(ue.node.name.name))}})};E(c);let b=l.get("body").get("body").filter(H=>(H.node.start??1/0)<(u.node.start??-1)),S=c_({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,T=(H,he)=>{let ue=he.path.parentPath;if(!he.path.isImportSpecifier()||!qe.isIdentifier(he.path.node.imported,{name:"cms"})||!ue?.isImportDeclaration())return!1;let je=wt(o.sourceFile,ue.node.source.value,n);if(!je||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(je))return!1;let He=H;for(;He.parentPath?.isMemberExpression()&&He.parentPath.node.object===He.node&&!He.parentPath.node.computed;)He=He.parentPath;let ht=He.parentPath;return!!(ht?.isCallExpression()&&ht.node.callee===He.node&&$n(ht.node,{file:o.sourceFile,imports:new Map([[he.identifier.name,{source:je,importedName:"cms"}]])}))},C=!0;for(;C&&!y;){C=!1;for(let H of b){if(m.has(H.node))continue;let he=!1;if(H.traverse({ReferencedIdentifier(je){let He=je.scope.getBinding(je.node.name);He&&(d.has(He)||I.has(He))&&!T(je,He)&&(he=!0)}}),!he)continue;if(H.isVariableDeclaration({kind:"const"})&&H.node.declarations.length===1){let je=H.get("declarations")[0];if(je.get("id").isIdentifier()&&S(je.get("init"))){let He=je.node.id.name,ht=H.scope.getBinding(He);ht&&!I.has(ht)&&(I.add(ht),C=!0);continue}}let ue=!1;if(H.traverse({Function(je){je.skip()},ReturnStatement(je){je.node.argument&&(ue=!0)}}),ue){y=!0;break}m.add(H.node),E(H);for(let je of Object.keys(qe.getBindingIdentifiers(H.node)))x(H.scope.getBinding(je));C=!0}}if(y||!d.size)return{complete:!1};let A=l_("sha256").update(JSON.stringify([t.sourceHash,t.ownerSourceHash,o.callLocator.sourceRange])).digest("hex"),P=`components/site/portable/${A.slice(0,24)}/page.tsx`;if(n.has(P))return{complete:!1};let F=[];for(let[H,he]of p){let ue=qe.cloneNode(H,!0);if(ue.specifiers=H.specifiers.filter(je=>he.has(je)||qe.isImportSpecifier(je)&&je.importKind==="type").map(je=>qe.cloneNode(je,!0)),ue.source.value.startsWith(".")){let je=wt(o.sourceFile,ue.source.value,n);if(!je)return{complete:!1};ue.source=qe.stringLiteral(`@/${je.replace(/\.[cm]?[jt]sx?$/u,"")}`)}F.push(ue)}let B=qe.functionDeclaration(qe.identifier(`PortableCmsDataEntry_${A.slice(0,8)}`),l.node.params.map(H=>qe.cloneNode(H,!0)),qe.blockStatement([...[...m].sort(Qm).map(H=>qe.cloneNode(H,!0)),qe.returnStatement(qe.cloneNode(c.node,!0))]));B.async=l.node.async;let U=qe.program([...F.sort(Qm),...[...g].sort(Qm).map(H=>qe.cloneNode(H,!0)),qe.exportDefaultDeclaration(B)]),G=A0(qe.file(U)).code,X=c.node.loc;if(!X||c.node.start==null||c.node.end==null)return{complete:!1};let Z=[...f].sort().map(H=>({propName:H,value:{kind:H==="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:X.start.line,start_column:X.start.column,end_line:X.end.line,end_column:X.end.column},owner:t.descriptor.owner,call_chain:[],strategy:"extract-jsx",entry_file:P,entry_export:{kind:"default"},invocation:null},extracted:{complete:!0,entry_file:P,source_files:[{path:P,content:G}],source_mapping:[],invocation_bindings:Z,selected_root_ref:t.root.rootRef}}}function Qm(e,t){return(e.start??0)-(t.start??0)}import eg from"@babel/traverse";import*as kt from"@babel/types";import{createHash as d_}from"node:crypto";var f_=typeof eg=="function"?eg:eg.default,T0=/^[a-z0-9][a-z0-9_-]{0,123}$/u;function p_(e){let t=br({entry_files:[e.entry_file],files:e.files,max_nodes:512}),n=new Map,r=[],o=new Map([[e.entry_file,new Set([e.entry_export?.kind==="named"?e.entry_export.name:"default"])]]);for(let i of t.nodes){if(i.kind!=="source")continue;let s=_t(e.files.get(i.path)),a=s===null?null:we(i.path,s);a?.ok&&f_(a.module.ast,{ImportDeclaration(c){if(c.node.importKind==="type")return;let l=wt(i.path,c.node.source.value,e.files);if(l)for(let u of c.node.specifiers){if(kt.isImportSpecifier(u)&&u.importKind==="type"||!c.scope.getBinding(u.local.name)?.referencePaths.length)continue;let d=o.get(l)??new Set;d.add(kt.isImportDefaultSpecifier(u)?"default":kt.isImportSpecifier(u)?kt.isIdentifier(u.imported)?u.imported.name:u.imported.value:"*"),o.set(l,d)}}})}for(let i of t.nodes){if(i.kind!=="source"||!/\.[cm]?[jt]sx?$/u.test(i.path)||/^(?:src\/)?lib\/cms\/(?!generated\/)/u.test(i.path))continue;let s=_t(e.files.get(i.path));if(s===null)continue;let a=we(i.path,s);if(!a.ok){r.push({code:"CMS_BINDING_SOURCE_INVALID",source_path:i.path,message:a.diagnostic.message});continue}let c=new Map;for(let l of a.module.ast.program.body){if(!kt.isImportDeclaration(l)||l.importKind==="type")continue;let u=wt(i.path,l.source.value,e.files);if(u)for(let d of l.specifiers)!kt.isImportSpecifier(d)||d.importKind==="type"||c.set(d.local.name,{source:u,importedName:kt.isIdentifier(d.imported)?d.imported.name:d.imported.value})}f_(a.module.ast,{FunctionDeclaration(l){let u=l.parentPath.isExportDefaultDeclaration()?"default":l.parentPath.isExportNamedDeclaration()?l.node.id?.name:void 0;u&&!o.get(i.path)?.has(u)&&!o.get(i.path)?.has("*")&&(!l.node.id||!l.scope.getBinding(l.node.id.name)?.referencePaths.some(d=>!d.isExportDeclaration()))&&l.skip()},CallExpression(l){let u=l.get("callee"),d=new Set;for(;u.isIdentifier()&&!c.has(u.node.name);){let S=u.scope.getBinding(u.node.name);if(!S?.constant||!S.path.isVariableDeclarator()||d.has(S.path.node))break;d.add(S.path.node);let I=S.path.get("init");if(!I.node)break;u=I}if(!kt.isExpression(u.node))return;let p=u;for(;p.isMemberExpression()&&!p.node.computed;)p=p.get("object");if(p.isIdentifier()&&["cms","collections"].includes(c.get(p.node.name)?.importedName??"")){let S=p.scope.getBinding(p.node.name);if(!S?.path.isImportSpecifier())return;if(rn(a.module.ast,p.node.name)||!m_(S,new Set)){r.push({code:"CMS_BINDING_MUTATED",source_path:i.path,message:"The CMS application facade has been modified or escaped."});return}}let g=$n(kt.callExpression(u.node,[]),{file:i.path,imports:c});if(!g)return;if(g.sourceKind!=="vcp-cms-collection"){r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"The selected code depends on a non-collection CMS capability."});return}let m=g.operation;if(m==="getByUrlStrict"&&e.allow_build_sample&&e.on_build_only_value){let S=l.get("arguments")[1];if(S?.isObjectExpression()){let I=S.get("properties").find(C=>C.isObjectProperty()&&!C.node.computed&&(kt.isIdentifier(C.node.key,{name:"buildSample"})||kt.isStringLiteral(C.node.key,{value:"buildSample"}))),T=I?.isObjectProperty()?I.get("value"):void 0;if(T?.isIdentifier()){let C=T.scope.getBinding(T.node.name);T=C?.constant&&C.referencePaths.length===1&&C.path.isVariableDeclarator()?C.path.get("init"):void 0}for(;T?.isTSAsExpression()||T?.isTSSatisfiesExpression();)T=T.get("expression");T?.isObjectExpression()&&T.node.start!=null&&T.node.end!=null&&e.on_build_only_value({file_path:i.path,start:T.node.start,end:T.node.end,source_hash:`sha256:${d_("sha256").update(s).digest("hex")}`})}}let f=l.get("arguments")[0];if(f?.isObjectExpression()&&m.startsWith("cmsFetch")){let S=f.get("properties").find(I=>I.isObjectProperty()&&!I.node.computed&&(kt.isIdentifier(I.node.key,{name:"path"})||kt.isStringLiteral(I.node.key,{value:"path"})));f=S?.isObjectProperty()?S.get("value"):void 0}let y=m.startsWith("getByUrl")||m.startsWith("cmsFetch"),x=f?Vi(f,y,new Set):null,E=x&&y?Pi(x):x;if(!E||!T0.test(E)){r.push({code:"CMS_BINDING_UNRESOLVED",source_path:i.path,message:"The CMS application identity cannot be determined from its request binding.",...l.node.loc?{call_site:l.node.loc.start}:{}});return}y&&!e.confirmed_slugs?.has(E)&&r.push({code:"CMS_URL_COLLECTION_UNPROVEN",source_path:i.path,message:"The CMS request namespace requires a matching site-authorized application schema."});let b=n.get(E)??[];b.push({source_path:i.path,operation:m,binding:"trusted-cms",call_site:{line:l.node.loc?.start.line??1,column:l.node.loc?.start.column??0}}),n.set(E,b)},JSXOpeningElement(l){if(!e.on_host_call||!kt.isJSXIdentifier(l.node.name)||l.node.start==null||l.node.end==null)return;let u=c.get(l.node.name.name);u?.importedName==="SafeImage"&&/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(u.source)&&e.on_host_call({file_path:i.path,host_file:u.source,start:l.node.start,end:l.node.end,source_hash:`sha256:${d_("sha256").update(s).digest("hex")}`})}})}return n.size>16&&r.push({code:"CMS_BINDING_BUDGET_EXCEEDED",source_path:e.entry_file,message:"The selected block exceeds the application export budget; no applications were truncated."}),{complete:r.length===0,dependencies:[...n].sort(([i],[s])=>i.localeCompare(s)).map(([i,s])=>({requirement_key:`cms-${i}`,slug:i,evidence:s})),unresolved:r}}function m_(e,t){if(t.has(e.path.node))return!1;let n=new Set(t).add(e.path.node);return e.referencePaths.every(r=>{if(r.isExportDeclaration())return!0;let o=r.parentPath;if(o?.isMemberExpression()&&o.node.object===r.node)return!0;if(o?.isVariableDeclarator()&&o.node.init===r.node&&kt.isIdentifier(o.node.id)){let i=o.scope.getBinding(o.node.id.name);return!!i?.constant&&m_(i,n)}return!1})}function Vi(e,t,n){if(n.has(e.node))return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return e.node.value;if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return Vi(e.get("expression"),t,r);if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);if(o?.constant&&o.path.isVariableDeclarator()){let i=o.path.get("init");if(i.node)return Vi(i,t,r)}return null}if(e.isBinaryExpression({operator:"+"})){let o=Vi(e.get("left"),t,r),i=Vi(e.get("right"),t,r);return o!==null&&i!==null?o+i:t&&o!==null?`${o}:record`:null}if(e.isTemplateLiteral()){let o=e.node.quasis[0]?.value.cooked??"",i=e.get("expressions");for(let[s,a]of i.entries()){let c=Vi(a,t,r);if(c===null&&!t)return null;o+=(c??":record")+(e.node.quasis[s+1]?.value.cooked??"")}return o}return null}import{createHash as dk}from"node:crypto";import kg from"node:path";import Cg from"@babel/traverse";import*as ct from"@babel/types";import{GeneratedSiteCapabilitiesSchema as rU,SiteEditSourcePathSchema as oU}from"@vcp-dev/contracts";import{parse as Ig}from"@babel/parser";import*as ie from"@babel/types";import{PortableCollectionRecipeFactsSchema as j$}from"@vcp-dev/contracts";import{parse as bo}from"@babel/parser";import dg from"@babel/traverse";import*as D from"@babel/types";import{createHash as n$}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as r$,generateDetailBreadcrumb as o$,ResolvedFieldSchema as i$}from"@vcp-dev/contracts";import rg from"@babel/traverse";import*as W from"@babel/types";import{PORTABLE_AUDITED_SAFE_IMAGE as E_}from"@vcp-dev/contracts";import{createHash as og}from"node:crypto";import{createHash as w0}from"node:crypto";import O0 from"@babel/traverse";import*as Ze from"@babel/types";var tg=O0,L0=typeof tg=="function"?tg:tg.default,F0=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),ho=new Set(["backgroundimage","fallbacksrc","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),x_=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,D0=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function Ji(e){let t=we(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=>{if(e.static_only&&!c.complete)return;let l=y_(c.node),u=J0(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:K0(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=y_(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})};L0(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;B0(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=b_(c.node.name),u=D0.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=$0(p);if(g==="style"&&!M0(p.value)){i({node:p.value??p,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!g||!j0(g,u))continue;let m=ma(d.get("value"));i({node:p.value??p,kind:g_(g),source:"jsx-attribute",value:m.value,complete:m.complete})}},ObjectProperty(c){let l=ga(c);if(!l.known){i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1});return}let u=l.name;if(!u||!ho.has(u)&&!(h_(c)&&ng(u)))return;let d=c.get("value");if(ho.has(u)&&(d.isObjectExpression()||d.isArrayExpression())&&mu(d))return;let p=go(c.node.value);i({node:c.node.value,kind:g_(u),source:"object-property",value:p.value,complete:p.complete})},ObjectMethod(c){let l=ga(c);(!l.known||c.node.kind!=="method"&&l.name&&(ho.has(l.name)||h_(c)&&ng(l.name)))&&i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1})},ArrayExpression(c){if(V0(c))for(let l of c.get("elements")){if(!l.node||(l.isObjectExpression()||l.isArrayExpression())&&mu(l))continue;let u=go(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(!Ze.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!Ze.isExpression(u)){s(c.node,null);return}let d=go(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!U0(c.node.object))return;let l=c.node.computed?go(c.node.property):Ze.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=X0(r).sort(z0);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function M0(e){return!Ze.isJSXExpressionContainer(e)||!Ze.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!Ze.isObjectProperty(t)||t.computed||!(Ze.isIdentifier(t.key)||Ze.isStringLiteral(t.key)))return!1;let n=Ze.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:Ze.isNumericLiteral(t.value)?Number.isFinite(t.value.value):Ze.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function B0(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&F0.has(n)}function j0(e,t){return e!=="src"||t?ho.has(e):!1}function g_(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function $0(e){return Ze.isJSXIdentifier(e.name)?e.name.name.toLowerCase():Ze.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function b_(e){return Ze.isJSXIdentifier(e)?e.name:Ze.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${b_(e.object)}.${e.property.name}`}function ga(e){if(!e.node.computed){let n=e.node.key;return Ze.isIdentifier(n)?{known:!0,name:n.name.toLowerCase()}:Ze.isStringLiteral(n)?{known:!0,name:n.value.toLowerCase()}:{known:!0,name:null}}let t=ma(e.get("key"));if(t.complete&&t.value!==null)return{known:!0,name:t.value.toLowerCase()};if(Ze.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=[...ho,"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 U0(e){return Ze.isIdentifier(e,{name:"mediaAssets"})}function V0(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=ga(t).name;return n!==null&&ho.has(n)}return t?.isVariableDeclarator()&&Ze.isIdentifier(t.node.id)?x_.test(t.node.id.name):!1}function h_(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=ga(r).name;if(o&&ho.has(o))return!0;t=r.parentPath;continue}return!!(r?.isVariableDeclarator()&&r.node.init===t.node&&Ze.isIdentifier(r.node.id)&&x_.test(r.node.id.name))}return t!==null}function ng(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function mu(e,t=0){if(t>=32)return!1;if(e.isArrayExpression())return e.get("elements").some(r=>r.node!==null&&(r.isObjectExpression()||r.isArrayExpression()?mu(r,t+1):!0));let n=!1;for(let r of e.get("properties")){if(!r.isObjectProperty()&&!r.isObjectMethod())return!1;let o=ga(r);if(!o.known)return!0;let i=o.name;if(r.isObjectMethod()&&r.node.kind==="method")continue;if(i!==null&&(ho.has(i)||ng(i))){n=!0;continue}if(r.isObjectMethod())continue;let s=r.get("value");(s.isObjectExpression()||s.isArrayExpression())&&mu(s,t+1)&&(n=!0)}return n}function go(e){return e?Ze.isStringLiteral(e)?{value:e.value,complete:!0}:Ze.isJSXExpressionContainer(e)?go(e.expression):Ze.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:Ze.isTSAsExpression(e)||Ze.isTSTypeAssertion(e)||Ze.isParenthesizedExpression(e)?go(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function ma(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 ma(e.get("expression"),n);if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r?.constant||r.kind!=="const"||!r.path.isVariableDeclarator()||!Ze.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}:ma(r.path.get("init"),n)}return go(e.node)}function y_(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 J0(e,t){return e.slice(t.start_offset,t.end_offset)}function K0(e){return`sha256:${w0("sha256").update(e).digest("hex")}`}function X0(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 z0(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 R_=typeof rg=="function"?rg:rg.default,gu=256,ig=16,H0=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 P_(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(L){return e.files.has(L)}get(L){let z=super.get(L);if(z||this.attempted.has(L))return z;this.attempted.add(L);let j=e.files.get(L),K;try{if(typeof j=="string")K=j;else if(j instanceof Uint8Array)K=new TextDecoder("utf-8",{fatal:!0}).decode(j);else return}catch{return}let ee=we(L,K);if(ee.ok)return super.set(L,ee.module),o.set(ee.module.ast.program,ee.module),ee.module}}let l=new c,u=Fr(e.files,e.trusted_host_file_hashes??new Map),d=lu(e.files,e.trusted_host_file_hashes??new Map),p=(O,L)=>{if(!d||!e.on_build_only_value||O.node.arguments.length!==2)return;let z=O.get("arguments")[1];if(!z?.isObjectExpression())return;let j=z.get("properties").filter(ee=>ee.isObjectProperty()&&!ee.node.computed&&(W.isIdentifier(ee.node.key,{name:"buildSample"})||W.isStringLiteral(ee.node.key,{value:"buildSample"})));if(j.length!==1||!j[0].isObjectProperty())return;let K=j[0].get("value");if(K.isIdentifier()){let ee=K.scope.getBinding(K.node.name);if(!ee?.constant||!ee.path.isVariableDeclarator()||ee.referencePaths.length!==1||ee.referencePaths[0].node!==K.node)return;K=ee.path.get("init")}for(;K.isTSAsExpression()||K.isTSSatisfiesExpression()||K.isParenthesizedExpression();){let ee=K.get("expression");if(Array.isArray(ee))return;K=ee}!K.isObjectExpression()||K.node.start==null||K.node.end==null||e.on_build_only_value({file_path:L.file,start:K.node.start,end:K.node.end,source_hash:`sha256:${og("sha256").update(L.source).digest("hex")}`})},g=new Set(["next/link","next/navigation","lucide-react"]),m=O=>{let L=O.findParent(z=>z.isProgram());return L&&W.isProgram(L.node)?o.get(L.node):void 0},f=u?pu({resolve_function(O){let L=m(O);return L&&O.isIdentifier()?he(O.scope.getBinding(O.node.name),L):null},resolve_value(O){let L=O.scope.getBinding(O.node.name),z=L?.path.parentPath,j=m(O);if(!j||!L?.constant||!L.path.isImportSpecifier()||L.path.node.importKind==="type"||!z?.isImportDeclaration()||z.node.importKind==="type")return null;let K=wt(j.file,z.node.source.value,e.files),ee=K?l.get(K):void 0,pe=L.path.node.imported;return ee?Hn(ee,W.isIdentifier(pe)?pe.name:pe.value,l):null},cms_value(O,L,z){let j=m(O);if(!j)return null;let K=ue(O.get("callee"),j,new Set);if(!K||rn(j.ast,K.originalName))return null;if(K.importedName==="cms"&&K.name.startsWith("__vcpCms.field.")){let $=Ym(K.name.slice(15)),te=O.get("arguments")[0],Ie=te&&f?.value(te,L,z)?.origin;return $&&Ie?{...$,origin:Ie}:$}let ee=$n(W.callExpression(k_(K.name),[]),{file:j.file,imports:new Map([["__vcpCms",{source:K.source,importedName:K.importedName}]])})?.operation,pe=O.get("arguments")[0],v=pe?ee==="getByUrl"||ee==="getByUrlStrict"?hu(pe,new Map):Gt(pe,new Map,new Set)?.[0]:void 0;return ee?fu(ee,v??void 0):null}}):null,y=new Map;function x(O,L,z){if(!e.on_cms_media_value||!f||O.node.start==null||O.node.end==null)return;let j=y.get(L.file);if(j||(j=new Set(Ji({file_path:L.file,source:L.source}).references.filter(K=>!K.complete).map(K=>`${K.source_range.start_offset}:${K.source_range.end_offset}`)),y.set(L.file,j)),j.has(`${O.node.start}:${O.node.end}`)){let K=f.value(O,z)?.origin;e.on_cms_media_value({file_path:L.file,start:O.node.start,end:O.node.end,...K?{origin:K}:{}})}}function E(O){return u&&/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(O.file)&&e.trusted_host_file_hashes?.get(O.file)===`sha256:${E_.digest_sha256}`&&og("sha256").update(O.source).digest("hex")===E_.digest_sha256}function b(O){let L=O?.path.parentPath;return!!(u&&O?.constant&&L?.isImportDeclaration()&&g.has(L.node.source.value))}function S(O){if(!u||!W.isJSXIdentifier(O.node.name))return!1;let L=O.scope.getBinding(O.node.name.name),z=L?.path.parentPath;return!!(L?.constant&&L.path.isImportDefaultSpecifier()&&z?.isImportDeclaration()&&z.node.source.value==="next/link")}function I(O,L,z,j){let K=j?.loc?.start;t.push({code:O,source_path:L,message:z,...K?{call_site:{line:K.line,column:K.column}}:{}})}function T(O,L,z,j){let K=j.loc?.start;if(!K){I("CMS_CALL_SITE_UNAVAILABLE",z.file,"The CMS call has no source location.",j);return}let ee={source_path:z.file,operation:L,binding:"trusted-cms",call_site:{line:K.line,column:K.column}},pe=n.get(O)??[];pe.some(v=>JSON.stringify(v)===JSON.stringify(ee))||pe.push(ee),n.set(O,pe)}function C(O){if(!i.has(O.file)){if(i.size>=gu){I("CMS_MODULE_BUDGET_EXHAUSTED",O.file,"The module analysis budget was exhausted.");return}if(i.add(O.file),!E(O)){for(let L of O.ast.program.body){let z=null;if(W.isImportDeclaration(L)&&L.importKind!=="type"){if(L.specifiers.length&&L.specifiers.every(ee=>W.isImportSpecifier(ee)&&ee.importKind==="type"))continue;z=L.source.value}else if(W.isExportNamedDeclaration(L)&&L.source&&L.exportKind!=="type"){if(L.specifiers.length&&L.specifiers.every(ee=>W.isExportSpecifier(ee)&&ee.exportKind==="type"))continue;z=L.source.value}else W.isExportAllDeclaration(L)&&L.exportKind!=="type"&&(z=L.source.value);if(!z)continue;if(!mt(z)){if(u&&g.has(z))continue;I("CMS_EXTERNAL_MODULE_UNRESOLVED",O.file,"An external module's initialization effects cannot be proven safe.",L);continue}let j=wt(O.file,z,e.files);if(!j){I("CMS_IMPORT_UNRESOLVED",O.file,`The local import ${z} is unavailable.`,L);continue}if(!/\.[cm]?[jt]sx?$/iu.test(j)||v_(j))continue;let K=l.get(j);K?C(K):I("CMS_SOURCE_UNAVAILABLE",j,"The imported source cannot be parsed.",L)}R_(O.ast,{Program(L){A(L,O,new Map,new Map),L.stop()}})}}}function A(O,L,z,j,K=new Map){let ee=v=>L_(v,z,j,U)||xt(f?.value(v,K)??null),pe=v=>{let $=v.parentPath;return!($?.isAssignmentExpression()&&$.node.left===v.node||$?.isUpdateExpression()||$?.isUnaryExpression({operator:"delete"}))&&xt(f?.value(v,K)??null)};O.traverse({enter(v){x(v,L,K)},Function(v){(v.isObjectMethod()||v.isClassMethod()||v.isClassPrivateMethod())&&v.node.computed&&!ee(v.get("key"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.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!=="!=="&&(!ee(v.get("left"))||!ee(v.get("right"))))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"An operator may execute an unproven coercion or proxy trap.",v.node)},TemplateLiteral(v){v.get("expressions").some($=>!ee($))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"Template interpolation may execute an unproven coercion.",v.node)},UnaryExpression(v){["+","-","~"].includes(v.node.operator)&&!ee(v.get("argument"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"A unary operator may execute an unproven coercion.",v.node)},UpdateExpression(v){I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"An update may execute an unproven coercion or proxy trap.",v.node)},ObjectProperty(v){v.node.computed&&!ee(v.get("key"))&&I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"A computed property key may execute an unproven coercion.",v.node)},ForInStatement(v){I("CMS_IMPLICIT_EXECUTION_UNRESOLVED",L.file,"Property enumeration may execute an unproven proxy trap.",v.node)},JSXOpeningElement(v){let $=v.node.name;if(W.isJSXIdentifier($)&&/^[a-z]/u.test($.name)){($.name.includes("-")||v.node.attributes.some(Pe=>W.isJSXAttribute(Pe)&&W.isJSXIdentifier(Pe.name,{name:"is"})))&&I("CMS_COMPONENT_UNRESOLVED",L.file,"A custom element may execute an unproven implementation.",v.node);return}if(__(v,S)){I("CMS_COMPONENT_REACHABILITY_UNPROVEN",L.file,"A component value is not proven to be rendered by the selected root.",v.node);return}if(!W.isJSXIdentifier($)){I("CMS_COMPONENT_UNRESOLVED",L.file,"A dynamic or namespace component target is not proven.",v.node);return}let te=he(v.scope.getBinding($.name),L);if(!te){if(b(v.scope.getBinding($.name))){for(let Pe of v.get("attributes")){if(!Pe.isJSXAttribute()||!W.isJSXIdentifier(Pe.node.name)){I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"A runtime component spread is not a proven data argument.",Pe.node);continue}let nt=Pe.get("value");nt.isJSXExpressionContainer()&&!/^(?:on[A-Za-z]|ref$)/u.test(Pe.node.name.name)&&!xt(f?.value(nt.get("expression"),K)??null)&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"A runtime component argument is not proven plain data.",Pe.node)}return}I("CMS_COMPONENT_UNRESOLVED",L.file,"A rendered component target is not proven.",v.node);return}let Ie=v.node.attributes.every(Pe=>W.isJSXAttribute(Pe)&&W.isJSXIdentifier(Pe.name)&&Pe.name.name!=="__proto__"),Re=m(te);Ie&&Re&&E(Re)&&v.node.start!=null&&v.node.end!=null&&e.on_audited_ui_call?.({file_path:L.file,host_file:Re.file,start:v.node.start,end:v.node.end,source_hash:`sha256:${og("sha256").update(L.source).digest("hex")}`}),Z(te,B(te,v,z),Ie?"jsx-props":"unknown",Ie?X(te,v,L,z,j):new Map,f?f.bind(te,[P(v,K)],K):K)},JSXExpressionContainer(v){let $=v.get("expression"),te=v.parentPath;if(te?.isJSXAttribute()&&W.isJSXIdentifier(te.node.name)&&(te.node.name.name==="ref"||/^on[A-Za-z]/u.test(te.node.name.name))){F($,L,z,j);return}if($.isFunctionExpression()||$.isArrowFunctionExpression())Z($,z,"unknown",j);else if($.isIdentifier()){I_($,j)&&!U($)&&!xt(f?.value($,K)??null)&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"A local data object escapes through an unproven JSX value.",$.node);let Ie=he($.scope.getBinding($.node.name),L);Ie&&Z(Ie,z,"unknown",j)}},MemberExpression(v){let $=v.parentPath;$?.isMemberExpression()&&$.node.object===v.node||($?.isCallExpression()||$?.isOptionalCallExpression())&&$.node.callee===v.node||$?.isVariableDeclarator()&&$.node.init===v.node&&ue(v,L,new Set)||pe(v)||sg(v,z,j,U)||I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"A property read may invoke an unproven getter or proxy.",v.node)},OptionalMemberExpression(v){pe(v)||sg(v,z,j,U)||I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"An optional property read may invoke an unproven getter or proxy.",v.node)},VariableDeclarator(v){(W.isObjectPattern(v.node.id)&&!xt(f?.value(v.get("init"),K)??null)&&!G0(v,z,j,U)||W.isArrayPattern(v.node.id))&&I("CMS_DESTRUCTURING_UNRESOLVED",L.file,"Destructuring can invoke an unproven getter or iterator.",v.node)},CatchClause(v){v.node.param&&!W.isIdentifier(v.node.param)&&I("CMS_DESTRUCTURING_UNRESOLVED",L.file,"A caught value may invoke an unproven getter or iterator.",v.node.param)},AssignmentExpression(v){let $=v.get("left");$.isIdentifier()&&["Boolean","Number","String","Promise","Object","encodeURIComponent"].includes($.node.name)&&!$.scope.getBinding($.node.name)&&I("CMS_GLOBAL_BUILTIN_MUTATED",L.file,"A relied-upon global builtin is reassigned by reachable source.",v.node),(W.isObjectPattern(v.node.left)||W.isArrayPattern(v.node.left))&&I("CMS_DESTRUCTURING_UNRESOLVED",L.file,"A destructuring assignment may invoke an unproven getter or iterator.",v.node)},ForOfStatement(v){I("CMS_ITERATION_UNRESOLVED",L.file,"An iterable may invoke an unproven iterator.",v.node)},SpreadElement(v){I("CMS_ITERATION_UNRESOLVED",L.file,"A spread may invoke an unproven iterator or getter.",v.node)},JSXSpreadAttribute(v){I("CMS_PROPERTY_ACCESS_UNRESOLVED",L.file,"A JSX spread may invoke an unproven getter or proxy.",v.node)},AwaitExpression(v){let $=f?.value(v.get("argument"),K);$?.kind!=="promise"&&!xt($??null)&&!H(v.get("argument"),L,z)&&I("CMS_AWAIT_TARGET_UNRESOLVED",L.file,"Awaiting an unproven value may execute a hidden thenable.",v.node)},ReturnStatement(v){let $=v.getFunctionParent(),te=v.get("argument");$?.node.async&&te.node&&!H(te,L,z)&&!xt(f?.value(te,K)??null)&&I("CMS_ASYNC_RETURN_UNRESOLVED",L.file,"An async return may execute an unproven thenable.",v.node)},CallExpression(v){if(W.isImport(v.node.callee)){I("CMS_DYNAMIC_IMPORT_UNRESOLVED",L.file,"A dynamic import cannot prove the selected call closure.",v.node);return}let $=W0(v),te=f?.arrayCall(v,K);if(te){te.empty||Z(te.target,new Map,"unknown",j,f.bind(te.target,te.args,K));return}for(let Pe of v.get("arguments"))if(Pe.isFunctionExpression()||Pe.isArrowFunctionExpression()){let nt=$?.callback===Pe.node?new Map(j).set($.parameter,$.properties):j;Z(Pe,new Map,"unknown",nt,K)}if($)return;let Ie=v.get("callee"),Re=ue(Ie,L,new Set);if(Re){if(rn(L.ast,Re.originalName)){I("CMS_BINDING_MUTATED",L.file,"The trusted CMS binding or one of its aliases is modified.",v.node);return}let nt=v.get("arguments")[0],Ut=k_(Re.name),Vt={file:L.file,imports:new Map([["__vcpCms",{source:Re.source,importedName:Re.importedName}]])},pt=$n(W.callExpression(Ut,[]),Vt)?.operation;if(u&&pt&&!v.get("arguments").every(Bt=>xt(f?.value(Bt,K)??null))){I("CMS_REQUEST_ARGUMENT_UNPROVEN",L.file,"The audited CMS reader requires data-only request arguments.",v.node);return}if(u&&Re.importedName==="cms"&&Re.name.startsWith("__vcpCms.field.")&&Ym(Re.name.slice(15))){v.get("arguments").every(Bt=>xt(f?.value(Bt,K)??null))||I("CMS_FIELD_VALUE_UNPROVEN",L.file,"The audited field helper requires proven plain data arguments.",v.node);return}if(pt==="getByUrl"||pt==="getByUrlStrict"){let Bt=nt&&hu(nt,z);if(Bt&&r.add(Bt),u&&Bt&&e.trusted_cms_schemas?.some(Mr=>Mr.source_slug===Bt)){T(Bt,pt,L,v.node),pt==="getByUrlStrict"&&p(v,L);return}I("CMS_URL_COLLECTION_UNPROVEN",L.file,"A site-wide CMS URL lookup does not prove which application owns the returned record.",v.node);return}let Vn=["cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(Re.importedName),Ir=nt?Vn?t$(nt,z):Gt(nt,z,new Set):null;if(!Ir||Ir.length===0){I("CMS_IDENTITY_UNRESOLVED",L.file,"The CMS application identity is not statically bounded.",v.node);return}for(let Bt of Ir){if(Vn&&Bt==="/content/by-url"){I("CMS_URL_COLLECTION_UNPROVEN",L.file,"A site-wide CMS URL lookup does not prove which application owns the returned record.",v.node);continue}if(Vn&&!/^\/collections\/[a-z0-9][a-z0-9_-]{0,79}\/(?:records(?:\/[a-z0-9_-]+)?|schema|categories)$/iu.test(Bt)){I("CMS_OPERATION_UNRESOLVED",L.file,"The CMS transport path does not prove a collection-scoped read.",v.node);continue}let Mr=$n(W.callExpression(Ut,[W.stringLiteral(Bt)]),Vt),Gi=Mr?.collection;if(!Mr||Mr.sourceKind!=="vcp-cms-collection"||!Gi||!/^[a-z0-9][a-z0-9_-]*$/iu.test(Gi)){I("CMS_OPERATION_UNRESOLVED",L.file,"The CMS operation or application identity cannot be proven.",v.node);continue}T(Gi,Mr.operation,L,v.node)}return}if(Ie.isIdentifier()){let Pe=Ie.scope.getBinding(Ie.node.name),nt=he(Pe,L);if(nt){let Ut=new Map,Vt=nt.get("params");for(let[pt,Vn]of Vt.entries()){if(!Vn.isIdentifier())continue;let Ir=nt.scope.getBinding(Vn.node.name),Bt=v.get("arguments")[pt];Ir&&Ut.set(Ir.identifier,Bt?Gt(Bt,z,new Set):null)}Z(nt,Ut,"unknown",j,f?f.bind(nt,v.get("arguments").map(pt=>f.value(pt,K)),K):K);return}if(!Pe&&Ie.node.name==="Boolean"||!Pe&&["String","Number","encodeURIComponent"].includes(Ie.node.name)&&v.get("arguments").every(Ut=>ee(Ut)))return}C_(v,z,Pe=>!!ue(Pe,L,new Set))||b(Ie.isIdentifier()?Ie.scope.getBinding(Ie.node.name):void 0)&&v.get("arguments").every(Pe=>ee(Pe))||f?.value(v,K)||I("CMS_CALL_TARGET_UNRESOLVED",L.file,"A reachable call target cannot be proven free of hidden CMS access.",v.node)},OptionalCallExpression(v){I("CMS_CALL_TARGET_UNRESOLVED",L.file,"An optional call target cannot be proven.",v.node)},NewExpression(v){u&&W.isIdentifier(v.node.callee,{name:"Error"})&&!v.scope.getBinding("Error")&&v.get("arguments").every($=>ee($))||I("CMS_CALL_TARGET_UNRESOLVED",L.file,"A constructor's effects cannot be proven.",v.node)},TaggedTemplateExpression(v){I("CMS_CALL_TARGET_UNRESOLVED",L.file,"A tagged template's effects cannot be proven.",v.node)}})}function P(O,L){let z=new Map;for(let j of O.get("attributes")){if(!j.isJSXAttribute()||!W.isJSXIdentifier(j.node.name)||z.has(j.node.name.name))return null;let K=j.get("value"),ee=!K.node||K.isStringLiteral()?{kind:"primitive"}:K.isJSXExpressionContainer()?f?.value(K.get("expression"),L):null;ee&&z.set(j.node.name.name,ee)}return{kind:"object",properties:z}}function F(O,L,z,j,K=0){if(!O.node||K>=32){I("CMS_CALL_TARGET_UNRESOLVED",L.file,"An event handler target cannot be proven.",O.node??void 0);return}let ee=v=>F(v,L,z,j,K+1);if(O.isTSAsExpression()||O.isTSSatisfiesExpression()||O.isTSNonNullExpression()||O.isParenthesizedExpression()){ee(O.get("expression"));return}if(O.isConditionalExpression()){ee(O.get("consequent")),ee(O.get("alternate"));return}if(O.isLogicalExpression()){ee(O.get("left")),ee(O.get("right"));return}if(yo(O,z)||O.isUnaryExpression({operator:"void"})||O.isIdentifier({name:"undefined"})&&!O.scope.getBinding("undefined"))return;let pe=O.isFunctionExpression()||O.isArrowFunctionExpression()?O:O.isIdentifier()?he(O.scope.getBinding(O.node.name),L):null;pe?Z(pe,z,"unknown",j):I("CMS_CALL_TARGET_UNRESOLVED",L.file,"An event handler target cannot be proven.",O.node)}function B(O,L,z){let j=new Map,K=O.get("params")[0];if(!K?.isObjectPattern())return j;let ee=L.get("attributes"),pe=ee.some(v=>v.isJSXSpreadAttribute());for(let v of K.get("properties")){if(!v.isObjectProperty()||v.node.computed)continue;let $=v.node.key,te=W.isIdentifier($)?$.name:W.isStringLiteral($)?$.value:null,Ie=v.get("value"),Re=Ie.isIdentifier()?Ie:Ie.isAssignmentPattern()&&Ie.get("left").isIdentifier()?Ie.get("left"):null;if(!te||!Re?.isIdentifier())continue;let Pe=O.scope.getBinding(Re.node.name);if(!Pe)continue;let nt=ee.filter(pt=>pt.isJSXAttribute()&&W.isJSXIdentifier(pt.node.name,{name:te})),Ut=null,Vt=nt[0];if(!pe&&nt.length===1&&Vt?.isJSXAttribute()){let pt=Vt.get("value");pt.isStringLiteral()?Ut=[pt.node.value]:pt.isJSXExpressionContainer()&&(Ut=Gt(pt.get("expression"),z,new Set))}j.set(Pe.identifier,Ut)}return j}function U(O){let L=O.parentPath,z=L?.parentPath,j=z?.parentPath;if(!L?.isJSXExpressionContainer()||L.node.expression!==O.node||!z?.isJSXAttribute()||!W.isJSXIdentifier(z.node.name)||!j?.isJSXOpeningElement()||!W.isJSXIdentifier(j.node.name)||/^[a-z]/u.test(j.node.name.name)||__(j,S)||j.node.attributes.some($=>!W.isJSXAttribute($)||!W.isJSXIdentifier($.name)||$.name.name==="__proto__"))return!1;let K=z.node.name.name;if(j.node.attributes.filter($=>W.isJSXAttribute($)&&W.isJSXIdentifier($.name,{name:K})).length!==1)return!1;let ee=j.findParent($=>$.isProgram()),pe=ee&&W.isProgram(ee.node)?o.get(ee.node):void 0;if(!pe)return!1;let v=he(j.scope.getBinding(j.node.name.name),pe);return v?G(v,K)!==null:!1}function G(O,L){let z=O.get("params")[0];if(!z?.isObjectPattern())return null;let j=z.get("properties").filter(pe=>!pe.isObjectProperty()||pe.node.computed?!1:Ki(pe.node.key,!1)===L&&pe.get("value").isIdentifier());if(j.length!==1)return null;let K=j[0];if(!K.isObjectProperty())return null;let ee=K.get("value");return ee.isIdentifier()?O.scope.getBinding(ee.node.name)??null:null}function X(O,L,z,j,K){let ee=new Map;for(let pe of L.get("attributes")){if(!pe.isJSXAttribute()||!W.isJSXIdentifier(pe.node.name))continue;let v=pe.node.name.name;if(L.node.attributes.filter(Pe=>W.isJSXAttribute(Pe)&&W.isJSXIdentifier(Pe.name,{name:v})).length!==1)continue;let $=pe.get("value");if(!$.isJSXExpressionContainer())continue;let te=$.get("expression");if(te.isIdentifier()&&!U(te))continue;let Ie=G(O,v);if(!Ie)continue;let Re=cg(te,j,K,U);if(!Re&&(te.isObjectExpression()||te.isIdentifier()&&I_(te,K))&&I("CMS_PROPERTY_ACCESS_UNRESOLVED",z.file,"A JSX data argument is not a proven unescaped primitive-valued object.",pe.node),Re){if(!lg(Ie,Re,U)){I("CMS_PROPERTY_ACCESS_UNRESOLVED",z.file,"A transferred data object has an unproven use or escape.",pe.node);continue}ee.set(Ie.identifier,Re)}}return ee}function Z(O,L,z="unknown",j=new Map,K=new Map){let ee=O.findParent($=>$.isProgram()),pe=ee&&W.isProgram(ee.node)?o.get(ee.node):void 0;if(!pe){I("CMS_FUNCTION_UNRESOLVED",e.entry_file,"A callable has no proven source module.",O.node);return}if(E(pe))return;if(s.has(O.node)||a++>=gu){I("CMS_CALL_BUDGET_EXHAUSTED",pe.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",pe.file,"An async generator's promise and iteration effects are not proven.",O.node);for(let[$,te]of O.node.params.entries())Y0(te,z==="jsx-props"&&$===0)&&I("CMS_DESTRUCTURING_UNRESOLVED",pe.file,"A parameter pattern can invoke an unproven getter or iterator.",te);let v=O.get("body");O.node.async&&!v.isBlockStatement()&&!H(v,pe,L)&&I("CMS_ASYNC_RETURN_UNRESOLVED",pe.file,"An async return may execute an unproven thenable.",v.node),A(O,pe,L,j,K),s.delete(O.node)}function H(O,L,z,j=new Set){if(!O.node||j.has(O.node)||j.size>=32)return!1;let K=new Set(j).add(O.node);if(O.isJSXElement()||O.isJSXFragment()||Wt(O,z))return!0;if(O.isIdentifier({name:"undefined"}))return!O.scope.getBinding("undefined");if(O.isTSAsExpression()||O.isTSSatisfiesExpression()||O.isTSNonNullExpression()||O.isParenthesizedExpression()||O.isAwaitExpression())return H(O.get(O.isAwaitExpression()?"argument":"expression"),L,z,K);if(O.isConditionalExpression())return H(O.get("consequent"),L,z,K)&&H(O.get("alternate"),L,z,K);if(!O.isCallExpression())return!1;let ee=ue(O.get("callee"),L,new Set);if(ee&&!rn(L.ast,ee.originalName)||C_(O,z,Pe=>{let nt=ue(Pe,L,new Set);return!!(nt&&!rn(L.ast,nt.originalName))}))return!0;let pe=O.get("callee");if(!pe.isIdentifier())return!1;let v=he(pe.scope.getBinding(pe.node.name),L);if(!v?.node.async||j.has(v.node))return!1;let $=v.findParent(Pe=>Pe.isProgram()),te=$&&W.isProgram($.node)?o.get($.node):void 0;if(!te)return!1;let Ie=v.get("body");if(!Ie.isBlockStatement())return H(Ie,te,new Map,K);let Re=Ie.get("body");return Re.length!==1||!Re[0].isReturnStatement()?!1:H(Re[0].get("argument"),te,new Map,new Set(K).add(v.node))}function he(O,L){if(!O||O.constantViolations.length)return null;let z=O.path;if(z.isFunctionDeclaration())return z;if(z.isVariableDeclarator()){let te=z.get("init");return te.isFunctionExpression()||te.isArrowFunctionExpression()?te:null}let j=z.parentPath;if(!j?.isImportDeclaration()||j.node.importKind==="type")return null;let K=j.node.source.value;if(!mt(K))return null;let ee=wt(L.file,K,e.files),pe=ee&&l.get(ee),v=z.isImportDefaultSpecifier()?"default":z.isImportSpecifier()&&W.isIdentifier(z.node.imported)?z.node.imported.name:null;if(!pe||!v)return null;let $=Hn(pe,v,l);return $&&($.isFunctionDeclaration()||$.isFunctionExpression()||$.isArrowFunctionExpression())?$:null}function ue(O,L,z){if(!O.node||z.has(O.node)||z.size>=32)return null;if(z.add(O.node),O.isMemberExpression()&&!O.node.optional){let $=!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,te=ue(O.get("object"),L,z);return te&&$?{...te,name:`${te.name}.${$}`}: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 ue(j.path.get("init"),L,z);let K=j.path.parentPath;if(!K?.isImportDeclaration()||!j.path.isImportSpecifier())return null;let ee=j.path.node.imported,pe=W.isIdentifier(ee)?ee.name:ee.value,v=wt(L.file,K.node.source.value,e.files);return!v||!v_(v)||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(pe)?null:{name:"__vcpCms",source:v,importedName:pe,originalName:j.identifier.name}}let je=l.get(e.entry_file);if(!je)I("CMS_ENTRY_UNAVAILABLE",e.entry_file,"The selected entry is missing or invalid.");else{C(je);let O=Hn(je,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."):Z(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(L=>L.value.kind==="route-search-params"||L.value.kind==="route-params"?[[L.propName,{kind:"promise",value:L.value.kind==="route-params"&&e.entry_route_id?du(e.entry_route_id):{kind:"json"}}]]:[]))}]):new Map)}let He=[...n.entries()].sort(([O],[L])=>O.localeCompare(L)).map(([O,L])=>({requirement_key:`cms-${O}`,slug:O,evidence:L.sort((z,j)=>z.source_path.localeCompare(j.source_path)||z.call_site.line-j.call_site.line||z.call_site.column-j.call_site.column)})),ht=[...new Map(t.map(O=>[JSON.stringify(O),O])).values()];return{complete:ht.length===0,dependencies:He,unresolved:ht,...r.size&&ht.length?{candidates:[...r].sort()}:{}}}function W0(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>gu)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=Ki(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||!lg(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)||!H0.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 S_(e,t){if(!e.isObjectExpression())return null;let n=new Set;for(let r of e.get("properties")){if(!r.isObjectProperty()||!yo(r.get("value"),t))return null;let o=Ki(r.node.key,r.node.computed);if(!o||["__proto__","prototype","constructor"].includes(o)||n.has(o))return null;n.add(o)}return n}function yo(e,t,n=new Set){if(!e.node||n.has(e.node)||n.size>=32)return!1;if(Wt(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"})&&yo(o.path.get("init"),t,r))}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return yo(e.get("expression"),t,r);if(e.isConditionalExpression())return yo(e.get("consequent"),t,r)&&yo(e.get("alternate"),t,r);if(e.isLogicalExpression())return yo(e.get("left"),t,r)&&yo(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 Ki(e,t){return!t&&W.isIdentifier(e)?e.name:W.isStringLiteral(e)?e.value:null}function N_(e,t){return W.isObjectPattern(e)&&e.properties.every(n=>{if(!W.isObjectProperty(n)||!W.isIdentifier(n.value))return!1;let r=Ki(n.key,n.computed);return r!==null&&t.has(r)})}function A_(e,t){let n=Ki(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 cg(e,t,n,r){if(e.isObjectExpression())return S_(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=S_(o.path.get("init"),t)}return i&&lg(o,i,r)?i:null}function lg(e,t,n){if(e.constantViolations.length||e.referencePaths.length>gu)return!1;for(let r of e.referencePaths){let o=r.parentPath;if(!((o?.isMemberExpression()||o?.isOptionalMemberExpression())&&o.node.object===r.node&&A_(o,t))&&!(o?.isVariableDeclarator()&&o.node.init===r.node&&N_(o.node.id,t))&&!(r.isIdentifier()&&n(r)))return!1}return!0}function sg(e,t,n,r){let o=cg(e.get("object"),t,n,r);return o!==null&&A_(e,o)}function G0(e,t,n,r){let o=cg(e.get("init"),t,n,r);return o!==null&&N_(e.node.id,o)}function I_(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 Y0(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 T_(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=we(i.source_path,u);if(!d.ok)return!1;s=new Map,R_(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||!Z0(c[0],i.operation))return!1}}return!0}function Z0(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=ag(i.get("value"),new Set);if(a===null||!Number.isSafeInteger(a)||(s==="page"?a!==1:a<1||a>100))return!1}return!0}function ag(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 ag(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:ag(n.path.get("init"),t)}function v_(e){return/^(?:src\/)?lib\/cms(?:\/index|\/collections|\/client)?\.[cm]?[jt]s$/u.test(e)}function __(e,t=()=>!1){let n=e.parentPath,r=n?.parentPath;for(;r&&!r.isFunction()&&!r.isProgram();){if(r.isVariableDeclarator())return!q0(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()&&!w_(r,n?.node)||r.isLogicalExpression()&&r.node.left===n?.node||r.isLogicalExpression()&&!O_(r))return!0;if(r.isJSXElement()){let o=r.node.openingElement.name;if((!W.isJSXIdentifier(o)||!/^[a-z]/u.test(o.name))&&!ug(r.get("openingElement"))&&!t(r.get("openingElement")))return!0}n=r,r=r.parentPath}return!1}function ug(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 q0(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=Q0(o,t);if(i===null)return!1;i==="direct"&&(r=!0)}return r}function Q0(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(!w_(a,r.node))return null;r=a;continue}if(a.isLogicalExpression()&&a.node.right===r.node){if(!O_(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 w_(e,t){let n=er(e.get("test"),new Set);return n.known?n.value?t===e.node.consequent:t===e.node.alternate:!0}function O_(e){let t=er(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 er(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}:er(r.path.get("init"),n)}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return er(e.get("expression"),n);if(e.isUnaryExpression({operator:"!"})){let r=er(e.get("argument"),n);return r.known?{known:!0,value:!r.value}:{known:!1}}if(e.isBinaryExpression()&&["===","!=="].includes(e.node.operator)){let r=er(e.get("left"),n),o=er(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=er(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:er(e.get("right"),n):{known:!1}}if(e.isConditionalExpression()){let r=er(e.get("test"),n);return r.known?er(r.value?e.get("consequent"):e.get("alternate"),n):{known:!1}}return{known:!1}}function k_(e){let[t,...n]=e.split(".");return n.reduce((r,o)=>W.memberExpression(r,W.identifier(o)),W.identifier(t))}function C_(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||Wt(i,t)||i.isCallExpression()&&n(i.get("callee"))):!1}function Wt(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"})&&Wt(o.path.get("init"),t,r)}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Wt(e.get("expression"),t,r);if(e.isUnaryExpression()&&["typeof","!","void"].includes(e.node.operator))return!0;if(e.isLogicalExpression())return Wt(e.get("left"),t,r)&&Wt(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=>Wt(i,t,r)):!1}return e.isConditionalExpression()?e$(e,t,r)||Wt(e.get("consequent"),t,r)&&Wt(e.get("alternate"),t,r):e.isBinaryExpression()?["===","!=="].includes(e.node.operator)||e.node.operator!=="in"&&e.node.operator!=="instanceof"&&Wt(e.get("left"),t,r)&&Wt(e.get("right"),t,r):!1}function e$(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&&Wt(g,t,n)}function L_(e,t,n,r,o=new Set){if(!e.node||o.has(e.node)||o.size>=32)return!1;if(Wt(e,t))return!0;let i=new Set(o).add(e.node),s=a=>L_(a,t,n,r,i);if(e.isMemberExpression()||e.isOptionalMemberExpression())return sg(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 Gt(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"})?Gt(o.path.get("init"),t,r):null}if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isTSNonNullExpression()||e.isParenthesizedExpression())return Gt(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=Gt(s,t,r),c=e.node.quasis[i+1]?.value.cooked;if(!a||c==null||o.length*a.length>ig)return null;o=o.flatMap(l=>a.map(u=>`${l}${u}${c}`))}return[...new Set(o)]}if(e.isConditionalExpression()){let o=Gt(e.get("consequent"),t,r),i=Gt(e.get("alternate"),t,r);if(!o||!i)return null;let s=[...new Set([...o,...i])];return s.length<=ig?s:null}if(e.isBinaryExpression({operator:"+"})){let o=Gt(e.get("left"),t,r),i=Gt(e.get("right"),t,r);return!o||!i||o.length*i.length>ig?null:[...new Set(o.flatMap(s=>i.map(a=>s+a)))]}return null}function t$(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=Ki(o.node.key,!1);if(!i||!["path","method"].includes(i)||n.has(i))return null;if(n.add(i),i==="path"&&(r=Gt(o.get("value"),t,new Set)),i==="method"){let s=Gt(o.get("value"),t,new Set);if(!s||s.length!==1||s[0]!=="GET")return null}}return r}function hu(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 hu(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:hu(a.path.get("init"),t,r)}let o=null,i=null;if(e.isBinaryExpression({operator:"+"})){let a=Gt(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:Pi(`${o}:record`)}var ya=typeof dg=="function"?dg:dg.default;function gg(e){return B_(e,!1)}function s$(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=B_({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 B_(e,t){let n=xg(e.files),r=(g,m,f)=>({complete:!1,relation:null,errors:[{code:g,path:m,message:f}]}),o=$_(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(W_),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=Yo(g,m,i,"getByUrlStrict",n,e.detail_prefix??`/${i}`);return f&&Eu(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(!k$(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=Bn(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let m=mn(u.path,g.source,n),f=m?n.get(m):void 0;return!m||typeof f!="string"||!J_(f,g.export_name)||!xu(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 j_(e){let t=$_(e,xg(e.files));return t.complete&&t.consumer!==null}function $_(e,t,n=!1){let r=(c,l)=>({complete:!1,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:c,message:l}]}),o=mn(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(!y$(i,o,"listStrict"))return{complete:!0,slug:null,consumer:null};if(!n&&!bu(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=h$(i,o),a=s?Yo(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 bu(e,t,n,r=!1,o="default"){let i=_t(n.get(e));if(i===null)return!1;let s=we(e,i);if(!s.ok)return!1;let a=qt({module:s.module,exportName:o,allowNonRenderingGuards:r});if(!a.ok||a.metadataOnly)return!1;let c=Bn(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(!D.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"&&D.isIdentifier(x.path.node.imported,{name:"default"}))&&typeof f.node.start=="number"&&l.has(f.node.start)&&mn(e,E.node.source.value,n)===t){p++;return}if(!ug(f))return}if(a$(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 a$(e){if(!D.isJSXIdentifier(e.name)||["template","noscript","script","style","head","dialog","details"].includes(e.name.name))return!0;for(let t of e.attributes){if(D.isJSXSpreadAttribute(t)||!D.isJSXIdentifier(t.name))return!0;let n=t.name.name;if(["style","dangerouslySetInnerHTML"].includes(n)||n==="className"&&!D.isStringLiteral(t.value)&&(!D.isJSXExpressionContainer(t.value)||!D.isStringLiteral(t.value.expression)))return!0;if(["hidden","inert","aria-hidden"].includes(n)){let r=t.value;if(n==="aria-hidden"&&D.isStringLiteral(r,{value:"false"})||D.isJSXExpressionContainer(r)&&D.isBooleanLiteral(r.expression,{value:!1}))continue;return!0}}return!1}function hg(e){let t=xg(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."});fg(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),fg(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),fg(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&&H_(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&&pg(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),W_(e.collection.detail_entry_file)?pg(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=br({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!r$.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"||Bi({node:b,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!C$(b.path))continue;d.add(b.path);let I=s.get(b.path),T=I===void 0?null:`sha256:${n$("sha256").update(I).digest("hex")}`;(!T||e.trusted_host_file_hashes?.get(b.path)!==T)&&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?l$(e.collection,t,s):null,m=e.trusted_schema===void 0?null:u$(e,t,n,e.trusted_schema),f=i&&m&&e.trusted_schema?c$(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(_$(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}pg(o,{path:b.path,kind:b.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}R$(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"&&I$(y,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=v$(e.page_template,t,n));let x=A$(r).map((b,S)=>({key:w$(b,S),pathTemplate:b.path,export:b.export,purpose:b.purpose,requirementKey:e.collection.requirement_key})),E=O$(n).sort(L$);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(T$),thin_entry_plan:a,collection_wiring:m,errors:E}}function c$(e,t,n,r,o){let i=i$.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=_t(r.get(t.list_container_file)),d=_t(r.get(e.detail_entry_file)),p=yg(e.detail_entry_file);if(u===null||d===null||!p)return null;let g=Yo(t.list_container_file,u,e.slug,"listStrict",r),m=Yo(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||mn(g.path,g.adapter_source,r)!==f||mn(m.path,m.adapter_source,r)!==f)return null;let y=o.get(f);if(y===void 0)return null;let x=wm(e.slug,s,{forceMultiMedia:l});return typeof y=="string"?y===x?f:null:Buffer.from(y).equals(Buffer.from(x))?f:null}function l$(e,t,n){let r=t.get(e.detail_entry_file),o=yg(e.detail_entry_file);if(typeof r!="string"||!o)return null;let i=Yo(e.detail_entry_file,r,e.slug,"getByUrlStrict",t,o);if(!i)return null;let s=Eu(i.ast,o),a=K_(i,t,s);if(!s||!a||a==="unproven")return null;let c=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!bu(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=o$({slug:e.slug,detailPrefix:s,...a,headerShell:d});return typeof l=="string"?l===p:Buffer.from(l).equals(Buffer.from(p))})?c:null}function u$(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 T=t.get(I.path);if(typeof T!="string")return[];let C=Yo(I.path,T,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?F_(a,t,I=>I!==e.collection.detail_view_file):null;c?a&&!xu(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=yg(e.collection.detail_entry_file),d=typeof l=="string"&&u?Yo(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t,u):null,p=d?F_(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."}):xu(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?mn(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(mg),x=[...e.force_multi_media??(typeof f=="string"?X_(f):[])].sort(mg);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"||!S$(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?Eu(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?E$(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?K_(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 Yo(e,t,n,r,o,i=`/${n}`){let s;try{s=bo(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=xo(s,u=>D.isCallExpression(u)&&Zo(u.callee,r));if(!g$(s,e,o,r)||r==="listStrict"&&(a.length!==1||!D.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||Eu(s,i)===null))return null;let l=s.program.body.flatMap(u=>D.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!D.isImportSpecifier(d))return[];let p=D.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=>xo(s,d=>D.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!d$(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 d$(e,t,n,r,o,i){let s=!1;return ya(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!D.isJSXIdentifier(a.node.name)||a.node.attributes.some(x=>D.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&&(!D.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=mn(t,p.node.source.value,n);if(!g||!xu(n.get(g),r.source,r.interface_name))return;let m=a.get("attributes").filter(x=>x.isJSXAttribute()&&D.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"?U_(f.get("expression"),c,r,i,y,new Set):V_(f.get("expression"),c,r,y,new Set))&&(s=!0)}}),s}function U_(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"})||ha(m.referencePaths,n,o)?!1:U_(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||!D.isIdentifier(s.node.property,{name:"map"}))return!1;let a=e.get("arguments")[0];if(!a||!yu(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||!D.isIdentifier(c.node.property,{name:"items"}))return!1;let l=c.get("object");if(!l.isMemberExpression()||l.node.computed||!D.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"})||ha(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()&&Zo(g.node.callee,"listStrict")&&D.isStringLiteral(g.node.arguments[0],{value:r})}function V_(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"})||ha(d.referencePaths,n,r)?!1:V_(d.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!yu(i,n))return!1;let s=e.get("arguments")[0];if(!s?.isMemberExpression()||s.node.computed||!D.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"})||ha(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()&&Zo(u.node.callee,"getByUrlStrict")}function yu(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"||!D.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function ha(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(!D.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),ha(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&&D.isIdentifier(c.node.property,{name:"map"})&&l&&yu(l,t))}let a=s.get("callee");return!(i.isMemberExpression()&&!i.node.computed&&D.isIdentifier(i.node.property,{name:"data"})&&yu(a,t))}if(s?.isJSXExpressionContainer()){let a=s.parentPath;return n?.attribute==="record"&&i.isMemberExpression()&&i.node.object===o.node&&!i.node.computed&&D.isIdentifier(i.node.property)&&a?.isJSXAttribute()&&f$(a,i.node.property.name,t,n)?!1:!(n&&a?.isJSXAttribute()&&a.parentPath===n.opening&&D.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 f$(e,t,n,r){if(["__proto__","prototype","constructor"].includes(t)||!D.isJSXIdentifier(e.node.name)||["key","ref"].includes(e.node.name.name))return!1;let o=e.parentPath;if(!o?.isJSXOpeningElement()||!D.isJSXIdentifier(o.node.name)||/^[a-z]/u.test(o.node.name.name)||o.node.attributes.some(d=>D.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=mn(r.file,s.node.source.value,r.files),c=mn(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:p$(l,a)&&m$(u,c,`to${n.interface_name}`,t)}function p$(e,t){let n=we(t,e);if(!n.ok||n.module.ast.program.body.length!==1)return!1;let r=n.module.ast.program.body[0];if(!D.isExportDefaultDeclaration(r)||!D.isFunctionDeclaration(r.declaration)||r.declaration.params.length!==0||r.declaration.async||r.declaration.generator)return!1;let o=!1;return ya(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||!D.isIdentifier(i.node.property,{name:"length"})||!a?.constant||!a.path.isVariableDeclarator()||!D.isArrayExpression(a.path.node.init))&&(o=!0)},OptionalMemberExpression(){o=!0},ObjectProperty(i){i.node.computed&&(o=!0)},VariableDeclarator(i){D.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;!D.isStringLiteral(s)&&!D.isNumericLiteral(s)&&!D.isBooleanLiteral(s)&&!D.isNullLiteral(s)&&!D.isJSXEmptyExpression(s)&&!(D.isMemberExpression(s)&&D.isJSXElement(i.parentPath.node))&&(o=!0)},JSXOpeningElement(i){(!D.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=>!D.isJSXAttribute(s)||!D.isJSXIdentifier(s.name)||!["className","id","role","title","aria-label"].includes(s.name.name)))&&(o=!0)}}),!o}function m$(e,t,n,r){let o=we(t,e);if(!o.ok)return!1;let i=o.module.ast.program.body.filter(d=>D.isExportNamedDeclaration(d)&&D.isFunctionDeclaration(d.declaration)&&d.declaration.id?.name===n);if(i.length!==1)return!1;let s=i[0].declaration;if(!D.isFunctionDeclaration(s)||s.async||s.generator)return!1;let a=!1;if(ya(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=xo(s.body,d=>D.isReturnStatement(d)),l=s.body.body.at(-1);if(c.length!==1||!D.isReturnStatement(l)||l!==c[0]||!D.isObjectExpression(l.argument))return!1;let u=new Set;for(let d of l.argument.properties){if(!D.isObjectProperty(d)||d.computed||!(D.isIdentifier(d.key)||D.isStringLiteral(d.key)))return!1;let p=D.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 g$(e,t,n,r){let o=0,i=rn(e,"cms");for(let s of e.program.body){if(!D.isImportDeclaration(s)||s.importKind==="type")continue;let a=mn(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(D.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!D.isImportSpecifier(c))return!0;let l=D.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return ya(e,{CallExpression(s){if(!Zo(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"||!D.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=mn(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&&D.isIdentifier(p.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===p.node&&!g.node.computed&&D.isIdentifier(g.node.property)&&m?.isCallExpression()&&m.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function h$(e,t){let n;try{n=bo(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=xo(n,o=>D.isCallExpression(o)&&Zo(o.callee,"listStrict")&&D.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 y$(e,t,n){let r;try{r=bo(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return xo(r,o=>D.isCallExpression(o)&&Zo(o.callee,n)).length>0}function F_(e,t,n){let r=Bn(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=mn(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!J_(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 J_(e,t){let n;try{n=bo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&D.isExportDefaultDeclaration(r))return!0;if(D.isExportNamedDeclaration(r)&&(r.declaration&&(D.isFunctionDeclaration(r.declaration)||D.isClassDeclaration(r.declaration)||D.isTSInterfaceDeclaration(r.declaration)||D.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||D.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>D.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>D.isExportSpecifier(o)?(D.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function xu(e,t,n){if(typeof e!="string")return!1;let r;try{r=bo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!D.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>D.isImportSpecifier(s)?(D.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>xo(r,s=>D.isIdentifier(s,{name:i})).length>1)}function Zo(e,t){return D.isMemberExpression(e)&&!e.computed&&D.isIdentifier(e.property,{name:t})&&D.isMemberExpression(e.object)&&!e.object.computed&&D.isIdentifier(e.object.property,{name:"collections"})&&D.isIdentifier(e.object.object,{name:"cms"})}function Eu(e,t){let n=[];return ya(e,{CallExpression(r){Zo(r.node.callee,"getByUrlStrict")&&n.push(x$(r.node.arguments[0],o=>b$(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function x$(e,t){return D.isBinaryExpression(e,{operator:"+"})&&D.isStringLiteral(e.left)&&D.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):D.isTemplateLiteral(e)&&e.expressions.length===1&&D.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 b$(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(D.isObjectPattern(r.id)&&D.isAwaitExpression(r.init)&&D.isIdentifier(r.init.argument))return r.id.properties.some(a=>D.isObjectProperty(a)&&!a.computed&&Su(a.key)==="slug"&&D.isIdentifier(a.value,{name:t}))&&D_(n.path,r.init.argument.name);let o=r.init;if(!D.isIdentifier(r.id,{name:t})||!D.isCallExpression(o)||!D.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!D.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 D.isMemberExpression(s)&&!s.computed&&D.isIdentifier(s.property,{name:"slug"})&&D.isAwaitExpression(s.object)&&D.isIdentifier(s.object.argument)&&D_(n.path,s.object.argument.name)}function D_(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=>D.isObjectPattern(i)&&i.properties.some(s=>D.isObjectProperty(s)&&!s.computed&&Su(s.key)==="params"&&D.isIdentifier(s.value,{name:t})))}function E$(e){for(let t of e.program.body)if(D.isVariableDeclaration(t))for(let n of t.declarations){if(!D.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=z_(n.init);if(!D.isObjectExpression(r))return null;let o=r.properties.find(i=>D.isObjectProperty(i)&&!i.computed&&Su(i.key)==="title");return o&&D.isStringLiteral(o.value)?o.value.value:null}return null}function K_(e,t,n){let o=Bn(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=mn(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=bo(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of xo(a,l=>D.isArrayExpression(l))){let l=c.elements.flatMap(p=>{if(!D.isObjectExpression(p))return[];let g=new Map;for(let m of p.properties){if(!D.isObjectProperty(m)||m.computed)continue;let f=Su(m.key);f&&D.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 X_(e){let t;try{t=bo(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(xo(t,n=>{if(!D.isCallExpression(n))return!1;let r=n.callee;if(!D.isMemberExpression(r)||r.computed||!D.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return D.isMemberExpression(o)&&!o.computed&&D.isIdentifier(o.object,{name:"d"})&&D.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return D.isMemberExpression(r)&&!r.computed&&D.isIdentifier(r.property)?[r.property.name]:[]}))].sort(mg)}function S$(e,t){return X_(e).includes(t)}function xo(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)M_(s)&&r(s);else M_(i)&&r(i)};return r(e),n}function M_(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function z_(e){return e?D.isTSAsExpression(e)||D.isTSTypeAssertion(e)||D.isTSNonNullExpression(e)?z_(e.expression):e:null}function Su(e){return D.isIdentifier(e)?e.name:D.isStringLiteral(e)?e.value:null}function mg(e,t){return e.localeCompare(t)}function I$(e,t,n,r,o,i){let s=Bn(e,{filePath:t,exportName:"default"});for(let a of s.components){let c=mn(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"||P$(u)&&o.push({path:c,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function v$(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=Bn(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 fg(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 _$(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 H_(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function W_(e){return H_(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function k$(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 yg(e){let t=/^(?:src\/)?app\/([A-Za-z0-9_-]+)\/\[slug\]\/page\.[cm]?[jt]sx?$/u.exec(e);return t?`/${t[1]}`:null}function C$(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function R$(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=G_(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 P$(e){try{return bo(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function mn(e,t,n){if(!mt(t))return null;let r=t.startsWith("@/")?t.slice(2):N$(`${G_(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 G_(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function N$(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 xg(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=_t(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function A$(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 pg(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function T$(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function w$(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function O$(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function L$(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import{parse as ek}from"@babel/parser";import bg from"@babel/traverse";import*as Fe from"@babel/types";var F$=typeof bg=="function"?bg:bg.default,D$=ek(`
41
+ `;return Dl({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)?Dt("SOURCE_INPUT_INVALID",r,"The deterministic extracted entry path collides with the fixed Snapshot map."):kj(t,o,n)}function kj(e,t,n){let r;try{r=xj(t,{sourceType:"module",sourceFilename:e.source_file,plugins:["jsx","typescript"]})}catch(C){return Dt("SOURCE_PARSE_FAILED",e.source_file,C instanceof Error?C.message:String(C))}let o=_j(r,e);if(o.length!==1)return Dt("SOURCE_NOT_PORTABLE",e.source_file,"The pinned source range must identify exactly one current JSX root.");let i=o[0],s=i.findParent(C=>C.isFunction());if(!s||!FI(s.node))return Dt("SOURCE_NOT_PORTABLE",e.source_file,"The selected JSX root is not inside one statically bounded component function.");let a=s,c=Kj(a);if(!c.ok)return Dt("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 C of r.program.body){if(!L.isImportDeclaration(C)||C.specifiers.length||C.importKind==="type")continue;let w=C.source.value,M=w.startsWith(".")||w.startsWith("@/")?$l(e.source_file,w,n):null;if(!M?.endsWith(".css"))return Dt("SOURCE_NOT_PORTABLE",e.source_file,"A bare module effect is not a proven portable stylesheet dependency.");u.has(M)||l.imports.add(C),u.add(M)}let d=Rj(a,e);if(!d.ok)return{complete:!1,errors:[d.error]};if(Cj(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(C=>L.isVariableDeclaration(C)&&C.declarations.some(w=>L.isIdentifier(w.id,{name:c.translationBinding}))))return Dt("SOURCE_NOT_PORTABLE",e.source_file,"The containing component's i18n hook is not part of the selected dependency closure.");let f=Hj(r,"__vcpPortableProps"),g=L.cloneNode(i.node,!0),m=[];for(let C of[...l.imports].sort(mm)){let w=Uj(C,e.source_file,e.entry_file,n);if(!w.ok)return{complete:!1,errors:[w.error]};m.push(w.node)}let p=[...l.moduleDeclarations].sort(mm).map(C=>L.cloneNode(C,!0)),y=[...l.functionDeclarations].sort(mm).map(C=>L.cloneNode(C,!0)),b=L.returnStatement(g),E=[...l.props].filter(([C])=>!C.startsWith("@")).map(([C,w])=>L.variableDeclaration("const",[L.variableDeclarator(L.identifier(C),L.memberExpression(L.identifier(f),L.identifier(w)))]));l.propsObjectName&&E.push(L.variableDeclaration("const",[L.variableDeclarator(L.identifier(l.propsObjectName),L.identifier(f))]));let x=L.blockStatement([...E,...y,b]),S=l.props.size?[$j(f)]:[],v=L.functionDeclaration(L.identifier("PortableBlockEntry"),S,x),N=L.program([...m,...p,v,L.exportDefaultDeclaration(L.identifier("PortableBlockEntry"))]);N.directives=r.program.directives.map(C=>L.cloneNode(C,!0));let R=vj(L.file(N),{jsescOption:{minimal:!0}}).code,A={generated_path:e.entry_file,source_file:e.source_file,structural_path:e.structural_path};return Dl({entryFile:e.entry_file,entryContent:R,files:n,selection:e,sourceMapping:A,invocationBindings:zj(e,l.props)})}function _j(e,t){let n=[];return bm(e,{JSXElement(r){r.node.start===t.source_range.start_offset&&r.node.end===t.source_range.end_offset&&n.push(r)}}),n}function Rj(e,t){let n=e.node.params;if(n.length>1)return{ok:!1,error:Et("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(L.isIdentifier(o))return{ok:!0,value:{bindingByLocalName:r,propsParameter:o}};if(!L.isObjectPattern(o))return{ok:!1,error:Et("SOURCE_NOT_PORTABLE",t.source_file,"Component props must use one identifier or a static object pattern.")};for(let i of o.properties){if(!L.isObjectProperty(i)||i.computed||!(L.isIdentifier(i.key)||L.isStringLiteral(i.key))||!(L.isIdentifier(i.value)||L.isAssignmentPattern(i.value)&&L.isIdentifier(i.value.left)))return{ok:!1,error:Et("SOURCE_NOT_PORTABLE",t.source_file,"Rest, computed, or nested component prop destructuring is not supported.")};let s=L.isIdentifier(i.key)?i.key.name:i.key.value,a=i.value,c=L.isIdentifier(a)?a.name:L.isAssignmentPattern(a)&&L.isIdentifier(a.left)?a.left.name:"";r.set(c,s)}return{ok:!0,value:{bindingByLocalName:r,propsParameter:null}}}function Cj(e,t,n,r,o,i,s,a){let c=new Set,l=new Map,u=m=>{let p=l.get(m);if(p!==void 0)return p;let y=Nj(n,r,m,o,a);return l.set(m,y),y||s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,`Selected prop ${m} is mutated or escapes its proven invocation value.`)),y},d=m=>{let p=m.node.name,y=m.scope.getBinding(p);if(!y){EI.has(p)||s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,`The selected root references unbound identifier ${p}.`));return}if(!Bl(y.path.node,t)){if(r.bindingByLocalName.has(p)&&y.scope===n.scope){let b=r.bindingByLocalName.get(p);vI(o,b)?u(b)&&s.props.set(p,b):s.errors.push(Et("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&&m.parentPath?.isMemberExpression()&&m.parentPath.node.object===m.node){let b=m.parentPath.node,E=!b.computed&&L.isIdentifier(b.property)?b.property.name:b.computed&&L.isStringLiteral(b.property)?b.property.value:null;E&&vI(o,E)?u(E)&&(s.propsObjectName=p,s.props.set(`@${p}.${E}`,E)):s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,`The selected root reads an unproven dynamic prop through ${p}.`));return}c.has(y)||(c.add(y),SI(y,n,o,s,d,f,a))}},f=(m,p)=>{let y=OI(m);if(!y||/^[a-z]/u.test(y.name))return;let b=p.scope.getBinding(y.name);if(!b){EI.has(y.name)||s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,`The selected root component ${y.name} has no proven import or declaration.`));return}c.has(b)||Bl(b.path.node,t)||(c.add(b),SI(b,n,o,s,d,f,a))};(m=>{m.isIdentifier()&&m.isReferencedIdentifier()&&d(m),m.isJSXElement()&&f(m.node.openingElement.name,m),m.traverse({ReferencedIdentifier(p){d(p)},JSXOpeningElement(p){f(p.node.name,p)},CallExpression(p){wI(p,i)||s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,"A selected-root call is not a proven pure helper or statically bound translation."))},AssignmentExpression(p){s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,"Assignments inside a selected root are not a closed Portable dependency.")),p.stop()},UpdateExpression(p){s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,"Updates inside a selected root are not a closed Portable dependency.")),p.stop()},NewExpression(p){s.errors.push(Et("SOURCE_NOT_PORTABLE",o.source_file,"Dynamic object construction inside a selected root is not proven portable.")),p.stop()}})})(e)}function SI(e,t,n,r,o,i,s){let a=e.path;if(Xj(a,t)||a.isFunctionDeclaration()&&a.node===t.node){r.errors.push(Et("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(Et("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is rebound outside its declaration.`));return}if(Oj(e)){r.errors.push(Et("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} has a member write outside its declaration.`));return}let c=new Ml(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=$l(n.source_file,u.node.source.value,s),b=y?c.get(y):void 0,E=a.isImportDefaultSpecifier()?"default":a.isImportSpecifier()&&a.node.importKind!=="type"?sn(a.node.imported,!1):null,x=b&&E&&u.node.importKind!=="type"?ho(b,E,c):null,S=x?on(x):null;if(!S?.length){r.errors.push(Et("SOURCE_NOT_PORTABLE",n.source_file,"The imported value has no bounded unique Snapshot source."));return}l.set(e.identifier,S),f=S.every(v=>v.isFunctionDeclaration()||v.isFunctionExpression()||v.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||Pj(e))&&!zs(e,{bindings:new Set,activeBindings:new Set,jsxCalls:new Set,inputs:l,files:s,modules:c},!1)){r.errors.push(Et("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,b=m.get("init");if(!y?.isVariableDeclaration()||y.node.kind!=="const"||!b.node||!gr(m.node.id)||!gr(b.node)&&!Jj(b)){r.errors.push(Et("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a side-effect-free const.`));return}let x=y.findParent(v=>v.isFunction())===t?r.functionDeclarations:r.moduleDeclarations,S=L.variableDeclaration("const",[L.cloneNode(m.node,!0)]);II(x,S,m.node),m.traverse({ReferencedIdentifier(v){v.isIdentifier()&&o(v)},JSXOpeningElement(v){i(v.node.name,v)}});return}let p=a.isFunctionDeclaration()?a:a.findParent(y=>y.isFunction());if(p?.isFunctionDeclaration()&&bc(p.node)){let b=p.findParent(E=>E.isFunction())===t?r.functionDeclarations:r.moduleDeclarations;II(b,L.cloneNode(p.node,!0),p.node),p.traverse({ReferencedIdentifier(E){E.isIdentifier()&&o(E)},JSXOpeningElement(E){i(E.node.name,E)}});return}r.errors.push(Et("SOURCE_NOT_PORTABLE",n.source_file,`Captured binding ${e.identifier.name} is not a statically portable declaration.`))}function Pj(e){let t=e.path;if(!t.isVariableDeclarator())return!1;let n=t.get("init");if(!n.node)return!0;let r=jj(n.node);return L.isFunctionExpression(r)||L.isArrowFunctionExpression(r)||L.isCallExpression(r)&&xc(r)?!1:!gf(e)?.every(i=>i.isFunctionExpression()||i.isArrowFunctionExpression()||hf(i,new Map))}var Ml=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=jl(this.files,t);if(r===null)return;let o=_e(t,r);if(o.ok)return super.set(t,o.module),o.module}};function Nj(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=L.file(L.program([L.expressionStatement(L.valueToNode(i.value.value))]));bm(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 Ml(o)};if(t.propsParameter)return gm(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),!zs(d,c,!0)))return!1}return!0}function Aj(e,t){if(hf(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(L.isJSXIdentifier(i)&&/^[a-z]/u.test(i.name))return!0;if(!L.isJSXIdentifier(i)||t.jsxCalls.has(o.node)||t.jsxCalls.size>=32)return!1;let s=Tj(o,t);if(!s)return!1;let a={...t,bindings:new Set(t.bindings),jsxCalls:new Set(t.jsxCalls).add(o.node)},c=on(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(!L.isObjectProperty(f)||f.computed)return!1;let g=sn(f.key,!1);if(g===null)return!1;u.add(g)}}return[...u].every(d=>{let f=Ec(c,d,t.inputs);return f!==null&&gm(s,d,f,a)})}let l=r.isJSXAttribute()&&L.isJSXIdentifier(r.node.name)?r.node.name.name:"children";return gm(s,l,c,a)}function Tj(e,t){let n=e.node.name;if(!L.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=$l(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()?sn(r.path.node.imported,!1):null;if(!l)return null;let u=jt({module:c,exportName:l,parsedModules:t.modules});return u.ok?u.roots[0]?.getFunctionParent()??null:null}function gm(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(sn(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=zs(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=sn(c.node.property,c.node.computed);return l===null?!1:l!==t?!0:(i.set(c.node,n),NI(c,{...r,inputs:i},!0))})}function zs(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=>NI(i,r,n));return o&&t.bindings.add(e),o}function Em(e,t,n){let r=e.node.id;if(L.isIdentifier(r)){let o=e.scope.getBinding(r.name);return o?zs(o,t,n):!1}if(L.isObjectPattern(r)||L.isArrayPattern(r)){let o=[];return vi(r,o)?wj(o,e,t):!1}return!1}function vi(e,t){if(L.isRestElement(e))return vi(e.argument,t);if(L.isIdentifier(e))return t.push(e.name),!0;if(L.isAssignmentPattern(e))return vi(e.left,t);if(L.isObjectPattern(e)){for(let n of e.properties){if(L.isRestElement(n)){if(!vi(n.argument,t))return!1;continue}if(!L.isObjectProperty(n)||n.computed||!(L.isIdentifier(n.key)||L.isStringLiteral(n.key)||L.isNumericLiteral(n.key))||!vi(n.value,t))return!1}return!0}if(L.isArrayPattern(e)){for(let n of e.elements)if(n&&!vi(n,t))return!1;return!0}return!1}function wj(e,t,n){return e.every(r=>{let o=t.scope.getBinding(r);return o?zs(o,n,!0):!1})}function Oj(e){return e.referencePaths.some(t=>{let{current:n,memberAccess:r}=PI(t);if(!r)return!1;let o=n.parentPath;return!!(CI(n)||o?.isUpdateExpression()||o?.isUnaryExpression({operator:"delete"}))})}function CI(e){let t=e.findParent(n=>n.isAssignmentExpression()||n.isForXStatement());return t&&(t.isAssignmentExpression()||t.isForXStatement())?Bl(e.node,t.node.left):!1}function PI(e){let t=hm(e),n=!1;for(;t.parentPath&&(t.parentPath.isMemberExpression()||t.parentPath.isOptionalMemberExpression())&&t.parentPath.node.object===t.node;)n=!0,t=hm(t.parentPath);return{current:t,memberAccess:n}}function NI(e,t,n){if(!Dj(e,t))return!1;let{current:r,memberAccess:o}=PI(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:Em(i,t,o||n)}return CI(r)||i.isUpdateExpression()||i.isUnaryExpression({operator:"delete"})?!1:i.isCallExpression()||i.isOptionalCallExpression()?i.node.callee===r.node?!1:Fj(i,r,t):i.isNewExpression()?!1:i.isExportSpecifier()||i.isExportNamedDeclaration()||i.isExportDefaultDeclaration()||i.isTSTypeQuery()||n&&(i.isJSXOpeningElement()||i.isJSXClosingElement())?!0:i.isJSXExpressionContainer()||i.isJSXSpreadAttribute()?Aj(r,t):i.isSpreadElement()||i.isArrayExpression()||i.isObjectExpression()||i.isObjectProperty()||i.isConditionalExpression()||i.isLogicalExpression()||i.isSequenceExpression()||i.isAwaitExpression()?Lj(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 Fj(e,t,n){if(!e.node.arguments.some(i=>i===t.node))return!1;let r=e.node.callee;if(L.isIdentifier(r)){if(RI.has(r.name))return e.scope.getBinding(r.name)===void 0;let i=e.scope.getBinding(r.name);return!i||!qo(i)?!1:Xs(e,n,new Set)}if(!L.isMemberExpression(r)&&!L.isOptionalMemberExpression(r)||!L.isIdentifier(r.property))return!1;let o=Sm(r);return!o||e.scope.getBinding(o.name)?!1:o.name==="Object"&&r.property.name==="assign"?e.node.arguments[0]===t.node?!1:Xs(e,n,new Set):_I.get(o.name)?.has(r.property.name)??!1?TI(e)?Xs(e,n,new Set):!0:!1}function Lj(e,t,n,r){let o=AI(e);return o.kind==="declarator"?Em(o.declarator,r,o.directValue):o.kind==="escape"||o.kind==="call"?!1:t||n}function AI(e){let t=hm(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 Xs(e,t,n){if(n.has(e.node))return!0;n.add(e.node);let r=AI(e);return r.kind==="declarator"?Em(r.declarator,t,r.directValue):r.kind==="escape"?!1:r.kind==="call"?r.call.node.callee===e.node?!1:TI(r.call)?Xs(r.call,t,n):Bj(r.call):!0}function Dj(e,t){let n=e.findParent(o=>o.isFunction());if(!n||!FI(n.node))return!0;let r=Mj(n);return!r||!qo(r)?!0:r.referencePaths.every(o=>{let i=o.parentPath;return!i?.isCallExpression()||i.node.callee!==o.node?!0:Xs(i,t,new Set)})}function Mj(e){let t=e.node,n=null;if(L.isFunctionDeclaration(t)?n=t.id?.name??null:(L.isArrowFunctionExpression(t)||L.isFunctionExpression(t))&&e.parentPath?.isVariableDeclarator()&&L.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 TI(e){let t=e.node.callee;if(L.isIdentifier(t)){let r=e.scope.getBinding(t.name);return!!(r&&qo(r))}if(!L.isMemberExpression(t)&&!L.isOptionalMemberExpression(t)||!L.isIdentifier(t.property))return!1;let n=Sm(t);return!n||e.scope.getBinding(n.name)?!1:n.name==="Object"&&Ij.has(t.property.name)}function Bj(e){let t=e.node.callee;if(L.isIdentifier(t))return RI.has(t.name)&&e.scope.getBinding(t.name)===void 0;if(!L.isMemberExpression(t)&&!L.isOptionalMemberExpression(t)||!L.isIdentifier(t.property))return!1;let n=Sm(t);return!n||e.scope.getBinding(n.name)||n.name==="Object"&&t.property.name==="assign"?!1:_I.get(n.name)?.has(t.property.name)??!1}function hm(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 jj(e){let t=e;for(;t&&(L.isTSAsExpression(t)||L.isTSTypeAssertion(t)||L.isTSNonNullExpression(t)||L.isTSSatisfiesExpression(t)||L.isParenthesizedExpression(t));)t=t.expression;return t&&L.isExpression(t)?t:null}function Sm(e){return!e.computed&&L.isIdentifier(e.object)?e.object:null}function $j(e){let t=L.identifier(e);return t.typeAnnotation=L.tsTypeAnnotation(L.tsTypeReference(L.identifier("Record"),L.tsTypeParameterInstantiation([L.tsStringKeyword(),L.tsAnyKeyword()]))),t}function Dl(e){let t=new Map(e.files);t.set(e.entryFile,e.entryContent);let n=or({entry_files:[e.entryFile],files:t});if(!n.complete)return{complete:!1,errors:n.errors.map(i=>Et(Wj(i.code),i.path,i.message))};let r=[];for(let i of n.nodes){if(i.kind!=="source"&&i.kind!=="asset")continue;let s=jl(t,i.path);if(s===null)return Dt("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 Uj(e,t,n,r){let o=L.cloneNode(e,!0),i=e.source.value;if(i.startsWith("./")||i.startsWith("../")){let s=$l(t,i,r);if(!s)return{ok:!1,error:Et("SOURCE_IMPORT_UNRESOLVED",t,`The selected import ${i} cannot be resolved in the fixed Snapshot map.`)};o.source.value=Vj(n,s)}return{ok:!0,node:o}}function $l(e,t,n){let r=t.startsWith("@/")?t.slice(2):Js.posix.normalize(Js.posix.join(Js.posix.dirname(e),t));if(!ym(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 Vj(e,t){let n=Js.posix.relative(Js.posix.dirname(e),t);return n.startsWith(".")?n:`./${n}`}function Kj(e){let t=null,n=0,r=!1;return e.traverse({CallExpression(o){let i=o.node.callee;if(!L.isIdentifier(i)||!/^use[A-Z0-9]/u.test(i.name))return;if(i.name!=="useTranslations"||o.node.arguments.length!==1||!L.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"||!L.isIdentifier(s.path.node.imported,{name:"useTranslations"})){r=!0,o.stop();return}n+=1;let c=o.findParent(l=>l.isVariableDeclarator());if(!c?.isVariableDeclarator()||!L.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 wI(e,t){let n=e.node.callee;if(L.isImport(n))return!1;if(t&&L.isIdentifier(n,{name:t})&&e.node.arguments.length>0&&e.node.arguments.every(o=>L.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!!(L.isCallExpression(s)&&xc(s))}if(!L.isIdentifier(n))return!1;let r=e.scope.getBinding(n.name);return r?qo(r):!1}function Jj(e){return e.isCallExpression()&&wI(e,null)&&L.isIdentifier(e.node.callee)&&e.scope.getBinding(e.node.callee.name)?.constantViolations.length===0&&e.node.arguments.every(t=>L.isExpression(t)&&gr(t))}function OI(e){return L.isJSXIdentifier(e)?L.isValidIdentifier(e.name)?L.identifier(e.name):null:L.isJSXMemberExpression(e)?OI(e.object):null}function Xj(e,t){return e.scope===t.scope&&(t.node.params.some(n=>n===e.node)||e.isIdentifier()&&t.node.params.some(n=>L.isObjectPattern(n)&&n.properties.some(r=>L.isObjectProperty(r)&&L.isIdentifier(r.value,{name:e.node.name}))))}function Bl(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 FI(e){return L.isFunction(e)}function vI(e,t){return!!e.invocation?.bindings.some(n=>n.propName===t)}function zj(e,t){let n=new Set(t.values());return e.invocation?.bindings.filter(r=>n.has(r.propName))??[]}function Hj(e,t){let n=new Set;bm(e,{Identifier(o){n.add(o.node.name)}});let r=t;for(;n.has(r);)r+="_";return r}function II(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 mm(e,t){return(e.start??0)-(t.start??0)}function jl(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 kI(e,t){let n=bj("sha256").update(t).digest("hex");return e.content_hash===`sha256:${n}`}function ym(e){return!!e&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith("."))}function Wj(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 Dt(e,t,n){return{complete:!1,errors:[Et(e,t,n)]}}function Et(e,t,n){return{code:e,path:t,message:n}}import{createHash as VI}from"node:crypto";import km from"@babel/generator";import _m from"@babel/traverse";import*as Ve from"@babel/types";function ht(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 $I from"@babel/types";import{createHash as vm}from"node:crypto";var Gj="sha256:cdea4bd5eec1d29e9a9693e6545fb0ac81b67b3260d5c957eee827c9f869842f",Yj="sha256:89b8fde9bf5ca807e238c3f5f6229e5f107b76a45d4972d245ec842ba3f6f6f5",Zj=new Set(["sha256:3cf25df4601562d673864ea135b8808cae2819ca315b16af5ad07a6afbb5d31c","sha256:7ad1062c59fabb7d584691e905919c84ddd0035f7b1ccd7cf58f2ba0b3fdde12"]),qj=new Set(["sha256:64f26e7284e844de65cfeaf268974aeb4a612ae796638fe219587f1d3e46b429"]),Qj=new Map([["sha256:3b952ddc14778008dac157346c997cdea06844d890f1e5280ea08d38fbf03776","sha256:061e4143d12a22f4256157df2824144ac8fb86744f456afa50ff963278ddb263"],["sha256:92f7425b0f1eb031ef47470adb2b777fe863234c268504287323ff06cd4f91cc","sha256:4b5aa33d4bbf4e895e0186ee7049a7f9606b5d85ee6e045b8eed084cee458646"]]);function Ul(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:${vm("sha256").update(s).digest("hex")}`;return a&&t.get(i)===a?a:""},o=r(n);return!!o&&Qj.get(o)===r(n.replace("jsonld.tsx","metadata-fields.ts"))}function e0(e){return e.index===Gj&&e.client===Yj&&Zj.has(e.collections)}function Ii(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:${vm("sha256").update(i).digest("hex")}`;return t.get(`${n}${o}.ts`)===s?s:""};return e0({index:r("index"),collections:r("collections"),client:r("client")})&&qj.has(r("field"))}function LI(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:${vm("sha256").update(r).digest("hex")}`;return o==="sha256:6e1c0d0af2938dc4e74d4a35b185bec0ad1fd6d16fd2323ee0cd72eaa05c836f"&&t.get(n)===o&&Ii(e,t)}import*as Qt from"@babel/types";var ct={kind:"primitive"},ir={kind:"json"},Im=new Set(["__proto__","prototype","constructor","then","toString","valueOf","toLocaleString"]),Vl=e=>({kind:"object",properties:new Map(Object.entries(e))}),To=e=>({kind:"array",item:e});function MI(e){let t=new Map;for(let n of e.split("/")){let r=/^\[(\[)?(\.\.\.)?([^\[\]/]+)\]\]?$/u.exec(n);r&&t.set(r[3],r[2]?To(ct):ct)}return{kind:"object",properties:t}}function Kt(e){return!!e&&e.kind!=="promise"&&e.kind!=="jsx"}function BI(e){let t=Vl({id:ct,url:ct,seo:ir,fields:ir}),n=["list","listStrict"].includes(e)?Vl({items:To(t),total:ct,page:ct,pageSize:ct}):["get","getStrict","getByUrl","getByUrlStrict"].includes(e)?t:e==="categories"?To(Vl({id:ct,label:ct,children:ir})):e==="schema"?ir:null;return n?{kind:"promise",value:e.endsWith("Strict")?Vl({kind:ct,data:n,error:ir}):n}:null}function DI(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=Qt.isIdentifier(c)?c.name:Qt.isStringLiteral(c)?c.value:null;l&&!Im.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 jI(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=DI(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):ct)}}):d.push(n(u,l,c));let f=Hs(d);return f&&o.node.async?{kind:"promise",value:f}:f},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 ct;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)?ct:null;if(!g.constant||g.constantViolations.length)return null;let m=i.get(g.identifier);if(m)return m;let p=e.resolve_value?.(o);return p?c(p):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:Kt(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 p=m.node.key,y=Qt.isIdentifier(p)?p.name:Qt.isStringLiteral(p)?p.value:null,b=n(m.get("value"),i,a);if(!y||Im.has(y)||g.has(y)||!Kt(b))return null;g.set(y,b)}return{kind:"object",properties:g}}if(o.isArrayExpression()){if(!o.node.elements.length)return{kind:"array",item:ir,empty:!0};let g=Hs(o.get("elements").map(m=>c(m)));return Kt(g)?To(g):null}if(o.isMemberExpression()||o.isOptionalMemberExpression()){let g=t0(o);if(!g||Im.has(g))return null;let m=c(o.get("object"));return m?.kind==="object"?m.properties.get(g)??null:m?.kind==="json"?ir:m?.kind==="array"?g==="length"?ct:/^\d+$/u.test(g)?m.item:null:m?.kind==="primitive"&&g==="length"?ct:null}if(o.isConditionalExpression())return Hs([c(o.get("consequent")),c(o.get("alternate"))]);if(o.isLogicalExpression())return Hs([c(o.get("left")),c(o.get("right"))]);if(o.isUnaryExpression())return["typeof","!","void"].includes(o.node.operator)||Kt(c(o.get("argument")))?ct:null;if(o.isBinaryExpression())return["in","instanceof"].includes(o.node.operator)?null:["===","!=="].includes(o.node.operator)||Kt(c(o.get("left")))&&Kt(c(o.get("right")))?ct:null;if(o.isTemplateLiteral())return o.get("expressions").every(g=>Kt(c(g)))?ct: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=>Kt(c(g)))?ct:null;let d=r(o,i,a);if(d)return d.result;if(u.isMemberExpression()&&!u.node.computed){if(Qt.isIdentifier(u.node.object,{name:"Object"})&&!u.scope.getBinding("Object")&&Qt.isIdentifier(u.node.property,{name:"keys"})&&o.node.arguments.length===1&&Kt(c(o.get("arguments")[0])))return To(ct);let g=c(u.get("object")),m=Qt.isIdentifier(u.node.property)?u.node.property.name:"";if(g?.kind==="array"&&m==="slice"&&o.node.arguments.length<=2&&o.get("arguments").every(p=>c(p)?.kind==="primitive"))return g;if(g?.kind==="primitive"&&["includes","startsWith","endsWith","trim","toLowerCase","toUpperCase","replace","split"].includes(m)&&o.get("arguments").every(p=>Kt(c(p))))return m==="split"?To(ct):ct}let f=e.resolve_function(u);return f?t(f,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||!Qt.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 f=[l.item,ct,l];if(l.empty)return{target:d,args:f,result:["map","filter"].includes(c)?l:ct,empty:!0};let g=t(d,f,i,s);return g?{target:d,args:f,result:c==="map"?To(g):c==="filter"?l:c==="find"?l.item:ct}:null}return{value:n,arrayCall:r,bind:DI}}function t0(e){let t=e.node.property;return!e.node.computed&&Qt.isIdentifier(t)?t.name:Qt.isStringLiteral(t)?t.value:Qt.isNumericLiteral(t)?String(t.value):null}function Hs(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:Hs(n.map(r=>r?.kind==="array"?r.item:null))??ir}:{kind:"array",item:ir,empty:!0}}return e.every(n=>n?.kind==="primitive")?ct:e.every(n=>n?.kind==="jsx")?t:e.every(Kt)?ir:null}function UI(e){if(!Ii(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 f=super.get(d);if(f)return f;let g=ht(e.files.get(d)),m=g===null?null:_e(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(f=>f.isProgram());return d?.isProgram()?t.get(d.node):void 0},i=u=>{let d=u.scope.getBinding(u.node.name),f=d?.path.parentPath,g=o(u);if(!g||!d?.constant||!d.path.isImportSpecifier()||d.path.node.importKind==="type"||!f?.isImportDeclaration()||f.node.importKind==="type")return null;let m=Tt(g.file,f.node.source.value,e.files);if(!m)return null;let p=d.path.node.imported;return{module:g,file:m,name:$I.isIdentifier(p)?p.name:p.value,local:d.identifier.name}},s=u=>{let d=i(u),f=d?r.get(d.file):void 0;return f&&d?ho(f,d.name,r):null},a=u=>{let d=u.get("callee");if(!d.isIdentifier())return!1;let f=i(d);if(!f||!["pickJsonLd","pickCustomMeta"].includes(f.name))return!1;let g=s(d),m=g&&o(g);return!!(g?.isFunctionDeclaration()&&g.node.id?.name===f.name&&m&&Ul(e.files,e.trusted_host_file_hashes,m.file))},c=jI({resolve_function(u){if(!u.isIdentifier())return null;let d=u.scope.getBinding(u.node.name);if(!d?.constant)return null;let f=s(u)??(d.path.isVariableDeclarator()?d.path.get("init"):d.path);return f.isFunctionDeclaration()||f.isFunctionExpression()||f.isArrowFunctionExpression()?f:null},resolve_value:s,cms_value(u,d,f){if(a(u))return u.get("arguments").every(y=>Kt(c.value(y,d,f)))?{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)||qn(m.module.ast,m.local))return null;let p=hr(u.node,{file:m.module.file,imports:new Map([[m.local,{source:m.file,importedName:m.name}]])})?.operation;return p?BI(p):null}}),l=c.bind(e.owner,[{kind:"object",properties:new Map([["params",{kind:"promise",value:MI(e.route_id)}],["searchParams",{kind:"promise",value:{kind:"json"}}]])}]);return u=>{if(!u.node||!Kt(c.value(u,l)))return!1;let d=!0,f=g=>{if(!d){g.skip();return}if(g.isCallExpression()){let m=g.get("callee"),p=m.isIdentifier()&&!m.scope.getBinding(m.node.name)&&["String","Number","Boolean","encodeURIComponent","decodeURIComponent"].includes(m.node.name);(!(a(g)||p)||!Kt(c.value(g,l)))&&(d=!1)}else g.isMemberExpression()||g.isOptionalMemberExpression()?Kt(c.value(g,l))||(d=!1):!gr(g.node)&&!g.isObjectExpression()&&!g.isObjectProperty()&&!g.isArrayExpression()&&!g.isLogicalExpression()&&!g.isConditionalExpression()&&!g.isBinaryExpression()&&!g.isTSAsExpression()&&!g.isTSSatisfiesExpression()&&!g.isParenthesizedExpression()&&(d=!1)};return f(u),u.traverse({enter:f}),d}}var n0=typeof _m=="function"?_m:_m.default,r0=typeof km=="function"?km:km.default;function KI(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=ht(n.get(o.sourceFile));if(i===null||`sha256:${VI("sha256").update(i).digest("hex")}`!==t.ownerSourceHash)return{complete:!1};let s=_e(o.sourceFile,i);if(!s.ok)return{complete:!1};let a=null;n0(s.module.ast,{JSXElement(K){let ge=o.callLocator.sourceRange;K.node.loc?.start.line===ge.startLine&&K.node.loc.start.column===ge.startColumn&&K.node.loc.end.line===ge.endLine&&K.node.loc.end.column===ge.endColumn&&(a=K)}});let c=a,l=c?.getFunctionParent();if(!c||!l?.isFunctionDeclaration()||!l.parentPath.isExportDefaultDeclaration()||!l.get("body").isBlockStatement())return{complete:!1};let u=c.findParent(K=>K.isReturnStatement());if(!u?.isReturnStatement()||u.parentPath!==l.get("body"))return{complete:!1};let d=new Set,f=new Map,g=new Set,m=new Set,p=new Set,y=!1,b=K=>{if(!K||d.has(K))return;if(d.add(K),!K.constant||K.constantViolations.length){y=!0;return}let ge=K.path;if(ge.isImportSpecifier()||ge.isImportDefaultSpecifier()||ge.isImportNamespaceSpecifier()){let Le=ge.parentPath;if(!Le.isImportDeclaration()){y=!0;return}let Je=f.get(Le.node)??new Set;Je.add(ge.node),f.set(Le.node,Je);return}if(K.kind==="param"){let Le=l.node.params[0];if(!Ve.isObjectPattern(Le)){y=!0;return}let Je=Le.properties.filter(st=>Ve.isObjectProperty(st)&&!st.computed&&Ve.isIdentifier(st.value,{name:K.identifier.name})),mt=Je[0];if(Je.length!==1||!Ve.isObjectProperty(mt)){y=!0;return}let be=Ve.isIdentifier(mt.key)?mt.key.name:Ve.isStringLiteral(mt.key)?mt.key.value:"";if(!["params","searchParams"].includes(be)){y=!0;return}p.add(be);return}let oe=ge.getStatementParent();if(!oe||oe.node===l.node){y=!0;return}if(ge.isVariableDeclarator()){if(!oe.isVariableDeclaration({kind:"const"})||oe.node.declarations.length!==1){y=!0;return}}else if(!ge.isFunctionDeclaration()&&!ge.isTSTypeAliasDeclaration()&&!ge.isTSInterfaceDeclaration()){y=!0;return}if(oe.parentPath===l.get("body"))m.add(oe.node);else if(oe.parentPath.isProgram())g.add(oe.node);else if(oe.parentPath.isExportNamedDeclaration()&&oe.parentPath.parentPath.isProgram())g.add(oe.node);else{y=!0;return}E(oe)},E=K=>{let ge=oe=>b(oe.scope.getBinding(oe.node.name));K.isReferencedIdentifier()&&ge(K),K.traverse({ReferencedIdentifier(oe){ge(oe)},JSXOpeningElement(oe){Ve.isJSXIdentifier(oe.node.name)&&!/^[a-z]/u.test(oe.node.name.name)&&b(oe.scope.getBinding(oe.node.name.name))}})};E(c);let x=l.get("body").get("body").filter(K=>(K.node.start??1/0)<(u.node.start??-1)),S=UI({module:s.module,owner:l,files:n,trusted_host_file_hashes:e.trusted_host_file_hashes,route_id:e.target.composition.routeId}),v=new Set,N=(K,ge)=>{let oe=ge.path.parentPath;if(!ge.path.isImportSpecifier()||!Ve.isIdentifier(ge.path.node.imported,{name:"cms"})||!oe?.isImportDeclaration())return!1;let Le=Tt(o.sourceFile,oe.node.source.value,n);if(!Le||!/^(?:src\/)?lib\/cms\/index\.ts$/u.test(Le))return!1;let Je=K;for(;Je.parentPath?.isMemberExpression()&&Je.parentPath.node.object===Je.node&&!Je.parentPath.node.computed;)Je=Je.parentPath;let mt=Je.parentPath;return!!(mt?.isCallExpression()&&mt.node.callee===Je.node&&hr(mt.node,{file:o.sourceFile,imports:new Map([[ge.identifier.name,{source:Le,importedName:"cms"}]])}))},R=!0;for(;R&&!y;){R=!1;for(let K of x){if(m.has(K.node))continue;let ge=!1;if(K.traverse({ReferencedIdentifier(Le){let Je=Le.scope.getBinding(Le.node.name);Je&&(d.has(Je)||v.has(Je))&&!N(Le,Je)&&(ge=!0)}}),!ge)continue;if(K.isVariableDeclaration({kind:"const"})&&K.node.declarations.length===1){let Le=K.get("declarations")[0];if(Le.get("id").isIdentifier()&&S(Le.get("init"))){let Je=Le.node.id.name,mt=K.scope.getBinding(Je);mt&&!v.has(mt)&&(v.add(mt),R=!0);continue}}let oe=!1;if(K.traverse({Function(Le){Le.skip()},ReturnStatement(Le){Le.node.argument&&(oe=!0)}}),oe){y=!0;break}m.add(K.node),E(K);for(let Le of Object.keys(Ve.getBindingIdentifiers(K.node)))b(K.scope.getBinding(Le));R=!0}}if(y||!d.size)return{complete:!1};let A=VI("sha256").update(JSON.stringify([t.sourceHash,t.ownerSourceHash,o.callLocator.sourceRange])).digest("hex"),C=`components/site/portable/${A.slice(0,24)}/page.tsx`;if(n.has(C))return{complete:!1};let w=[];for(let[K,ge]of f){let oe=Ve.cloneNode(K,!0);if(oe.specifiers=K.specifiers.filter(Le=>ge.has(Le)||Ve.isImportSpecifier(Le)&&Le.importKind==="type").map(Le=>Ve.cloneNode(Le,!0)),oe.source.value.startsWith(".")){let Le=Tt(o.sourceFile,oe.source.value,n);if(!Le)return{complete:!1};oe.source=Ve.stringLiteral(`@/${Le.replace(/\.[cm]?[jt]sx?$/u,"")}`)}w.push(oe)}let M=Ve.functionDeclaration(Ve.identifier(`PortableCmsDataEntry_${A.slice(0,8)}`),l.node.params.map(K=>Ve.cloneNode(K,!0)),Ve.blockStatement([...[...m].sort(Rm).map(K=>Ve.cloneNode(K,!0)),Ve.returnStatement(Ve.cloneNode(c.node,!0))]));M.async=l.node.async;let D=Ve.program([...w.sort(Rm),...[...g].sort(Rm).map(K=>Ve.cloneNode(K,!0)),Ve.exportDefaultDeclaration(M)]),U=r0(Ve.file(D)).code,B=c.node.loc;if(!B||c.node.start==null||c.node.end==null)return{complete:!1};let G=[...p].sort().map(K=>({propName:K,value:{kind:K==="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:B.start.line,start_column:B.start.column,end_line:B.end.line,end_column:B.end.column},owner:t.descriptor.owner,call_chain:[],strategy:"extract-jsx",entry_file:C,entry_export:{kind:"default"},invocation:null},extracted:{complete:!0,entry_file:C,source_files:[{path:C,content:U}],source_mapping:[],invocation_bindings:G,selected_root_ref:t.root.rootRef}}}function Rm(e,t){return(e.start??0)-(t.start??0)}import Cm from"@babel/traverse";import*as He from"@babel/types";import{createHash as JI}from"node:crypto";var XI=typeof Cm=="function"?Cm:Cm.default,o0=/^[a-z0-9][a-z0-9_-]{0,123}$/u;function zI(e){let t=or({entry_files:[e.entry_file],files:e.files,max_nodes:512}),n=new Map,r=t.errors.map(({code:i,path:s,message:a})=>({code:i,source_path:s,message:a})),o=new Map([[e.entry_file,new Set([e.entry_export?.kind==="named"?e.entry_export.name:"default"])]]);for(let i of t.nodes){if(i.kind!=="source")continue;let s=ht(e.files.get(i.path)),a=s===null?null:_e(i.path,s);a?.ok&&XI(a.module.ast,{ImportDeclaration(c){if(c.node.importKind==="type")return;let l=Tt(i.path,c.node.source.value,e.files);if(l)for(let u of c.node.specifiers){if(He.isImportSpecifier(u)&&u.importKind==="type"||!c.scope.getBinding(u.local.name)?.referencePaths.length)continue;let d=o.get(l)??new Set;d.add(He.isImportDefaultSpecifier(u)?"default":He.isImportSpecifier(u)?He.isIdentifier(u.imported)?u.imported.name:u.imported.value:"*"),o.set(l,d)}}})}for(let i of t.nodes){if(i.kind!=="source"||!/\.[cm]?[jt]sx?$/u.test(i.path)||/^(?:src\/)?lib\/cms\/(?!generated\/)/u.test(i.path))continue;let s=ht(e.files.get(i.path));if(s===null)continue;let a=_e(i.path,s);if(!a.ok){r.push({code:"CMS_BINDING_SOURCE_INVALID",source_path:i.path,message:a.diagnostic.message});continue}let c=new Map;for(let l of a.module.ast.program.body)if((He.isExportNamedDeclaration(l)||He.isExportAllDeclaration(l))&&l.source&&l.exportKind!=="type"){let u=Tt(i.path,l.source.value,e.files);u&&Pm(u)&&r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"A re-exported CMS request facade requires an explicit application binding."})}for(let l of a.module.ast.program.body){if(!He.isImportDeclaration(l)||l.importKind==="type")continue;let u=Tt(i.path,l.source.value,e.files);if(u)for(let d of l.specifiers)u&&Pm(u)&&!He.isImportSpecifier(d)&&r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"A namespace or default CMS request import has no explicit application binding."}),!(!He.isImportSpecifier(d)||d.importKind==="type")&&c.set(d.local.name,{source:u,importedName:He.isIdentifier(d.imported)?d.imported.name:d.imported.value})}XI(a.module.ast,{FunctionDeclaration(l){let u=l.parentPath.isExportDefaultDeclaration()?"default":l.parentPath.isExportNamedDeclaration()?l.node.id?.name:void 0;u&&!o.get(i.path)?.has(u)&&!o.get(i.path)?.has("*")&&(!l.node.id||!l.scope.getBinding(l.node.id.name)?.referencePaths.some(d=>!d.isExportDeclaration()))&&l.skip()},ReferencedIdentifier(l){let u=c.get(l.node.name);if(!u||!Pm(u.source)||!l.scope.getBinding(l.node.name)?.path.isImportSpecifier()||!["cms","collections","cmsFetch","cmsFetchResult","cmsFetchEnvelope"].includes(u.importedName))return;let f=l;for(;f.parentPath?.isMemberExpression()&&f.parentPath.node.object===f.node;)f=f.parentPath;if(!He.isExpression(f.node))return;let g=hr(He.callExpression(f.node,[]),{file:i.path,imports:c}),m=u.importedName==="cms"&&f.isMemberExpression()&&!f.node.computed&&f.get("object").isMemberExpression()&&He.isMemberExpression(f.node.object)&&!f.node.object.computed&&He.isIdentifier(f.node.object.object,{name:l.node.name})&&He.isIdentifier(f.node.object.property,{name:"field"});(!g||!Nm(f,new Set))&&!m&&r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"The CMS request facade is used outside a recognized application request.",...l.node.loc?{call_site:{line:l.node.loc.start.line,column:l.node.loc.start.column}}:{}})},CallExpression(l){let u=l.get("callee"),d=new Set;for(;u.isIdentifier()&&!c.has(u.node.name);){let S=u.scope.getBinding(u.node.name);if(!S?.constant||!S.path.isVariableDeclarator()||d.has(S.path.node))break;d.add(S.path.node);let v=S.path.get("init");if(!v.node)break;u=v}if(!He.isExpression(u.node))return;let f=u;for(;f.isMemberExpression()&&!f.node.computed;)f=f.get("object");if(f.isIdentifier()&&["cms","collections"].includes(c.get(f.node.name)?.importedName??"")){let S=f.scope.getBinding(f.node.name);if(!S?.path.isImportSpecifier())return;if(qn(a.module.ast,f.node.name)||!HI(S,new Set)){r.push({code:"CMS_BINDING_MUTATED",source_path:i.path,message:"The CMS application facade has been modified or escaped."});return}}let g=hr(He.callExpression(u.node,[]),{file:i.path,imports:c});if(!g)return;if(g.sourceKind!=="vcp-cms-collection"){r.push({code:"CMS_BINDING_UNSUPPORTED",source_path:i.path,message:"The selected code depends on a non-collection CMS capability."});return}let m=g.operation;if(m==="getByUrlStrict"&&e.allow_build_sample&&e.on_build_only_value){let S=l.get("arguments")[1];if(S?.isObjectExpression()){let v=S.get("properties").find(R=>R.isObjectProperty()&&!R.node.computed&&(He.isIdentifier(R.node.key,{name:"buildSample"})||He.isStringLiteral(R.node.key,{value:"buildSample"}))),N=v?.isObjectProperty()?v.get("value"):void 0;if(N?.isIdentifier()){let R=N.scope.getBinding(N.node.name);N=R?.constant&&R.referencePaths.length===1&&R.path.isVariableDeclarator()?R.path.get("init"):void 0}for(;N?.isTSAsExpression()||N?.isTSSatisfiesExpression();)N=N.get("expression");N?.isObjectExpression()&&N.node.start!=null&&N.node.end!=null&&e.on_build_only_value({file_path:i.path,start:N.node.start,end:N.node.end,source_hash:`sha256:${JI("sha256").update(s).digest("hex")}`})}}let p=l.get("arguments")[0];if(p?.isObjectExpression()&&m.startsWith("cmsFetch")){let S=p.get("properties").find(v=>v.isObjectProperty()&&!v.node.computed&&(He.isIdentifier(v.node.key,{name:"path"})||He.isStringLiteral(v.node.key,{value:"path"})));p=S?.isObjectProperty()?S.get("value"):void 0}let y=m.startsWith("getByUrl")||m.startsWith("cmsFetch"),b=p?ki(p,y,new Set):null,E=b&&y?el(b):b;if(!E||!o0.test(E)){r.push({code:"CMS_BINDING_UNRESOLVED",source_path:i.path,message:"The CMS application identity cannot be determined from its request binding.",...l.node.loc?{call_site:{line:l.node.loc.start.line,column:l.node.loc.start.column}}:{}});return}y&&!e.confirmed_slugs?.has(E)&&r.push({code:"CMS_URL_COLLECTION_UNPROVEN",source_path:i.path,message:"The CMS request namespace requires a matching site-authorized application schema."});let x=n.get(E)??[];x.push({source_path:i.path,operation:m,binding:"trusted-cms",call_site:{line:l.node.loc?.start.line??1,column:l.node.loc?.start.column??0}}),n.set(E,x)},JSXOpeningElement(l){if(!e.on_host_call||!He.isJSXIdentifier(l.node.name)||l.node.start==null||l.node.end==null)return;let u=c.get(l.node.name.name);u?.importedName==="SafeImage"&&/^(?:src\/)?components\/ui\/safe-image\.tsx$/u.test(u.source)&&e.on_host_call({file_path:i.path,host_file:u.source,start:l.node.start,end:l.node.end,source_hash:`sha256:${JI("sha256").update(s).digest("hex")}`})}})}return n.size>16&&r.push({code:"CMS_BINDING_BUDGET_EXCEEDED",source_path:e.entry_file,message:"The selected block exceeds the application export budget; no applications were truncated."}),{complete:r.length===0,dependencies:[...n].sort(([i],[s])=>i.localeCompare(s)).map(([i,s])=>({requirement_key:`cms-${i}`,slug:i,evidence:s})),unresolved:r}}function Pm(e){return/^(?:src\/)?lib\/cms(?:\/index)?\.[cm]?[jt]s$/u.test(e)||/^(?:src\/)?lib\/cms\/(?:collections|client)\.[cm]?[jt]s$/u.test(e)}function Nm(e,t){if(t.has(e.node)||t.size>=64)return!1;let n=new Set(t).add(e.node),r=e.parentPath;if(r?.isCallExpression()&&r.node.callee===e.node)return!0;if(r?.isTSAsExpression()||r?.isTSSatisfiesExpression()||r?.isParenthesizedExpression())return Nm(r,n);if(r?.isVariableDeclarator()&&r.node.init===e.node&&He.isIdentifier(r.node.id)){let o=r.scope.getBinding(r.node.id.name);return!!o?.constant&&o.referencePaths.length>0&&o.referencePaths.every(i=>Nm(i,n))}return!1}function HI(e,t){if(t.has(e.path.node))return!1;let n=new Set(t).add(e.path.node);return e.referencePaths.every(r=>{if(r.isExportDeclaration())return!0;let o=r.parentPath;if(o?.isMemberExpression()&&o.node.object===r.node)return!0;if(o?.isVariableDeclarator()&&o.node.init===r.node&&He.isIdentifier(o.node.id)){let i=o.scope.getBinding(o.node.id.name);return!!i?.constant&&HI(i,n)}return!1})}function ki(e,t,n){if(n.has(e.node))return null;let r=new Set(n).add(e.node);if(e.isStringLiteral())return e.node.value;if(e.isTSAsExpression()||e.isTSSatisfiesExpression()||e.isParenthesizedExpression())return ki(e.get("expression"),t,r);if(e.isIdentifier()){let o=e.scope.getBinding(e.node.name);if(o?.constant&&o.path.isVariableDeclarator()){let i=o.path.get("init");if(i.node)return ki(i,t,r)}return null}if(e.isBinaryExpression({operator:"+"})){let o=ki(e.get("left"),t,r),i=ki(e.get("right"),t,r);return o!==null&&i!==null?o+i:t&&o!==null?`${o}:record`:null}if(e.isTemplateLiteral()){let o=e.node.quasis[0]?.value.cooked??"",i=e.get("expressions");for(let[s,a]of i.entries()){let c=ki(a,t,r);if(c===null&&!t)return null;o+=(c??":record")+(e.node.quasis[s+1]?.value.cooked??"")}return o}return null}import{createHash as _k}from"node:crypto";import Jm from"node:path";import Xm from"@babel/traverse";import*as et from"@babel/types";import{GeneratedSiteCapabilitiesSchema as s$,SiteEditSourcePathSchema as a$}from"@vcp-dev/contracts";import{parse as Um}from"@babel/parser";import*as Y from"@babel/types";import{PortableCollectionRecipeFactsSchema as V0}from"@vcp-dev/contracts";import{parse as Yr}from"@babel/parser";import Am from"@babel/traverse";import*as O from"@babel/types";import{createHash as i0}from"node:crypto";import{GeneratedSiteCapabilitiesSchema as s0,generateDetailBreadcrumb as a0,ResolvedFieldSchema as c0}from"@vcp-dev/contracts";import*as yt from"@babel/types";function WI(e){if(!yt.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(!yt.isObjectPattern(o)||o.properties.length!==1||!yt.isObjectProperty(o.properties[0])||o.properties[0].computed||!yt.isIdentifier(o.properties[0].key,{name:"children"})||!yt.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=yt.isBlockStatement(s)?s.body.length===1&&yt.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(yt.isJSXExpressionContainer(u))return u.expression===i.referencePaths[0].node;if(!yt.isJSXElement(u)&&!yt.isJSXFragment(u)||yt.isJSXElement(u)&&(!yt.isJSXIdentifier(u.openingElement.name)||!c.has(u.openingElement.name.name)||u.openingElement.attributes.length>0))return!1;let f=u.children.filter(g=>!yt.isJSXText(g)||g.value.trim()!=="");return f.length===1&&l(f[0],d+1)};return l(a,0)}var Gs=typeof Am=="function"?Am:Am.default;function Fm(e){return qI(e,!1)}function l0(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=qI({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 qI(e,t){let n=Mm(e.files),r=(g,m,p)=>({complete:!1,relation:null,errors:[{code:g,path:m,message:p}]}),o=ek(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(ck),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 p=wo(g,m,i,"getByUrlStrict",n,e.detail_prefix??`/${i}`);return p&&zl(p.ast,e.detail_prefix??`/${i}`)!==null?[p]:[]});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(!P0(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=_n(u.source,{filePath:u.path,exportName:"default"}).components.flatMap(g=>{let m=en(u.path,g.source,n),p=m?n.get(m):void 0;return!m||typeof p!="string"||!rk(p,g.export_name)||!Jl(p,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 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 QI(e){let t=ek(e,Mm(e.files));return t.complete&&t.consumer!==null}function ek(e,t,n=!1){let r=(c,l)=>({complete:!1,errors:[{code:"RELATED_COLLECTION_LIST_CONTAINER_UNPROVEN",path:c,message:l}]}),o=en(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(!E0(i,o,"listStrict"))return{complete:!0,slug:null,consumer:null};if(!n&&!Xl(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=x0(i,o),a=s?wo(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 Xl(e,t,n,r=!1,o="default"){let i=ht(n.get(e));if(i===null)return!1;let s=_e(e,i);if(!s.ok)return!1;let a=jt({module:s.module,exportName:o,allowNonRenderingGuards:r});if(!a.ok||a.metadataOnly)return!1;let c=_n(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 f=0,g=m=>{if(m.isJSXElement()){let p=m.get("openingElement"),y=p.node.name;if(!O.isJSXIdentifier(y))return;if(!/^[a-z]/u.test(y.name)){let b=p.scope.getBinding(y.name),E=b?.path.parentPath;if(b?.constant&&E?.isImportDeclaration()&&E.node.importKind!=="type"&&(b.path.isImportDefaultSpecifier()||b.path.isImportSpecifier()&&b.path.node.importKind!=="type"&&O.isIdentifier(b.path.node.imported,{name:"default"}))&&typeof p.node.start=="number"&&l.has(p.node.start)&&en(e,E.node.source.value,n)===t){f++;return}if(!WI(p))return}if(u0(p.node))return}for(let p of m.get("children"))if(p.isJSXElement()||p.isJSXFragment())g(p);else if(p.isJSXExpressionContainer()){let y=p.get("expression");(y.isJSXElement()||y.isJSXFragment())&&g(y)}};for(let m of d)g(m);return f};return a.returnAlternatives?a.returnAlternatives.every(d=>u([d])===1):u(a.roots)===1}function u0(e){if(!O.isJSXIdentifier(e.name)||["template","noscript","script","style","head","dialog","details"].includes(e.name.name))return!0;for(let t of e.attributes){if(O.isJSXSpreadAttribute(t)||!O.isJSXIdentifier(t.name))return!0;let n=t.name.name;if(["style","dangerouslySetInnerHTML"].includes(n)||n==="className"&&!O.isStringLiteral(t.value)&&(!O.isJSXExpressionContainer(t.value)||!O.isStringLiteral(t.value.expression)))return!0;if(["hidden","inert","aria-hidden"].includes(n)){let r=t.value;if(n==="aria-hidden"&&O.isStringLiteral(r,{value:"false"})||O.isJSXExpressionContainer(r)&&O.isBooleanLiteral(r.expression,{value:!1}))continue;return!0}}return!1}function Lm(e){let t=Mm(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 x of e.source_closure.nodes)x.kind==="source"&&typeof t.get(x.path)!="string"&&n.push({code:"RELATED_SOURCE_CLOSURE_INCOMPLETE",path:x.path,message:"A selected source is missing or is not valid UTF-8 text."});Tm(t,e.collection.list_entry_file,"RELATED_LIST_ENTRY_MISSING",n),Tm(t,e.collection.detail_entry_file,"RELATED_DETAIL_ENTRY_MISSING",n),Tm(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&&ak(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&&wm(o,{path:e.collection.list_entry_file,kind:"route",requirementKey:e.collection.requirement_key}),ck(e.collection.detail_entry_file)?wm(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=or({entry_files:[e.collection.detail_entry_file],files:t}),d=new Set;if(i)if(!s0.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 x of u.nodes){if(x.kind==="external"||xi({node:x,host_capabilities:e.host_capabilities}).ownership!=="host-public"&&!N0(x.path))continue;d.add(x.path);let v=s.get(x.path),N=v===void 0?null:`sha256:${i0("sha256").update(v).digest("hex")}`;(!N||e.trusted_host_file_hashes?.get(x.path)!==N)&&n.push({code:"RELATED_HOST_IMPLEMENTATION_UNPROVEN",path:x.path,message:"A related host source requires trusted matching Snapshot provenance."})}for(let x of u.nodes)x.kind==="source"&&typeof t.get(x.path)!="string"&&n.push({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:x.path,message:"A detail source is missing or is not valid UTF-8 text."});u.complete||n.push(...u.errors.map(x=>({code:"RELATED_DETAIL_SOURCE_INCOMPLETE",path:x.path,message:x.message})));let f=u.nodes.find(x=>x.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?f0(e.collection,t,s):null,m=e.trusted_schema===void 0?null:p0(e,t,n,e.trusted_schema),p=i&&m&&e.trusted_schema?d0(e.collection,m,e.trusted_schema,t,s):null;for(let x of u.nodes)if(x.kind!=="external"&&x.path!==e.collection.detail_entry_file&&x.path!==e.collection.detail_view_file&&!d.has(x.path)&&!(!l&&x.path===e.collection.list_entry_file)){if(C0(x.path,e.collection)){if(i&&x.path!==g&&x.path!==p){n.push({code:"RELATED_MANAGED_SOURCE_UNPROVEN",path:x.path,message:"A related generated source cannot be omitted based on its pathname alone."});continue}wm(o,{path:x.path,kind:x.path.includes("/page.")?"route":"adapter",requirementKey:e.collection.requirement_key});continue}A0(x.path,e.collection.detail_view_file,e.collection.slug)&&r.push({path:x.path,export:{kind:"default"},purpose:"i18n-companion"})}let y=t.get(e.collection.detail_view_file);typeof y=="string"&&_0(y,e.collection.detail_view_file,u.nodes,t,r,d),e.page_template&&(a=R0(e.page_template,t,n));let b=O0(r).map((x,S)=>({key:L0(x,S),pathTemplate:x.path,export:x.export,purpose:x.purpose,requirementKey:e.collection.requirement_key})),E=D0(n).sort(M0);return{complete:E.length===0,entries:b.sort((x,S)=>x.pathTemplate.localeCompare(S.pathTemplate)||x.purpose.localeCompare(S.purpose)||x.key.localeCompare(S.key)),managed_requirements:o.sort(F0),thin_entry_plan:a,collection_wiring:m,errors:E}}function d0(e,t,n,r,o){let i=c0.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 x=["id","url","seo"].includes(E.name)?`${E.name}_field`:E.name;if(c.has(x))return null;c.add(x)}let l=new Set(t.force_multi_media??[]);for(let E of l){let x=s.find(S=>S.name===E);if(!x||x.front_display==="forbidden"||x.value_shape!=="media_list"&&!["Image","Avatar","Video","File","Audio"].includes(x.cms_type))return null}let u=ht(r.get(t.list_container_file)),d=ht(r.get(e.detail_entry_file)),f=Dm(e.detail_entry_file);if(u===null||d===null||!f)return null;let g=wo(t.list_container_file,u,e.slug,"listStrict",r),m=wo(e.detail_entry_file,d,e.slug,"getByUrlStrict",r,f),p=`lib/cms/generated/${e.slug}.ts`;if(!g||!m||g.adapter_source!==m.adapter_source||en(g.path,g.adapter_source,r)!==p||en(m.path,m.adapter_source,r)!==p)return null;let y=o.get(p);if(y===void 0)return null;let b=sm(e.slug,s,{forceMultiMedia:l});return typeof y=="string"?y===b?p:null:Buffer.from(y).equals(Buffer.from(b))?p:null}function f0(e,t,n){let r=t.get(e.detail_entry_file),o=Dm(e.detail_entry_file);if(typeof r!="string"||!o)return null;let i=wo(e.detail_entry_file,r,e.slug,"getByUrlStrict",t,o);if(!i)return null;let s=zl(i.ast,o),a=ok(i,t,s);if(!s||!a||a==="unproven")return null;let c=`components/site/generated/${e.slug}-breadcrumb.tsx`;if(!Xl(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 f=a0({slug:e.slug,detailPrefix:s,...a,headerShell:d});return typeof l=="string"?l===f:Buffer.from(l).equals(Buffer.from(f))})?c:null}function p0(e,t,n,r){let o=n.length,i=r.fields.map(v=>({...v}));(r.source_slug!==e.collection.slug||!r.evidence_path.trim()||i.length===0)&&n.push({code:"RELATED_COLLECTION_SCHEMA_UNPROVEN",path:r.evidence_path||`trusted-schema:${e.collection.slug}`,message:"Collection recipe facts require a non-empty trusted CMS schema with matching source identity."});let s=e.source_closure.nodes.filter(v=>v.kind==="source"&&v.status==="complete"&&v.path!==e.collection.list_entry_file).flatMap(v=>{let N=t.get(v.path);if(typeof N!="string")return[];let R=wo(v.path,N,e.collection.slug,"listStrict",t);return R?[R]:[]});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?GI(a,t,v=>v!==e.collection.detail_view_file):null;c?a&&!Jl(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=Dm(e.collection.detail_entry_file),d=typeof l=="string"&&u?wo(e.collection.detail_entry_file,l,e.collection.slug,"getByUrlStrict",t,u):null,f=d?GI(d,t,v=>v===e.collection.detail_view_file):null;!d||!f||f.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."}):Jl(t.get(f.source_path),d.adapter_source,d.interface_name)||n.push({code:"RELATED_COLLECTION_DETAIL_CONSUMER_UNPROVEN",path:f.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(v=>v.name)),m=a?en(a.path,a.adapter_source,t):null,p=m?t.get(m):null,y=[...e.required_fields??i.filter(v=>v.required).map(v=>v.name)].sort(Om),b=[...e.force_multi_media??(typeof p=="string"?ik(p):[])].sort(Om);for(let v of[...y,...b])g.has(v)||n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:`trusted-schema:${e.collection.slug}.${v}`,message:`Collection field ${v} is not present in the trusted schema.`});if(a&&b.length)for(let v of b)(typeof p!="string"||!k0(p,v))&&n.push({code:"RELATED_COLLECTION_FIELD_UNPROVEN",path:m??a.adapter_source,message:`The generated adapter does not prove multi-media handling for ${v}.`});let E=d&&u?zl(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 x=d?I0(d.ast):null;x||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?ok(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||!f||!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:{...f,interface_name:d.interface_name},...x?{title:x}:{},...S&&S!=="unproven"?{breadcrumb:S}:{},...y.length>0?{required_fields:y}:{},...b.length>0?{force_multi_media:b}:{}}}function wo(e,t,n,r,o,i=`/${n}`){let s;try{s=Yr(t,{sourceType:"module",sourceFilename:e,plugins:["jsx","typescript"]})}catch{return null}let a=Gr(s,u=>O.isCallExpression(u)&&Oo(u.callee,r));if(!b0(s,e,o,r)||r==="listStrict"&&(a.length!==1||!O.isStringLiteral(a[0]?.arguments[0],{value:n}))||r==="getByUrlStrict"&&(a.length===0||zl(s,i)===null))return null;let l=s.program.body.flatMap(u=>O.isImportDeclaration(u)?u.specifiers.flatMap(d=>{if(!O.isImportSpecifier(d))return[];let f=O.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=>Gr(s,d=>O.isIdentifier(d,{name:u.local_name})).length>1);return l.length!==1||!m0(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 m0(e,t,n,r,o,i){let s=!1;return Gs(e,{JSXOpeningElement(a){let c=a.getFunctionParent();if(!c?.isFunctionDeclaration()||!c.parentPath.isExportDefaultDeclaration()||!O.isJSXIdentifier(a.node.name)||a.node.attributes.some(b=>O.isJSXSpreadAttribute(b)))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&&(!O.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=en(t,f.node.source.value,n);if(!g||!Jl(n.get(g),r.source,r.interface_name))return;let m=a.get("attributes").filter(b=>b.isJSXAttribute()&&O.isJSXIdentifier(b.node.name,{name:o==="listStrict"?"records":"record"}));if(m.length!==1||!m[0].isJSXAttribute())return;let p=m[0].get("value");if(!p.isJSXExpressionContainer())return;let y={opening:a,attribute:o==="listStrict"?"records":"record",file:t,files:n};(o==="listStrict"?tk(p.get("expression"),c,r,i,y,new Set):nk(p.get("expression"),c,r,y,new Set))&&(s=!0)}}),s}function tk(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"})||Ws(m.referencePaths,n,o)?!1:tk(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||!O.isIdentifier(s.node.property,{name:"map"}))return!1;let a=e.get("arguments")[0];if(!a||!Kl(a,n))return!1;let c=s.get("object");if(c.isConditionalExpression()){let m=c.get("consequent"),p=c.get("alternate"),y=b=>b.isArrayExpression()&&b.node.elements.length===0;if(y(m))c=p;else if(y(p))c=m;else return!1}if(!c.isMemberExpression()||c.node.computed||!O.isIdentifier(c.node.property,{name:"items"}))return!1;let l=c.get("object");if(!l.isMemberExpression()||l.node.computed||!O.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"})||Ws(d.referencePaths,n,null))return!1;let f=d.path.get("init");if(!f.isAwaitExpression())return!1;let g=f.get("argument");return g.isCallExpression()&&Oo(g.node.callee,"listStrict")&&O.isStringLiteral(g.node.arguments[0],{value:r})}function nk(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"})||Ws(d.referencePaths,n,r)?!1:nk(d.path.get("init"),t,n,r,o)}if(!e.isCallExpression()||e.node.arguments.length!==1)return!1;let i=e.get("callee");if(!Kl(i,n))return!1;let s=e.get("arguments")[0];if(!s?.isMemberExpression()||s.node.computed||!O.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"})||Ws(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()&&Oo(u.node.callee,"getByUrlStrict")}function Kl(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"||!O.isIdentifier(r.node.imported,{name:`to${t.interface_name}`})||!o?.isImportDeclaration()||o.node.importKind==="type"||o.node.source.value!==t.source)}function Ws(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(!O.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),Ws(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&&O.isIdentifier(c.node.property,{name:"map"})&&l&&Kl(l,t))}let a=s.get("callee");return!(i.isMemberExpression()&&!i.node.computed&&O.isIdentifier(i.node.property,{name:"data"})&&Kl(a,t))}if(s?.isJSXExpressionContainer()){let a=s.parentPath;return n?.attribute==="record"&&i.isMemberExpression()&&i.node.object===o.node&&!i.node.computed&&O.isIdentifier(i.node.property)&&a?.isJSXAttribute()&&g0(a,i.node.property.name,t,n)?!1:!(n&&a?.isJSXAttribute()&&a.parentPath===n.opening&&O.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 g0(e,t,n,r){if(["__proto__","prototype","constructor"].includes(t)||!O.isJSXIdentifier(e.node.name)||["key","ref"].includes(e.node.name.name))return!1;let o=e.parentPath;if(!o?.isJSXOpeningElement()||!O.isJSXIdentifier(o.node.name)||/^[a-z]/u.test(o.node.name.name)||o.node.attributes.some(d=>O.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=en(r.file,s.node.source.value,r.files),c=en(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:h0(l,a)&&y0(u,c,`to${n.interface_name}`,t)}function h0(e,t){let n=_e(t,e);if(!n.ok||n.module.ast.program.body.length!==1)return!1;let r=n.module.ast.program.body[0];if(!O.isExportDefaultDeclaration(r)||!O.isFunctionDeclaration(r.declaration)||r.declaration.params.length!==0||r.declaration.async||r.declaration.generator)return!1;let o=!1;return Gs(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||!O.isIdentifier(i.node.property,{name:"length"})||!a?.constant||!a.path.isVariableDeclarator()||!O.isArrayExpression(a.path.node.init))&&(o=!0)},OptionalMemberExpression(){o=!0},ObjectProperty(i){i.node.computed&&(o=!0)},VariableDeclarator(i){O.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;!O.isStringLiteral(s)&&!O.isNumericLiteral(s)&&!O.isBooleanLiteral(s)&&!O.isNullLiteral(s)&&!O.isJSXEmptyExpression(s)&&!(O.isMemberExpression(s)&&O.isJSXElement(i.parentPath.node))&&(o=!0)},JSXOpeningElement(i){(!O.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=>!O.isJSXAttribute(s)||!O.isJSXIdentifier(s.name)||!["className","id","role","title","aria-label"].includes(s.name.name)))&&(o=!0)}}),!o}function y0(e,t,n,r){let o=_e(t,e);if(!o.ok)return!1;let i=o.module.ast.program.body.filter(d=>O.isExportNamedDeclaration(d)&&O.isFunctionDeclaration(d.declaration)&&d.declaration.id?.name===n);if(i.length!==1)return!1;let s=i[0].declaration;if(!O.isFunctionDeclaration(s)||s.async||s.generator)return!1;let a=!1;if(Gs(o.module.ast,{Program(d){let f=d.scope.getBinding(n);a=!!(f?.constant&&f.path.node===s),d.stop()}}),!a)return!1;let c=Gr(s.body,d=>O.isReturnStatement(d)),l=s.body.body.at(-1);if(c.length!==1||!O.isReturnStatement(l)||l!==c[0]||!O.isObjectExpression(l.argument))return!1;let u=new Set;for(let d of l.argument.properties){if(!O.isObjectProperty(d)||d.computed||!(O.isIdentifier(d.key)||O.isStringLiteral(d.key)))return!1;let f=O.isIdentifier(d.key)?d.key.name:d.key.value;if(["__proto__","prototype","constructor"].includes(f)||u.has(f))return!1;u.add(f)}return u.has(r)}function b0(e,t,n,r){let o=0,i=qn(e,"cms");for(let s of e.program.body){if(!O.isImportDeclaration(s)||s.importKind==="type")continue;let a=en(t,s.source.value,n);!a||!/^(?:src\/)?lib\/cms(?:\/index|\/collections)?\.[cm]?[jt]s$/u.test(a)||s.specifiers.some(c=>{if(O.isImportSpecifier(c)&&c.importKind==="type")return!1;if(!O.isImportSpecifier(c))return!0;let l=O.isIdentifier(c.imported)?c.imported.name:c.imported.value;return l==="collections"||l==="cms"&&c.local.name!=="cms"})&&(i=!0)}return Gs(e,{CallExpression(s){if(!Oo(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"||!O.isIdentifier(c.node.imported,{name:"cms"})||!l?.isImportDeclaration()||l.node.importKind==="type"){i=!0;return}let u=en(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,m=g?.parentPath;return!(f?.isMemberExpression()&&f.node.object===d.node&&!f.node.computed&&O.isIdentifier(f.node.property,{name:"collections"})&&g?.isMemberExpression()&&g.node.object===f.node&&!g.node.computed&&O.isIdentifier(g.node.property)&&m?.isCallExpression()&&m.node.callee===g.node)}))&&(i=!0)}}),o>0&&!i}function x0(e,t){let n;try{n=Yr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let r=Gr(n,o=>O.isCallExpression(o)&&Oo(o.callee,"listStrict")&&O.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 E0(e,t,n){let r;try{r=Yr(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return!1}return Gr(r,o=>O.isCallExpression(o)&&Oo(o.callee,n)).length>0}function GI(e,t,n){let r=_n(e.source,{filePath:e.path,exportName:"default"});if(r.diagnostics.length>0)return null;let o=r.components.flatMap(i=>{let s=en(e.path,i.source,t),a=s?t.get(s):null;return!s||!n(s)||typeof a!="string"||!rk(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 rk(e,t){let n;try{n=Yr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}for(let r of n.program.body){if(t==="default"&&O.isExportDefaultDeclaration(r))return!0;if(O.isExportNamedDeclaration(r)&&(r.declaration&&(O.isFunctionDeclaration(r.declaration)||O.isClassDeclaration(r.declaration)||O.isTSInterfaceDeclaration(r.declaration)||O.isTSTypeAliasDeclaration(r.declaration))&&r.declaration.id?.name===t||O.isVariableDeclaration(r.declaration)&&r.declaration.declarations.some(o=>O.isIdentifier(o.id,{name:t}))||r.specifiers.some(o=>O.isExportSpecifier(o)?(O.isIdentifier(o.exported)?o.exported.name:o.exported.value)===t:!1)))return!0}return!1}function Jl(e,t,n){if(typeof e!="string")return!1;let r;try{r=Yr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return!1}return r.program.body.flatMap(i=>!O.isImportDeclaration(i)||i.source.value!==t?[]:i.specifiers.flatMap(s=>O.isImportSpecifier(s)?(O.isIdentifier(s.imported)?s.imported.name:s.imported.value)===n?[s.local.name]:[]:[])).some(i=>Gr(r,s=>O.isIdentifier(s,{name:i})).length>1)}function Oo(e,t){return O.isMemberExpression(e)&&!e.computed&&O.isIdentifier(e.property,{name:t})&&O.isMemberExpression(e.object)&&!e.object.computed&&O.isIdentifier(e.object.property,{name:"collections"})&&O.isIdentifier(e.object.object,{name:"cms"})}function zl(e,t){let n=[];return Gs(e,{CallExpression(r){Oo(r.node.callee,"getByUrlStrict")&&n.push(S0(r.node.arguments[0],o=>v0(r,o)))}}),n.length===0?null:n.every(r=>r===t)?t:null}function S0(e,t){return O.isBinaryExpression(e,{operator:"+"})&&O.isStringLiteral(e.left)&&O.isIdentifier(e.right)&&t(e.right.name)&&/^\/[A-Za-z0-9_-]+\/$/u.test(e.left.value)?e.left.value.slice(0,-1):O.isTemplateLiteral(e)&&e.expressions.length===1&&O.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 v0(e,t){let n=e.scope.getBinding(t);if(!n?.constant||!n.path.isVariableDeclarator())return!1;let r=n.path.node;if(O.isObjectPattern(r.id)&&O.isAwaitExpression(r.init)&&O.isIdentifier(r.init.argument))return r.id.properties.some(a=>O.isObjectProperty(a)&&!a.computed&&Hl(a.key)==="slug"&&O.isIdentifier(a.value,{name:t}))&&YI(n.path,r.init.argument.name);let o=r.init;if(!O.isIdentifier(r.id,{name:t})||!O.isCallExpression(o)||!O.isIdentifier(o.callee)||o.arguments.length!==1)return!1;let i=n.path.scope.getBinding(o.callee.name);if(!i?.constant||!i.path.isImportSpecifier()||!O.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 O.isMemberExpression(s)&&!s.computed&&O.isIdentifier(s.property,{name:"slug"})&&O.isAwaitExpression(s.object)&&O.isIdentifier(s.object.argument)&&YI(n.path,s.object.argument.name)}function YI(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=>O.isObjectPattern(i)&&i.properties.some(s=>O.isObjectProperty(s)&&!s.computed&&Hl(s.key)==="params"&&O.isIdentifier(s.value,{name:t})))}function I0(e){for(let t of e.program.body)if(O.isVariableDeclaration(t))for(let n of t.declarations){if(!O.isIdentifier(n.id,{name:"PAGE_SEO"}))continue;let r=sk(n.init);if(!O.isObjectExpression(r))return null;let o=r.properties.find(i=>O.isObjectProperty(i)&&!i.computed&&Hl(i.key)==="title");return o&&O.isStringLiteral(o.value)?o.value.value:null}return null}function ok(e,t,n){let o=_n(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=en(e.path,o[0].source,t),s=i?t.get(i):null;if(typeof s!="string")return"unproven";let a;try{a=Yr(s,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return"unproven"}for(let c of Gr(a,l=>O.isArrayExpression(l))){let l=c.elements.flatMap(f=>{if(!O.isObjectExpression(f))return[];let g=new Map;for(let m of f.properties){if(!O.isObjectProperty(m)||m.computed)continue;let p=Hl(m.key);p&&O.isStringLiteral(m.value)&&g.set(p,m.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 ik(e){let t;try{t=Yr(e,{sourceType:"module",plugins:["jsx","typescript"]})}catch{return[]}return[...new Set(Gr(t,n=>{if(!O.isCallExpression(n))return!1;let r=n.callee;if(!O.isMemberExpression(r)||r.computed||!O.isIdentifier(r.property,{name:"images"}))return!1;let o=n.arguments[0];return O.isMemberExpression(o)&&!o.computed&&O.isIdentifier(o.object,{name:"d"})&&O.isIdentifier(o.property)}).flatMap(n=>{let r=n.arguments[0];return O.isMemberExpression(r)&&!r.computed&&O.isIdentifier(r.property)?[r.property.name]:[]}))].sort(Om)}function k0(e,t){return ik(e).includes(t)}function Gr(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)ZI(s)&&r(s);else ZI(i)&&r(i)};return r(e),n}function ZI(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function sk(e){return e?O.isTSAsExpression(e)||O.isTSTypeAssertion(e)||O.isTSNonNullExpression(e)?sk(e.expression):e:null}function Hl(e){return O.isIdentifier(e)?e.name:O.isStringLiteral(e)?e.value:null}function Om(e,t){return e.localeCompare(t)}function _0(e,t,n,r,o,i){let s=_n(e,{filePath:t,exportName:"default"});for(let a of s.components){let c=en(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"||T0(u)&&o.push({path:c,export:a.export_name==="default"?{kind:"default"}:{kind:"named",name:a.export_name},purpose:"client-importer"})}}function R0(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=_n(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 Tm(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 C0(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 ak(e){return/^(?:src\/)?app\/(?:[^/.][^/]*\/)*page\.[cm]?[jt]sx?$/u.test(e)}function ck(e){return ak(e)&&/\/\[slug\]\/page\.[cm]?[jt]sx?$/u.test(e)}function P0(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 Dm(e){let t=/^(?:src\/)?app\/([A-Za-z0-9_-]+)\/\[slug\]\/page\.[cm]?[jt]sx?$/u.exec(e);return t?`/${t[1]}`:null}function N0(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function A0(e,t,n){let r=e.replace(/\\/g,"/"),o=t.replace(/\.(?:tsx?|jsx?)$/u,""),i=lk(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 T0(e){try{return Yr(e,{sourceType:"module",plugins:["jsx","typescript"]}).program.directives.some(n=>n.value.value==="use client")}catch{return!1}}function en(e,t,n){if(!pt(t))return null;let r=t.startsWith("@/")?t.slice(2):w0(`${lk(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 lk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function w0(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 Mm(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=ht(r);return o!==null?(super.set(n,o),o):typeof r=="string"?new TextEncoder().encode(r):r}}(t)}function O0(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 wm(e,t){e.some(r=>r.path===t.path&&r.kind===t.kind)||e.push(t)}function F0(e,t){return e.path.localeCompare(t.path)||e.kind.localeCompare(t.kind)||e.requirementKey.localeCompare(t.requirementKey)}function L0(e,t){return`${`related.${e.purpose}.${e.path.replace(/[^A-Za-z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`.slice(0,112)}.${t}`}function D0(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function M0(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}import{parse as mk}from"@babel/parser";import Bm from"@babel/traverse";import*as ke from"@babel/types";var B0=typeof Bm=="function"?Bm:Bm.default,j0=mk(`
42
42
  async function list({ searchParams }) {
43
43
  const sp = (await searchParams) ?? {};
44
44
  const pageValue = typeof sp.page === "string" ? sp.page : undefined;
45
45
  const page = Number(pageValue ?? 1) || 1;
46
46
  const category = typeof sp.category === "string" && sp.category !== "" ? sp.category : undefined;
47
47
  }
48
- `).program.body[0],Y_=D$.body.body;function tk(e,t,n){let r;try{r=ek(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=[];F$(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||!Fe.isBlockStatement(i.node.body))return null;let s=i.node.body.body,a=Q_(i.node,f=>Fe.isCallExpression(f)&&Z_(f,"listStrict",n));if(a.length!==1||a[0].arguments.length!==2)return null;let c=a[0],l=s.findIndex(f=>q_(f,c));if(l<0)return null;let u=c.arguments[1];if(!Fe.isObjectExpression(u))return null;let d=new Map;for(let f of u.properties){if(!Fe.isObjectProperty(f)||f.computed)return null;let y=Fe.isIdentifier(f.key)?f.key.name:Fe.isStringLiteral(f.key)?f.key.value:null;if(!y||!["page","pageSize","category"].includes(y)||d.has(y)||!Fe.isExpression(f.value))return null;d.set(y,f.value)}let p=d.get("page"),g=d.get("pageSize");if(!p||!Fe.isNumericLiteral(g)||!Number.isSafeInteger(g.value)||g.value<1||g.value>100)return null;let m=Q_(i.node,f=>Fe.isCallExpression(f)&&Z_(f,"categories",n));return d.has("category")?!Fe.isIdentifier(p,{name:"page"})||!Fe.isIdentifier(d.get("category"),{name:"category"})||m.length!==1||m[0].arguments.length!==1||!q_(s[l+1],m[0])||!B$(i,s.slice(0,l))?null:{paginate:!0,limit:g.value}:m.length||!M$(p,s.slice(0,l),i)?null:{paginate:!1,limit:g.value}}function Z_(e,t,n){let r=e.callee;return Fe.isMemberExpression(r)&&!r.computed&&Fe.isIdentifier(r.property,{name:t})&&Fe.isMemberExpression(r.object)&&!r.object.computed&&Fe.isIdentifier(r.object.property,{name:"collections"})&&Fe.isIdentifier(r.object.object,{name:"cms"})&&Fe.isStringLiteral(e.arguments[0],{value:n})}function q_(e,t){return!!(Fe.isVariableDeclaration(e,{kind:"const"})&&e.declarations.length===1&&Fe.isIdentifier(e.declarations[0].id)&&Fe.isAwaitExpression(e.declarations[0].init)&&e.declarations[0].init.argument===t)}function M$(e,t,n){if(n.scope.getBinding("searchParams")?.referencePaths.length)return!1;if(Fe.isNumericLiteral(e,{value:1}))return t.length===0;if(!Fe.isIdentifier(e)||t.length!==1)return!1;let o=t[0];if(!Fe.isVariableDeclaration(o,{kind:"const"})||o.declarations.length!==1)return!1;let i=o.declarations[0],s=n.scope.getBinding(e.name);return!!(Fe.isIdentifier(i.id,{name:e.name})&&Fe.isNumericLiteral(i.init,{value:1})&&s?.identifier===i.id&&s.constant)}function B$(e,t){if(t.length!==Y_.length||!t.every((u,d)=>Fe.isNodesEquivalent(u,Y_[d]))||e.scope.getBinding("Number")||e.scope.getBinding("undefined"))return!1;let n=e.node.params[0];if(!Fe.isObjectPattern(n)||n.properties.length!==1||!Fe.isObjectProperty(n.properties[0])||n.properties[0].computed||!Fe.isIdentifier(n.properties[0].key,{name:"searchParams"})||!Fe.isIdentifier(n.properties[0].value,{name:"searchParams"}))return!1;let r=t.map(u=>Fe.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||!Eg(l.referencePaths,[o.init])||!Eg(c[0].referencePaths,[i.init,a.init])||!Eg(c[1].referencePaths,[s.init]))}function Eg(e,t){return e.every(n=>!!n.findParent(r=>t.includes(r.node)))}function Q_(e,t){let n=[],r=o=>{if(!(o!==e&&Fe.isFunction(o))){t(o)&&n.push(o);for(let i of Fe.VISITOR_KEYS[o.type]??[]){let s=o[i];if(Array.isArray(s))for(let a of s)Fe.isNode(a)&&r(a);else Fe.isNode(s)&&r(s)}}};return r(e),n}var $$=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),U$=new Set(["data-vcp-block-id","data-vcp-edit-key"]),V$=new Set(["data-vcp-order","sourceOrder","source_order"]);function Xi(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(ba)}),n;try{n=Ig(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=Y$(n),o=Bn(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(vu(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=lk(m.name);if(!y)return;let x=Q$(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=>sk(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=ak(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:_g(d).sort(ba)}}function ik(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(ba)}),n;try{n=Ig(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(vu(n,new Set,(a,c)=>{if(!ie.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||lk(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=>sk(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=ak(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:_g(s.errors).sort(ba)}: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 J$(e){let t;try{t=Ig(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=Bn(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>Xi({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 K$(e){let t=Xi(e),n=z$(e.files),r=H$(e.file_path,e.target.source,n),o=r?_t(n.get(r)):null,i=r&&typeof o=="string"?tk(o,r,e.collection.slug):null,s=hg({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:X$(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=j$.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=_g(a).sort(ba);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:c.sort(G$),related_entries:s}}function X$(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 z$(e){return e instanceof Map?e:new Map(Object.entries(e))}function H$(e,t,n){if(!mt(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):W$(`${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 W$(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function G$(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function Y$(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 sk(e,t,n,r,o,i){let s=nU(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=Eo(f.argument);if(!S.ok||!ck(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,T]of Object.entries(S.value)){if(!rk(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,Sg(T))}continue}let y=eU(f.name);if(!y)continue;let x=f.value,E=x&&ie.isJSXExpressionContainer(x)?x.expression:null;if(U$.has(y)){let S=x?Iu(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(V$.has(y)){let S=x?Iu(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(!rk(y)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${y}`,message:`Portable invocation cannot encode prop ${y}.`,source_range:s});continue}if($$.has(y)){let S=x?Iu(x):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&nk(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&&nk(E,o)){g(y,{kind:"route-search-params"});continue}let b=x?Iu(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,Sg(b.value))}let m=Z$(n);return m.ok?m.value!==void 0&&g("children",Sg(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 ak(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 Iu(e){return e===null?{ok:!0,value:!0}:ie.isStringLiteral(e)?{ok:!0,value:e.value}:ie.isJSXExpressionContainer(e)?Eo(e.expression):{ok:!1}}function Eo(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 Eo(e.expression);if(ie.isUnaryExpression(e)){let t=Eo(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=Eo(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=Eo(n.argument);if(!i.ok||!ck(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!ie.isObjectProperty(n)||n.computed)return{ok:!1};let r=tU(n.key);if(!r)return{ok:!1};let o=Eo(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function Z$(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of ie.react.buildChildren(e)){let r=Eo(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 vu(e,t,n){let r=uk(e)?new Set([...t,...q$(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)ok(i)&&vu(i,r,n);else ok(o)&&vu(o,r,n)}function q$(e){if(!uk(e))return[];let t=[];for(let n of e.params)xa(n,t);return t}function xa(e,t){if(ie.isIdentifier(e)){t.push(e.name);return}if(ie.isAssignmentPattern(e)){xa(e.left,t);return}if(ie.isObjectPattern(e)){for(let n of e.properties)ie.isRestElement(n)?xa(n.argument,t):ie.isObjectProperty(n)&&xa(n.value,t);return}if(ie.isArrayPattern(e))for(let n of e.elements)n&&xa(n,t)}function nk(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 Sg(e){return{kind:"json-literal",value:e}}function ck(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rk(e){return/^[A-Za-z][A-Za-z0-9_]{0,127}$/u.test(e)}function lk(e){if(ie.isJSXIdentifier(e))return e.name;if(!ie.isJSXMemberExpression(e))return null;let t=vg(e.object);return t?`${t}.${e.property.name}`:null}function vg(e){if(ie.isJSXIdentifier(e))return e.name;if(!ie.isJSXMemberExpression(e))return null;let t=vg(e.object);return t?`${t}.${e.property.name}`:null}function Q$(e,t){if(ie.isJSXIdentifier(e))return t.get(e.name)??null;if(!ie.isJSXMemberExpression(e))return null;let n=vg(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 eU(e){return ie.isJSXIdentifier(e)?e.name:ie.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function tU(e){return ie.isIdentifier(e)?e.name:ie.isStringLiteral(e)||ie.isNumericLiteral(e)?String(e.value):null}function uk(e){return ie.isFunctionDeclaration(e)||ie.isFunctionExpression(e)||ie.isArrowFunctionExpression(e)}function ok(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function nU(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 _g(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function ba(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var iU=typeof Cg=="function"?Cg:Cg.default,Rg=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=_u(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=we(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 sU(e){return pk(e,!1)}function fk(e){return pk(e,!0)}function pk(e,t){let{binding:n,files:r}=e;if(e.hostCapabilities!==null&&!rU.safeParse(e.hostCapabilities).success)return Nt("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!Ea(n.descriptor.source.file)||!Ea(n.ownerFile))return Nt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let o=_u(r,n.descriptor.source.file),i=_u(r,n.ownerFile);if(o===null||i===null)return Nt("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(Ue(o)!==n.descriptor.source.contentHash||Ue(o)!==n.sourceHash||Ue(i)!==n.ownerSourceHash)return Nt("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let s=we(n.descriptor.source.file,o);if(!s.ok)return Nt("INVOCATION_PARSE_FAILED",n.descriptor.source.file,s.diagnostic.message);let a=ku(s.module.ast,n.rootLocator.sourceRange);if(a.length!==1)return Nt("INVOCATION_TARGET_AMBIGUOUS",n.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let c=a[0],l=gk(c.node);if(!l)return Nt("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 Rg(r),g=aU(e,l,p,t);if(g)return g;if(d.some(x=>(x.alternativeLocators?.length??0)>1))return Nt("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=_u(r,E.sourceFile);if(b===null||!Ea(E.sourceFile))return Nt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let S=we(E.sourceFile,b);if(!S.ok)return Nt("INVOCATION_PARSE_FAILED",E.sourceFile,S.diagnostic.message);let I=ku(S.module.ast,E.callLocator.sourceRange);if(I.length!==1)return Nt("INVOCATION_TARGET_AMBIGUOUS",E.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let T=d[x+1]?.sourceFile??n.descriptor.source.file,C=d[x+1]?.callLocator.sourceRange??n.rootLocator.sourceRange,A=Fn({module:S.module,componentName:E.component,callSourceRange:E.callLocator.sourceRange});if(A.ok){if(A.sourceFile!==T)return Nt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(A.roots.filter(ue=>zi(ue.node,C)).length!==1)return Nt("INVOCATION_TARGET_NOT_RENDERED",A.sourceFile,"The local component definition does not select exactly one proven JSX root.");let he=ik({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:A,entryExport:null});continue}let P=Pg(S.module.ast,I[0].node.openingElement.name,E.component,E.exportName);if(!P)return Nt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The statically proven component call no longer resolves through one exact import.");let F=Ng(E.sourceFile,P.source,r);if(!F)return Nt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let B=p.read(F);if(!B.ok)return Nt(B.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",F,B.message);let U=qt({module:B.module,exportName:P.exportName,parsedModules:p});if(!U.ok)return Nt("INVOCATION_TARGET_NOT_RENDERED",U.diagnostic.file,U.diagnostic.message);if(U.sourceFile!==T)return Nt("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let G=U.roots.filter(H=>zi(H.node,C));if(G.length!==1)return Nt("INVOCATION_TARGET_NOT_RENDERED",U.sourceFile,"The unique component export does not select exactly one proven JSX root.");let X=null;if(x===d.length-1&&d.length===1&&!yk(n.ownerFile)&&zi(G[0].node,n.rootLocator.sourceRange)){let H=p.read(U.sourceFile);if(!H.ok)return Nt(H.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",U.sourceFile,H.message);if(X=mk(H.module,U.componentName,P.exportName),!X)return Nt("INVOCATION_TARGET_AMBIGUOUS",U.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let Z=Xi({file_path:E.sourceFile,source:b,target:{source:P.source,export_name:P.exportName,local_name:P.localName},call_source_range:{start_line:E.callLocator.sourceRange.startLine,start_column:E.callLocator.sourceRange.startColumn}});if(!Z.call||!Z.complete)return{complete:!1,errors:Z.errors.length>0?Z.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:Z.call,invocation:Z,definition:U,entryExport:X})}let m={kind:"page-block",composition:hk(n.composition),blockKey:n.blockKey},f=cU(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 aU(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=ku(l.ast,a.callLocator.sourceRange);if(u.length!==1)return null;let d=Pg(l.ast,u[0].node.openingElement.name,a.component,a.exportName);if(!d)return null;let p=Ng(a.sourceFile,d.source,i),g=p?n.get(p):void 0;if(!g)return null;let m=qt({module:g,exportName:d.exportName,parsedModules:n});if(!m.ok||m.sourceFile!==c.sourceFile)return null;let f=n.get(m.sourceFile);if(!f||mk(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(!j_(y))return null}else{let T=gg(y);if(!T.complete||!T.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(T=>x.filter(C=>zi(T.node,C.sourceRange)).length===1))return null;for(let T of x){let C=ku(f.ast,T.sourceRange);if(C.length!==1)return null;let A=Pg(f.ast,C[0].node.openingElement.name,c.component,c.exportName);if(!A)return null;let P=Ng(m.sourceFile,A.source,i),F=P?n.get(P):void 0;if(!F)return null;let B=qt({module:F,exportName:A.exportName,parsedModules:n});if(!B.ok||B.sourceFile!==o.descriptor.source.file||B.roots.length!==1||!zi(B.roots[0].node,o.rootLocator.sourceRange))return null}let b=Xi({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/${dk("sha256").update(JSON.stringify(["collection-container",o.composition,o.blockKey,o.sourceHash,Ue(f.source)])).digest("hex").slice(0,24)}/page.tsx`;return i.has(I)?Nt("INVOCATION_TARGET_AMBIGUOUS",I,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:hk(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 cU(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&zi(i.definition.roots[0].node,e.rootLocator.sourceRange),u=yk(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(!gk(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/${dk("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!Ea(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 mk(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=lU(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)ct.isExportSpecifier(s)&&s.exportKind!=="type"&&Tg(s.local)===t&&r.add(Tg(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 lU(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 Pg(e,t,n,r){let o=Ag(t);if(!o||o!==n)return null;let i=ct.isJSXMemberExpression(t)?Ag(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=Tg(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 ku(e,t){let n=[];return iU(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 gk(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 zi(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 _u(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 Ng(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?kg.posix.normalize(kg.posix.join(kg.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=>Ea(i)&&n.has(i))??null}function Ag(e){if(ct.isJSXIdentifier(e))return e.name;if(ct.isJSXMemberExpression(e)){let t=Ag(e.object);return t?`${t}.${e.property.name}`:null}return null}function Tg(e){return ct.isIdentifier(e)?e.name:e.value}function hk(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function Ea(e){return oU.safeParse(e).success}function yk(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function Nt(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import wg from"@babel/generator";import Og from"@babel/traverse";import*as ye from"@babel/types";var xk=typeof Og=="function"?Og:Og.default,uU=typeof wg=="function"?wg:wg.default;function Ek(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=Ik(t.get(o));if(i===null||!/\.[cm]?[jt]sx?$/iu.test(o))continue;let s=we(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;xk(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),bk(l)&&(a=!0))}}}),xk(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=bk(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||Hi(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=wt(o,d.node.source.value,t);if(!(!p||!n.has(p))&&!d.node.specifiers.some(g=>c.scope.getBinding(g.local.name)?.referenced)){if(!Sk(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,uU(s.module.ast).code)}return{files:t,errors:r}}function bk(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 Sk(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=Ik(t.get(e));if(r===null)return!1;let o=we(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!mt(a))return!1;let c=wt(e,a,t);return c!==null&&Sk(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?Lg(a.declaration):!0:ye.isExportDefaultDeclaration(a)?Lg(a.declaration):Lg(a))}function Lg(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||Hi(t.init))):Hi(e)}function Hi(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)&&Hi(t)):ye.isObjectExpression(e)?e.properties.every(t=>ye.isObjectProperty(t)&&!t.computed&&!t.shorthand&&Hi(t.value)):ye.isTSAsExpression(e)||ye.isTSSatisfiesExpression(e)||ye.isTSNonNullExpression(e)||ye.isParenthesizedExpression(e)?Hi(e.expression):!1}function Ik(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 Sa}from"node:crypto";import Fg from"@babel/traverse";import*as De from"@babel/types";import{PORTABLE_AUDITED_PLACEHOLDER_SVG as Dg,PORTABLE_AUDITED_SAFE_IMAGE as dU}from"@vcp-dev/contracts";var Bg=typeof Fg=="function"?Fg:Fg.default,Cu=dU.digest_sha256;function _k(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:${Cu}`)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(Dg.path);if(i===void 0||Sa("sha256").update(i).digest("hex")!==Cu||!(s instanceof Uint8Array)||s.byteLength!==Dg.byte_size||Sa("sha256").update(s).digest("hex")!==Dg.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=fU(e,n);for(let u of a){let d=u.from,p=(e.selected_host_calls??[]).filter(P=>P.file_path===d&&P.host_file===e.host_file);if(!p.length&&!l(d))return t();let g=_t(e.files.get(d));if(g===null)return t();let m=we(d,g);if(!m.ok)return t();let f=qt({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(Bg(m.module.ast,{ImportDeclaration(P){if(wt(d,P.node.source.value,e.files)!==e.host_file||P.node.importKind==="type")return;let F=P.get("specifiers"),B=F[0];if(y||F.length!==1||!B?.isImportSpecifier()||B.node.importKind==="type"||!De.isIdentifier(B.node.imported,{name:"SafeImage"})){x=!0;return}y=B}}),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 P=`sha256:${Sa("sha256").update(g).digest("hex")}`;if(p.length>256||p.some(G=>G.source_hash!==P))return t();let F=new Set(p.map(G=>`${G.start}:${G.end}`)),B=new Map,U=!1;if(Bg(m.module.ast,{JSXOpeningElement(G){if(!(!De.isJSXIdentifier(G.node.name)||G.scope.getBinding(G.node.name.name)!==b)){if(!F.has(`${G.node.start}:${G.node.end}`)||!vk(G.node)){U=!0;return}B.set(G.node,G)}}}),U||B.size!==F.size||!Mg(b.referencePaths,new Set(B.keys())))return t();for(let G of B.values()){let X=G.node;if(X.start==null||X.end==null||!X.loc)return t();let Z=g.slice(X.start,X.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:Z,asset_key:null,source_range:{start_offset:X.start,end_offset:X.end,start_line:X.loc.start.line,start_column:X.loc.start.column,end_line:X.loc.end.line,end_column:X.loc.end.column},content_digest:`sha256:${Sa("sha256").update(Z).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:Cu}})}continue}if(!f.ok||f.metadataOnly||f.returnAlternatives)return t();let S=new Map,I=new Map,T=!1,C=0,A=(P,F=0,B=!1)=>{if(++C>2048||F>128){T=!0;return}if(P.isJSXElement()){let U=P.get("openingElement");if(!De.isJSXIdentifier(U.node.name)){T=!0;return}if(U.scope.getBinding(U.node.name.name)===b){vk(U.node)||(T=!0),S.set(U.node,U);return}if(!/^[a-z]/u.test(U.node.name.name)){if(B)return;let G=U.scope.getBinding(U.node.name.name);if(!G?.constant)return;let X=G.path;if(!(X.isFunctionDeclaration()&&!X.parentPath.isExportNamedDeclaration()&&!X.parentPath.isExportDefaultDeclaration()||X.isVariableDeclarator()&&X.parentPath.isVariableDeclaration({kind:"const"})&&!X.parentPath.parentPath.isExportNamedDeclaration()&&(De.isFunctionExpression(X.node.init)||De.isArrowFunctionExpression(X.node.init)))||!P.node.loc)return;let H=I.get(G.identifier);if(H){H.openings.add(U.node),H.active&&(T=!0);return}if(I.size>=32){T=!0;return}let he={references:G.referencePaths,openings:new Set([U.node]),active:!0};I.set(G.identifier,he);let ue=Fn({module:m.module,componentName:U.node.name.name,callSourceRange:{startLine:P.node.loc.start.line,startColumn:P.node.loc.start.column,endLine:P.node.loc.end.line,endColumn:P.node.loc.end.column}});if(!ue.ok||ue.metadataOnly||ue.returnAlternatives||ue.sourceFile!==d){T=!0;return}for(let je of ue.roots)A(je,F+1,B);he.active=!1;return}if(["template","script","style","noscript"].includes(U.node.name.name)||U.node.attributes.some(G=>!De.isJSXAttribute(G)||!De.isJSXIdentifier(G.name)||/^(?:on|ref$|style$|dangerouslySetInnerHTML$)/iu.test(G.name.name))){T=!0;return}}for(let U of P.get("children"))if(U.isJSXElement()||U.isJSXFragment())A(U,F+1,B);else if(U.isJSXExpressionContainer()){let G=U.get("expression");if(G.isJSXElement()||G.isJSXFragment())A(G,F+1,B);else if(G.isLogicalExpression({operator:"&&"})&&Ru(G.node.left)&&mU(G.get("left"))){let X=G.get("right");(X.isJSXElement()||X.isJSXFragment())&&A(X,F+1,!0)}}};for(let P of f.roots)A(P);if(T||S.size===0||!Mg(b.referencePaths,new Set(S.keys())))return t();for(let P of I.values())if(!Mg(P.references,P.openings))return t();for(let P of S.values()){let F=P.node;if(F.start==null||F.end==null||!F.loc)return t();let B=g.slice(F.start,F.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:B,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:${Sa("sha256").update(B).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:Cu}})}}return{complete:!0,references:c}}function Mg(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 fU(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=pU(d.from,a,e.files,t.get(d.from)??"default")&&bu(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 pU(e,t,n,r){let o=_t(n.get(e));if(o===null)return!1;let i=we(e,o);if(!i.ok)return!1;let s=null,a=!1;if(Bg(i.module.ast,{ImportDeclaration(f){if(f.node.importKind==="type"||wt(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"&&De.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=Bn(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=qt({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 vk(e){let t=new Set;for(let n of e.attributes){if(!De.isJSXAttribute(n)||!De.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"&&De.isJSXExpressionContainer(o)&&qo(o.expression))&&o!==null&&!De.isStringLiteral(o)&&!(De.isJSXExpressionContainer(o)&&(De.isStringLiteral(o.expression)||De.isNumericLiteral(o.expression)||De.isBooleanLiteral(o.expression))))return!1}return t.has("src")}function mU(e){try{let t=e.evaluate();return!t.confident||!!t.value}catch{return!1}}function Ru(e,t=0){return t>32?!1:De.isIdentifier(e)?!["undefined","NaN","Infinity"].includes(e.name):De.isMemberExpression(e)||De.isOptionalMemberExpression(e)?qo(e):De.isUnaryExpression(e,{operator:"!"})?Ru(e.argument,t+1):De.isBinaryExpression(e)?Ru(e.left,t+1)&&qo(e.right)||qo(e.left)&&Ru(e.right,t+1):!1}function qo(e,t=0){if(t>32)return!1;if(De.isStringLiteral(e)||De.isNumericLiteral(e)||De.isBooleanLiteral(e)||De.isNullLiteral(e)||De.isIdentifier(e))return!0;if(De.isMemberExpression(e)||De.isOptionalMemberExpression(e)){let n=e.property;return!e.computed&&!De.isIdentifier(n)||e.computed&&!(De.isStringLiteral(n)||De.isNumericLiteral(n))||(De.isIdentifier(n)||De.isStringLiteral(n))&&["__proto__","prototype","constructor"].includes(De.isIdentifier(n)?n.name:n.value)?!1:qo(e.object,t+1)}return De.isLogicalExpression(e)?qo(e.left,t+1)&&qo(e.right,t+1):!1}async function Ck(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=_t(n.get(t.ownerFile)),s=_t(n.get(t.descriptor.source.file));if(i===null||s===null)return[];let a=async c=>{let l=_t(n.get(c));if(l===null)throw new Error("Snapshot source unavailable");return l};try{let c=await ci(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||!gU(l[0].sourceRange,o.callLocator.sourceRange))return[];let u=[...c.graph.elements.values()].filter(f=>f.sourceFile===t.descriptor.source.file&&kk(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=Fn({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 T=I.node.loc;return T&&kk({startLine:T.start.line,startColumn:T.start.column,endLine:T.end.line,endColumn:T.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 Al({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 gU(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function kk(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 jg from"@babel/traverse";import*as bt from"@babel/types";var hU=typeof jg=="function"?jg:jg.default;function Rk(e){let t=we(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&&yU(s,e.current_route)){r.add(e.current_route);return}if(!bt.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=Pk(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return hU(t.module.ast,{JSXOpeningElement(s){let a=bt.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=>bt.isJSXAttribute(d)&&bt.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),l=c.length===1&&bt.isJSXAttribute(c[0])?c[0].value:null,u=bt.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(!bt.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(bt.isJSXExpressionContainer(c)?c.expression:c)},JSXSpreadAttribute(){o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=Ia(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=Ia(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=Ia(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)&&bt.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"&&bt.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){(bt.isIdentifier(s.node.left,{name:"location"})||bt.isMemberExpression(s.node.left)&&(Ia(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&Ia(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){bt.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 yU(e,t){if(!t||t.includes("?")||t.includes("#")||Pk(t)!=="host-route")return!1;let n=bt.isStringLiteral(e)?[e.value]:bt.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 Ia(e,t){return bt.isStringLiteral(e)?e.value:!t&&bt.isIdentifier(e)?e.name:t&&bt.isNumericLiteral(e)?String(e.value):null}function Pk(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 Ak=512,vU=1024*1024,_U=8*1024*1024,Tk=256;function kU(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||wk(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%Nk!==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>EU||e.offset>=a.byteLength)return t();let c=CU(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:Tu("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+Nk).toString("base64")}}function CU(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===$g.path&&t.byteLength===$g.byte_size&&Tu("sha256").update(t).digest("hex")===$g.digest_sha256?"image/svg+xml":null}async function RU(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return gn("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=SU.safeParse(e.target),c=xU.safeParse(e.selection_ref);if(!a.success||!c.success)return gn("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let l=a.data,u=c.data,d=Pu(o,t,n,r);if(d)return d;let p=bU.safeParse(e.host_capabilities);if(!p.success)return gn("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let g=new Map;for(let[v,$]of e.snapshot.files){if(typeof $!="string"&&!($ instanceof Uint8Array))return gn("SNAPSHOT_CONTENT_MISMATCH",v,"A Snapshot file has an unsupported content type.");g.set(v,typeof $=="string"?$:new Uint8Array($))}if(!AU(e.snapshot.manifest,t,n,g))return gn("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let m=wk(g),f=await Lm({site_id:t,base_snapshot_id:n,composition:l.composition,document_version:r,target:l,selection_ref:u,files:g});if(!f.ok)return gn(`BLOCK_${f.code}`,l.blockKey,f.message);if(!f.binding.descriptor.capabilities.save)return gn("BLOCK_EXPORT_NOT_ALLOWED",l.blockKey,"The selected block is not exportable.");let y=fk({binding:f.binding,files:g,hostCapabilities:p.data}),x;if(!y.complete){let v=Nu(y.errors.map(({code:Re,path:Pe,message:nt})=>({code:Re,path:Pe,message:nt})));if(!y.errors.some(Re=>Re.code==="INVOCATION_VALUE_UNRESOLVED"))return v;let $=Fr(g,i)?u_({binding:f.binding,target:l,files:g,trusted_host_file_hashes:i}):null,te=$?.complete?[]:await Ck({binding:f.binding,files:g}),Ie=Pu(o,t,n,r);if(Ie)return Ie;if(!$?.complete)return te.length?{...v,cms_candidates:{kind:"partial-unproven",slugs:te}}:v;y={complete:!0,selection:$.selection},x=$.extracted}let E=x??Xm({selection:y.selection,files:g});if(!E.complete)return Nu(E.errors.map(({code:v,path:$,message:te})=>({code:v,path:$,message:te})));let b=new Map(g);for(let v of E.source_files){let $=b.get(v.path);if($!==void 0&&!PU($,v.content))return gn("SOURCE_COLLISION",v.path,"An extracted entry conflicts with the pinned Snapshot.");b.set(v.path,v.content)}let S=br({entry_files:[E.entry_file],files:b,max_nodes:Ak}),I=S.nodes.filter(v=>Au(v.path)&&i.get(v.path)===va(b.get(v.path))).map(v=>v.path),T=tu({closure:S,host_capabilities:p.data,platform_managed_paths:I,platform_managed_packages:["server-only"]}),C=Ek({files:b,private_paths:T.nodes.filter(v=>v.ownership==="private").map(v=>v.path)});b=new Map(C.files);let A=br({entry_files:[E.entry_file],files:b,max_nodes:Ak}),P=tu({closure:A,host_capabilities:p.data,platform_managed_paths:I,platform_managed_packages:["server-only"]}),F=new Map,B=[],U=[],G=p_({entry_file:E.entry_file,entry_export:y.selection.entry_export,files:b,confirmed_slugs:new Set(s.map(v=>v.source_slug)),allow_build_sample:lu(b,i),on_host_call:v=>U.push(v),on_build_only_value:v=>B.push(v)}),X=G.dependencies.length>0&&Fr(b,i);X||(U.length=0,B.length=0);let Z=X?G:P_({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(v){let $=`${v.file_path}:${v.start}:${v.end}`,te=F.get($)??{invalid:!1,sources:new Map};!v.origin||!v.origin.field_path?te.invalid=!0:te.sources.set(`${v.origin.slug}:${v.origin.field_path}`,v.origin),F.set($,te)},on_audited_ui_call(v){U.push(v)},on_build_only_value(v){B.push(v)},...x||y.selection.strategy==="collection-container"?{entry_argument_origin:"jsx-props"}:{}}),H=[...C.errors.filter(v=>A.nodes.some($=>$.path===v.path)),...P.errors.map(({code:v,path:$,message:te})=>({code:v,path:$,message:te})),...Z.unresolved.map(({code:v,source_path:$,message:te,call_site:Ie})=>({code:v,path:$,message:te,...Ie?{call_site:Ie}:{}}))];if(Z.complete){let v=new Set(Z.dependencies.map(te=>te.slug)),$=new Set;X&&s.length>0&&s.length!==Z.dependencies.length&&H.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"Every selected application requires exactly one matching schema."});for(let te of s){if($.has(te.source_slug)||!v.has(te.source_slug)){H.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}$.add(te.source_slug)}}let he=new Set(I);for(let v of A.nodes)X&&/^(?:src\/)?lib\/cms\/jsonld\.tsx$/u.test(v.path)&&!au(b,i,v.path)&&H.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:v.path,message:"A modified CMS helper cannot be omitted from the exported code dependencies."}),Au(v.path)&&!he.has(v.path)&&H.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:v.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let v of P.nodes)v.kind==="external"||v.ownership!=="host-public"||Au(v.path)||i.get(v.path)!==va(g.get(v.path))&&H.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:v.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let ue=[];for(let v of P.nodes){if(v.kind!=="source"||!["host-public","platform-managed"].includes(v.ownership))continue;let $=_t(b.get(v.path)),te=$===null?null:Ji({file_path:v.path,source:$});if(!te||te.references.length>0||te.errors.length>0){let Ie=v.ownership==="host-public"&&y.selection.entry_export.kind==="default"?_k({entry_file:E.entry_file,host_file:v.path,files:b,closure:A,trusted_host_file_hashes:i,...Z.complete?{selected_host_calls:U}:{}}):{complete:!1};if(Ie.complete){ue.push(...Ie.references);continue}H.push({code:"HOST_MEDIA_DEPENDENCY_UNPROVEN",path:v.path,message:"The omitted host source has media that cannot yet be bound to this archive."})}}let je=new Map(P.nodes.map(v=>[v.path,v.ownership])),He=[];for(let v of A.nodes){if(je.get(v.path)!=="private")continue;let $=b.get(v.path),te=null;try{typeof $=="string"?te=$:$ instanceof Uint8Array&&(te=new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{}te===null?H.push({code:"SOURCE_TEXT_UNSUPPORTED",path:v.path,message:"A private source dependency is not valid UTF-8 text."}):He.push({path:v.path,content:te})}for(let v of He)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(v.path)||v.path==="lib/generated/product-search-config.json")&&H.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:v.path,message:"A managed capability requires a proven requirement before exporting the block."});He.some(v=>v.path===E.entry_file)||H.push({code:"ENTRY_NOT_PRIVATE",path:E.entry_file,message:"The selected entry is not site-owned source."});let ht=0,O=[];for(let v of He){let $=Buffer.byteLength(v.content,"utf8");if(ht+=$,($>vU||ht>_U)&&H.push({code:"SOURCE_BUDGET_EXCEEDED",path:v.path,message:"The selected source exceeds its export byte budget."}),/\.[cm]?[jt]sx?$/iu.test(v.path)){let te=Ji({file_path:v.path,source:v.content,static_only:X}),Ie=new Set;O.push(...te.references.filter(Re=>!Z.complete||!B.some(Pe=>Pe.file_path===v.path&&Pe.source_hash===va(v.content)&&Pe.start<=Re.source_range.start_offset&&Pe.end>=Re.source_range.end_offset)).map(Re=>{if(Re.complete||!Z.complete)return Re;let Pe=Re.source_range,nt=F.get(`${v.path}:${Pe.start_offset}:${Pe.end_offset}`);if(!nt||nt.invalid||!nt.sources.size)return Re;let Ut=[...nt.sources.values()].sort((Vt,pt)=>`${Vt.slug}:${Vt.field_path}`.localeCompare(`${pt.slug}:${pt.field_path}`));return Ut.every(Vt=>Z.dependencies.some(pt=>pt.slug===Vt.slug)&&s.some(pt=>pt.source_slug===Vt.slug&&pt.fields.some(Vn=>Vn.name===Vt.field_path&&["Image","Images","MultiImage","RichText","Richtext"].includes(Vn.cms_type))))?(Ie.add(`${Pe.start_offset}:${Pe.end_offset}`),{...Re,complete:!0,cms_field:{sources:Ut}}):Re})),H.push(...te.errors.filter(Re=>!Re.source_range||!Ie.has(`${Re.source_range.start_offset}:${Re.source_range.end_offset}`)).map(({code:Re,file_path:Pe,message:nt})=>({code:Re,path:Pe,message:nt})))}}for(let v of ue){let te=O.filter(Ie=>Ie.file_path===v.file_path).reduce((Ie,Re)=>Math.max(Ie,Re.occurrence+1),0);O.push({...v,occurrence:te})}let L=new Map,z=!0;if(Z.complete){let v=new Map(He.map($=>[$.path,$.content]));for(let $ of P.nodes){if($.kind!=="source"||!["host-public","platform-managed"].includes($.ownership))continue;let te=b.get($.path);try{if(typeof te=="string")v.set($.path,te);else if(te instanceof Uint8Array)v.set($.path,new TextDecoder("utf-8",{fatal:!0}).decode(te));else throw new Error("missing source")}catch{z=!1,Z.dependencies.length===0&&H.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:$.path,message:"A host source cannot be inspected for navigation."})}}for(let[$,te]of v){if(!/\.[cm]?[jt]sx?$/iu.test($))continue;let Ie=Rk({file_path:$,source:te,current_route:l.composition.routeId});Ie.complete||(z=!1),Z.dependencies.length===0&&H.push(...Ie.errors);for(let Re of Ie.dependencies)L.set(Re.href,Re)}L.size>256&&Z.dependencies.length===0&&H.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let j=Z.dependencies.length>0&&y.selection.strategy!=="collection-container"&&z&&L.size===0&&NU(A,b,i)&&T_(Z,b),K=Z.complete&&Z.dependencies.length>0&&s.length===Z.dependencies.length&&new Set(s.map(v=>v.source_slug)).size===s.length&&Z.dependencies.every(v=>s.some($=>$.source_slug===v.slug)&&v.evidence.every($=>["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"].includes($.operation)))&&Fr(b,i);if(H.length>0||!A.complete||!P.complete||!Z.complete){let v=[...new Set([...Z.dependencies.map(Ie=>Ie.slug),...Z.candidates??[]])].sort();if(!(v.length>0&&v.length<=16&&new Set(v).size===v.length&&v.every(Ie=>/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(Ie))))return Nu(H);let te=Pu(o,t,n,r);return te||{...Nu(H),cms_candidates:{kind:"partial-unproven",slugs:v}}}let ee=Pu(o,t,n,r);if(ee)return ee;let pe={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:He.map(({path:v,content:$})=>({path:v,content:$})),source_closure:A,dependency_audit:P,cms:Z,media:O,invocation_bindings:E.invocation_bindings,host_contract_digest:p.data.host_contract_digest,...Z.dependencies.length===0?{route_dependencies:[...L.values()].sort((v,$)=>v.href.localeCompare($.href))}:{},...X&&K?{cms_sample_proof:{kind:"whole-application"}}:K?{cms_sample_proof:{kind:"application-first-page-example"}}:j?{cms_sample_proof:{kind:"first-page-no-host-routes"}}:{}};return IU.safeParse(pe).success?pe:gn("PORTABLE_EXPORT_RESULT_INVALID","<export>","The selected source result failed its bounded export contract.")}function Pu(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return gn("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?gn("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?gn("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return gn("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function wk(e){let t=Tu("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 PU(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function Au(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function NU(e,t,n){let r=e.nodes.filter(s=>Au(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")||va(t.get(a))!==c)return!1;i.set(s,c)}return cu({index:i.get("index.ts"),collections:i.get("collections.ts"),client:i.get("client.ts")})}function va(e){return e===void 0?null:`sha256:${Tu("sha256").update(e).digest("hex")}`}function AU(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||va(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function gn(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function Nu(e){return e.length?e.length<=Tk?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,Tk-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:gn("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import Ug from"@babel/generator";import{parse as TU}from"@babel/parser";import wU from"@babel/traverse";import*as Dt from"@babel/types";var Vg=wU,OU=typeof Vg=="function"?Vg:Vg.default,LU=typeof Ug=="function"?Ug:Ug.default,Bk="components/site/generated/{{$INSTANCE}}/",jk=new Set([".tsx",".ts",".jsx",".js"]),Ok=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),FU=new Set(["data-site-block-order","data-vcp-order"]);function DU(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=Dr(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=Dr(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=Dr(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:KU(b)})),c=new Map(a.map(b=>[b.source_path,b.path_template])),l=MU(e.source_mapping??[],c,t),u=BU(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=$U(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=Dk(t).sort(Mk);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(T=>T.path_template===b.path_template)?.source_path,I=n.get(S)?.content??"";return{source_path:S,path_template:b.path_template,original_byte_size:Lk(I),output_byte_size:Lk(b.content),original_line_count:Fk(I),output_line_count:Fk(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=jU(e.thin_entry_plan,c,t);b&&(g.push(b),x=b.path_template)}let E=Dk(t).sort(Mk);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(GU),block_metadata:y,errors:[]}}function MU(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=Dr(s.generated_path),c=Dr(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 BU(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=Dr(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 jU(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(Dr(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=`${Bk}__managed-root-entry.tsx`,i=$k(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}
48
+ `).program.body[0],uk=j0.body.body;function gk(e,t,n){let r;try{r=mk(e,{sourceType:"module",sourceFilename:t,plugins:["jsx","typescript"]})}catch{return null}let o=[];B0(r,{ExportDefaultDeclaration(p){let y=p.get("declaration");(y.isFunctionDeclaration()||y.isFunctionExpression()||y.isArrowFunctionExpression())&&o.push(y)}});let i=o.length===1?o[0]:void 0;if(!i||!ke.isBlockStatement(i.node.body))return null;let s=i.node.body.body,a=pk(i.node,p=>ke.isCallExpression(p)&&dk(p,"listStrict",n));if(a.length!==1||a[0].arguments.length!==2)return null;let c=a[0],l=s.findIndex(p=>fk(p,c));if(l<0)return null;let u=c.arguments[1];if(!ke.isObjectExpression(u))return null;let d=new Map;for(let p of u.properties){if(!ke.isObjectProperty(p)||p.computed)return null;let y=ke.isIdentifier(p.key)?p.key.name:ke.isStringLiteral(p.key)?p.key.value:null;if(!y||!["page","pageSize","category"].includes(y)||d.has(y)||!ke.isExpression(p.value))return null;d.set(y,p.value)}let f=d.get("page"),g=d.get("pageSize");if(!f||!ke.isNumericLiteral(g)||!Number.isSafeInteger(g.value)||g.value<1||g.value>100)return null;let m=pk(i.node,p=>ke.isCallExpression(p)&&dk(p,"categories",n));return d.has("category")?!ke.isIdentifier(f,{name:"page"})||!ke.isIdentifier(d.get("category"),{name:"category"})||m.length!==1||m[0].arguments.length!==1||!fk(s[l+1],m[0])||!U0(i,s.slice(0,l))?null:{paginate:!0,limit:g.value}:m.length||!$0(f,s.slice(0,l),i)?null:{paginate:!1,limit:g.value}}function dk(e,t,n){let r=e.callee;return ke.isMemberExpression(r)&&!r.computed&&ke.isIdentifier(r.property,{name:t})&&ke.isMemberExpression(r.object)&&!r.object.computed&&ke.isIdentifier(r.object.property,{name:"collections"})&&ke.isIdentifier(r.object.object,{name:"cms"})&&ke.isStringLiteral(e.arguments[0],{value:n})}function fk(e,t){return!!(ke.isVariableDeclaration(e,{kind:"const"})&&e.declarations.length===1&&ke.isIdentifier(e.declarations[0].id)&&ke.isAwaitExpression(e.declarations[0].init)&&e.declarations[0].init.argument===t)}function $0(e,t,n){if(n.scope.getBinding("searchParams")?.referencePaths.length)return!1;if(ke.isNumericLiteral(e,{value:1}))return t.length===0;if(!ke.isIdentifier(e)||t.length!==1)return!1;let o=t[0];if(!ke.isVariableDeclaration(o,{kind:"const"})||o.declarations.length!==1)return!1;let i=o.declarations[0],s=n.scope.getBinding(e.name);return!!(ke.isIdentifier(i.id,{name:e.name})&&ke.isNumericLiteral(i.init,{value:1})&&s?.identifier===i.id&&s.constant)}function U0(e,t){if(t.length!==uk.length||!t.every((u,d)=>ke.isNodesEquivalent(u,uk[d]))||e.scope.getBinding("Number")||e.scope.getBinding("undefined"))return!1;let n=e.node.params[0];if(!ke.isObjectPattern(n)||n.properties.length!==1||!ke.isObjectProperty(n.properties[0])||n.properties[0].computed||!ke.isIdentifier(n.properties[0].key,{name:"searchParams"})||!ke.isIdentifier(n.properties[0].value,{name:"searchParams"}))return!1;let r=t.map(u=>ke.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||!jm(l.referencePaths,[o.init])||!jm(c[0].referencePaths,[i.init,a.init])||!jm(c[1].referencePaths,[s.init]))}function jm(e,t){return e.every(n=>!!n.findParent(r=>t.includes(r.node)))}function pk(e,t){let n=[],r=o=>{if(!(o!==e&&ke.isFunction(o))){t(o)&&n.push(o);for(let i of ke.VISITOR_KEYS[o.type]??[]){let s=o[i];if(Array.isArray(s))for(let a of s)ke.isNode(a)&&r(a);else ke.isNode(s)&&r(s)}}};return r(e),n}var K0=new Set(["blockId","block_id","targetBlockId","target_block_id","sourceBlockId","source_block_id"]),J0=new Set(["data-vcp-block-id","data-vcp-edit-key"]),X0=new Set(["data-vcp-order","sourceOrder","source_order"]);function _i(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(Zs)}),n;try{n=Um(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=Q0(n),o=_n(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(Gl(n,new Set,(f,g)=>{if(!Y.isJSXElement(f))return;let m=f.openingElement,p=m.start;if(typeof p!="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=Ik(m.name);if(!y)return;let b=n$(m.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(p)&&a.push({node:m,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=>Ek(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=Sk(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:Km(d).sort(Zs)}}function xk(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(Zs)}),n;try{n=Um(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(Gl(n,new Set,(a,c)=>{if(!Y.isJSXElement(a))return;let l=a.openingElement;if(typeof l.start!="number"||Ik(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=>Ek(e,a.node,a.element,{kind:"local",local_name:e.target.local_name},a.context,a.ordinal)),s=Sk(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:Km(s.errors).sort(Zs)}: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 z0(e){let t;try{t=Um(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=Tn({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=_n(e.source,{filePath:e.file_path,exportName:"default"});if(i.components.length===0)return{invocation:null,errors:[]};let s=i.components.map(a=>_i({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 H0(e){let t=_i(e),n=G0(e.files),r=Y0(e.file_path,e.target.source,n),o=r?ht(n.get(r)):null,i=r&&typeof o=="string"?gk(o,r,e.collection.slug):null,s=Lm({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:W0(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(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=V0.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=Km(a).sort(Zs);return{...t,complete:d.length===0&&u!==null,errors:d,collection_recipe:u,collection_evidence:c.sort(q0),related_entries:s}}function W0(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 G0(e){return e instanceof Map?e:new Map(Object.entries(e))}function Y0(e,t,n){if(!pt(t))return null;let r=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",o=t.startsWith("@/")?t.slice(2):Z0(`${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 Z0(e){let t=[];for(let n of e.split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return t.join("/")}function q0(e,t){return e.fact.localeCompare(t.fact)||e.path.localeCompare(t.path)}function Q0(e){let t=new Map;for(let n of e.program.body){if(!Y.isImportDeclaration(n))continue;let r=n.source.value;for(let o of n.specifiers)if(Y.isIdentifier(o.local)){if(Y.isImportDefaultSpecifier(o))t.set(o.local.name,{source:r,export_name:"default",local_name:o.local.name});else if(Y.isImportNamespaceSpecifier(o))t.set(o.local.name,{source:r,export_name:"*",local_name:o.local.name});else if(Y.isImportSpecifier(o)){let i=Y.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 Ek(e,t,n,r,o,i){let s=i$(t),a=[],c=[],l={},u=new Set,d=null,f=null,g=(p,y)=>{if(u.has(p)){a.push({code:"INVOCATION_DUPLICATE_PROP",path:`${e.file_path}:${p}`,message:`Portable invocation contains duplicate prop ${p}.`,source_range:s});return}u.add(p),c.push({propName:p,value:y}),(p==="type"||p==="variant")&&y.kind==="json-literal"&&(l[p]=y.value)};for(let p of t.attributes){if(Y.isJSXSpreadAttribute(p)){let S=Zr(p.argument);if(!S.ok||!vk(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[v,N]of Object.entries(S.value)){if(!yk(v)){a.push({code:"INVOCATION_VALUE_UNRESOLVED",path:`${e.file_path}:${v}`,message:`Portable invocation cannot encode prop ${v}.`,source_range:s});continue}g(v,$m(N))}continue}let y=r$(p.name);if(!y)continue;let b=p.value,E=b&&Y.isJSXExpressionContainer(b)?b.expression:null;if(J0.has(y)){let S=b?Wl(b):{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(X0.has(y)){let S=b?Wl(b):{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}):f=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(K0.has(y)){let S=b?Wl(b):{ok:!0,value:!0};S.ok&&typeof S.value=="string"?d=S.value:E&&hk(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&&hk(E,o)){g(y,{kind:"route-search-params"});continue}let x=b?Wl(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,$m(x.value))}let m=e$(n);return m.ok?m.value!==void 0&&g("children",$m(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:f,semantic_props:l,errors:a}}function Sk(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 Wl(e){return e===null?{ok:!0,value:!0}:Y.isStringLiteral(e)?{ok:!0,value:e.value}:Y.isJSXExpressionContainer(e)?Zr(e.expression):{ok:!1}}function Zr(e){if(!e)return{ok:!1};if(Y.isStringLiteral(e))return{ok:!0,value:e.value};if(Y.isNumericLiteral(e)&&Number.isFinite(e.value))return{ok:!0,value:e.value};if(Y.isBooleanLiteral(e))return{ok:!0,value:e.value};if(Y.isNullLiteral(e))return{ok:!0,value:null};if(Y.isTemplateLiteral(e)&&e.expressions.length===0)return{ok:!0,value:e.quasis[0]?.value.cooked??""};if(Y.isTSAsExpression(e)||Y.isTSTypeAssertion(e)||Y.isTSNonNullExpression(e))return Zr(e.expression);if(Y.isUnaryExpression(e)){let t=Zr(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(Y.isArrayExpression(e)){let t=[];for(let n of e.elements){let r=Zr(n);if(!r.ok)return{ok:!1};t.push(r.value)}return{ok:!0,value:t}}if(Y.isObjectExpression(e)){let t={};for(let n of e.properties){if(Y.isSpreadElement(n)){let i=Zr(n.argument);if(!i.ok||!vk(i.value))return{ok:!1};Object.assign(t,i.value);continue}if(!Y.isObjectProperty(n)||n.computed)return{ok:!1};let r=o$(n.key);if(!r)return{ok:!1};let o=Zr(n.value);if(!o.ok)return{ok:!1};t[r]=o.value}return{ok:!0,value:t}}return{ok:!1}}function e$(e){if(e.children.length===0)return{ok:!0,value:void 0};let t=[];for(let n of Y.react.buildChildren(e)){let r=Zr(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 Gl(e,t,n){let r=kk(e)?new Set([...t,...t$(e)]):t;n(e,{names:r});for(let o of Object.values(e))if(Array.isArray(o))for(let i of o)bk(i)&&Gl(i,r,n);else bk(o)&&Gl(o,r,n)}function t$(e){if(!kk(e))return[];let t=[];for(let n of e.params)Ys(n,t);return t}function Ys(e,t){if(Y.isIdentifier(e)){t.push(e.name);return}if(Y.isAssignmentPattern(e)){Ys(e.left,t);return}if(Y.isObjectPattern(e)){for(let n of e.properties)Y.isRestElement(n)?Ys(n.argument,t):Y.isObjectProperty(n)&&Ys(n.value,t);return}if(Y.isArrayPattern(e))for(let n of e.elements)n&&Ys(n,t)}function hk(e,t){return Y.isIdentifier(e)?e.name==="searchParams"&&t.names.has(e.name):Y.isMemberExpression(e)&&!e.computed&&Y.isIdentifier(e.property)&&e.property.name==="searchParams"&&Y.isIdentifier(e.object)&&t.names.has(e.object.name)}function $m(e){return{kind:"json-literal",value:e}}function vk(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 Ik(e){if(Y.isJSXIdentifier(e))return e.name;if(!Y.isJSXMemberExpression(e))return null;let t=Vm(e.object);return t?`${t}.${e.property.name}`:null}function Vm(e){if(Y.isJSXIdentifier(e))return e.name;if(!Y.isJSXMemberExpression(e))return null;let t=Vm(e.object);return t?`${t}.${e.property.name}`:null}function n$(e,t){if(Y.isJSXIdentifier(e))return t.get(e.name)??null;if(!Y.isJSXMemberExpression(e))return null;let n=Vm(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 r$(e){return Y.isJSXIdentifier(e)?e.name:Y.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:null}function o$(e){return Y.isIdentifier(e)?e.name:Y.isStringLiteral(e)||Y.isNumericLiteral(e)?String(e.value):null}function kk(e){return Y.isFunctionDeclaration(e)||Y.isFunctionExpression(e)||Y.isArrowFunctionExpression(e)}function bk(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function i$(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 Km(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Zs(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||e.message.localeCompare(t.message)}var c$=typeof Xm=="function"?Xm:Xm.default,zm=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=Yl(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=_e(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 l$(e){return Ck(e,!1)}function Rk(e){return Ck(e,!0)}function Ck(e,t){let{binding:n,files:r}=e;if(e.hostCapabilities!==null&&!s$.safeParse(e.hostCapabilities).success)return St("INVOCATION_VALUE_UNRESOLVED","generated-site-capabilities","Trusted host capabilities failed their strict schema.");if(!qs(n.descriptor.source.file)||!qs(n.ownerFile))return St("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The resolved block source path is not a safe Snapshot source path.");let o=Yl(r,n.descriptor.source.file),i=Yl(r,n.ownerFile);if(o===null||i===null)return St("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(Ae(o)!==n.descriptor.source.contentHash||Ae(o)!==n.sourceHash||Ae(i)!==n.ownerSourceHash)return St("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The pinned block or owner source hash no longer matches the resolved binding.");let s=_e(n.descriptor.source.file,o);if(!s.ok)return St("INVOCATION_PARSE_FAILED",n.descriptor.source.file,s.diagnostic.message);let a=Zl(s.module.ast,n.rootLocator.sourceRange);if(a.length!==1)return St("INVOCATION_TARGET_AMBIGUOUS",n.descriptor.source.file,"The selected block source range does not identify exactly one JSX element.");let c=a[0],l=Nk(c.node);if(!l)return St("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The selected JSX element has no complete source range.");let u=[],d=n.root.callChain,f=new zm(r),g=u$(e,l,f,t);if(g)return g;if(d.some(b=>(b.alternativeLocators?.length??0)>1))return St("INVOCATION_TARGET_NOT_RENDERED",n.descriptor.source.file,"The conditional invocation has no single statically proven props binding.");for(let[b,E]of d.entries()){let x=Yl(r,E.sourceFile);if(x===null||!qs(E.sourceFile))return St("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"A statically proven call-chain source is missing from the fixed Snapshot map.");let S=_e(E.sourceFile,x);if(!S.ok)return St("INVOCATION_PARSE_FAILED",E.sourceFile,S.diagnostic.message);let v=Zl(S.module.ast,E.callLocator.sourceRange);if(v.length!==1)return St("INVOCATION_TARGET_AMBIGUOUS",E.sourceFile,"A call-chain locator does not identify exactly one current JSX element.");let N=d[b+1]?.sourceFile??n.descriptor.source.file,R=d[b+1]?.callLocator.sourceRange??n.rootLocator.sourceRange,A=vn({module:S.module,componentName:E.component,callSourceRange:E.callLocator.sourceRange});if(A.ok){if(A.sourceFile!==N)return St("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected local component does not resolve to the source definition proven by the block graph.");if(A.roots.filter(oe=>Ri(oe.node,R)).length!==1)return St("INVOCATION_TARGET_NOT_RENDERED",A.sourceFile,"The local component definition does not select exactly one proven JSX root.");let ge=xk({file_path:E.sourceFile,source:x,target:{kind:"local",local_name:E.component},call_source_range:{start_line:E.callLocator.sourceRange.startLine,start_column:E.callLocator.sourceRange.startColumn}});if(!ge.call||!ge.complete)return{complete:!1,errors:ge.errors.length>0?ge.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:ge.call,invocation:ge,definition:A,entryExport:null});continue}let C=Hm(S.module.ast,v[0].node.openingElement.name,E.component,E.exportName);if(!C)return St("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The statically proven component call no longer resolves through one exact import.");let w=Wm(E.sourceFile,C.source,r);if(!w)return St("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import is not a resolvable local Snapshot source.");let M=f.read(w);if(!M.ok)return St(M.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",w,M.message);let D=jt({module:M.module,exportName:C.exportName,parsedModules:f});if(!D.ok)return St("INVOCATION_TARGET_NOT_RENDERED",D.diagnostic.file,D.diagnostic.message);if(D.sourceFile!==N)return St("INVOCATION_TARGET_NOT_RENDERED",E.sourceFile,"The selected component import does not resolve to the source definition proven by the block graph.");let U=D.roots.filter(K=>Ri(K.node,R));if(U.length!==1)return St("INVOCATION_TARGET_NOT_RENDERED",D.sourceFile,"The unique component export does not select exactly one proven JSX root.");let B=null;if(b===d.length-1&&d.length===1&&!Tk(n.ownerFile)&&Ri(U[0].node,n.rootLocator.sourceRange)){let K=f.read(D.sourceFile);if(!K.ok)return St(K.missing?"INVOCATION_TARGET_NOT_RENDERED":"INVOCATION_PARSE_FAILED",D.sourceFile,K.message);if(B=Pk(K.module,D.componentName,C.exportName),!B)return St("INVOCATION_TARGET_AMBIGUOUS",D.sourceFile,"The proven component definition has no unique final export for a Portable entry.")}let G=_i({file_path:E.sourceFile,source:x,target:{source:C.source,export_name:C.exportName,local_name:C.localName},call_source_range:{start_line:E.callLocator.sourceRange.startLine,start_column:E.callLocator.sourceRange.startColumn}});if(!G.call||!G.complete)return{complete:!1,errors:G.errors.length>0?G.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:G.call,invocation:G,definition:D,entryExport:B})}let m={kind:"page-block",composition:Ak(n.composition),blockKey:n.blockKey},p=d$(n,c,u,r,e.hostCapabilities);if(!p.ok)return{complete:!1,errors:[p.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:b})=>b),strategy:p.strategy,entry_file:p.entryFile,entry_export:p.entryExport,invocation:y}}}function u$(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=Zl(l.ast,a.callLocator.sourceRange);if(u.length!==1)return null;let d=Hm(l.ast,u[0].node.openingElement.name,a.component,a.exportName);if(!d)return null;let f=Wm(a.sourceFile,d.source,i),g=f?n.get(f):void 0;if(!g)return null;let m=jt({module:g,exportName:d.exportName,parsedModules:n});if(!m.ok||m.sourceFile!==c.sourceFile)return null;let p=n.get(m.sourceFile);if(!p||Pk(p,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(!QI(y))return null}else{let N=Fm(y);if(!N.complete||!N.relation)return null}let b=c.alternativeLocators?.length?c.alternativeLocators:[c.callLocator],E=m.returnAlternatives?.length?m.returnAlternatives:m.roots;if(E.length!==b.length||!E.every(N=>b.filter(R=>Ri(N.node,R.sourceRange)).length===1))return null;for(let N of b){let R=Zl(p.ast,N.sourceRange);if(R.length!==1)return null;let A=Hm(p.ast,R[0].node.openingElement.name,c.component,c.exportName);if(!A)return null;let C=Wm(m.sourceFile,A.source,i),w=C?n.get(C):void 0;if(!w)return null;let M=jt({module:w,exportName:A.exportName,parsedModules:n});if(!M.ok||M.sourceFile!==o.descriptor.source.file||M.roots.length!==1||!Ri(M.roots[0].node,o.rootLocator.sourceRange))return null}let x=_i({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(!x.complete||!x.call)return{complete:!1,errors:x.errors};let v=`components/site/portable/${_k("sha256").update(JSON.stringify(["collection-container",o.composition,o.blockKey,o.sourceHash,Ae(p.source)])).digest("hex").slice(0,24)}/page.tsx`;return i.has(v)?St("INVOCATION_TARGET_AMBIGUOUS",v,"The isolated collection entry collides with a pinned Snapshot source."):{complete:!0,selection:{target:{kind:"page-block",composition:Ak(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:[x.call],strategy:"collection-container",collection_container_file:m.sourceFile,entry_file:v,entry_export:{kind:"default"},invocation:x}}}function d$(e,t,n,r,o){let i=n.at(-1);if(i?.kind==="import"){let l=i.definition.roots.length===1&&Ri(i.definition.roots[0].node,e.rootLocator.sourceRange),u=Tk(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(!Nk(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/${_k("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!qs(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 Pk(e,t,n){let r=new Set;for(let i of e.ast.program.body){if(et.isExportDefaultDeclaration(i)){let s=i.declaration;(et.isFunctionDeclaration(s)&&(s.id?.name===t||t==="default")||et.isIdentifier(s)&&s.name===t)&&r.add("default");continue}if(!(!et.isExportNamedDeclaration(i)||i.exportKind==="type")){if(i.declaration){let s=f$(i.declaration,t);s&&r.add(s)}if(!i.source)for(let s of i.specifiers)et.isExportSpecifier(s)&&s.exportKind!=="type"&&Ym(s.local)===t&&r.add(Ym(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 f$(e,t){return et.isFunctionDeclaration(e)?e.id?.name===t?t:null:et.isVariableDeclaration(e)&&e.declarations.some(n=>et.isIdentifier(n.id)&&n.id.name===t)?t:null}function Hm(e,t,n,r){let o=Gm(t);if(!o||o!==n)return null;let i=et.isJSXMemberExpression(t)?Gm(t.object):et.isJSXNamespacedName(t)?t.namespace.name:o,s=et.isJSXMemberExpression(t)?t.property.name:null;for(let a of e.program.body)if(et.isImportDeclaration(a))for(let c of a.specifiers){if(et.isImportDefaultSpecifier(c)&&c.local.name===i)return r==="default"&&!s?{source:a.source.value,exportName:"default",localName:o}:null;if(et.isImportSpecifier(c)&&c.local.name===i){let l=Ym(c.imported);return l===r&&!s?{source:a.source.value,exportName:l,localName:o}:null}if(et.isImportNamespaceSpecifier(c)&&c.local.name===i&&s)return s===r?{source:a.source.value,exportName:s,localName:o}:null}return null}function Zl(e,t){let n=[];return c$(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 Nk(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 Ri(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 Yl(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 Wm(e,t,n){let r=t.startsWith("@/")?t.slice(2):t.startsWith("./")||t.startsWith("../")?Jm.posix.normalize(Jm.posix.join(Jm.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=>qs(i)&&n.has(i))??null}function Gm(e){if(et.isJSXIdentifier(e))return e.name;if(et.isJSXMemberExpression(e)){let t=Gm(e.object);return t?`${t}.${e.property.name}`:null}return null}function Ym(e){return et.isIdentifier(e)?e.name:e.value}function Ak(e){return{routeId:e.routeId,...e.effectiveTemplateId!==void 0?{templateId:e.effectiveTemplateId}:{}}}function qs(e){return a$.safeParse(e).success}function Tk(e){return/(?:^|\/)\.vcp\/page-templates\//u.test(e)}function St(e,t,n){return{complete:!1,errors:[{code:e,path:t,message:n}]}}import Zm from"@babel/generator";import qm from"@babel/traverse";import*as ae from"@babel/types";var wk=typeof qm=="function"?qm:qm.default,p$=typeof Zm=="function"?Zm:Zm.default;function Fk(e){let t=new Map(e.files),n=new Set(e.private_paths),r=[];for(let o of e.private_paths){let i=Dk(t.get(o));if(i===null||!/\.[cm]?[jt]sx?$/iu.test(o))continue;let s=_e(o,i);if(!s.ok){r.push({code:"SOURCE_PARSE_FAILED",path:o,message:s.diagnostic.message});continue}let a=!1;wk(s.module.ast,{Function:{exit(c){let l=c.get("body");l.isBlockStatement()&&(l.scope.crawl(),Ok(l)&&(a=!0))}}}),wk(s.module.ast,{Program(c){let l;do{c.scope.crawl(),l=Ok(c),l&&(a=!0),l&&c.scope.crawl();for(let f of c.get("body"))(f.isFunctionDeclaration()&&f.node.id&&!c.scope.getBinding(f.node.id.name)?.referenced||f.isVariableDeclaration({kind:"const"})&&f.node.declarations.every(g=>ae.isIdentifier(g.id)&&!c.scope.getBinding(g.id.name)?.referenced&&(!g.init||Ci(g.init))))&&(f.remove(),l=a=!0)}while(l);c.scope.crawl();let u=0,d=f=>o===e.entry_file||!c.scope.getBinding(f)?.referencePaths.some(g=>!g.isExportDeclaration()&&!g.parentPath?.isExportSpecifier());for(let f of c.node.body)ae.isExportDefaultDeclaration(f)?u+=1:ae.isExportAllDeclaration(f)&&f.exportKind!=="type"?u+=2:ae.isExportNamedDeclaration(f)&&f.exportKind!=="type"&&(f.declaration&&!ae.isTSInterfaceDeclaration(f.declaration)&&!ae.isTSTypeAliasDeclaration(f.declaration)&&(u+=Object.keys(ae.getOuterBindingIdentifiers(f.declaration)).filter(d).length),u+=f.specifiers.filter(g=>!ae.isExportSpecifier(g)||g.exportKind!=="type"&&d(g.local.name)).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 f of c.get("body")){if(!f.isImportDeclaration()||f.node.importKind==="type"||f.node.specifiers.length===0||!pt(f.node.source.value))continue;let g=Tt(o,f.node.source.value,t);if(!(!g||!n.has(g))&&!f.node.specifiers.some(m=>c.scope.getBinding(m.local.name)?.referenced)){if(!Lk(g,t,new Set)){r.push({code:"SOURCE_UNUSED_IMPORT_UNPROVEN",path:o,message:`The unused import ${f.node.source.value} may have initialization effects.`});continue}f.remove(),a=!0}}c.stop()}}),a&&t.set(o,p$(s.module.ast).code)}return{files:t,errors:r}}function Ok(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];ae.isIdentifier(f.id)&&(ae.isFunctionExpression(f.init)||ae.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 Lk(e,t,n){if(n.has(e)||n.size>=64)return!1;let r=Dk(t.get(e));if(r===null)return!1;let o=_e(e,r);if(!o.ok)return!1;let i=new Set(n).add(e),s=a=>{if(!pt(a))return!1;let c=Tt(e,a,t);return c!==null&&Lk(c,t,i)};return o.module.ast.program.body.every(a=>ae.isImportDeclaration(a)?a.importKind==="type"||a.specifiers.length>0&&a.specifiers.every(c=>ae.isImportSpecifier(c)&&c.importKind==="type")?!0:s(a.source.value):ae.isExportAllDeclaration(a)?a.exportKind==="type"||s(a.source.value):ae.isExportNamedDeclaration(a)?a.exportKind==="type"?!0:a.source?s(a.source.value):a.declaration?Qm(a.declaration):!0:ae.isExportDefaultDeclaration(a)?Qm(a.declaration):Qm(a))}function Qm(e){return ae.isFunctionDeclaration(e)||ae.isTSInterfaceDeclaration(e)||ae.isTSTypeAliasDeclaration(e)||ae.isTSDeclareFunction(e)||ae.isEmptyStatement(e)?!0:ae.isVariableDeclaration(e)&&e.kind==="const"?e.declarations.every(t=>ae.isIdentifier(t.id)&&(!t.init||Ci(t.init))):Ci(e)}function Ci(e){return ae.isStringLiteral(e)||ae.isNumericLiteral(e)||ae.isBooleanLiteral(e)||ae.isNullLiteral(e)||ae.isFunctionExpression(e)||ae.isArrowFunctionExpression(e)?!0:ae.isArrayExpression(e)?e.elements.every(t=>t===null||!ae.isSpreadElement(t)&&Ci(t)):ae.isObjectExpression(e)?e.properties.every(t=>ae.isObjectProperty(t)&&!t.computed&&!t.shorthand&&Ci(t.value)):ae.isTSAsExpression(e)||ae.isTSSatisfiesExpression(e)||ae.isTSNonNullExpression(e)||ae.isParenthesizedExpression(e)?Ci(e.expression):!1}function Dk(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 Qs}from"node:crypto";import eg from"@babel/traverse";import*as Re from"@babel/types";import{PORTABLE_AUDITED_PLACEHOLDER_SVG as tg,PORTABLE_AUDITED_SAFE_IMAGE as m$}from"@vcp-dev/contracts";var rg=typeof eg=="function"?eg:eg.default,ql=m$.digest_sha256;function Bk(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:${ql}`)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:""]),f=o.get(u.file);if(f!==void 0){if(f!==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||Qs("sha256").update(i).digest("hex")!==ql||!(s instanceof Uint8Array)||s.byteLength!==tg.byte_size||Qs("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=g$(e,n);for(let u of a){let d=u.from,f=(e.selected_host_calls??[]).filter(C=>C.file_path===d&&C.host_file===e.host_file);if(!f.length&&!l(d))return t();let g=ht(e.files.get(d));if(g===null)return t();let m=_e(d,g);if(!m.ok)return t();let p=jt({module:m.module,exportName:n.get(d)??"default"});if(!f.length&&(!p.ok||p.metadataOnly||p.returnAlternatives))return t();let y=null,b=!1;if(rg(m.module.ast,{ImportDeclaration(C){if(Tt(d,C.node.source.value,e.files)!==e.host_file||C.node.importKind==="type")return;let w=C.get("specifiers"),M=w[0];if(y||w.length!==1||!M?.isImportSpecifier()||M.node.importKind==="type"||!Re.isIdentifier(M.node.imported,{name:"SafeImage"})){b=!0;return}y=M}}),b||!y)return t();let E=y,x=E.scope.getBinding(E.node.local.name);if(!x?.constant||x.path.node!==E.node)return t();if(f.length){let C=`sha256:${Qs("sha256").update(g).digest("hex")}`;if(f.length>256||f.some(U=>U.source_hash!==C))return t();let w=new Set(f.map(U=>`${U.start}:${U.end}`)),M=new Map,D=!1;if(rg(m.module.ast,{JSXOpeningElement(U){if(!(!Re.isJSXIdentifier(U.node.name)||U.scope.getBinding(U.node.name.name)!==x)){if(!w.has(`${U.node.start}:${U.node.end}`)||!Mk(U.node)){D=!0;return}M.set(U.node,U)}}}),D||M.size!==w.size||!ng(x.referencePaths,new Set(M.keys())))return t();for(let U of M.values()){let B=U.node;if(B.start==null||B.end==null||!B.loc)return t();let G=g.slice(B.start,B.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:G,asset_key:null,source_range:{start_offset:B.start,end_offset:B.end,start_line:B.loc.start.line,start_column:B.loc.start.column,end_line:B.loc.end.line,end_column:B.loc.end.column},content_digest:`sha256:${Qs("sha256").update(G).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:ql}})}continue}if(!p.ok||p.metadataOnly||p.returnAlternatives)return t();let S=new Map,v=new Map,N=!1,R=0,A=(C,w=0,M=!1)=>{if(++R>2048||w>128){N=!0;return}if(C.isJSXElement()){let D=C.get("openingElement");if(!Re.isJSXIdentifier(D.node.name)){N=!0;return}if(D.scope.getBinding(D.node.name.name)===x){Mk(D.node)||(N=!0),S.set(D.node,D);return}if(!/^[a-z]/u.test(D.node.name.name)){if(M)return;let U=D.scope.getBinding(D.node.name.name);if(!U?.constant)return;let B=U.path;if(!(B.isFunctionDeclaration()&&!B.parentPath.isExportNamedDeclaration()&&!B.parentPath.isExportDefaultDeclaration()||B.isVariableDeclarator()&&B.parentPath.isVariableDeclaration({kind:"const"})&&!B.parentPath.parentPath.isExportNamedDeclaration()&&(Re.isFunctionExpression(B.node.init)||Re.isArrowFunctionExpression(B.node.init)))||!C.node.loc)return;let K=v.get(U.identifier);if(K){K.openings.add(D.node),K.active&&(N=!0);return}if(v.size>=32){N=!0;return}let ge={references:U.referencePaths,openings:new Set([D.node]),active:!0};v.set(U.identifier,ge);let oe=vn({module:m.module,componentName:D.node.name.name,callSourceRange:{startLine:C.node.loc.start.line,startColumn:C.node.loc.start.column,endLine:C.node.loc.end.line,endColumn:C.node.loc.end.column}});if(!oe.ok||oe.metadataOnly||oe.returnAlternatives||oe.sourceFile!==d){N=!0;return}for(let Le of oe.roots)A(Le,w+1,M);ge.active=!1;return}if(["template","script","style","noscript"].includes(D.node.name.name)||D.node.attributes.some(U=>!Re.isJSXAttribute(U)||!Re.isJSXIdentifier(U.name)||/^(?:on|ref$|style$|dangerouslySetInnerHTML$)/iu.test(U.name.name))){N=!0;return}}for(let D of C.get("children"))if(D.isJSXElement()||D.isJSXFragment())A(D,w+1,M);else if(D.isJSXExpressionContainer()){let U=D.get("expression");if(U.isJSXElement()||U.isJSXFragment())A(U,w+1,M);else if(U.isLogicalExpression({operator:"&&"})&&Ql(U.node.left)&&y$(U.get("left"))){let B=U.get("right");(B.isJSXElement()||B.isJSXFragment())&&A(B,w+1,!0)}}};for(let C of p.roots)A(C);if(N||S.size===0||!ng(x.referencePaths,new Set(S.keys())))return t();for(let C of v.values())if(!ng(C.references,C.openings))return t();for(let C of S.values()){let w=C.node;if(w.start==null||w.end==null||!w.loc)return t();let M=g.slice(w.start,w.end);c.push({file_path:d,kind:"host-fallback",source:"host-fallback",value:"/media/placeholder.svg",expression:M,asset_key:null,source_range:{start_offset:w.start,end_offset:w.end,start_line:w.loc.start.line,start_column:w.loc.start.column,end_line:w.loc.end.line,end_column:w.loc.end.column},content_digest:`sha256:${Qs("sha256").update(M).digest("hex")}`,complete:!0,host_fallback:{file_path:e.host_file,digest_sha256:ql}})}}return{complete:!0,references:c}}function ng(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 g$(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 f=JSON.stringify([d.from,a]),g=i.get(f);if(g===void 0){if(i.size>=2048){u=!1;break}g=h$(d.from,a,e.files,t.get(d.from)??"default")&&Xl(d.from,a,e.files,!1,t.get(d.from)??"default"),i.set(f,g)}if(!g||!s(d.from)){u=!1;break}}return o.delete(a),r.set(a,u),u};return s}function h$(e,t,n,r){let o=ht(n.get(e));if(o===null)return!1;let i=_e(e,o);if(!i.ok)return!1;let s=null,a=!1;if(rg(i.module.ast,{ImportDeclaration(p){if(p.node.importKind==="type"||Tt(e,p.node.source.value,n)!==t)return;let y=p.get("specifiers"),b=y[0];if(s||y.length!==1||!b||!(b.isImportDefaultSpecifier()||b.isImportSpecifier()&&b.node.importKind!=="type"&&Re.isIdentifier(b.node.imported,{name:"default"}))){a=!0;return}s=b}}),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 p of l.referencePaths){let y=p.parentPath;if(y?.isJSXOpeningElement()&&y.node.name===p.node)u.push(y);else if(y?.isJSXClosingElement()&&y.node.name===p.node)d.push(y);else return!1}let f=_n(o,{filePath:e,exportName:r}),g=new Set(f.rendered_component_openings.filter(p=>!p.static_render_blockers?.length).map(p=>p.start_offset)),m=new Set(u.map(p=>p.node));if(u.length>1){let p=jt({module:i.module,exportName:r});if(!p.ok||p.metadataOnly||!p.returnAlternatives||p.returnAlternatives.length!==u.length||!p.returnAlternatives.every(y=>y.isJSXElement()&&m.has(y.node.openingElement))||new Set(p.returnAlternatives.map(y=>y.node)).size!==u.length)return!1}return u.length>0&&u.length<=256&&u.every(p=>typeof p.node.start=="number"&&g.has(p.node.start))&&d.every(p=>p.parentPath?.isJSXElement()&&m.has(p.parentPath.node.openingElement))}function Mk(e){let t=new Set;for(let n of e.attributes){if(!Re.isJSXAttribute(n)||!Re.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"&&Re.isJSXExpressionContainer(o)&&Fo(o.expression))&&o!==null&&!Re.isStringLiteral(o)&&!(Re.isJSXExpressionContainer(o)&&(Re.isStringLiteral(o.expression)||Re.isNumericLiteral(o.expression)||Re.isBooleanLiteral(o.expression))))return!1}return t.has("src")}function y$(e){try{let t=e.evaluate();return!t.confident||!!t.value}catch{return!1}}function Ql(e,t=0){return t>32?!1:Re.isIdentifier(e)?!["undefined","NaN","Infinity"].includes(e.name):Re.isMemberExpression(e)||Re.isOptionalMemberExpression(e)?Fo(e):Re.isUnaryExpression(e,{operator:"!"})?Ql(e.argument,t+1):Re.isBinaryExpression(e)?Ql(e.left,t+1)&&Fo(e.right)||Fo(e.left)&&Ql(e.right,t+1):!1}function Fo(e,t=0){if(t>32)return!1;if(Re.isStringLiteral(e)||Re.isNumericLiteral(e)||Re.isBooleanLiteral(e)||Re.isNullLiteral(e)||Re.isIdentifier(e))return!0;if(Re.isMemberExpression(e)||Re.isOptionalMemberExpression(e)){let n=e.property;return!e.computed&&!Re.isIdentifier(n)||e.computed&&!(Re.isStringLiteral(n)||Re.isNumericLiteral(n))||(Re.isIdentifier(n)||Re.isStringLiteral(n))&&["__proto__","prototype","constructor"].includes(Re.isIdentifier(n)?n.name:n.value)?!1:Fo(e.object,t+1)}return Re.isLogicalExpression(e)?Fo(e.left,t+1)&&Fo(e.right,t+1):!1}async function $k(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=ht(n.get(t.ownerFile)),s=ht(n.get(t.descriptor.source.file));if(i===null||s===null)return[];let a=async c=>{let l=ht(n.get(c));if(l===null)throw new Error("Snapshot source unavailable");return l};try{let c=await Jo(t.ownerFile,i,a,async p=>n.has(p));if(!c.entryModule||c.diagnostics.length)return[];let l=[...c.graph.elements.values()].filter(p=>p.importedFrom===t.descriptor.source.file);if(l.length!==1||l[0].sourceFile!==o.sourceFile||l[0].exportName!==o.exportName||!b$(l[0].sourceRange,o.callLocator.sourceRange))return[];let u=[...c.graph.elements.values()].filter(p=>p.sourceFile===t.descriptor.source.file&&jk(t.rootLocator.sourceRange,p.sourceRange));if(!u.length||u.length>256)return[];let d=new Set(u.map(p=>p.identity.key));for(let p of u){if(p.boundaryKind!=="component-boundary"||p.isPublicUiComponent)continue;let y=c.parsedModules.get(p.sourceFile);if(!y)continue;let b=vn({module:y,componentName:p.tag,callSourceRange:p.sourceRange,...p.importedFrom?{imported:{file:p.importedFrom,module:c.parsedModules.get(p.importedFrom),exportName:p.exportName??p.tag,parsedModules:c.parsedModules}}:{}});if(!b.ok||b.metadataOnly)continue;let E=[...b.roots,...b.returnAlternatives??[]];for(let x of c.graph.fileIndex.get(b.sourceFile)??[]){let S=c.graph.elements.get(x);if(!(!S||d.has(x)||!E.some(v=>{let N=v.node.loc;return N&&jk({startLine:N.start.line,startColumn:N.start.column,endLine:N.end.line,endColumn:N.end.column},S.sourceRange)}))&&(d.add(x),u.push(S),u.length>256))return[]}}d.add(l[0].identity.key);let f={...c.graph,elements:new Map([...c.graph.elements].filter(([p])=>d.has(p))),regions:c.graph.regions.filter(p=>d.has(p.ownerKey))},g=new Set,m=new Map;for(let p of u){let y=await ul({element:p,graph:f,file:p.sourceFile,source:await a(p.sourceFile),readFile:a,exists:async b=>n.has(b),fileCache:m});for(let b of y.bindings)b.sourceKind==="vcp-cms-collection"&&b.collection&&/^[a-z0-9][a-z0-9_-]{0,79}$/u.test(b.collection)&&((b.operation==="getByUrl"||b.operation==="getByUrlStrict")&&b.endpointPattern==="/content/by-url"&&b.evidence.some(E=>E.reason==="CMS collection namespace from the actual content request path")||["list","listStrict","get","schema","categories"].includes(b.operation??"")&&(b.endpointPattern===`/collections/${b.collection}`||b.endpointPattern?.startsWith(`/collections/${b.collection}/`))&&b.evidence.some(E=>E.reason==="VCP CMS fetch helper"))&&g.add(b.collection);if(g.size>16)return[]}return[...g].sort()}catch{return[]}}function b$(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function jk(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 og from"@babel/traverse";import*as rt from"@babel/types";var Uk=typeof og=="function"?og:og.default;function Vk(e){let t=new Map;for(let[n,r]of e.sources){if(!/\.[cm]?[jt]sx?$/iu.test(n))continue;let o=_e(n,r);o.ok&&Uk(o.module.ast,{ImportDeclaration(i){if(i.node.importKind==="type")return;let s=Tt(n,i.node.source.value,e.files);if(!(!s||!e.sources.has(s)))for(let a of i.node.specifiers){if(rt.isImportSpecifier(a)&&a.importKind==="type")continue;let c=i.scope.getBinding(a.local.name);if(!c?.referencePaths.length)continue;let l=!rt.isImportNamespaceSpecifier(a)&&c.constant&&c.referencePaths.every(u=>(u.parentPath?.isJSXOpeningElement()||u.parentPath?.isJSXClosingElement())&&u.parentPath.node.name===u.node);t.set(s,(t.get(s)??!0)&&l)}}})}return new Set([...t].filter(([,n])=>n).map(([n])=>n))}function Kk(e){let t=_e(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&&E$(s,e.current_route)){r.add(e.current_route);return}if(!rt.isStringLiteral(s)){o("ROUTE_VALUE_UNRESOLVED","A navigation destination is not a proven literal.");return}let a=Jk(s.value);a==="host-route"?r.add(s.value):a==="unknown"&&o("ROUTE_VALUE_UNRESOLVED","A navigation destination is unsafe or unsupported.")};return Uk(t.module.ast,{JSXOpeningElement(s){let a=rt.isJSXIdentifier(s.node.name)?s.node.name.name:"";if((["form","iframe","embed","object","portal","script","base","meta","link"].includes(a)||/^[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=>rt.isJSXAttribute(d)&&rt.isJSXIdentifier(d.name)&&d.name.name.toLowerCase()==="type"),l=c.length===1&&rt.isJSXAttribute(c[0])?c[0].value:null,u=rt.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(!rt.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(rt.isJSXExpressionContainer(c)?c.expression:c)},JSXSpreadAttribute(s){e.allow_props_forwarding&&x$(s)||o("ROUTE_VALUE_UNRESOLVED","A JSX spread may contain an unproven navigation destination.")},ObjectProperty(s){let a=ea(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=ea(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=ea(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)&&rt.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"&&rt.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){(rt.isIdentifier(s.node.left,{name:"location"})||rt.isMemberExpression(s.node.left)&&(ea(s.node.left.property,s.node.left.computed)==="href"||s.node.left.computed&&ea(s.node.left.property,!0)===null))&&o("ROUTE_VALUE_UNRESOLVED","Imperative navigation is not proven.")},CallExpression(s){rt.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 x$(e){let t=e.get("argument");if(!t.isIdentifier())return!1;let n=t.scope.getBinding(t.node.name);return n?.kind==="param"&&n.constant}function E$(e,t){if(!t||t.includes("?")||t.includes("#")||Jk(t)!=="host-route")return!1;let n=rt.isStringLiteral(e)?[e.value]:rt.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 ea(e,t){return rt.isStringLiteral(e)?e.value:!t&&rt.isIdentifier(e)?e.name:t&&rt.isNumericLiteral(e)?String(e.value):null}function Jk(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 S$}from"node:crypto";import v$ from"@babel/traverse";import*as $e from"@babel/types";var ig=v$,I$=typeof ig=="function"?ig:ig.default,k$=new Set(["avif","bmp","gif","jpeg","jpg","mp3","mp4","ogg","png","svg","wav","webm","webp"]),Qr=new Set(["backgroundimage","fallbacksrc","image","imageurl","media","mediaurl","poster","src","srcset","thumbnail","thumbnailurl"]),Wk=/(?:asset|avatar|gallery|image|media|photo|poster|thumbnail|video)/iu,_$=/^(?:audio|img|image|picture|safeimage|source|video|media|.*(?:audio|image|video))$/iu;function tu(e){let t=_e(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=>{if(e.static_only&&!c.complete)return;let l=Hk(c.node),u=w$(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:O$(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=Hk(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})};I$(t.module.ast,{ImportDeclaration(c){let l=c.node.source.value;C$(l)&&i({node:c.node.source,kind:"import",source:"import",value:l,complete:!0})},JSXOpeningElement(c){let l=Gk(c.node.name),u=_$.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 f=d.node,g=N$(f);if(g==="style"&&!R$(f.value)){i({node:f.value??f,kind:"object",source:"jsx-attribute",value:null,complete:!1});continue}if(!g||!P$(g,u))continue;let m=ta(d.get("value"));i({node:f.value??f,kind:Xk(g),source:"jsx-attribute",value:m.value,complete:m.complete})}},ObjectProperty(c){let l=na(c);if(!l.known){i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1});return}let u=l.name;if(!u||!Qr.has(u)&&!(zk(c)&&sg(u)))return;let d=c.get("value");if(Qr.has(u)&&(d.isObjectExpression()||d.isArrayExpression())&&eu(d))return;let f=qr(c.node.value);i({node:c.node.value,kind:Xk(u),source:"object-property",value:f.value,complete:f.complete})},ObjectMethod(c){let l=na(c);(!l.known||c.node.kind!=="method"&&l.name&&(Qr.has(l.name)||zk(c)&&sg(l.name)))&&i({node:c.node,kind:"object",source:"object-property",value:null,complete:!1})},ArrayExpression(c){if(T$(c))for(let l of c.get("elements")){if(!l.node||(l.isObjectExpression()||l.isArrayExpression())&&eu(l))continue;let u=qr(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(!$e.isIdentifier(l,{name:"mediaAsset"})||c.node.arguments.length!==1)return;let u=c.node.arguments[0];if(!$e.isExpression(u)){s(c.node,null);return}let d=qr(u);s(c.node,d.complete?d.value:null)},MemberExpression(c){if(!A$(c.node.object))return;let l=c.node.computed?qr(c.node.property):$e.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=F$(r).sort(L$);return{complete:a.length===0,references:n.map((c,l)=>({...c,occurrence:l})),errors:a}}function R$(e){return!$e.isJSXExpressionContainer(e)||!$e.isObjectExpression(e.expression)?!1:e.expression.properties.every(t=>{if(!$e.isObjectProperty(t)||t.computed||!($e.isIdentifier(t.key)||$e.isStringLiteral(t.key)))return!1;let n=$e.isIdentifier(t.key)?t.key.name:t.key.value;return!n||n==="__proto__"||n.startsWith("--")?!1:$e.isNumericLiteral(t.value)?Number.isFinite(t.value.value):$e.isStringLiteral(t.value)&&/^[\w\s#.,%+!-]*$/u.test(t.value.value)})}function C$(e){let n=(e.split(/[?#]/u,1)[0]??"").split(".").pop()?.toLowerCase();return n!==void 0&&k$.has(n)}function P$(e,t){return e!=="src"||t?Qr.has(e):!1}function Xk(e){return e==="srcset"?"srcset":e==="poster"?"poster":e.startsWith("thumbnail")?"thumbnail":e==="src"?"src":"object"}function N$(e){return $e.isJSXIdentifier(e.name)?e.name.name.toLowerCase():$e.isJSXNamespacedName(e.name)?`${e.name.namespace.name}:${e.name.name.name}`.toLowerCase():null}function Gk(e){return $e.isJSXIdentifier(e)?e.name:$e.isJSXNamespacedName(e)?`${e.namespace.name}:${e.name.name}`:`${Gk(e.object)}.${e.property.name}`}function na(e){if(!e.node.computed){let n=e.node.key;return $e.isIdentifier(n)?{known:!0,name:n.name.toLowerCase()}:$e.isStringLiteral(n)?{known:!0,name:n.value.toLowerCase()}:{known:!0,name:null}}let t=ta(e.get("key"));if(t.complete&&t.value!==null)return{known:!0,name:t.value.toLowerCase()};if($e.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=[...Qr,"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 A$(e){return $e.isIdentifier(e,{name:"mediaAssets"})}function T$(e){let t=e.parentPath;if(t?.isObjectProperty()){let n=na(t).name;return n!==null&&Qr.has(n)}return t?.isVariableDeclarator()&&$e.isIdentifier(t.node.id)?Wk.test(t.node.id.name):!1}function zk(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=na(r).name;if(o&&Qr.has(o))return!0;t=r.parentPath;continue}return!!(r?.isVariableDeclarator()&&r.node.init===t.node&&$e.isIdentifier(r.node.id)&&Wk.test(r.node.id.name))}return t!==null}function sg(e){return e==="src"||e==="srcset"||e==="url"||e==="thumbnail_url"}function eu(e,t=0){if(t>=32)return!1;if(e.isArrayExpression())return e.get("elements").some(r=>r.node!==null&&(r.isObjectExpression()||r.isArrayExpression()?eu(r,t+1):!0));let n=!1;for(let r of e.get("properties")){if(!r.isObjectProperty()&&!r.isObjectMethod())return!1;let o=na(r);if(!o.known)return!0;let i=o.name;if(r.isObjectMethod()&&r.node.kind==="method")continue;if(i!==null&&(Qr.has(i)||sg(i))){n=!0;continue}if(r.isObjectMethod())continue;let s=r.get("value");(s.isObjectExpression()||s.isArrayExpression())&&eu(s,t+1)&&(n=!0)}return n}function qr(e){return e?$e.isStringLiteral(e)?{value:e.value,complete:!0}:$e.isJSXExpressionContainer(e)?qr(e.expression):$e.isTemplateLiteral(e)&&e.expressions.length===0?{value:e.quasis.map(t=>t.value.cooked??t.value.raw).join(""),complete:!0}:$e.isTSAsExpression(e)||$e.isTSTypeAssertion(e)||$e.isParenthesizedExpression(e)?qr(e.expression):{value:null,complete:!1}:{value:null,complete:!1}}function ta(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 ta(e.get("expression"),n);if(e.isIdentifier()){let r=e.scope.getBinding(e.node.name);return!r?.constant||r.kind!=="const"||!r.path.isVariableDeclarator()||!$e.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}:ta(r.path.get("init"),n)}return qr(e.node)}function Hk(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 w$(e,t){return e.slice(t.start_offset,t.end_offset)}function O$(e){return`sha256:${S$("sha256").update(e).digest("hex")}`}function F$(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 L$(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 Zk=512,U$=1024*1024,V$=8*1024*1024,qk=256;function K$(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||Qk(e.snapshot_files)!==e.snapshot_digest||!Number.isSafeInteger(e.occurrence)||e.occurrence<0||!Number.isSafeInteger(e.offset)||e.offset<0||e.offset%Yk!==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>B$||e.offset>=a.byteLength)return t();let c=J$(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:iu("sha256").update(l).digest("hex"),offset:e.offset,data_base64:l.subarray(e.offset,e.offset+Yk).toString("base64")}}function J$(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===ag.path&&t.byteLength===ag.byte_size&&iu("sha256").update(t).digest("hex")===ag.digest_sha256?"image/svg+xml":null}async function X$(e){if(e.snapshot.site_id!==e.site_id||e.snapshot.snapshot_id!==e.base_snapshot_id)return tn("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=j$.safeParse(e.target),c=D$.safeParse(e.selection_ref);if(!a.success||!c.success)return tn("BLOCK_SELECTION_INVALID","<selection>","The block target or render occurrence is invalid.");let l=a.data,u=c.data,d=nu(o,t,n,r);if(d)return d;let f=M$.safeParse(e.host_capabilities);if(!f.success)return tn("HOST_CAPABILITIES_INVALID","<host-capabilities>","The host capability contract is invalid.");let g=new Map;for(let[F,Z]of e.snapshot.files){if(typeof Z!="string"&&!(Z instanceof Uint8Array))return tn("SNAPSHOT_CONTENT_MISMATCH",F,"A Snapshot file has an unsupported content type.");g.set(F,typeof Z=="string"?Z:new Uint8Array(Z))}if(!H$(e.snapshot.manifest,t,n,g))return tn("SNAPSHOT_CONTENT_MISMATCH","<snapshot>","The file mapping does not match the authenticated Snapshot manifest.");let m=Qk(g),p=await cm({site_id:t,base_snapshot_id:n,composition:l.composition,document_version:r,target:l,selection_ref:u,files:g});if(!p.ok)return tn(`BLOCK_${p.code}`,l.blockKey,p.message);if(!p.binding.descriptor.capabilities.save)return tn("BLOCK_EXPORT_NOT_ALLOWED",l.blockKey,"The selected block is not exportable.");let y=Rk({binding:p.binding,files:g,hostCapabilities:f.data}),b;if(!y.complete){let F=ru(y.errors.map(({code:Ge,path:Pn,message:Ni})=>({code:Ge,path:Pn,message:Ni})));if(!y.errors.some(Ge=>Ge.code==="INVOCATION_VALUE_UNRESOLVED"))return F;let Z=Ii(g,i)?KI({binding:p.binding,target:l,files:g,trusted_host_file_hashes:i}):null,ue=Z?.complete?[]:await $k({binding:p.binding,files:g}),Ue=nu(o,t,n,r);if(Ue)return Ue;if(!Z?.complete)return ue.length?{...F,cms_candidates:{kind:"partial-unproven",slugs:ue}}:F;y={complete:!0,selection:Z.selection},b=Z.extracted}let E=b??xm({selection:y.selection,files:g});if(!E.complete)return ru(E.errors.map(({code:F,path:Z,message:ue})=>({code:F,path:Z,message:ue})));let x=new Map(g);for(let F of E.source_files){let Z=x.get(F.path);if(Z!==void 0&&!z$(Z,F.content))return tn("SOURCE_COLLISION",F.path,"An extracted entry conflicts with the pinned Snapshot.");x.set(F.path,F.content)}let S=or({entry_files:[E.entry_file],files:x,max_nodes:Zk}),v=S.nodes.filter(F=>cg(F.path)&&i.get(F.path)===ou(x.get(F.path))).map(F=>F.path),N=Ll({closure:S,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),R=Fk({files:x,entry_file:E.entry_file,private_paths:N.nodes.filter(F=>F.ownership==="private").map(F=>F.path)});x=new Map(R.files);let A=or({entry_files:[E.entry_file],files:x,max_nodes:Zk}),C=Ll({closure:A,host_capabilities:f.data,platform_managed_paths:v,platform_managed_packages:["server-only"]}),w=[],M=[],D=zI({entry_file:E.entry_file,entry_export:y.selection.entry_export,files:x,confirmed_slugs:new Set(s.map(F=>F.source_slug)),allow_build_sample:LI(x,i),on_host_call:F=>M.push(F),on_build_only_value:F=>w.push(F)}),U=D.dependencies.length>0,B=[...R.errors.filter(F=>A.nodes.some(Z=>Z.path===F.path)),...C.errors.map(({code:F,path:Z,message:ue})=>({code:F,path:Z,message:ue})),...D.unresolved.map(({code:F,source_path:Z,message:ue,call_site:Ue})=>({code:F,path:Z,message:ue,...Ue?{call_site:Ue}:{}}))];if(D.complete){let F=new Set(D.dependencies.map(ue=>ue.slug)),Z=new Set;U&&s.length>0&&s.length!==D.dependencies.length&&B.push({code:"CMS_SCHEMA_DEPENDENCY_UNPROVEN",path:"<cms-schema>",message:"Every selected application requires exactly one matching schema."});for(let ue of s){if(Z.has(ue.source_slug)||!F.has(ue.source_slug)){B.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}Z.add(ue.source_slug)}}let G=new Set(v);for(let F of A.nodes)U&&/^(?:src\/)?lib\/cms\/jsonld\.tsx$/u.test(F.path)&&!Ul(x,i,F.path)&&B.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:F.path,message:"A modified CMS helper cannot be omitted from the exported code dependencies."}),cg(F.path)&&!G.has(F.path)&&B.push({code:"HOST_CMS_IMPLEMENTATION_UNPROVEN",path:F.path,message:"A CMS host implementation requires trusted matching provenance regardless of its declared ownership."});for(let F of C.nodes)F.kind==="external"||F.ownership!=="host-public"||cg(F.path)||i.get(F.path)!==ou(g.get(F.path))&&B.push({code:"HOST_IMPLEMENTATION_UNPROVEN",path:F.path,message:"A host-public source requires trusted matching provenance before it may be omitted from the export."});let K=[];for(let F of C.nodes){if(F.kind!=="source"||!["host-public","platform-managed"].includes(F.ownership))continue;let Z=ht(x.get(F.path)),ue=Z===null?null:tu({file_path:F.path,source:Z});if(!ue||ue.references.length>0||ue.errors.length>0){let Ue=F.ownership==="host-public"&&y.selection.entry_export.kind==="default"?Bk({entry_file:E.entry_file,host_file:F.path,files:x,closure:A,trusted_host_file_hashes:i,...D.complete?{selected_host_calls:M}:{}}):{complete:!1};if(Ue.complete){K.push(...Ue.references);continue}B.push({code:"HOST_MEDIA_DEPENDENCY_UNPROVEN",path:F.path,message:"The omitted host source has media that cannot yet be bound to this archive."})}}let ge=new Map(C.nodes.map(F=>[F.path,F.ownership])),oe=[];for(let F of A.nodes){if(ge.get(F.path)!=="private")continue;let Z=x.get(F.path),ue=null;try{typeof Z=="string"?ue=Z:Z instanceof Uint8Array&&(ue=new TextDecoder("utf-8",{fatal:!0}).decode(Z))}catch{}ue===null?B.push({code:"SOURCE_TEXT_UNSUPPORTED",path:F.path,message:"A private source dependency is not valid UTF-8 text."}):oe.push({path:F.path,content:ue})}for(let F of oe)(/^(?:src\/)?components\/site\/generated\/(?:forms|product-search)\//u.test(F.path)||F.path==="lib/generated/product-search-config.json")&&B.push({code:"MANAGED_REQUIREMENT_UNPROVEN",path:F.path,message:"A managed capability requires a proven requirement before exporting the block."});oe.some(F=>F.path===E.entry_file)||B.push({code:"ENTRY_NOT_PRIVATE",path:E.entry_file,message:"The selected entry is not site-owned source."});let Le=0,Je=[];for(let F of oe){let Z=Buffer.byteLength(F.content,"utf8");if(Le+=Z,(Z>U$||Le>V$)&&B.push({code:"SOURCE_BUDGET_EXCEEDED",path:F.path,message:"The selected source exceeds its export byte budget."}),/\.[cm]?[jt]sx?$/iu.test(F.path)){let ue=tu({file_path:F.path,source:F.content,static_only:U});Je.push(...ue.references.filter(Ue=>!D.complete||!w.some(Ge=>Ge.file_path===F.path&&Ge.source_hash===ou(F.content)&&Ge.start<=Ue.source_range.start_offset&&Ge.end>=Ue.source_range.end_offset))),B.push(...ue.errors.map(({code:Ue,file_path:Ge,message:Pn})=>({code:Ue,path:Ge,message:Pn})))}}for(let F of K){let ue=Je.filter(Ue=>Ue.file_path===F.file_path).reduce((Ue,Ge)=>Math.max(Ue,Ge.occurrence+1),0);Je.push({...F,occurrence:ue})}let mt=new Map;if(D.complete){let F=new Map(oe.map(ue=>[ue.path,ue.content]));for(let ue of C.nodes){if(ue.kind!=="source"||!["host-public","platform-managed"].includes(ue.ownership))continue;let Ue=x.get(ue.path);try{if(typeof Ue=="string")F.set(ue.path,Ue);else if(Ue instanceof Uint8Array)F.set(ue.path,new TextDecoder("utf-8",{fatal:!0}).decode(Ue));else throw new Error("missing source")}catch{D.dependencies.length===0&&B.push({code:"ROUTE_SOURCE_UNAVAILABLE",path:ue.path,message:"A host source cannot be inspected for navigation."})}}let Z=Vk({sources:F,files:x});for(let[ue,Ue]of F){if(!/\.[cm]?[jt]sx?$/iu.test(ue))continue;let Ge=Kk({file_path:ue,source:Ue,current_route:l.composition.routeId,allow_props_forwarding:ue!==E.entry_file&&Z.has(ue)});D.dependencies.length===0&&B.push(...Ge.errors);for(let Pn of Ge.dependencies)mt.set(Pn.href,Pn)}mt.size>256&&D.dependencies.length===0&&B.push({code:"ROUTE_BUDGET_EXCEEDED",path:"<routes>",message:"The selected source exceeds its route dependency limit."})}let be=D.complete&&D.dependencies.length>0&&s.length===D.dependencies.length&&new Set(s.map(F=>F.source_slug)).size===s.length&&D.dependencies.every(F=>s.some(Z=>Z.source_slug===F.slug)&&F.evidence.every(Z=>["list","listStrict","get","getStrict","getByUrl","getByUrlStrict","schema","categories"].includes(Z.operation)))&&Ii(x,i);if(B.length>0||!A.complete||!C.complete||!D.complete){let F=[...new Set([...D.dependencies.map(Ue=>Ue.slug)])].sort();if(!(F.length>0&&F.length<=16&&new Set(F).size===F.length&&F.every(Ue=>/^[a-z0-9][a-z0-9_-]{0,123}$/u.test(Ue))))return ru(B);let ue=nu(o,t,n,r);return ue||{...ru(B),cms_candidates:{kind:"partial-unproven",slugs:F}}}let st=nu(o,t,n,r);if(st)return st;let Ke={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:oe.map(({path:F,content:Z})=>({path:F,content:Z})),source_closure:A,dependency_audit:C,cms:D,media:Je,invocation_bindings:E.invocation_bindings,host_contract_digest:f.data.host_contract_digest,...D.dependencies.length===0?{route_dependencies:[...mt.values()].sort((F,Z)=>F.href.localeCompare(Z.href))}:{},...be?{cms_sample_proof:{kind:"whole-application"}}:{}};return $$.safeParse(Ke).success?Ke:tn("PORTABLE_EXPORT_RESULT_INVALID","<export>","The selected source result failed its bounded export contract.")}function nu(e,t,n,r){if(!Number.isSafeInteger(r)||r<0)return tn("DOCUMENT_VERSION_STALE","<document>","The selected document version is invalid.");try{let o=e();return o.site_id!==t||o.snapshot_id!==n?tn("SNAPSHOT_MISMATCH","<snapshot>","The live runtime no longer matches the requested Snapshot."):o.document_version!==r?tn("DOCUMENT_VERSION_STALE","<document>","The live document version changed during export."):null}catch{return tn("RUNTIME_IDENTITY_UNAVAILABLE","<document>","The live runtime identity could not be verified.")}}function Qk(e){let t=iu("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 z$(e,t){return typeof e=="string"?e===t:Buffer.from(e).equals(Buffer.from(t,"utf8"))}function cg(e){return/^(?:src\/)?lib\/cms(?:\.[cm]?[jt]sx?$|\/(?!generated\/))/u.test(e)}function ou(e){return e===void 0?null:`sha256:${iu("sha256").update(e).digest("hex")}`}function H$(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||ou(s)!==i.hash||(typeof s=="string"?Buffer.byteLength(s,"utf8"):s.byteLength)!==i.size_bytes)return!1}return!0}function tn(e,t,n){return{complete:!1,unresolved:[{code:e,path:t,message:n}]}}function ru(e){return e.length?e.length<=qk?{complete:!1,unresolved:e}:{complete:!1,unresolved:[...e.slice(0,qk-1),{code:"PORTABLE_DIAGNOSTICS_TRUNCATED",path:"<selection>",message:"Additional unresolved export diagnostics were omitted."}]}:tn("PORTABLE_EXPORT_INCOMPLETE","<selection>","The selected block's export proof is incomplete.")}import lg from"@babel/generator";import{parse as W$}from"@babel/parser";import G$ from"@babel/traverse";import*as Ct from"@babel/types";var ug=G$,Y$=typeof ug=="function"?ug:ug.default,Z$=typeof lg=="function"?lg:lg.default,i_="components/site/generated/{{$INSTANCE}}/",s_=new Set([".tsx",".ts",".jsx",".js"]),e_=new Set(["data-site-block-id","data-vcp-block-id","data-vcp-edit-key"]),q$=new Set(["data-site-block-order","data-vcp-order"]);function Q$(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 S=xr(x.path);if(!S||n.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:x.path,message:"Portable source files must have unique safe paths."});continue}n.set(S,{...x,path:S})}for(let x of e.ownership){let S=xr(x.path);if(!S||r.has(S)){t.push({code:"SOURCE_INPUT_INVALID",path:x.path,message:"Portable source ownership entries must be unique and safe."});continue}r.set(S,{...x,path:S})}let o=xr(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,S)=>x.localeCompare(S)),a=s.map(x=>({source_path:x,path_template:aU(x)})),c=new Map(a.map(x=>[x.source_path,x.path_template])),l=eU(e.source_mapping??[],c,t),u=tU(e.required_source_paths??[],c,t),d=[],f=new Map,g=[];for(let x of s){let S=n.get(x);if(!S)continue;let v=rU(x,S.content,r,c,d,f,t);v!==null&&g.push({path_template:c.get(x),content:v,...S.role?{role:S.role}:{}})}let m=r_(t).sort(o_);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 p=g.map(x=>{let S=a.find(N=>N.path_template===x.path_template)?.source_path,v=n.get(S)?.content??"";return{source_path:S,path_template:x.path_template,original_byte_size:t_(v),output_byte_size:t_(x.content),original_line_count:n_(v),output_line_count:n_(x.content)}}),y=[...f.values()].map(x=>({...x,normalized:!0})).sort((x,S)=>x.source_path.localeCompare(S.source_path)),b=c.get(o)??null;if(e.thin_entry_plan){let x=nU(e.thin_entry_plan,c,t);x&&(g.push(x),b=x.path_template)}let E=r_(t).sort(o_);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:b,files:g.sort((x,S)=>x.path_template.localeCompare(S.path_template)),source_path_mappings:p.sort((x,S)=>x.path_template.localeCompare(S.path_template)),required_path_mappings:u,source_mapping:l,managed_rebindings:d.sort(fU),block_metadata:y,errors:[]}}function eU(e,t,n){let r=new Set,o=[];for(let[i,s]of e.entries()){let a=xr(s.generated_path),c=xr(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 tU(e,t,n){let r=new Set,o=new Set,i=[];for(let[s,a]of e.entries()){let c=xr(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 nU(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(xr(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=`${i_}__managed-root-entry.tsx`,i=a_(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}
49
49
  export default function PortableManagedRootEntry(props: Parameters<typeof Root>[0]) {
50
50
  return <Root {...props} />;
51
51
  }
52
- `}}function $U(e,t,n,r,o,i,s){if(!WU(e))return t;let a;try{a=TU(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=UU(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=$k(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=VU(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 OU(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];(Dt.isImport(u)||Dt.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&Dt.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=XU(l.node.name);if(!u||!Ok.has(u)&&!FU.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};Ok.has(u)?(m.original_block_attribute=u,m.original_block_id=zU(l.node.value)):m.original_order=HU(l.node.value),i.set(g,m),l.remove()}}),LU(a,{jsescOption:{minimal:!0}}).code}function UU(e,t,n){if(!t.startsWith(".")&&!t.startsWith("@/"))return{status:"external"};let r=t.startsWith("@/")?t.slice(2):Dr(`${Jk(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 $k(e,t,n){let r=Jk(e),o=JU(r,t),i=o.startsWith(".")?o:`./${o}`;return Uk(n)?i:Vk(i)}function VU(e,t){let n=`@/${e}`;return Uk(t)?n:Vk(n)}function JU(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 KU(e){let t=Dr(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${Bk}${r}`}function XU(e){return Dt.isJSXIdentifier(e)?e.name:Dt.isJSXNamespacedName(e)&&Dt.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function zU(e){return e?Dt.isStringLiteral(e)?e.value:Dt.isJSXExpressionContainer(e)&&Dt.isStringLiteral(e.expression)?e.expression.value:null:null}function HU(e){if(!e)return null;if(Dt.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return Dt.isJSXExpressionContainer(e)&&Dt.isNumericLiteral(e.expression)?e.expression.value:null}function WU(e){return[...jk].some(t=>e.endsWith(t))}function Uk(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function Vk(e){for(let t of jk)if(e.endsWith(t))return e.slice(0,-t.length);return e}function Dr(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 Jk(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Lk(e){return new TextEncoder().encode(e).byteLength}function Fk(e){return e.length===0?0:e.split(`
53
- `).length}function Dk(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function Mk(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function GU(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 YU from"node:path";import{GeneratedSiteCapabilitiesSchema as ZU,FormDefinitionIdSchema as qU,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as QU,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as eV,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as tV,SiteEditMaterializationExportSchema as nV,SiteEditMaterializationSchema as rV,SiteEditSourcePathSchema as oV}from"@vcp-dev/contracts";var wu="components/site/generated",iV=/^[a-z][a-z0-9._-]{0,127}$/,Lu=/^[a-z][a-z0-9._-]{0,127}$/,sV=new Set(["collection-detail-view","i18n-companion","client-importer"]);function aV(e){if(!Wi(e))return st("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!iV.test(e.instanceId))return st("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=ZU.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(!dV(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!qU.safeParse(f).success||!Ou(e.existingSources,`${m.slice(2)}.tsx`)})))return st("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=cV(e.resolved);if(!n.ok)return n;let r=rV.safeParse(n.materialization);if(!r.success)return st("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=lV(n.relatedEntries,r.data);if(!o.ok)return o;let i=uV(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=YU.posix.join(wu,e.instanceId),a=[],c=new Set;for(let m of r.data.files){let f=Es({pathTemplate:m.pathTemplate,generatedRoot:wu,instanceName:e.instanceId,instanceRoot:s});if(!f.ok)return Jg(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>eV)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>QU)return st("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",m.path);l+=f}if(l>tV)return st("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=Kk(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=Kk(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(Ou(e.existingSources,s)||a.some(m=>Ou(e.existingSources,m.path)))return st("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=df({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:wu,instanceRoot:s,entry:u.data,relatedEntries:d.sort((m,f)=>m.path.localeCompare(f.path)),entryConsumers:i.data,files:a}}):Jg(g.error)}function cV(e){if(!Wi(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&&!Wi(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 lV(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(!Wi(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=nV.safeParse(c.export);if(typeof l!="string"||!Lu.test(l)||typeof u!="string"||!Lu.test(u)||typeof d!="string"||typeof p!="string"||!sV.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 uV(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(!Wi(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"||!Lu.test(d)||typeof p!="string"||!Lu.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"||!oV.safeParse(m).success||!/^app\/.*\/page\.tsx$/u.test(m)||!Ou(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 Kk(e,t,n,r,o){let i=Es({pathTemplate:e,generatedRoot:wu,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):Jg(i.error)}function Ou(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function dV(e){return Array.isArray(e)||e instanceof Map||Wi(e)}function Wi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jg(e){return{ok:!1,error:e}}function st(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import Xk from"node:path";import{SiteEditSourcePathSchema as Kg}from"@vcp-dev/contracts";function fV(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||!Kg.safeParse(e.entryFile).success||!Kg.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 Mt("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 Mt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(Ue(n)!==t.sourceHash)return Mt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=hV(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?Mt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):pV(e,n):gV(e,n))}function pV(e,t){let n=we(e.entryFile,t);if(!n.ok)return Mt("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 Mt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=mV(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return Mt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=Rf({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 Mt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return Mt("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||!zg(a,e.resolvedBoundary.anchorLocator.sourceRange))?Mt("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 mV(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!zg(o.anchorSourceRange,t)?[]:zk(o.members).filter(i=>i.sourceRange!==null&&zg(i.sourceRange,t)));return r.length===1?r[0].label:null}function zk(e){return e.flatMap(t=>[t,...zk(t.children)])}function gV(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return Mt("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 Mt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=Zr({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return Mt(o.error.code,o.error.message,n.ownerFile);if(o.plan.requiresRouteParams)return Mt("UNSUPPORTED_ROUTE_PARAMS","A captured native detail parameter cannot be injected into an unproven shared owner.",n.ownerFile);let i=yV(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=Tn({source:t,locator:Xg(r),anchorLocator:Xg(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return Mt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=wn({source:s.source,moduleSpecifier:xV(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}]}:Mt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function hV(e){return!Kg.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)?Mt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function yV(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=we(t,e);if(!o.ok)return Mt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Be(o.module.ast,Xg(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?Mt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function Xg(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 xV(e,t){let n=Xk.posix.relative(Xk.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function zg(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Mt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as bV}from"@babel/parser";import Hg from"@babel/traverse";import*as Ot from"@babel/types";var EV=typeof Hg=="function"?Hg:Hg.default,SV=new Set(["slice","map","trim","toString"]);function IV(e){let t=new Set;try{let n=bV(e,{sourceType:"module",plugins:["jsx","typescript"]});EV(n,{JSXExpressionContainer(r){let o=r.get("expression");_a(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function _a(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=_a(e.get("object"),t),c=e.node;return!c.computed&&Ot.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&Ot.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&Ot.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!Ot.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>Ot.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:_a(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)||!Wg(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&Ot.isIdentifier(n.path.node.id))return _a(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=>Ot.isObjectPattern(a)&&a.properties.some(c=>Ot.isObjectProperty(c)&&!c.computed&&Ot.isIdentifier(c.key,{name:"record"})&&Ot.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!Ot.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||!Ot.isIdentifier(s.node.property,{name:"map"})?null:_a(s.get("object"),r)==="array"?"item":null}function Wg(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(!Ot.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&Wg(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&Ot.isIdentifier(r.node.property)&&SV.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&Ot.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!Ot.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!Wg(a,t))return!1}return!0}return r!==n}):!1)}export{Oe as FileHistoryStoreError,Os as PageTemplateManagedSourceError,eu as PreviewFileSystemSiteEditEngineRuntime,bx as SITE_EDIT_RAW_COLOR_LITERAL_RE,ql as SnapshotSiteEditEngineRuntime,K$ as analyzePortableCollectionInvocation,Xi as analyzePortableInvocation,hg as analyzePortableRelatedEntries,af as auditGeneratedCode,tu as auditPortableDependencies,Ts as buildPageBlockIndex,Zr as buildPortableInvocation,aV as buildPortableMaterializationPlan,br as buildPortableSourceClosure,qi as checkComponentI18nHostCompatibility,Bi as classifyPortableDependencyOwnership,Tm as cmsFieldAccessor,Ub as computeManagedPageTemplatePaths,mj as createPreviewSiteEditEngineRuntime,uj as createSiteEditEngineRuntime,Bb as decodePageTemplateKey,gg as discoverPortableCollectionSourceRelation,s$ as discoverPortableExistingCollectionRelation,Yf as encodePageTemplateId,RU as exportPortableBlockFromSnapshot,Xm as extractPortableBlockEntry,wm as generateCollectionAdapter,NC as instrumentSiteEditRuntimeAttributes,Vb as isManagedPageTemplateSourcePath,hw as normalizePortableBlockMetadata,DU as normalizePortableSource,jy as openFileHistoryStore,pC as parseSourceModule,fV as planPortableBlockPatch,Rf as planPortableRouteCompositionPatch,_s as planRouteCompositionRewrite,IV as provenRecordThumbnailRanges,kU as readPortableBlockLocalAssetChunk,mC as resolveImportBase,rL as resolveManagedPageTemplateComposition,zc as resolvePageBlockBoundary,Lm as resolvePageBlockFromSnapshot,xi as resolvePageBlockTarget,Xn as resolvePageCompositionProjection,sU as resolvePortableBlockSelection,hj as resolvePortableDependencyOwnership,wt as resolvePortableSourcePath,Yc as scanManagedPageTemplateCandidates,Ji as scanPortableMediaReferences,Zc as scanSiteEditCompositionsFromFiles,rf as scanSiteEditThemeStyleViolations,J$ as selectPortablePageUnitInvocation};
52
+ `}}function rU(e,t,n,r,o,i,s){if(!dU(e))return t;let a;try{a=W$(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 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 p=r.get(d.path);if(!p){s.push({code:"SOURCE_IMPORT_TARGET_UNOWNED",path:e,specifier:u,message:`The private import target ${d.path} was not materialized.`});return}l.value=a_(r.get(e),p,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=iU(d.path,u);l.value=g;let m=f.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 Y$(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];(Ct.isImport(u)||Ct.isIdentifier(u,{name:"require"})&&l.node.arguments.length===1)&&Ct.isStringLiteral(d)&&c(d)},JSXAttribute(l){let u=cU(l.node.name);if(!u||!e_.has(u)&&!q$.has(u))return;let d=l.parentPath.parentPath?.node,f=typeof d?.start=="number"?d.start:l.node.start??0,g=`${e}:${f}`,m=i.get(g)??{source_path:e,original_block_attribute:null,original_block_id:null,original_order:null};e_.has(u)?(m.original_block_attribute=u,m.original_block_id=lU(l.node.value)):m.original_order=uU(l.node.value),i.set(g,m),l.remove()}}),Z$(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):xr(`${u_(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 a_(e,t,n){let r=u_(e),o=sU(r,t),i=o.startsWith(".")?o:`./${o}`;return c_(n)?i:l_(i)}function iU(e,t){let n=`@/${e}`;return c_(t)?n:l_(n)}function sU(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 aU(e){let t=xr(e),n="components/site/generated/",r=t.startsWith(n)?t.slice(n.length):`source/${t}`;return`${i_}${r}`}function cU(e){return Ct.isJSXIdentifier(e)?e.name:Ct.isJSXNamespacedName(e)&&Ct.isJSXIdentifier(e.name)?`${e.namespace.name}:${e.name.name}`:null}function lU(e){return e?Ct.isStringLiteral(e)?e.value:Ct.isJSXExpressionContainer(e)&&Ct.isStringLiteral(e.expression)?e.expression.value:null:null}function uU(e){if(!e)return null;if(Ct.isStringLiteral(e)){let t=Number(e.value);return Number.isFinite(t)?t:null}return Ct.isJSXExpressionContainer(e)&&Ct.isNumericLiteral(e.expression)?e.expression.value:null}function dU(e){return[...s_].some(t=>e.endsWith(t))}function c_(e){return/\.[a-z0-9]+(?:[?#].*)?$/iu.test(e)}function l_(e){for(let t of s_)if(e.endsWith(t))return e.slice(0,-t.length);return e}function xr(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 u_(e){let t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function t_(e){return new TextEncoder().encode(e).byteLength}function n_(e){return e.length===0?0:e.split(`
53
+ `).length}function r_(e){let t=new Set;return e.filter(n=>{let r=JSON.stringify(n);return t.has(r)?!1:(t.add(r),!0)})}function o_(e,t){return e.path.localeCompare(t.path)||e.code.localeCompare(t.code)||(e.specifier??"").localeCompare(t.specifier??"")}function fU(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 pU from"node:path";import{GeneratedSiteCapabilitiesSchema as mU,FormDefinitionIdSchema as gU,SITE_EDIT_MATERIALIZATION_MAX_FILE_CONTENT_BYTES as hU,SITE_EDIT_MATERIALIZATION_MAX_FILE_COUNT as yU,SITE_EDIT_MATERIALIZATION_MAX_TOTAL_CONTENT_BYTES as bU,SiteEditMaterializationExportSchema as xU,SiteEditMaterializationSchema as EU,SiteEditSourcePathSchema as SU}from"@vcp-dev/contracts";var su="components/site/generated",vU=/^[a-z][a-z0-9._-]{0,127}$/,cu=/^[a-z][a-z0-9._-]{0,127}$/,IU=new Set(["collection-detail-view","i18n-companion","client-importer"]);function kU(e){if(!Pi(e))return qe("PORTABLE_INPUT_INVALID","Portable materialization input must be an object.","input");if(typeof e.instanceId!="string"||!vU.test(e.instanceId))return qe("PORTABLE_INSTANCE_INVALID","Portable instanceId must be a single safe directory name.","instanceId");let t=mU.safeParse(e.trustedHostPolicy);if(!t.success)return qe("PORTABLE_INPUT_INVALID","Portable materialization requires valid trusted host capabilities.","trustedHostPolicy");if(!Array.isArray(e.entryConsumers))return qe("PORTABLE_INPUT_INVALID","Portable materialization requires an entry consumer list.","entryConsumers");if(!PU(e.existingSources))return qe("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 p=/^@\/components\/site\/generated\/forms\/form-([^/]+)$/u.exec(m)?.[1];return!gU.safeParse(p).success||!au(e.existingSources,`${m.slice(2)}.tsx`)})))return qe("PORTABLE_INPUT_INVALID","Trusted managed imports must name exact existing canonical form sources.","trustedManagedImports");let n=_U(e.resolved);if(!n.ok)return n;let r=EU.safeParse(n.materialization);if(!r.success)return qe("PORTABLE_INPUT_INVALID","Resolved portable materialization failed the strict contract.","resolved.materialization");let o=RU(n.relatedEntries,r.data);if(!o.ok)return o;let i=CU(e.entryConsumers,o.data,r.data,e.existingSources);if(!i.ok)return i;let s=pU.posix.join(su,e.instanceId),a=[],c=new Set;for(let m of r.data.files){let p=es({pathTemplate:m.pathTemplate,generatedRoot:su,instanceName:e.instanceId,instanceRoot:s});if(!p.ok)return dg(p.error);if(c.has(p.data))return qe("MATERIALIZATION_PATH_INVALID",`Portable materialization resolves duplicate target path: ${p.data}`,p.data);c.add(p.data),a.push({kind:"create-only",path:p.data,content:m.content,...m.role?{role:m.role}:{},sourcePathTemplate:m.pathTemplate})}if(a.length>yU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file count exceeds the reusable limit.");let l=0;for(let m of a){let p=Buffer.byteLength(m.content,"utf8");if(p>hU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization file exceeds the per-file content limit.",m.path);l+=p}if(l>bU)return qe("MATERIALIZATION_LIMIT_EXCEEDED","Portable materialization exceeds the reusable total content limit.");let u=d_(r.data.entry.pathTemplate,r.data.entry.export,c,e.instanceId,s);if(!u.ok)return u;let d=[],f=[u.data];for(let m of o.data){let p=d_(m.pathTemplate,m.export,c,e.instanceId,s);if(!p.ok)return p;d.push({...m,path:p.data.path}),f.push(p.data)}if(au(e.existingSources,s)||a.some(m=>au(e.existingSources,m.path)))return qe("PORTABLE_INSTANCE_CONFLICT","Portable materialization cannot overwrite an existing instance source.",s);let g=Bd({preserveCapturedStyles:!0,files:a,instanceRoot:s,entries:f,hostCapabilities:t.data,trustedManagedImports:e.trustedManagedImports});return g.ok?(a.sort((m,p)=>m.path.localeCompare(p.path)),{ok:!0,data:{kind:"portable-materialization",instanceId:e.instanceId,generatedRoot:su,instanceRoot:s,entry:u.data,relatedEntries:d.sort((m,p)=>m.path.localeCompare(p.path)),entryConsumers:i.data,files:a}}):dg(g.error)}function _U(e){if(!Pi(e))return qe("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 qe("PORTABLE_INPUT_INVALID","Resolved related entries must be an array.","resolved.relatedEntries");if(n!==void 0&&!Pi(n))return qe("PORTABLE_INPUT_INVALID","Resolved portable descriptor must be an object.","resolved.portable");let r=n?.relatedEntries;if(r!==void 0&&!Array.isArray(r))return qe("PORTABLE_INPUT_INVALID","Resolved portable related entries must be an array.","resolved.portable.relatedEntries");let o=t,i=r;return o&&i?qe("PORTABLE_INPUT_INVALID","Resolved portable materialization must expose related entries once.","resolved.relatedEntries"):{ok:!0,materialization:e.materialization,relatedEntries:o??i??[]}}function RU(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 qe("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=xU.safeParse(c.export);if(typeof l!="string"||!cu.test(l)||typeof u!="string"||!cu.test(u)||typeof d!="string"||typeof f!="string"||!IU.has(f)||!g.success)return qe("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 qe("MATERIALIZATION_PATH_INVALID","Portable related entry keys and paths must be unique.",d);if(d===t.entry.pathTemplate)return qe("MATERIALIZATION_ENTRY_INVALID","A related entry cannot reuse the primary materialization entry.",d);if(!n.has(d))return qe("MATERIALIZATION_ENTRY_INVALID","Every related entry must reference a materialization file.",d);if(!r.has(u))return qe("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 CU(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 qe("PORTABLE_INPUT_INVALID","Every entry consumer must be an object.",`entryConsumers[${l}]`);let d=u.entry_key,f=u.requirement_key,g=u.kind,m=u.consumer_path;if(typeof d!="string"||!cu.test(d)||typeof f!="string"||!cu.test(f)||typeof m!="string"||!m.trim()||g!=="route"&&g!=="capability"&&g!=="preserved-route")return qe("PORTABLE_INPUT_INVALID","Entry consumers must declare a strict entry, requirement, kind and path.",`entryConsumers[${l}]`);let p=o.get(d);if(!p)return qe("PORTABLE_ENTRY_UNCONSUMED","An entry consumer must reference a declared related entry.",d);if(g==="preserved-route"&&(p.purpose!=="collection-detail-view"||!SU.safeParse(m).success||!/^app\/.*\/page\.tsx$/u.test(m)||!au(r,m)))return qe("PORTABLE_ENTRY_UNCONSUMED","A preserved detail entry requires an existing source route proven by the collection recipe.",d);if(s.has(d))return qe("PORTABLE_ENTRY_UNCONSUMED","A related entry must have exactly one managed consumer.",d);if(p.requirementKey!==f)return qe("PORTABLE_REQUIREMENT_UNRESOLVED","An entry consumer must use the related entry requirement.",d);if(!i.has(f))return qe("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:m})}let c=t.find(l=>!s.has(l.key));return c?qe("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 d_(e,t,n,r,o){let i=es({pathTemplate:e,generatedRoot:su,instanceName:r,instanceRoot:o});return i.ok?n.has(i.data)?{ok:!0,data:{path:i.data,export:t}}:qe("MATERIALIZATION_ENTRY_INVALID","Portable entry must match one controlled source file.",i.data):dg(i.error)}function au(e,t){return Array.isArray(e)?e.includes(t):e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function PU(e){return Array.isArray(e)||e instanceof Map||Pi(e)}function Pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dg(e){return{ok:!1,error:e}}function qe(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import f_ from"node:path";import{SiteEditSourcePathSchema as fg}from"@vcp-dev/contracts";function NU(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||!fg.safeParse(e.entryFile).success||!fg.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 Pt("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 Pt("INVALID_TARGET","The verified Portable owner is absent from the fixed source map.",t.ownerFile);if(Ae(n)!==t.sourceHash)return Pt("VERSION_STALE","The Portable boundary owner changed after resolution.",t.ownerFile);let r=OU(e);return r||(e.binding.root.ownerNode.kind==="route-member"?t.ownerFile!==e.entryFile?Pt("INVALID_TARGET","A route-member block boundary must remain in its route entry file.",t.ownerFile):AU(e,n):wU(e,n))}function AU(e,t){let n=_e(e.entryFile,t);if(!n.ok)return Pt("PORTABLE_ROUTE_SOURCE_INVALID",n.diagnostic.message,e.entryFile);let r=Tn({route:e.routeId,composition:e.binding.composition,entryFile:e.entryFile,version:e.documentVersion,source:t,ast:n.module.ast});if(!r.ok)return Pt("PORTABLE_ROUTE_UNSUPPORTED","The route owner does not expose a supported composition boundary.",e.entryFile);let o=TU(r.projection.placements,e.resolvedBoundary.anchorLocator.sourceRange,e.resolvedBoundary.placement);if(!o)return Pt("INVALID_TARGET","The exact route-member boundary has no unique page-composition member.",e.entryFile);let i=ef({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 Pt(i.error.code,i.error.message,e.entryFile);if(i.patch.path!==e.resolvedBoundary.ownerFile||i.patch.expectedSourceHash!==e.resolvedBoundary.sourceHash)return Pt("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||!mg(a,e.resolvedBoundary.anchorLocator.sourceRange))?Pt("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 TU(e,t,n){let r=e.flatMap(o=>o.relation!==n||!o.anchorSourceRange||!mg(o.anchorSourceRange,t)?[]:p_(o.members).filter(i=>i.sourceRange!==null&&mg(i.sourceRange,t)));return r.length===1?r[0].label:null}function p_(e){return e.flatMap(t=>[t,...p_(t.children)])}function wU(e,t){let n=e.resolvedBoundary,r=n.parentLocator;if(!r)return Pt("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 Pt("INVALID_TARGET","The verified shared owner parent is not a JSX child container.",n.ownerFile);let o=Or({component:e.component.localName,bindings:e.invocation.bindings,targetBlockId:e.invocation.targetBlockId,targetOrder:e.invocation.targetOrder});if(!o.ok)return Pt(o.error.code,o.error.message,n.ownerFile);if(o.plan.requiresRouteParams)return Pt("UNSUPPORTED_ROUTE_PARAMS","A captured native detail parameter cannot be injected into an unproven shared owner.",n.ownerFile);let i=FU(t,n.ownerFile,r,o.plan.bindings);if(i)return i;let s=bn({source:t,locator:pg(r),anchorLocator:pg(n.anchorLocator),placement:n.placement,node:{jsx:o.plan.jsx}});if(!s.ok)return Pt("PORTABLE_BLOCK_PATCH_FAILED",s.diagnostic.message,n.ownerFile);let a=xn({source:s.source,moduleSpecifier:LU(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}]}:Pt("PORTABLE_BLOCK_PATCH_FAILED",a.diagnostic.message,n.ownerFile)}function OU(e){return!fg.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)?Pt("INVALID_TARGET","The Portable component source or export is not a safe materialized reference.",e.component.source):null}function FU(e,t,n,r){if(!r.some(s=>s.value.kind==="route-search-params"))return null;let o=_e(t,e);if(!o.ok)return Pt("INVOCATION_VALUE_UNRESOLVED",o.diagnostic.message,t);let i=Pe(o.module.ast,pg(n));return!i.ok||!i.match.path.scope.getBinding("searchParams")?Pt("INVOCATION_VALUE_UNRESOLVED","The shared owner has no proven searchParams binding for this invocation.",t):null}function pg(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 LU(e,t){let n=f_.posix.relative(f_.posix.dirname(e),t.replace(/\.(?:tsx?|jsx?)$/u,""));return n=n.replaceAll("\\","/"),n.startsWith(".")?n:`./${n}`}function mg(e,t){return e.startLine===t.startLine&&e.startColumn===t.startColumn&&e.endLine===t.endLine&&e.endColumn===t.endColumn}function Pt(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{path:n}:{}}}}import{parse as DU}from"@babel/parser";import gg from"@babel/traverse";import*as kt from"@babel/types";var MU=typeof gg=="function"?gg:gg.default,BU=new Set(["slice","map","trim","toString"]);function jU(e){let t=new Set;try{let n=DU(e,{sourceType:"module",plugins:["jsx","typescript"]});MU(n,{JSXExpressionContainer(r){let o=r.get("expression");ra(o,new Set)==="url"&&t.add(`${r.node.start}:${r.node.end}`)}})}catch{}return t}function ra(e,t){if(e.isMemberExpression()||e.isOptionalMemberExpression()){let a=ra(e.get("object"),t),c=e.node;return!c.computed&&kt.isIdentifier(c.property,{name:"thumbnail"})&&a==="record"?"array":c.computed&&kt.isNumericLiteral(c.property)&&Number.isSafeInteger(c.property.value)&&c.property.value>=0&&a==="array"?"item":!c.computed&&kt.isIdentifier(c.property,{name:"url"})&&a==="item"?"url":null}if(e.isCallExpression()){let a=e.get("callee");return!a.isMemberExpression()||a.node.computed||!kt.isIdentifier(a.node.property,{name:"slice"})||!e.node.arguments.every(c=>kt.isNumericLiteral(c)&&Number.isSafeInteger(c.value)&&c.value>=0)?null:ra(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)||!hg(n,new Set))return null;let r=new Set(t).add(n);if(n.path.isVariableDeclarator()&&kt.isIdentifier(n.path.node.id))return ra(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=>kt.isObjectPattern(a)&&a.properties.some(c=>kt.isObjectProperty(c)&&!c.computed&&kt.isIdentifier(c.key,{name:"record"})&&kt.isIdentifier(c.value,{name:"record"}))))return"record";if(!o.isArrowFunctionExpression()||!kt.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||!kt.isIdentifier(s.node.property,{name:"map"})?null:ra(s.get("object"),r)==="array"?"item":null}function hg(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(!kt.isIdentifier(o.node.id)||o.node.init!==r.node)return!1;let i=o.scope.getBinding(o.node.id.name);return!!i&&hg(i,t)}if(o.isCallExpression()||o.isOptionalCallExpression()){if(!(o.node.callee===r.node&&(r.isMemberExpression()||r.isOptionalMemberExpression())&&!r.node.computed&&kt.isIdentifier(r.node.property)&&BU.has(r.node.property.name)))return!1;if((r.isMemberExpression()||r.isOptionalMemberExpression())&&kt.isIdentifier(r.node.property,{name:"map"})){let s=o.get("arguments.0");if(!s?.isArrowFunctionExpression()||!kt.isIdentifier(s.node.params[0]))return!1;let a=s.scope.getBinding(s.node.params[0].name);if(!a||!hg(a,t))return!1}return!0}return r!==n}):!1)}export{ve as FileHistoryStoreError,ps as PageTemplateManagedSourceError,Fl as PreviewFileSystemSiteEditEngineRuntime,Wy as SITE_EDIT_RAW_COLOR_LITERAL_RE,wl as SnapshotSiteEditEngineRuntime,H0 as analyzePortableCollectionInvocation,_i as analyzePortableInvocation,Lm as analyzePortableRelatedEntries,Fd as auditGeneratedCode,Ll as auditPortableDependencies,ds as buildPageBlockIndex,Or as buildPortableInvocation,kU as buildPortableMaterializationPlan,or as buildPortableSourceClosure,wi as checkComponentI18nHostCompatibility,xi as classifyPortableDependencyOwnership,im as cmsFieldAccessor,hx as computeManagedPageTemplatePaths,$B as createPreviewSiteEditEngineRuntime,DB as createSiteEditEngineRuntime,px as decodePageTemplateKey,Fm as discoverPortableCollectionSourceRelation,l0 as discoverPortableExistingCollectionRelation,kf as encodePageTemplateId,X$ as exportPortableBlockFromSnapshot,xm as extractPortableBlockEntry,sm as generateCollectionAdapter,tR as instrumentSiteEditRuntimeAttributes,yx as isManagedPageTemplateSourcePath,VT as normalizePortableBlockMetadata,Q$ as normalizePortableSource,my as openFileHistoryStore,j_ as parseSourceModule,NU as planPortableBlockPatch,ef as planPortableRouteCompositionPatch,os as planRouteCompositionRewrite,jU as provenRecordThumbnailRanges,K$ as readPortableBlockLocalAssetChunk,$_ as resolveImportBase,NO as resolveManagedPageTemplateComposition,_c as resolvePageBlockBoundary,cm as resolvePageBlockFromSnapshot,ei as resolvePageBlockTarget,Tn as resolvePageCompositionProjection,l$ as resolvePortableBlockSelection,VB as resolvePortableDependencyOwnership,Tt as resolvePortableSourcePath,Nc as scanManagedPageTemplateCandidates,tu as scanPortableMediaReferences,Ac as scanSiteEditCompositionsFromFiles,Td as scanSiteEditThemeStyleViolations,z0 as selectPortablePageUnitInvocation};